Compare commits

...
Author SHA1 Message Date
Julius MarmingeandClaude Fable 5 993407dd9e fix(server): reject replaying a command receipt across threads in v2
Ports v1's #5246 guard into the v2 dispatcher: a stored receipt only
proves that this exact command already ran for the thread it was recorded
against, so returning it for a command aimed at a different thread reports
success for work that never happened there. The check is extracted as
canReplayCommandReceipt so the rule is unit-testable, and reuse now fails
with OrchestratorCommandIdConflictError like the v1 path.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 17:25:53 +02:00
Julius MarmingeandClaude Fable 5 0c68291bc6 fix: reconcile main's round-8 features after the rebase
Re-applies the deltas that mid-stack blob reverts discarded, and merges
main's work into the v2-owned surfaces:

- keybindings: main's STATIC_KEYBINDING_COMMANDS rename plus both new
  commands (rightPanel.toggleMaximized alongside threadPanel.toggle)
- OpenInPicker: main's remote-open/SSH routing and favorite-editor
  shortcut layered onto the branch's panel/toolbar variants; the
  extracted shouldShowOpenInPicker now takes remoteOpenMode
- ChatMarkdown: main's bare-filename resolver (#6297) ported into the
  branch's module-level component factory, plus #4133 title-attribute
  stripping on links and images
- ComposerPrimaryActions: main's #4781 model (stop stays reachable, send
  joins it when Enter-to-send is unavailable) carrying the branch's
  steering send button
- ComposerPendingUserInputPanel: main's collapsible redesign with the v2
  RuntimeRequestId and responseCapability gate
- ChatComposer: main's oversized-prompt submission guard wrapping the
  branch's dispatch-mode send
- preview shell: main's container-aware width clamp ported into the
  branch's usePreviewPanelInlineSize hook
- MessagesTimeline/Sidebar: main's day-aware timestamps, code-font tool
  bodies and provider accent badges on the v2 runtime shell
- index.css: main's @variant dark migration (#6381) replaces the branch's
  standalone .dark block
- contracts: main's send-turn image mime allowlist re-homed to
  chatAttachment.ts, where v2 keeps the other send-turn limits

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 17:18:32 +02:00
Julius Marminge 4442054fc7 perf(server): keep shell snapshots bounded and active-only
- Omit transcript bodies from shell rows
- Query archived threads separately and stream compact resume metadata
2026-08-15 16:51:45 +02:00
Julius MarmingeandClaude Fable 5 4ef9640d2e fix(web): size the titlebar layout-control icons like the sidebar trigger
The trigger's icon falls through to the Button default (size-4) while the
right cluster hard-coded size-3.5, so the two ends of the titlebar read a
pixel apart on every edge. All five layout-control icons now use size-4,
matching the trigger and the pull requests page's refresh icon.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:44 +02:00
Julius MarmingeandClaude Fable 5 0730577f7a fix(web): align titlebar clusters to one shared pixel inset
The right controls carry mr-px (main's border compensation for anchoring
inside the panel frame), which left the sidebar trigger one pixel closer
to its edge and the sheet-mode tab bar one pixel tighter than the closed
state. Mirror the pixel on the trigger and the sheet layout-controls slot
so all three read the same inset.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:44 +02:00
Julius MarmingeandClaude Fable 5 05c236b2e9 fix(web): keep the titlebar layout controls fixed across right-panel toggles
Restores main's one-inset rule (#5226) that a rebase resolution had
overridden with a conditional right-2 offset, which made the controls jump
sideways whenever the right panel opened. Also restores the live-agent
count badge on the right-panel toggle (#5745) that the round-6 replay
dropped, and applies the same fixed-position rule to the pull requests
page: the toggle now stays mounted at one absolute inset in both states,
with a footprint spacer in the list header so the refresh button never
slides underneath it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:44 +02:00
Julius MarmingeandClaude Fable 5 70fc7b9e82 fix: reconcile main's round-6 features after the rebase
- ChatView: #5880 auto-settle-on-merge setting flows into effectiveSettled,
  #5644 browser favicon project registration effect, activeProjectRef memo,
  desktopByTabId on both RightPanelTabs mounts
- server: provide ServerSecretStore to the McpSessionRegistry's
  ServerEnvironment layer (#6325 reads publish opt-in per descriptor)
- mobile: 3-way merged main's deltas into the v2 thread screens
  (NewTaskDraftScreen keeps the branch title seed + main's environmentId,
  threadListV2 keeps both new test suites, queries imports deduped)

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:44 +02:00
Julius Marminge 2d325c5a58 feat(contracts): track thread title regeneration
- Add optional title regeneration request and start time to thread shells
- Cover cache serialization on mobile and client runtime
2026-08-15 16:51:44 +02:00
Julius Marminge f875dff07d feat(orchestration): bound thread history and resume payloads
- Add paginated thread history with bounded snapshots and replay limits
- Trim oversized wire payloads and support progressive mobile history loading
2026-08-15 16:51:44 +02:00
Julius MarmingeandClaude Fable 5 8fac43950a fix(web): restore main's collapse chrome and tab-status keying on the PR panel
The round-5 ChatView reconciliation kept the round-3-era PullRequestDetailPanel
call, so the panel mounted without chromeVariant="collapse" — the #6039
scroll-condensing chrome never engaged and the description scrolled under a
full-height chrome. Restore main's call exactly: collapse chrome,
composerDraftTarget for same-thread hand-offs, the isThreadOwnPullRequest
context check, and tab statuses keyed by the active surface id via
updatePullRequestTabStatus instead of a key rebuilt from the status payload.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:44 +02:00
Julius Marminge 0e370e7521 feat(web): prioritize pull request row actions
- Add conflict, draft, failing-check, and merge action ranking
- Show check progress and pull request details in row tooltips
2026-08-15 16:51:44 +02:00
Julius MarmingeandClaude Fable 5 c3c01cba3d fix(web): reconcile main's round-5 features after the rebase
- PullRequestDetailPanel takes main's #6039 rework wholesale (reactions,
  update-branch, auto-merge, in-place editing); the thread-details action
  hooks stay in usePullRequestActions with label maps extended for the
  new action variants
- CommandPalette #6330 provider subtitles adapted to the v2 shell
  (session -> runtime for provider instance and display name)

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:44 +02:00
Julius MarmingeandClaude Fable 5 4511210a45 fix(mobile): port main's composer stabilization into the v2 thread screens
Round-4 reconciliation of #5986/#5988 with the v2 cutover files:
- PendingUserInputCard adopts main's collapsible overlay redesign with the
  v2 RuntimeRequestId/responseCapability plumbing (dead provider processes
  still read-only the card)
- ThreadFeed adopts the thread-feed-live-follow transition model, the
  user-scroll settle window, momentum handoff, and env-scoped feed keys
  while keeping the v2 nearListEnd layout gating
- ThreadDetailScreen hides (not unmounts) the composer while a user-input
  request owns the slot; multi-select answers flow as arrays end to end
  (threadActivity toggle/build helpers + tests, ThreadUserInputQuestion)
- ThreadComposer keeps the v2 canStopThread stop gate under main's
  onEditorFocusChange rename; standalone stop reuses the shared renderer
- Restored the branch's steer stop/send tests alongside main's composer
  test suite

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:38 +02:00
Julius Marminge 893c04b94b feat(web): add pull request actions to thread details
- Add ready, merge, and conflict-resolution actions to the PR row
- Share pull request action and handoff logic with the detail panel
- Fix thread details scrolling and row alignment
2026-08-15 16:51:38 +02:00
Julius MarmingeandClaude Fable 5 3b08f94ccc fix(web): restore the branch's slim chat header
The round-3 reconciliation took main's ChatHeader wholesale and wired its
full prop set, resurrecting the scripts/open-in/git-actions cluster the
branch had deliberately relocated into the thread panel. Restore the
79-line slim header (project favicon + name + thread title) and its
minimal ChatView call. #5592's header actions stay a documented v2
follow-up, as decided in round 2.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:33 +02:00
Julius MarmingeandClaude Fable 5 44f7b15a35 test(server): expect attachment saved-at lines in ClaudeAdapterV2 turn text
Follow-up to the #5757 port: start and steer turns now append the
'[Attached ... is saved at: path]' line, so the adapter fixtures assert it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:33 +02:00
Julius MarmingeandClaude Fable 5 0a2a1a775f test(web): restore main's right-panel migration expectations after the panel-visibility merge
The keep-both merge nested main's plan-surface migration test inside a
branch popover test and dropped the threadPanelVisibilityByThreadKey key
from the migration results. Restore main's test body and include the
branch's (empty) visibility map in the expected persisted shape.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:33 +02:00
Julius MarmingeandClaude Fable 5 a325fa337e fix(server): port round-3 main fixes into the v2 orchestrator
- a6c9b41f90 (agents open pasted images): ClaudeAdapterV2 now grants the
  attachments dir alongside cwd via additionalDirectories and appends
  '[Attached ... is saved at: path]' lines to the turn text so tools can
  dereference pasted images (pixels alone are not tool-readable).
- 5bb8c03664 (settle leaves monitors running): thread.settle now joins
  archive/delete in the provider-session detach set, so PR monitors, dev
  servers and subagent fleets stop when the user parks the thread. The
  settle guard already rejects active runs, and serialized dispatch closes
  the re-engage race the v1 fix handled with onlyIfSettled.
- e70cdb478d (Claude resume handshakes) and 2c7267ad43 (reaper vs live
  background subagents) are already covered structurally in v2: results
  are turn-scoped with explicit zero-turn handshake drops, and idle
  release is pinned while background work is pending.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:33 +02:00
Julius MarmingeandClaude Fable 5 f3d2958518 chore(server): renumber v2 migrations 038-046 to 041-049 after main's 038-040
Main released ProjectionThreadsPinOrderKey (038),
ProjectionProjectsDefaultThreadEnvMode (039) and
ProjectionProjectFaviconPath (040), so the branch-private v2 stack shifts
up by three. Registry ids were already 41-49; this renames the files and
identifiers to match and updates the ledger expectations and through-id
boundaries in the migration tests (released boundary 37 -> 40).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:33 +02:00
Julius MarmingeandClaude Fable 5 f096e0717b fix: repair rerere-damaged files and reconcile main's round-3 features with v2
Post-rebase reconciliation sweep:
- Sidebar: main's folded Sidebar.tsx/Sidebar.logic.ts adapted to v2 shells
  (latestRun/runtime naming, waiting status instead of monitoring), with
  subagent-thread filtering and main's pinned-reorder helpers re-exported
- Pinned drag reorder (#5581) ported into v2: thread.pin orderKey +
  thread.pin.reorder command, thread.pin-reordered event, Orchestrator fold,
  ProjectionStore/Maintenance, client-runtime commands and shell mapping
- Project favicon (#4849-era) and defaultThreadEnvMode flowed through v2
  contracts (OrchestrationProjectShell, application event payloads)
- ChatView: main's #5592 header props, pull-request right-panel surfaces,
  liveAgentCount badge (#5745) wired into the v2 panel layout
- enableAssistantStreaming -> enableLegacyTokenStreaming rename applied to
  v2 RunExecutionService and replay testkit
- Removed v1 zombies resurrected by the rebase (provider service/reaper/
  ingestion + v1 layer tests, server.test.ts, integration harness)
- routeTree: main's tree + branch's /settings/scheduled-tasks route
- Misc marker-sweep syntax repairs (rpc.ts, entities.ts, localApi.test.ts,
  rightPanelStore.test.ts, GitManager.test.ts, mobile model menu helpers)

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:33 +02:00
Julius Marminge 5d3740b01a fix(web): show Git action success inline in panel
- Keep success feedback visible in the Git action control for 10 seconds
- Move the running elapsed timer into the panel menu slot
2026-08-15 16:51:27 +02:00
Julius MarmingeandClaude Fable 5 733afbc6fa fix(web): let LegendList own end-follow and disclosure anchoring (#5449)
Complete the #5449 architecture on the v2 timeline, following the
LegendList author's direction to lean on the list's native mechanisms
instead of app-side scroll layers:

- maintainScrollAtEnd is enabled and owned by LegendList, gated off only
  while the user reads history (liveFollowEnabled), while a sent turn
  anchors near the top (anchoredEndSpace), or during the two-frame settle
  of a fold toggle.
- maintainVisibleContentPosition compensates size changes natively
  ({data, size, shouldRestorePosition}); fold toggles anchor compensation
  to the toggled row via a disclosure anchor key, so the trigger stays
  under the pointer instead of the viewport chasing the end.
- ChatView's hand-rolled streaming follow (double-rAF scrollToEnd on
  every data change) is gone; the app now only owns streaming
  adjustments during anchored-end-space mode, mirroring main.
- timelineLiveFollowEnabled state mirrors the follow refs so the
  render-visible gate switches native follow off when a gesture breaks
  follow and back on when the viewport returns to the end band.

Timeline tests updated to assert the native-ownership invariants.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:27 +02:00
Julius MarmingeandClaude Fable 5 4ceb892265 fix(web): port the refined live-follow gesture gating to the v2 timeline
The rebase kept the LegendList 3.3.3 upgrade and patch from #5449 and the
mobile end-follow latch from #5566, but the v2 MessagesTimeline/ChatView
still carried the branch's blunt any-gesture-breaks-follow listeners.
Port main's #5566 web mechanics onto the v2 follow architecture:

- resolveTimelineIsAtEnd measures the 40px follow re-arm band from real
  geometry (contentLength/scroll/scrollLength minus the composer inset),
  keeping the isNearEnd fallback for older state shapes.
- Follow now breaks only on gestures that can actually leave the live
  edge: upward wheel with overflowing content, touch drags that exited
  the end band, scrollbar drags vs content clicks, and keyboard
  navigation (PageUp/Home/ArrowUp) — previously keyboard scrolling never
  broke follow and the next stream chunk yanked the view back down.
- Listener attach retries across frames so a thread switch cannot mount
  the list without its opt-out listeners.

Deliberately not ported: #5449's shouldRestorePosition disclosure
anchoring and follow-gated maintainScrollAtEnd — the v2 timeline keeps
maintainScrollAtEnd={false} with its own follow scrolls and anchor
system; flipping that core is a separate change.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:27 +02:00
Julius MarmingeandClaude Fable 5 aded5afa3f chore(web): prune plan-sidebar leftovers after the inline-plans rework
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:27 +02:00
Julius MarmingeandClaude Fable 5 807072b7c1 fix: port main fixes stranded by the v2 rewrite (round 2)
Native subagent observability (#5219), wired per its spec's v2 merge plan:
- getWorkflowScript RPC re-homed onto the v2 WS surface (contracts, rpc
  group, ws handler, auth scope, client atom).
- AgentsPanel fed by the spec's mapper swap: projectedSubagentsToRuntime
  maps orchestration-v2 subagent entities into the panel model;
  deriveAgentPanelModel's v2Projection leg is now live and the v1 fold
  never runs. Agents surface wired into ChatView + RightPanelTabs.
Other ports and reconciliations:
- Shell reconnect-loop fix (#5561) ported into the v2 shell sync
  (same-session resubscribes resume from the in-memory cursor), with the
  cursor-resume regression test adapted to v2 fixtures.
- Mobile end-follow latch (#5566) ported onto the v2 ThreadFeed.
- Claude ede_diagnostic interrupt classification (#5557) ported into
  ClaudeAdapterV2 (aborted_tools/aborted_streaming => interrupted; CLI
  telemetry never becomes the failure banner). #5559 needs no v2 port
  (unknown system subtypes are already ignored).
- Plan sidebar removed from the v2 ChatView/ChatComposer per main's
  plans-fold-into-chat rework (#5558); rightPanelStore stays at main's
  surface set.
- SettingsPanels rebuilt as main's refactored version plus the branch's
  composer-context setting; sidebar snooze respects the time format
  (#4438 follow-through).
- v1-only leftovers deleted: zombie v1 adapters/ingestion/tests the v2
  rewrite removes, the v1-bound transfer-budget CI harness (#5350, needs
  a v2 rebuild), and main's v1 client pagination machinery (#5493 client
  side; the 037 keyset migration is kept — server-side v2 windowing is a
  follow-up).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:27 +02:00
Julius MarmingeandClaude Fable 5 4cd4e62417 fix(server): renumber v2 migrations after main's 037_ProjectionTurnsKeysetIndex
Main owns migration numbering: 037_ProjectionTurnsKeysetIndex landed on
main (#5493), so the v2 migrations shift from 037-045 to 038-046.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:19 +02:00
Julius MarmingeandClaude Fable 5 e992d844b6 fix: repair conflict-marker artifacts from rebase auto-resolutions
rerere replayed stale resolutions during the rebase and committed nested
conflict markers in several files. Restore the branch-intended v2 shapes
and re-graft main's compatible additions (pending-card opacity comments,
theme-editor keybinding test, mobile scroll re-arm effects from #5566).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:19 +02:00
Julius Marminge cc44d43b4b fix(web): align git action progress button layout
- Match progress button spacing and single-line height to static git actions
2026-08-15 16:51:19 +02:00
Mike Olson 18a91d6822 feat(orchestrator): Surface waiting background work (#4378) 2026-08-15 16:51:19 +02:00
Julius MarmingeandClaude Fable 5 b5cada5e89 test(server): align migration expectations with renumbered ids
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:19 +02:00
Julius MarmingeandClaude Fable 5 3b903fc423 fix: port main fixes stranded by the v2 rewrite
- Port thread pinning (#5312) into the orchestration-v2 command pipeline:
  thread.pin/unpin commands, thread.pinned/unpinned events, pinnedAt on the
  v2 thread state and projected shells, promotion semantics (pin clears
  settle/snooze, settle clears pin) matching the v1 decider, and client
  pin/unpin operations in the v2 dispatch style.
- Port the regenerated-title context anchoring (#5365) into
  ThreadTitleRegenerationService: pin the first user message ahead of the
  retained tail when the digest is truncated.
- Re-apply the right-panel controls positioning from #5260 to the v2
  ChatView title bar controls.
- Repair merge artifacts: committed conflict markers in BranchToolbar,
  duplicate capability keys, duplicate CommandPalette import, v1 turn
  naming in DiffPanel's focus-refresh effect, onSend signature merge.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:19 +02:00
Julius MarmingeandClaude Fable 5 e538616255 fix(server): renumber v2 migrations after main's 036_ProjectionThreadsPinned
Main owns migration numbering: 036_ProjectionThreadsPinned landed on main,
so the v2 migrations shift from 036-044 to 037-045. Release path runs all
of main's migrations first, then the v2 stack.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:19 +02:00
Julius Marminge 8ada620ce8 fix(web): remove open PR actions from git controls
- Keep the git action control disabled when the branch is up to date
- Omit open PR menu entries and remove their link-opening behavior
- Update logic tests for the new states
2026-08-15 16:51:19 +02:00
Julius MarmingeandClaude Fable 5 482c46f6e2 fix(server): stop tying codex text-generation temp files to the caller's scope (#5406)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 16:51:18 +02:00
Mike Olson 5133fdbed5 fix(orchestrator): Prevent redundant delegated completion turns (#5311) 2026-08-15 16:51:18 +02:00
Julius MarmingeandClaude Fable 5 a6216cf3dc fix(test): keep codex replay recovery off the repo checkout
The codex resume test was the only replay scenario without a
runtimePolicyOverride, so its checkpoint scope cwd fell back to
process.cwd() and baseline capture ran real git over the entire
checkout. Locally the capture short-circuits on checkpoint refs left
behind by earlier runs; on a fresh CI checkout it is a cold multi-second
capture that outlives the scenario wait budget, failing await_thread_idle
while the run is still mid-checkpoint. Point the fixture's turn/start
frames at the <workspace> placeholder and checkpoint a throwaway git
workspace like every other replay test.

Scenario waits are also wall-clock-bounded now: the iteration budget
counts event-loop turns, which burn at full speed while git/fixture IO
is in flight, so exhaustion additionally requires a 60s real-time
deadline to pass.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:18 +02:00
Julius MarmingeandClaude Fable 5 7b1d62e39c chore: resolve lint warnings across v2 code
Hoist inline Schema compiles to module scope, drop unused
imports/vars, stabilize react-markdown component identities via a
module-scope factory, remove useless spreads, and use data-derived
keys for release-note bullets. No behavior changes.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:18 +02:00
Julius MarmingeandClaude Fable 5 2d379a19fa test(server): cover v2 thread title regeneration
Ports the deleted v1 ProviderCommandReactor title coverage onto the v2
service: marker arming/clearing via thread.metadata.update, superseded
requestId no-ops, digest-driven regeneration, the "New thread" and
unchanged-title fallbacks, generation failure, and missing initial
messages, plus unit tests for formatThreadTitleContext.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:13 +02:00
Julius MarmingeandClaude Fable 5 0285d41813 fix(web): restore compact header sizing for project script controls
The thread-panel mapping change replaced the compact className on the
Run and Add controls with the isPanel conditional and dropped the
non-panel icon-compact classes that the responsive test asserts.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:13 +02:00
Julius MarmingeandClaude Fable 5 298d797e72 fix: send mcp-protocol-version header in worktree registration test
Required for follow-up requests by the 2025-06-18 MCP HTTP transport
that effect beta.103 enforces.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:13 +02:00
Julius MarmingeandClaude Fable 5 c2b4f965a3 fix: adopt effect beta.103 APIs in rebased v2 code
- Schema.UnknownFromJsonString -> Schema.fromJsonString(Schema.Unknown)
- SchemaIssue.InvalidValue single-argument form in checkpointDiff
- McpServerClient requires protocolVersion

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:51:13 +02:00
maria 22d79b30ff feat(chat): refine V2 conversation UI (#5307) 2026-08-15 16:51:13 +02:00
Julius MarmingeandClaude Fable 5 2a6f05fb43 fix(server): restore worktree branch naming in the v2 orchestrator (#5309)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 16:51:13 +02:00
Mike Olson 89886c403b fix(orchestrator): Order thread lineage by creation time (#5310) 2026-08-15 16:51:13 +02:00
Yusuf Rawat 0dd6b54c8a fix(orchestration-v2): restore generated thread titles (#5176) 2026-08-15 16:51:13 +02:00
maria-rcks 28d429d047 fix: reconcile rebase with latest main 2026-08-15 16:51:08 +02:00
Julius Marminge d2d785cebf fix(web): keep Git progress title anchored
- Prevent the title row from shifting when output is revealed
- Preserve panel and compact button sizing
2026-08-15 16:50:26 +02:00
Julius Marminge 1e52051723 fix(web): remove elevated thread details panel styling 2026-08-15 16:50:25 +02:00
Julius MarmingeandClaude Fable 5 80b181c6a8 refactor(orchestration): split thread-not-sendable into typed errors
Effect service conventions: ThreadManagementThreadNotSendableError
carried an Archived/NoSteerableRun reason union and switched on
reason._tag inside the message getter. Modelled as two error classes
(ThreadManagementThreadArchivedError, ThreadManagementNoSteerableRunError);
both still map to the MCP thread_not_sendable failure code.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:50:25 +02:00
Julius MarmingeandClaude Fable 5 65f11099fe fix(orchestration): promoted queued messages keep the queued_turn intent
The turn item materialized when a queued run is promoted was emitted
with inputIntent "turn_start", but the deterministic replay driver (and
the recorded queued_turn fixtures) expect "queued_turn" — the mismatch
stalled replay before the queued run could start, leaving run 1 waiting
and run 2 queued forever in all five queued_turn fixtures.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:50:25 +02:00
Yusuf Rawat 17a2932583 fix(orchestration): thread visits no longer create activity loops (#5038) 2026-08-15 16:50:25 +02:00
Julius MarmingeandClaude Fable 5 0e7452f059 feat(orchestration): port thread title regeneration to the v2 runtime
Follow-ups from the main merge:

- Migration numbering: main's 035_ProjectionThreadTitleRegeneration is
  released and keeps its id; this branch's unreleased v2 migrations shift
  to 036-044 instead (a released migration can never be renumbered).
- thread.metadata.update accepts regenerateTitle: true arms an in-flight
  titleRegeneration marker on the thread payload (requestId + startedAt),
  a landing title or explicit false clears it. The marker projects onto
  thread shells and through the client-runtime shell model, so the
  sidebar's Regenerating state works unchanged.
- New ThreadTitleRegenerationService worker reacts to armed markers on
  the live domain-event stream (so ws, MCP, and mobile dispatches all
  behave the same): builds a newest-first conversation digest from the
  v2 projection (8k-char budget, retained attachments — ported from the
  v1 reactor), generates via TextGeneration, and lands the title with a
  follow-up metadata update. Failures clear the marker and log.
- The server advertises threadTitleRegeneration again, and the client
  updateThreadMetadata dispatches regenerateTitle-only updates.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:50:25 +02:00
Julius MarmingeandClaude Fable 5 08ab4239d5 perf(web): keep timeline minimap animations off the main thread
A renderer performance trace showed the minimap strips as a standing
source of main-thread frame work: each strip transitioned
background-color (paint) and width (layout), and both fire constantly —
scrolling or streaming flips a band of in-view states at once, and the
hover fisheye animates several widths at a time — so any interaction
kept a 60fps style/layout/paint pipeline running.

The strip now animates only compositor-friendly properties: width tiers
are scale-x on a fixed-width box, and the in-view highlight is a bright
overlay faded with opacity. The scroll handler also skips no-op
data-in-view attribute writes, which previously re-dirtied style state
for every strip on every scroll tick.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:50:25 +02:00
Julius MarmingeandClaude Fable 5 ef433a39ec fix(relay): stop replaying the whole event store into the awareness relay
Live profiling of the built app (debugger pause inside the hot sqlite
call) showed AgentAwarenessRelay.publishThread grinding at ~8 full shell
snapshots per second after boot. Two causes:

- streamDomainEvents was eventSink.stream() with no cursor, which
  replays every stored event from genesis before going live — so each
  boot fed the relay the entire event history as fresh activity, and it
  queued a publish per activity-relevant event for hours. It now tails
  from the current high-water mark; the relay's startup snapshot publish
  already covers initial state, and the sink subscribes before reading
  the cursor so no live event is lost.
- publishThreadUnsafe materialized the full shell snapshot to find one
  thread; it now uses getThreadShell (archived/deleted map to the
  tombstone path exactly as the active-list lookup did).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-15 16:50:25 +02:00
Julius Marminge 49375b88db fix(chat): prevent stale timeline scroll and rerenders
- Disable LegendList end-maintenance that could snap after user scrolling
- Cancel stale imperative scrolls and release settled turn anchors
- Stabilize handoff run data to avoid per-event timeline rerenders
2026-08-15 16:50:25 +02:00
Julius MarmingeandClaude Fable 5 fefd57fc54 perf(orchestration): per-thread shell deltas, visit throttling, event compaction (#4971)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 16:50:25 +02:00
Julius Marmingeandcodex 3305785508 [codex] feat(web): show git progress in the commit button (#4963)
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:25 +02:00
Julius Marminge 5e058ee234 feat(orchestration): track provider retries and thread visits
- Project retry progress and recovery for Codex and Claude turns
- Sync thread completion markers through server-side visit timestamps
2026-08-15 16:50:25 +02:00
Julius Marminge ba05523ed2 feat(server): surface legacy thread migration progress
- Publish migration lifecycle events during startup
- Show a web toast while legacy threads are restored
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex dbf97e42bf fix: close failed provider adapter scopes
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex f5d80b1d16 fix: preserve thread management failure semantics
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex e77b08358d fix: address latest orchestration review findings
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex e4b59b169e fix: preserve orchestration task identity
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex 6f459c12d0 fix: address orchestration review findings
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex 808dd3d7e7 fix(mobile): label queued message intent
Distinguish queued and steering user messages in the mobile thread feed, matching the web timeline.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex 18c2458673 fix: address orchestration review findings
Use shared cache schemas, close the OpenCode abort race, and assert fixture collection sizes correctly.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex fff6e73842 fix(orchestrator): preserve migrated and nested history
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex 729304a428 fix(server): preserve project mutation client errors
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex 55ff7a676f fix(orchestrator): validate rollback and search links
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex af6060be1c fix(orchestrator): close cancellation edge cases
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex 7d185275db fix(orchestrator): decode direct Claude result blocks
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex 2c0125489a fix(orchestrator): validate replay edge cases
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex ef08c6fa53 fix(orchestrator): preserve terminal effect outcomes
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex 9d089a5430 fix(orchestrator): preserve retryable effect failures
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex a151a77206 fix(orchestrator): avoid replaying settled effects
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex 6750918ab1 fix(worktrees): make handoff rollback atomic
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:19 +02:00
Julius Marmingeandcodex b324a91812 fix(orchestrator): release stranded effect claims
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex c5f20fbc57 fix(orchestrator): execute resolved runtime responses
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex d9ea5b182c fix(orchestrator): harden provider edge cases
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex c2a1c56596 fix(orchestrator): handle fresh review edge cases
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex 926be24e17 fix(orchestrator): address late review findings
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex 2e6f21179e fix(mobile): gate thread controls on live runs
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex c63da0a2cb fix(checkpoints): retain thread-start baseline after failed runs
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex fdf06c403a fix(client): preserve live thread relationships
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex a40a1d8630 fix(web): enforce secure provider field defaults
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex 4c743ff634 fix(claude): preserve explicit model options
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex 997289b565 fix(server): isolate deterministic attachment ids
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex b115390123 fix(testkit): harden provider replay recording
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex d8a198a2c0 fix(acp): enforce task and permission invariants
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex 25abd50f8d fix(orchestration): preserve imported conversation state
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex 38c7a868a1 fix(checkpoints): preserve valid run history
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex a434c32e93 fix(acp): discover final teardown descendants
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex d8fd8c0edc fix(cursor): log close attempts before execution
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:18 +02:00
Julius Marmingeandcodex 76d35a2f3c fix(mobile): distinguish queued and waiting archive states
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:17 +02:00
Julius Marmingeandcodex ee78e27154 fix(mobile): allow archiving post-provider work
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:17 +02:00
Julius Marmingeandcodex aece3cb2f3 fix(orchestration): cancel queued work on archive
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:17 +02:00
Julius Marmingeandcodex 63231d74c5 fix(orchestration): handle checkpoint-wait runs
Allow merge-back from provider-finished runs awaiting checkpoint capture while keeping waiting runs visible but non-interruptible in mobile.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:17 +02:00
Julius Marmingeandcodex 12737831e9 fix(acp): make xai cancellation reliable
Cancel pending prompt completions without restarting ACP, and keep text-only monitor acknowledgements tracked as background work.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:17 +02:00
Julius Marmingeandcodex 6d07a156d8 fix(contracts): reject invalid legacy intervals
Keep positive sub-minute schedules readable without accepting corrupt zero or negative persisted intervals.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:17 +02:00
Julius Marmingeandcodex 221d15181b fix(orchestration): preserve legacy schedule compatibility
Enforce the one-minute floor only on writes, clamp legacy execution intervals, and keep queued work protected from archive while reusing shared active-run derivation.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:17 +02:00
Julius Marmingeandcodex b8a596f666 fix(mobile): preserve active thread state
Keep executing runs visible when newer work is queued, expose provider errors in compact shells, and preserve mobile creation metadata for fork and merge operations.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:17 +02:00
Julius Marmingeandcodex 1827fb2959 fix(orchestration): harden scheduled task startup
Reject scheduled task intervals below one minute and tear down the effect worker when awareness relay startup fails.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:12 +02:00
Julius Marmingeandcodex 6ef497fc24 fix(orchestrator): schedule effects from durable deadlines (#4656)
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:12 +02:00
Julius Marmingeandcodex 50030b4e61 feat: migrate v1 state into orchestrator v2 (#4400)
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:12 +02:00
Julius Marmingeandcodex 47beb7da4e chore(orchestrator): refresh checks after main sync
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:12 +02:00
Julius Marmingeandcodex 97d935cfdd fix(web): restore checked-in project scripts
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:12 +02:00
Yusuf007Randcodex 28e55c211d fix: ignore subagents when sorting sidebar projects
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:12 +02:00
Yusuf007Randcodex 08b97fe6df fix: hide subagent threads from v2 lists
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:12 +02:00
Mike Olsonandcodex e11eb373f6 fix(claude): Settle positive task-notification results
A Claude V2 turn whose terminal SDK result carried origin.kind
"task-notification" had that result discarded, so the run stayed running
forever and every run queued behind it stalled. The drop is now limited to
results reporting zero model turns, which is what the stale debris the guard
was written for actually looks like.

ClaudeAdapterV2 dropped any task-notification-origin result unless the turn was
an agent/provider continuation. An app-owned delegated-task wake run is
agent/server, so its terminal results were discarded and finalizeActiveTurn
never ran. Any turn whose final result carries that origin hangs, not just
wakes. Observed in production against a real session: three terminal success
results with num_turns 154, 60 and 7 were all dropped, the session went silent
for 8h27m, and five queued runs behind it never dispatched.

The guard could not simply be deleted. After interrupt recovery a stale stopped
task_notification and its origin result interleave ahead of the real root
assistant stream and must not terminalize the turn or leak their text.
Zero-turn results are still dropped, so that path is unchanged: this drops
strictly fewer results than before, so no previously working path can regress.

num_turns separates the two cases cleanly. The existing stale fixture sets
numTurns 0 explicitly, makeResultFrame defaults to 1, and the production
results all carried positive turns. The predicate is num_turns === 0 rather
than < 1 or a truthiness check on purpose: num_turns is required on both result
variants in 0.3.205, but if an older emitter ever omitted it, undefined === 0
is false, so the result is accepted rather than dropped. That fails toward
terminalizing rather than toward the hang class this fixes.

Both drops and accepts are logged with num_turns, stop_reason, terminal_reason,
result uuid, session id and message provenance. The drop is debug level because
interrupt recovery produces it routinely; the accept is info, because a
positive-turn task-notification result settling a non-continuation turn is both
the hang fix working and the exact shape a stale positive-turn result would
take.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:12 +02:00
Mike Olsonandcodex 4fc73fd290 fix(orchestrator): Wake settled parents when delegated children finish
An app-owned delegated child wrote its result into the parent projection but
never started a parent run, so an async delegation's result sat unread until the
user's next message. Offer a provider continuation request when a delegated
child terminalizes, with a per-task completionWake policy separating async
delegations from blocking waits.

The wake must also reach the model. ProviderContinuationRequests is a
provider-native mechanism whose dispatch only triggers ingestion of output the
adapter already buffered, and both ClaudeAdapterV2 and AcpAdapterV2 discard the
message text when it is marked creationSource provider. An app-owned child
buffers nothing, so a wake marked that way settled instantly having prompted
nothing. App-owned wakes now dispatch as message_text via a shared
delegatedTaskWakeRequest helper used by both producers.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:12 +02:00
Mike Olson 661f21eb72 fix(acp): Preserve wake evidence across an app-owned wake
This PR introduces the only wakeBuffer clear at the ACP startTurn site, and it
also clears midTurnUnreportedCompletedTaskIds there, both on the reasoning that
a user turn owns the conversation.

An orchestrator-injected wake is not a user turn. #4499
fix/delegated-task-parent-wake dispatches app-owned delegated-child wakes as
creationSource "server", which is non-continuation, so once both land such a
wake would discard this session's pending native wake frames and its kept
mid-turn completion marks, losing agent output and a continuation offer that
nothing else can recover.

acpIsAppOwnedWakeTurn exempts orchestrator-injected wakes from both clears,
matching what ClaudeAdapterV2 already does with its own buffer. Inert without
#4499, since nothing else dispatches creationSource "server". Kept as its own
commit because the concern originates in a different PR.
2026-08-15 16:50:12 +02:00
Mike Olson 07ce295e8d fix(grok): Prevent spurious wake run after in-turn monitors
- Defer continuation offers for background completions that land while a
  root turn is active and un-finalized; finalize offers exactly one wake
  only when unhandled completed work remains
- Stop late monitor-event mutations from erasing in-turn handled marks, so
  injected-turn ack chatter is never retained as wake evidence
- Clear stale wake buffer frames at non-continuation user-turn start
- Make the late-mutation suppress logic's running/terminal branches
  mutually exclusive
2026-08-15 16:50:12 +02:00
Julius Marmingeandcodex cb3fc2a81a test(orchestrator): align merged V2 compatibility checks
Remove the unreferenced V1 activity payload projection that arrived from main and assert only the public serialized SchemaError shape under Effect beta.102.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:11 +02:00
Julius Marmingeandcodex 9b547f9e4f fix(server): clean up Claude replay failures
Wake replay stream waiters when outbound validation fails and ensure interrupted recordings close when no tool use arrives.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
Julius Marmingeandcodex c9fff5904f fix(server): enforce ACP auth and preserve fork provenance
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
Julius Marmingeandcodex 3cbd672e13 fix(server): keep derived threads awake
Reset snooze metadata when creating forks and provider subagent children, with focused regressions for both inheritance paths.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
Julius Marmingeandcodex 144b309868 fix(mobile): wait for fork shell before navigation
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
David Whatleyandcodex dee3de20fd Add worktree handoff and status tools to the t3-code MCP server (#3754)
Expose MCP tools for worktree handoff and status inspection, with focused server and contract coverage.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
Alexandcodex d957b368d6 feat(subagents): disclose projected results consistently (#3866)
Normalize subagent result disclosure across timeline rendering and collapsed/expanded states.

Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
Mike Olson c7d47abd42 fix(orchestrator): hydrate shell cache and group multi-environment projects (#3640)
Restore versioned shell-cache hydration, reconcile repository enrichment across multiple environments, and decode non-null settled shell timestamps correctly.
2026-08-15 16:50:05 +02:00
Julius Marminge 9e258c2b99 test(orchestrator): align Codex approval reviewer replays (#4457)
Update every deterministic Codex turn/start expectation with the explicit user approvals reviewer emitted by the adapter, restoring exact replay coverage and unblocking the merge lane.
2026-08-15 16:50:05 +02:00
Mike Olson cd4ef48406 fix(orchestrator): Preserve claude/codex post-interrupt recovery state (#4229) 2026-08-15 16:50:05 +02:00
Mike Olson d6a607aceb test(orchestrator): Align post-merge CTM fixtures (#4193) 2026-08-15 16:50:05 +02:00
Julius Marmingeandcodex c71c7b4331 fix(web): contain thread details panel effects
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
Julius Marmingeandcodex 411be44733 refactor(web): use shared glass surfaces
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
Julius Marmingeandcodex 8d6e0490e1 fix(web): remove stacked composer shadows
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
Julius Marmingeandcodex 78153d5ef3 fix(web): restore v2 composer chrome
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:05 +02:00
Julius Marmingeandcodex 2760da1395 fix(server): preserve released migration ordering
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:04 +02:00
Julius Marmingeandcodex 7f74aa3594 fix(orchestration): clarify agent delegation and scheduling
Co-authored-by: codex <[email protected]>
2026-08-15 16:50:04 +02:00
Julius Marminge c974f41b50 Unify T3 MCP tool presentation across clients
- Extract shared T3 MCP tool label resolution
- Show T3 Code branding for matched tool activity rows
- Add tests for shared resolution and mobile feed output
2026-08-15 16:50:04 +02:00
Julius Marminge 333d7ef8b7 Render T3 MCP tools with branded timeline labels
- Pretty-print known T3 MCP tool names in work rows
- Show the T3 Code logo for recognized MCP tool entries
- Add logic and UI tests for the new tool presentation
2026-08-15 16:50:04 +02:00
Julius Marmingeandcodex 0f78716903 fix(grok): align ACP extensions with open source runtime
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex 496b8755e4 fix(mobile): support Hermes collection sorting
Reuses the focused compatibility approach from closed PR #3923 and covers the remaining hardware-keyboard reverse iteration.

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex 6e1b1334e9 test(orchestrator): align integration fixtures
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Mike Olson 9a7d3ec4ed fix(orchestrator): Harden Grok v2 runtime lifecycle
Settle root turns from provider signals and preserve post-settle continuations.

Track asynchronous subagent and monitor work, allow image prompts, and keep steered messages visible.

Separate soft steering from hard Stop while containing and reaping native process trees.
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex bf8fa545bd fix(orchestrator): dedupe Grok continuation dispatch
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Mike Olsonandcodex e16d4e514b fix(orchestrator): harden Grok v2 lifecycle (#3578)
Integrate the current Grok settlement, monitor/subagent lifecycle, interrupt containment, steer visibility, and image support stack into the orchestration-v2 branch.

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex 0282ab8608 fix(acp): bind MCP credentials to activated threads
Passes the current target thread MCP configuration through ACP load, resume, and fork requests instead of reusing the credentials captured when the provider process opened.

Addresses https://github.com/pingdotgg/t3code/pull/2829#discussion_r3507807130

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex fc1fb688d0 fix(acp): release turns after interrupt timeout
Clears the timed-out turn with an identity guard so a late completion cannot clobber a newer active turn.

Addresses https://github.com/pingdotgg/t3code/pull/2829#discussion_r3483533894

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex 6d82418637 fix(claude): reopen queries after MCP credential rotation
Fixes review: https://github.com/pingdotgg/t3code/pull/2829#discussion_r3566081244

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex e59cf5d967 fix(claude): enforce read-only tool availability
Fixes review: https://github.com/pingdotgg/t3code/pull/2829#discussion_r3509702833

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex 4a9421d53c fix(claude): honor never-approval runtime policies
Fixes review: https://github.com/pingdotgg/t3code/pull/2829#discussion_r3507807129

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex e1d14b2895 fix(claude): allow questions during plan mode
Fixes review: https://github.com/pingdotgg/t3code/pull/2829#discussion_r3501073032

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex 40af3e26a8 fix(claude): preserve approvals with full-access sandbox
Fixes review: https://github.com/pingdotgg/t3code/pull/2829#discussion_r3476628169

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex 1bd9e00990 fix(claude): redact launch arguments from protocol logs
Fixes review: https://github.com/pingdotgg/t3code/pull/2829#discussion_r3471595059

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex 76bdcd9548 test(desktop): expect orchestrator v2 state directory
Refs CI: https://github.com/pingdotgg/t3code/actions/runs/29750215334/job/88378428137

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:58 +02:00
Julius Marmingeandcodex e70df336e8 fix(ci): restore Claude permission request identity
Refs CI: https://github.com/pingdotgg/t3code/actions/runs/29750215334/job/88378428015

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:57 +02:00
Julius Marmingeandcodex f182e5f605 fix(orchestrator): align Claude permission replay with SDK
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:57 +02:00
Alex 4aeeddd20f feat(orchestrator): pass model options through MCP thread targets (#3872) 2026-08-15 16:49:57 +02:00
Alex 8a192fdf44 fix(orchestrator): scope Claude MCP tool pre-approval (#3862) 2026-08-15 16:49:57 +02:00
Mike Olson fe79930e0b [orchestrator-v2] fix(orchestrator): Codex background command completion and subagent resume (#3908) 2026-08-15 16:49:57 +02:00
ee5098e75f [orchestrator-v2] fix(orchestrator): Restore Claude session continuity for resume, wake, and idle release (#3860)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 16:49:57 +02:00
Mike Olson f141e20ec3 feat(orchestrator): Add shared provider continuation and background item plumbing
Introduce a provider-agnostic continuation request queue, worker, and optional
hasPendingBackgroundWork idle pin so adapters can surface post-settle native
wake traffic as first-class runs. No adapter offers continuations here; the
per-provider specialty commits wire attach mode.

Also fix shared run event ingestion dropping late background item
completions. The per-run provider event fiber stopped as soon as the root
turn terminalized and no child provider turns or subagent rows remained
active. Background-capable turn items (background commands, monitors,
subagent rows) that complete after root settlement then lost their trailing
turn_item.updated: the projection kept the item running forever even when
the underlying work (and any wake) succeeded.

Track non-terminal command_execution, dynamic_tool, and subagent turn items
owned by the run or an owned child thread, and keep ingesting until they
terminalize, gated on the root terminal status being completed so
interrupted and failed runs do not pin the stream open.

Repro evidence: Codex emits subagent.updated(completed) before the trailing
turn_item.updated(completed), so post-settle subagent items stuck at running
in the UI; background command items never completed in the
codex-background-exec-wake projection even though the wake run fired. The
same stuck-running signature appears on the Claude background Bash wake and
Grok monitor paths, which reuse this shared ingestion loop.
2026-08-15 16:49:57 +02:00
Julius MarmingeandClaude Fable 5 ec5ac9564a feat: scheduled tasks (automations) (#3638)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 16:49:57 +02:00
Julius Marmingeandcodex 20bea8ebdd Fix Claude task turn mapping
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:57 +02:00
Julius Marminge 2f75c8d119 Allow provider switching via handoff in chat threads
- Let started threads switch providers when handoff is supported
- Keep model picker and block reasons aligned with thread capabilities
- Update logic tests for the new provider-switching rule
2026-08-15 16:49:57 +02:00
Julius Marminge a78a813910 Remove early access badges from Cursor and Grok
- Keep provider labels aligned across server and web metadata
- Leave interaction mode and thread-change behavior unchanged
2026-08-15 16:49:57 +02:00
Julius Marminge cabab2bce8 Switch Cursor provider to the official SDK
- remove ACP model discovery and mismatch probe code
- update provider, orchestration, and tests for SDK-based flows
- refresh marketing copy to match the SDK runtime
2026-08-15 16:49:57 +02:00
maria aab3fdafe5 fix(web): align thread details panel controls and menus (#3606) 2026-08-15 16:49:57 +02:00
Julius Marminge 3104ecf322 Require Cursor API key for provider checks
- Switch Cursor provider status and model discovery to the SDK catalog
- Improve chat content lane alignment and provider secret handling
2026-08-15 16:49:57 +02:00
Julius Marminge f3d8017c76 Keep persistent cards visible in folded turns
- Treat persistent resource cards as foldable turn entries
- Preserve cards that arrive before commentary when collapsing settled turns
2026-08-15 16:49:56 +02:00
Julius Marminge 0c2e9627f6 Clarify thread relationship icons and ordering
- Show parent-thread links with a dedicated return icon
- Prioritize parent and merge relationships in the thread panel
2026-08-15 16:49:56 +02:00
Julius Marminge dfd6e9ec1d Map nested Codex subagent threads correctly
- Preserve app-thread projection when spawning Codex subagents
- Add replay fixture coverage for nested provider-native subagents
2026-08-15 16:49:56 +02:00
Julius Marminge ed2ca16bcc Adopt userdata-v2 and subagent activity mapping
- Move desktop and server state paths to `userdata-v2`
- Handle Codex subagent activity events in orchestration v2
- Update related path and lifecycle tests
2026-08-15 16:49:56 +02:00
Julius Marminge 2c5aa70cf3 Map Grok task envelopes to subagent lineage
- Detect xAI Task tool calls as native subagents
- Project child session IDs and buffered chunks into the orchestration tree
- Add replay fixture coverage for Grok subagent lineage
2026-08-15 16:49:56 +02:00
Julius Marminge 928e72a23d Add iOS associated domains for Clerk
- Configure applinks and webcredentials for all mobile variants
- Set the Clerk relying party used by app config
2026-08-15 16:49:56 +02:00
Julius Marmingeandcodex 25862ffc34 Retire V1 client orchestration parity
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:56 +02:00
Julius Marmingeandcodex 86941636d7 Expose V2 thread workflows on mobile
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:56 +02:00
Julius Marmingeandcodex 9b22fa56f2 Enrich mobile V2 execution items
Share V2 item-to-entity linkage across clients and give mobile targeted execution, provider, request, checkpoint, search, subagent, and handoff inspection without reconstructing the timeline.

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:56 +02:00
Julius Marmingeandcodex af04d37c1c Render mobile timelines from V2 turn items
Use the authoritative visibleTurnItems projection directly so mobile preserves server ordering, inherited items, and synthetic items without rebuilding a parallel feed.

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:56 +02:00
Julius Marminge 686be78b69 Hide subagent threads and simplify thread controls
- Remove subagent prefixes from titles and timeline labels
- Hide subagent threads in the sidebar and add parent-thread navigation
- Align thread details, picker, and git/script controls with panel styling
2026-08-15 16:49:56 +02:00
Julius Marminge a39d2fda26 Split open-in editor controls into panel and toolbar variants
- Move Open in editor shortcut handling into a shared hook
- Show Open in picker inside the thread details panel and restyle PR actions
- Tighten popover positioning for the panel layout
2026-08-15 16:49:56 +02:00
Julius Marminge 97736c47a5 Reserve space for inline thread details panel
- Move the inline thread panel to an absolute overlay
- Add shared inset styling so the timeline and composer avoid overlap
- Rename composer glass styling to the shared floating surface class
2026-08-15 16:49:50 +02:00
Julius Marmingeandcodex c8aea5db0b Map thread panel into title bar and sidebar
- Add thread-panel presentation logic for inline vs popover layouts
- Move thread details controls into the chat header/sidebar flow
- Add shared wait-for-atom helper and workspace display name parsing

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:46 +02:00
Julius Marminge 4d64e80184 Record created threads and subagent progress
- Add parent-thread records for spawned child threads
- Persist Claude subagent progress as reasoning items
- Tighten projection verification around readable thread projections
2026-08-15 16:49:40 +02:00
Julius Marminge 661dbc96d4 Handle preparing turns across provider orchestration
- Treat preparing as an active turn state in mobile and server flows
- Tighten ACP model option validation and selection reconfiguration
- Add coverage for turn mapping, raw protocol logging, and recovery paths
2026-08-15 16:49:40 +02:00
Julius Marminge 5073b0356d Integrate orchestration V2 controls and process recovery
- Add V2 item inspection, thread relationships, queued-run controls, and composer dispatch policies
- Reconcile interrupted provider state safely across shutdown and startup
- Preserve checkpoint baselines and shared provider-session projections
2026-08-15 16:49:39 +02:00
Julius Marminge f456ee9630 Complete orchestration V2 frontend cutover
- Migrate web and mobile state, commands, and persistence to V2 projections
- Render conversations from authoritative visible turn items
- Harden runtime policy, launch handling, attachments, and cache invalidation
2026-08-15 16:49:33 +02:00
Julius Marminge 1bbbaafb1e Split the V2 frontend plan into parity and enrichment phases
- Define Shape 4.0 for the client cutover and product parity
- Define Shape 4.5 for V2-native UI capabilities
- Defer existing V1 state migration to an out-of-scope Stage 5
2026-08-15 16:49:25 +02:00
Julius Marminge a2944d622a Integrate orchestration v2 with the application runtime
Retain the existing event-sourced application data plane for projects and shell state while making orchestration v2 the sole agent runtime. Adapt v2 events and receipts to the shared infrastructure and remove the v1 provider reactors.
2026-08-15 16:49:25 +02:00
Julius Marminge 6ee48838d8 Guarantee MCP revocation during session release 2026-08-15 16:49:08 +02:00
Julius Marminge 355ee8f130 Remove MCP credential expiration 2026-08-15 16:49:08 +02:00
Julius Marminge f527603a6f Require MCP registry for V2 provider sessions 2026-08-15 16:49:08 +02:00
Julius Marminge a86fc05aa3 Complete orchestration V2 application services 2026-08-15 16:49:08 +02:00
Julius Marminge f19bb07de6 Start orchestration V2 application services 2026-08-15 16:49:08 +02:00
Julius Marminge c61153b467 Align orchestration V2 with Effect service conventions 2026-08-15 16:49:08 +02:00
Julius Marminge be6b66cd1b Share Codex sessions across orchestration threads
- Track explicit thread-to-session bindings and detach without stopping siblings
- Apply runtime settings per Codex thread and filter multiplexed events by turn
- Add migration, projection, lifecycle, and concurrency coverage
2026-08-15 16:49:08 +02:00
Julius Marminge 9355809b65 Map orchestration turns to provider instances
- Separate provider driver identity from configured provider instances
- Add durable event, effect, checkpoint, and turn-position persistence
- Route turn lifecycle and recovery through shared orchestration services
2026-08-15 16:49:07 +02:00
Julius Marminge bb14bae94d Add Orchestration V2 application integration plan
- Define four implementation shapes for the V2-only migration
- Add the plan to the plans index
2026-08-15 16:49:00 +02:00
Julius Marminge fdcbae983d Add MCP thread management and Codex turn mapping
- Add scoped thread list, read, send, wait, and interrupt tools
- Track creation provenance and map provider turns across adapters
- Centralize thread lifecycle operations in a management service
2026-08-15 16:49:00 +02:00
Julius Marminge 1f90765b5f Add ACP replay harness and session lifecycle support
- Add replay agent and fixture-driven ACP transcript testing
- Support session lifecycle, auth methods, and session resume/fork flows
- Expand orchestration V2 adapter coverage and debug tooling
2026-08-15 16:49:00 +02:00
Julius Marminge a9fd14e824 Handle segmented Cursor turns and stable visible timelines
- split streaming assistant and reasoning output into separate segments
- filter hidden interruption artifacts from projections and replay fixtures
- keep visible timeline positions stable when upserting streamed items
2026-08-15 16:49:00 +02:00
Julius Marminge ce64e37094 Add Cursor SDK orchestration replay support
- Wire Cursor adapter and provider session handling into orchestration v2
- Add replay fixtures, recording script, and coverage for Cursor turn flows
- Update docs and debug timeline mapping for Cursor events
2026-08-15 16:49:00 +02:00
Julius Marminge 4fae73ee08 Add orchestration MCP toolkit
- Register orchestration tools on the MCP HTTP server
- Grant orchestration capability to MCP sessions
- Add service and integration coverage for delegated tasks and thread creation
2026-08-15 16:49:00 +02:00
Julius Marmingeandcodex b493c4bd53 refactor(orchestration-v2): adopt host process spawn policy
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:00 +02:00
Julius Marminge 4b9f0e78cc wip 2026-08-15 16:49:00 +02:00
Julius Marmingeandcodex b78320f249 feat(orchestration-v2): model native subagents
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:00 +02:00
Julius Marminge 5038b3a756 Map orchestration v2 WS methods to auth scopes
- Require operate scope for v2 command dispatch
- Allow read scope for v2 thread and shell subscriptions
2026-08-15 16:49:00 +02:00
Julius Marmingeandcodex 9a8eaf33d3 fix(orchestration-v2): preserve source history on merged switch
Send full canonical target-thread context when a provider switch consumes a merge-back, and cover returning to an existing provider thread after a cross-provider fork.

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:00 +02:00
Julius Marmingeandcodex d3449cdf1d fix(orchestration-v2): compose provider switch merge context
Allow a pending merge-back to be consumed while changing providers and deliver both the provider-switch history and fork delta to the selected provider.

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:00 +02:00
Julius Marmingeandcodex 49a3ba50c1 feat(orchestration-v2): add merge-back replay coverage
Record provider fixtures for continued forks and sibling merge-backs, exercise context survival end to end, and stop completed run listeners from consuming later provider events.

Co-authored-by: codex <[email protected]>
2026-08-15 16:49:00 +02:00
Julius Marmingeandcodex fd3c09aa08 fix(orchestration-v2): resolve cross-provider forks
Co-authored-by: codex <[email protected]>
2026-08-15 16:49:00 +02:00
Julius Marmingeandcodex 823bb8a4a0 feat(orchestration-v2): support cross-provider handoff
Co-authored-by: codex <[email protected]>
2026-08-15 16:48:59 +02:00
Julius Marmingeandcodex 1a681d2904 feat(orchestration-v2): wire claude adapter primitives
Co-authored-by: codex <[email protected]>
2026-08-15 16:48:59 +02:00
Julius Marminge b0d0f71dbc Document Cursor SDK MCP projection for V2
- Map Cursor SDK agents and runs to V2 thread and turn lifecycles
- Update MCP capability, tool, and testing guidance for SDK-based injection
2026-08-15 16:48:59 +02:00
Julius Marminge b041b6256a Add turn-interrupt replay coverage and protocol logging
- add interrupt and mid-tool replay fixtures for Claude and Codex
- log Claude Agent SDK protocol frames to native event traces
- project Codex commandExecution start events into orchestration updates
2026-08-15 16:48:59 +02:00
Julius Marminge e0790df1e9 Support active Claude steering and turn replay mapping
- add active steering and interrupt-restart replay fixtures
- update Claude adapter/orchestrator turn handling for steering
- refresh replay and integration test coverage
2026-08-15 16:48:59 +02:00
Julius Marmingeandcodex bfa2c8773a Map Claude turns to runtime query policies
- Derive Claude SDK query options from runtime policy
- Add read-only replay fixture and policy mapping tests
- Reuse shared approval-policy fixtures across orchestrator tests

Co-authored-by: codex <[email protected]>
2026-08-15 16:48:59 +02:00
Julius Marminge 732a25aad6 Map Claude replay fixtures to multi-turn turns
- Record Claude SDK transcripts across multiple prompts and restart/query modes
- Add approval and tool-call replay coverage for new orchestration fixtures
- Update Claude adapter testkit to model open/prompt/permission frames
2026-08-15 16:48:59 +02:00
Julius Marminge 4b2542dd46 Add model selection to orchestration runs
- persist the selected model on run records
- surface run model selection in the debug UI
- update replay fixtures and contracts for the new field
2026-08-15 16:48:59 +02:00
Julius Marminge 640460fae4 Extract Claude SDK query runner from provider adapter
- Move Claude provider runtime logic into its own module
- Share the SDK query runner between live and replay paths
- Add replay driver error wrapping for unexpected failures
2026-08-15 16:48:59 +02:00
Julius Marminge b8e9869b78 Add Claude replay fixture recorder
- Move Codex replay recording into `apps/server`
- Add Claude Agent SDK replay fixtures and test harness
- Update orchestration-v2 fixture scenarios and docs
2026-08-15 16:48:59 +02:00
Julius Marmingeandcodex d80ca8e8ae Add V2 command capability policy
Co-authored-by: codex <[email protected]>
2026-08-15 16:48:59 +02:00
Julius Marminge 5a789cb875 Add merge-back context handoff support
- Map fork and merge-back turns into stored handoffs and transfer resolutions
- Add shell snapshot projection support plus coverage tests
- Update replay fixtures and web contracts for the new turn flow
2026-08-15 16:48:59 +02:00
Julius Marminge 37dc60d3cf Add orchestration V2 backend checklist
- Track remaining projection, context transfer, rollback, capability, and subagent work
- Clarify current V2 baseline and debugger-only follow-ups
2026-08-15 16:48:59 +02:00
Julius Marminge 08813d1097 Add thread fork lineage and lazy context transfer
- Add context transfer IDs, schemas, and projections
- Support cheap fork creation and Codex native fork rollback
- Cover fork idempotency and replay behavior in tests
2026-08-15 16:48:59 +02:00
Julius Marmingeandcodex e8eb83a738 Implement orchestration v2 runtime
Co-authored-by: codex <[email protected]>
2026-08-15 16:48:59 +02:00
Julius Marminge fa376a9e52 Map Codex turns into orchestration v2
- Add Codex adapter and replay harness wiring
- Introduce in-memory orchestration projections and provider registry
- Expand orchestration contracts for turn and runtime events
2026-08-15 16:48:53 +02:00
Julius Marmingeandcodex 6df0bfbf2b Add orchestration v2 replay and service contracts
- Introduce orchestration v2 service interfaces and error types
- Add replay runtime, fixtures, and integration coverage
- Update shared contracts and probe transcripts

Co-authored-by: codex <[email protected]>
2026-08-15 16:48:53 +02:00
Julius Marminge 99b24dfa2f Add orchestration v2 docs and probe fixtures
- Document the target orchestration graph, IDs, lifecycles, and capability model
- Add Codex app-server probe fixtures and update the probe test harness
2026-08-15 16:48:52 +02:00
Julius Marmingeandcodex 4b6ae7be55 Fix Codex provider status test expectations
Co-authored-by: codex <[email protected]>
2026-08-15 16:48:52 +02:00
Julius Marmingeandcodex 6b5e216667 Address Codex review feedback
Co-authored-by: codex <[email protected]>
2026-08-15 16:48:52 +02:00
Julius Marminge 96143bcb5f Switch Codex provider checks to app-server probe
- Use codex app-server snapshots for auth, models, and skills
- Remove legacy CLI/config discovery paths and related helpers
- Update tests for the new provider status flow
2026-08-15 16:48:52 +02:00
Julius Marminge 40f01b13d3 Flush native logs on adapter shutdown
- Close the managed native event logger when the adapter layer tears down
- Make session runtime close idempotent with an atomic closed flag
- Add coverage for flushing thread native logs on shutdown
2026-08-15 16:48:52 +02:00
Julius Marminge 9beb0c049d decoders 2026-08-15 16:48:52 +02:00
Julius Marminge 76a4227729 Scope Codex session runtime lifetimes
- Transfer session-owned scopes into adapter state
- Ensure runtime scopes close on stop and startup failure
- Add regression coverage for scoped lifecycle cleanup
2026-08-15 16:48:52 +02:00
Julius Marminge cd35a10904 Normalize Codex IDs and preserve streamed stdout decoding
- Use strict TurnId and ProviderItemId parsing in Codex session routing
- Decode in-memory stdio chunks in streaming mode to avoid split UTF-8 corruption
2026-08-15 16:48:52 +02:00
Julius Marminge b113ff14b4 Return Cursor ACP runtime with explicit scope
- Type the runtime effect with `Scope`
- Build the ACP session runtime without wrapping it in `Effect.scoped`
2026-08-15 16:48:52 +02:00
Julius Marminge 0c9ec3a664 Delay Codex provider availability until checked
- Initialize provider as unchecked in a pending state
- Update initial probe message to reflect session-local status
2026-08-15 16:48:52 +02:00
Julius Marminge 90b3e90700 resynclock 2026-08-15 16:48:52 +02:00
Julius Marminge 53ae164a1e revert more 2026-08-15 16:48:52 +02:00
Julius Marminge c90c67e62a nit 2026-08-15 16:48:52 +02:00
Julius Marmingeandcodex 5740af634a Integrate Codex app-server support
Co-authored-by: codex <[email protected]>
2026-08-15 16:48:52 +02:00
883 changed files with 181417 additions and 85814 deletions

No files matched your search

-429
View File
@@ -1,429 +0,0 @@
const fs = require("node:fs");
const path = require("node:path");
const ARTIFACT_NAME = "thread-transfer-results";
const RESULT_FILE = "thread-transfer-result.json";
const COMMENT_MARKER = "<!-- t3-thread-transfer-report -->";
const PROVIDERS = ["codex", "claudeAgent"];
const OBSERVED_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"threadSnapshotDecodedBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const CEILING_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const SCENARIO_KEYS = [
"id",
"historyTurns",
"historyCommandToolsPerTurn",
"historyMcpResultBytes",
"measuredCommandTools",
"measuredMcpResultBytes",
];
function resultShaMarker(sha) {
return `<!-- t3-thread-transfer-result-sha:${sha} -->`;
}
function assertObject(value, label) {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`${label} must be an object`);
}
}
function assertExactKeys(value, expected, label) {
assertObject(value, label);
const actual = Object.keys(value).sort();
const wanted = [...expected].sort();
if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
throw new Error(`${label} has unexpected fields`);
}
}
function assertMetric(value, label) {
if (!Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000) {
throw new Error(`${label} must be a non-negative safe integer below 1,000,000,000`);
}
}
function validateResult(value) {
assertExactKeys(value, ["schemaVersion", "scenario", "providers"], "result");
if (value.schemaVersion !== 1) {
throw new Error("result.schemaVersion must be 1");
}
assertExactKeys(value.scenario, SCENARIO_KEYS, "result.scenario");
if (value.scenario.id !== "thread-transfer-v1") {
throw new Error("result.scenario.id is not supported");
}
for (const key of SCENARIO_KEYS.slice(1)) {
assertMetric(value.scenario[key], `result.scenario.${key}`);
}
assertExactKeys(value.providers, PROVIDERS, "result.providers");
for (const provider of PROVIDERS) {
const entry = value.providers[provider];
assertExactKeys(entry, ["observed", "ceiling"], `result.providers.${provider}`);
assertExactKeys(entry.observed, OBSERVED_KEYS, `result.providers.${provider}.observed`);
assertExactKeys(entry.ceiling, CEILING_KEYS, `result.providers.${provider}.ceiling`);
for (const key of OBSERVED_KEYS) {
assertMetric(entry.observed[key], `result.providers.${provider}.observed.${key}`);
}
for (const key of CEILING_KEYS) {
assertMetric(entry.ceiling[key], `result.providers.${provider}.ceiling.${key}`);
}
}
return value;
}
function readResult(directory) {
if (!directory) return undefined;
const file = path.join(directory, RESULT_FILE);
if (!fs.existsSync(file)) return undefined;
const stat = fs.lstatSync(file);
if (!stat.isFile() || stat.size > 64 * 1_024) {
throw new Error("thread transfer result must be a regular file smaller than 64 KiB");
}
return validateResult(JSON.parse(fs.readFileSync(file, "utf8")));
}
function formatBytes(bytes) {
if (bytes < 1_024) return `${bytes} B`;
if (bytes >= 1_024 * 1_024) return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB`;
return `${(bytes / 1_024).toFixed(1)} KiB`;
}
function formatValue(value, kind) {
return kind === "messages" ? value.toLocaleString("en-US") : formatBytes(value);
}
function formatImpact(current, baseline, kind) {
if (baseline === undefined) return "—";
const delta = current - baseline;
const prefix = delta > 0 ? "+" : delta < 0 ? "−" : "";
const magnitude = formatValue(Math.abs(delta), kind);
const percent =
baseline === 0 ? "" : ` (${prefix}${Math.abs((delta / baseline) * 100).toFixed(1)}%)`;
return `${prefix}${magnitude}${percent}`;
}
function sameScenario(left, right) {
return SCENARIO_KEYS.every((key) => left[key] === right[key]);
}
const METRICS = [
{ key: "totalWireBytes", label: "Total thread wire", kind: "bytes" },
{ key: "threadSnapshotWireBytes", label: "Thread snapshot wire", kind: "bytes" },
{
key: "measuredTurnWebSocketWireBytes",
label: "Live turn WebSocket wire",
kind: "bytes",
},
{
key: "measuredTurnWebSocketDecodedBytes",
label: "Live turn WebSocket decoded",
kind: "bytes",
},
{ key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" },
];
function renderComment(input) {
const current = input.current;
const baseline = input.baseline;
const comparable = baseline !== undefined && sameScenario(current.scenario, baseline.scenario);
const rows = [];
const ceilingChanges = [];
let failed = false;
for (const provider of PROVIDERS) {
for (const metric of METRICS) {
const observed = current.providers[provider].observed[metric.key];
const ceiling = current.providers[provider].ceiling[metric.key];
const baselineObserved = comparable
? baseline.providers[provider].observed[metric.key]
: undefined;
const pass = observed <= ceiling;
failed ||= !pass;
rows.push(
`| ${provider === "codex" ? "Codex" : "Claude"} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`,
);
if (baseline && baseline.providers[provider].ceiling[metric.key] !== ceiling) {
ceilingChanges.push(
`- ${provider === "codex" ? "Codex" : "Claude"} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`,
);
}
}
}
const baselineLink = input.baselineRun
? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})`
: "unavailable";
const currentLink = `[\`${input.currentRun.sha.slice(0, 7)}\`](${input.currentRun.url})`;
const notices = [];
if (!baseline) {
notices.push(
"> ℹ️ No successful `main` baseline artifact is available yet. This run establishes the initial measurement.",
);
} else if (!comparable) {
notices.push(
"> ⚠️ The thread fixture changed, so impact percentages are not directly comparable to the `main` baseline.",
);
} else if (!input.baselineRun.matchesBase) {
notices.push(
"> ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful `main` measurement shown below.",
);
}
if (ceilingChanges.length > 0) {
notices.push(
`> ⚠️ **This PR changes transfer ceilings:**\n>\n${ceilingChanges.map((line) => `> ${line}`).join("\n")}`,
);
}
return [
COMMENT_MARKER,
resultShaMarker(input.currentRun.sha),
"## Thread transfer impact",
"",
failed
? "❌ One or more thread transfer ceilings were exceeded."
: "✅ Thread transfer remains within every enforced ceiling.",
...(notices.length > 0 ? ["", ...notices] : []),
"",
"| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |",
"| --- | --- | ---: | ---: | ---: | ---: | --- |",
...rows,
"",
`Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`,
"",
"<details>",
"<summary>Scenario and decoded snapshot size</summary>",
"",
`${current.scenario.historyTurns} historical turns, ${current.scenario.historyCommandToolsPerTurn} command tools per turn, ${formatBytes(current.scenario.historyMcpResultBytes)} retained MCP result per historical turn, and a ${formatBytes(current.scenario.measuredMcpResultBytes)} retained result in the measured turn.`,
"",
...PROVIDERS.map(
(provider) =>
`- ${provider === "codex" ? "Codex" : "Claude"} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
),
"",
"</details>",
"",
"_Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed._",
].join("\n");
}
async function artifactsForRun(github, owner, repo, runId) {
return github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
owner,
repo,
run_id: runId,
per_page: 100,
});
}
function findResultArtifact(artifacts) {
return artifacts.find((artifact) => artifact.name === ARTIFACT_NAME && !artifact.expired);
}
async function resolve({ github, context, core }) {
const source = context.payload.workflow_run;
const { owner, repo } = context.repo;
if (source.event !== "pull_request") {
core.setOutput("publish", "false");
return;
}
let pullNumber = source.pull_requests?.[0]?.number;
if (!pullNumber) {
const associated = await github.paginate(
github.rest.repos.listPullRequestsAssociatedWithCommit,
{ owner, repo, commit_sha: source.head_sha, per_page: 100 },
);
const matchingPulls = associated.filter(
(pull) =>
pull.state === "open" &&
pull.head.sha === source.head_sha &&
pull.head.ref === source.head_branch,
);
if (matchingPulls.length !== 1) {
core.info(
`Expected one open pull request for ${source.head_repository?.full_name ?? "unknown repository"}:${source.head_branch ?? "unknown branch"} at ${source.head_sha}; found ${matchingPulls.length}.`,
);
core.setOutput("publish", "false");
return;
}
pullNumber = matchingPulls[0].number;
}
if (!pullNumber) {
core.info("No open pull request is associated with the completed CI run.");
core.setOutput("publish", "false");
return;
}
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
if (pull.head.sha !== source.head_sha) {
core.info(`Skipping stale CI result ${source.head_sha}; PR head is ${pull.head.sha}.`);
core.setOutput("publish", "false");
return;
}
const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id);
const sourceArtifact = findResultArtifact(sourceArtifacts);
const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, {
owner,
repo,
workflow_id: source.workflow_id,
branch: pull.base.ref,
event: "push",
status: "success",
per_page: 100,
});
const orderedRuns = [
...workflowRuns.filter((run) => run.head_sha === pull.base.sha),
...workflowRuns.filter((run) => run.head_sha !== pull.base.sha),
].slice(0, 20);
let baselineRun;
for (const run of orderedRuns) {
const artifacts = await artifactsForRun(github, owner, repo, run.id);
if (findResultArtifact(artifacts)) {
baselineRun = run;
break;
}
}
core.setOutput("publish", "true");
core.setOutput("pull_number", String(pullNumber));
core.setOutput("pr_artifact", sourceArtifact ? "true" : "false");
core.setOutput("pr_run_id", String(source.id));
core.setOutput("pr_sha", source.head_sha);
core.setOutput("pr_conclusion", source.conclusion ?? "unknown");
core.setOutput("baseline_artifact", baselineRun ? "true" : "false");
core.setOutput("baseline_run_id", baselineRun ? String(baselineRun.id) : "");
core.setOutput("baseline_sha", baselineRun?.head_sha ?? "");
core.setOutput(
"baseline_matches_base",
baselineRun?.head_sha === pull.base.sha ? "true" : "false",
);
}
async function upsertComment(github, context, pullNumber, body, options = {}) {
const { owner, repo } = context.repo;
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: pullNumber,
per_page: 100,
});
const existing = comments.find(
(comment) =>
comment.user?.login === "github-actions[bot]" && comment.body?.includes(COMMENT_MARKER),
);
if (
options.preserveResultSha &&
existing?.body?.includes(resultShaMarker(options.preserveResultSha))
) {
return;
}
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: pullNumber, body });
}
}
async function upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
expectedSha,
body,
options,
) {
const { owner, repo } = context.repo;
const { data: pull } = await github.rest.pulls.get({
owner,
repo,
pull_number: pullNumber,
});
if (pull.head.sha !== expectedSha) {
core.info(`Skipping stale CI result ${expectedSha}; PR head is ${pull.head.sha}.`);
return false;
}
await upsertComment(github, context, pullNumber, body, options);
return true;
}
async function publish({ github, context, core }) {
const pullNumber = Number(process.env.PR_NUMBER);
if (!Number.isSafeInteger(pullNumber) || pullNumber <= 0) {
throw new Error("PR_NUMBER is invalid");
}
const current = readResult(process.env.PR_RESULT_DIR);
const currentRun = {
sha: process.env.PR_SHA,
conclusion: process.env.PR_CONCLUSION,
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.PR_RUN_ID}`,
};
if (!current) {
await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
[
COMMENT_MARKER,
"## Thread transfer impact",
"",
`⚠️ The latest [CI run](${currentRun.url}) did not produce a thread transfer result for \`${currentRun.sha.slice(0, 7)}\`.`,
"",
"_This comment will update automatically after the next completed run._",
].join("\n"),
{ preserveResultSha: currentRun.sha },
);
return;
}
const baseline = readResult(process.env.BASELINE_RESULT_DIR);
const baselineRun = baseline
? {
sha: process.env.BASELINE_SHA,
matchesBase: process.env.BASELINE_MATCHES_BASE === "true",
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.BASELINE_RUN_ID}`,
}
: undefined;
const body = renderComment({ current, baseline, currentRun, baselineRun });
const published = await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
body,
);
if (published) {
core.info(`Updated thread transfer report on PR #${pullNumber}.`);
}
}
module.exports = {
publish,
readResult,
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
};
@@ -1,292 +0,0 @@
const assert = require("node:assert/strict");
const test = require("node:test");
const {
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
} = require("./thread-transfer-report.cjs");
function result(overrides = {}) {
const observed = {
totalWireBytes: 2_200_000,
threadSnapshotWireBytes: 1_950_000,
threadSnapshotDecodedBytes: 9_100_000,
measuredTurnWebSocketWireBytes: 250_000,
measuredTurnWebSocketDecodedBytes: 1_150_000,
measuredTurnWebSocketMessages: 15,
};
const ceiling = {
totalWireBytes: 2_900_000,
threadSnapshotWireBytes: 2_600_000,
measuredTurnWebSocketWireBytes: 320_000,
measuredTurnWebSocketDecodedBytes: 1_550_000,
measuredTurnWebSocketMessages: 20,
};
return {
schemaVersion: 1,
scenario: {
id: "thread-transfer-v1",
historyTurns: 10,
historyCommandToolsPerTurn: 5,
historyMcpResultBytes: 900_000,
measuredCommandTools: 20,
measuredMcpResultBytes: 1_100_000,
},
providers: {
codex: { observed: { ...observed, ...overrides }, ceiling },
claudeAgent: { observed, ceiling },
},
};
}
test("validates the fixed artifact schema", () => {
assert.equal(validateResult(result()).schemaVersion, 1);
assert.throws(
() => validateResult({ ...result(), injectedMarkdown: "@everyone" }),
/unexpected fields/,
);
assert.throws(
() => validateResult(result({ totalWireBytes: "lots" })),
/non-negative safe integer/,
);
});
test("renders baseline, impact, ceiling, and ceiling changes", () => {
const baseline = result();
const current = result({ measuredTurnWebSocketWireBytes: 260_000 });
current.providers.codex.ceiling = {
...current.providers.codex.ceiling,
measuredTurnWebSocketWireBytes: 330_000,
};
const comment = renderComment({
current,
baseline,
currentRun: {
sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
conclusion: "success",
url: "https://github.com/pingdotgg/t3code/actions/runs/2",
},
baselineRun: {
sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
matchesBase: true,
url: "https://github.com/pingdotgg/t3code/actions/runs/1",
},
});
assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/);
assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/);
assert.match(comment, /This PR changes transfer ceilings/);
assert.match(comment, /312\.5 KiB → 322\.3 KiB/);
assert.match(comment, /<!-- t3-thread-transfer-report -->/);
assert.match(
comment,
/<!-- t3-thread-transfer-result-sha:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->/,
);
});
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
const outputs = {};
const listWorkflowRunArtifacts = () => {};
const listWorkflowRuns = () => {};
const listPullRequestsAssociatedWithCommit = () => {};
const github = {
paginate: async (method, input) => {
if (method === listPullRequestsAssociatedWithCommit) {
return [
{
number: 5350,
state: "open",
head: { sha: "head-sha", ref: "feature-branch", repo: null },
},
];
}
if (method === listWorkflowRunArtifacts) {
return [
{
name: "thread-transfer-results",
expired: false,
runId: input.run_id,
},
];
}
if (method === listWorkflowRuns) {
return [{ id: 1, head_sha: "base-sha" }];
}
throw new Error("unexpected pagination call");
},
rest: {
actions: { listWorkflowRunArtifacts, listWorkflowRuns },
pulls: {
get: async () => ({
data: {
head: { sha: "head-sha" },
base: { sha: "base-sha", ref: "main" },
},
}),
},
repos: { listPullRequestsAssociatedWithCommit },
},
};
await resolve({
github,
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "true");
assert.equal(outputs.pull_number, "5350");
assert.equal(outputs.pr_artifact, "true");
assert.equal(outputs.baseline_run_id, "1");
assert.equal(outputs.baseline_matches_base, "true");
});
test("does not guess when a fallback commit belongs to multiple PRs", async () => {
const outputs = {};
const listPullRequestsAssociatedWithCommit = () => {};
let fetchedPull = false;
await resolve({
github: {
paginate: async (method) => {
assert.equal(method, listPullRequestsAssociatedWithCommit);
return [5350, 5351].map((number) => ({
number,
state: "open",
head: {
sha: "head-sha",
ref: "feature-branch",
repo: { full_name: "pingdotgg/t3code" },
},
}));
},
rest: {
actions: {},
pulls: {
get: async () => {
fetchedPull = true;
},
},
repos: { listPullRequestsAssociatedWithCommit },
},
},
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "false");
assert.equal(fetchedPull, false);
});
test("does not publish a stale result after the PR head advances", async () => {
let listedComments = false;
const info = [];
const published = await upsertCommentForCurrentHead(
{
paginate: async () => {
listedComments = true;
return [];
},
rest: {
issues: {
listComments: () => {},
createComment: () => {
throw new Error("must not create a stale comment");
},
updateComment: () => {
throw new Error("must not update a stale comment");
},
},
pulls: {
get: async () => ({ data: { head: { sha: "new-head-sha" } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: (message) => info.push(message) },
5350,
"old-head-sha",
"stale body",
);
assert.equal(published, false);
assert.equal(listedComments, false);
assert.deepEqual(info, ["Skipping stale CI result old-head-sha; PR head is new-head-sha."]);
});
test("preserves a successful result when a same-SHA rerun has no artifact", async () => {
let updatedComment = false;
const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const published = await upsertCommentForCurrentHead(
{
paginate: async () => [
{
id: 1,
user: { login: "github-actions[bot]" },
body: `<!-- t3-thread-transfer-report -->\n<!-- t3-thread-transfer-result-sha:${sha} -->`,
},
],
rest: {
issues: {
listComments: () => {},
createComment: () => {
updatedComment = true;
},
updateComment: () => {
updatedComment = true;
},
},
pulls: {
get: async () => ({ data: { head: { sha } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: () => {} },
5350,
sha,
"missing artifact warning",
{ preserveResultSha: sha },
);
assert.equal(published, true);
assert.equal(updatedComment, false);
});
+10
View File
@@ -70,6 +70,16 @@ jobs:
!/.repos/
sparse-checkout-cone-mode: false
# Blacksmith boots GitHub's Ubuntu runner image (gcc is usually present),
# but ACP process-tree live tests compile a small pthread fixture with `cc`
# and soft-skip when it is missing. Install build-essential so that path
# always runs in CI instead of silently no-oping.
- name: Install C toolchain for process-tree fixtures
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends build-essential
command -v cc
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
@@ -1,75 +0,0 @@
name: Thread Transfer Report
on:
workflow_run:
workflows: [CI]
types: [completed]
permissions:
actions: read
contents: read
pull-requests: write
jobs:
publish:
name: Publish PR comment
if: github.event.workflow_run.event == 'pull_request'
runs-on: ubuntu-24.04
concurrency:
group: thread-transfer-report-${{ github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.id }}
cancel-in-progress: true
steps:
# workflow_run has a write-capable token even for fork PRs. Only load the
# publisher from the trusted default branch and never execute PR code.
- name: Checkout trusted publisher
uses: actions/checkout@v6
with:
ref: ${{ github.event.repository.default_branch }}
sparse-checkout: .github/scripts
- name: Test trusted publisher
run: node --test .github/scripts/thread-transfer-report.test.cjs
- id: resolve
name: Resolve PR and baseline artifacts
uses: actions/github-script@v8
with:
script: |
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
await reporter.resolve({ github, context, core });
- name: Download PR result
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.pr_artifact == 'true'
uses: actions/download-artifact@v8
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer/pr
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ steps.resolve.outputs.pr_run_id }}
- name: Download main baseline
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.baseline_artifact == 'true'
uses: actions/download-artifact@v8
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer/main
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ steps.resolve.outputs.baseline_run_id }}
- name: Update thread transfer comment
if: steps.resolve.outputs.publish == 'true'
uses: actions/github-script@v8
env:
PR_NUMBER: ${{ steps.resolve.outputs.pull_number }}
PR_SHA: ${{ steps.resolve.outputs.pr_sha }}
PR_CONCLUSION: ${{ steps.resolve.outputs.pr_conclusion }}
PR_RUN_ID: ${{ steps.resolve.outputs.pr_run_id }}
PR_RESULT_DIR: ${{ runner.temp }}/thread-transfer/pr
BASELINE_SHA: ${{ steps.resolve.outputs.baseline_sha }}
BASELINE_MATCHES_BASE: ${{ steps.resolve.outputs.baseline_matches_base }}
BASELINE_RUN_ID: ${{ steps.resolve.outputs.baseline_run_id }}
BASELINE_RESULT_DIR: ${{ runner.temp }}/thread-transfer/main
with:
script: |
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
await reporter.publish({ github, context, core });
@@ -0,0 +1,246 @@
# Plan: Thread Lineage And Lazy Context Transfer
## Summary
Implement the shared backend foundation for forking, provider handoff, merge-back, and future subagents without forcing provider selection at fork time. The first slice should create cheap app-level fork lineage and defer expensive context materialization until a run starts and the target provider is known.
Architecture reference: `docs/orchestration-v2/thread-lineage-and-context-transfer.md`.
## Goals
- Support user-created fork threads for exploration.
- Keep fork creation provider-neutral and cheap.
- Reuse the same source-point/context-transfer model for provider switching, merge-back, and future subagents.
- Prefer native same-provider fork at first dispatch when available.
- Fall back to portable context only when native transfer is unavailable or target provider differs.
- Keep all behavior replayable through V2 events/projections.
## Non-Goals For First Slice
- Full portable context generation quality.
- Cross-provider adapter implementation beyond the data/runtime hook.
- Merge-back UI.
- Native or custom subagent orchestration.
- Forking from actively streaming provider state.
- Backward compatibility with old dev databases.
## Core Data Model
Add schema/contracts for:
```ts
type ContextTransferType =
| "fork"
| "provider_handoff"
| "merge_back"
| "subagent_spawn"
| "subagent_result";
type ContextSourcePoint = {
threadId: ThreadId;
runId?: RunId;
checkpointId?: CheckpointId;
turnItemId?: TurnItemId;
providerThreadRef?: NativeThreadRef;
providerTurnRef?: NativeTurnRef;
};
type ContextTransferStatus =
| "pending"
| "resolved_native"
| "resolved_portable"
| "failed"
| "consumed"
| "superseded";
```
Persist:
- `orchestration_v2_projection_context_transfers`
- optional later portable handoff payload columns/table if the existing context handoff projection is not enough
For the first slice, `ContextTransfer` is required. Materialized `ContextHandoff` payloads can be deferred until portable context is implemented.
## Events
Add V2 events:
- `context-transfer.created`
- `context-transfer.updated`
- possibly `context-handoff.created` later
Do not emit provider-native fork details as app identity. Native fork refs belong in the transfer resolution payload and provider thread refs.
## Commands
Add:
```ts
type ThreadForkCommand = {
type: "thread.fork";
commandId: CommandId;
sourceThreadId: ThreadId;
targetThreadId: ThreadId;
sourcePoint:
| { type: "latest_stable" }
| { type: "run"; runId: RunId }
| { type: "checkpoint"; checkpointId: CheckpointId };
title?: string;
createdAt: string;
};
```
First-slice policy:
- `latest_stable` resolves to latest completed run checkpoint.
- explicit completed run/checkpoint is accepted.
- active run source is rejected or resolved to latest stable checkpoint; choose one policy and test it.
- target thread starts idle.
- no provider session/thread is created by `thread.fork`.
## Runtime Hook
Add a provider-neutral start-context resolver used by run startup:
```ts
resolveStartContext({
threadId,
runId,
provider,
modelSelection,
userMessage,
}): Effect<StartContextResolution, StartContextResolutionError>
```
Resolution order:
1. No pending transfer targeting the thread/run: normal run start.
2. Pending fork transfer and same provider with native fork support: resolve native fork.
3. Pending transfer requiring portable context: return explicit unsupported/stub result in first slice, or build minimal portable context if cheap.
4. Failed resolution: fail command before provider side effects.
The resolver should be called before provider thread creation/startTurn so the adapter can decide whether to create, resume, or native-fork provider state.
## Codex Native Fork Path
Investigate the app-server native fork API in `effect-codex-app-server` and Codex docs/probes.
Implementation target:
- use native fork only when source provider is Codex and source native refs are strong;
- create or bind a new `ProviderThread` for the forked native thread;
- when the source point is an earlier completed Codex provider turn, fork the latest native thread first and then rollback the forked native thread by later terminal provider turns;
- mark `ContextTransfer.status = resolved_native` and then `consumed` when the first run starts;
- preserve source app thread lineage separately from native thread refs.
If native API details are not clean, land the data model and resolver first with native fork marked unsupported, then add Codex native fork in a follow-up.
## Portable Context Fallback
The first slice should define the fallback boundary even if it does not fully implement high-quality summarization.
Minimum viable fallback:
- detect cross-provider fork/handoff need;
- create failed/unsupported transfer resolution with a clear command error, or
- generate a deterministic minimal context handoff from app projection if we want a usable MVP.
Do not silently concatenate hidden summaries into the user message without a `ContextTransfer`/`ContextHandoff` record.
## Merge-Back Preparation
Do not implement merge-back in the first slice, but keep model support:
- `ContextTransfer.type = "merge_back"`
- `basePoint` on transfer
- source thread may differ from target thread
The later merge-back command should create a transfer from fork latest stable point back to source thread and consume it with the next user message.
## Subagent Preparation
Do not implement subagents in this slice, but keep model support:
- `createdBy: "agent"`
- `type: "subagent_spawn"` and `"subagent_result"`
- source/target thread relationship fields
Native subagent ingestion can later map provider-native child refs into the same graph. Cross-provider app-owned subagents can later create child app threads using the same transfer primitive.
## Projection And Debugger
Backend projection first:
- expose thread lineage in thread projection;
- expose context transfers in debug projection;
- expose transfer status and resolution strategy.
Debugger after backend:
- fork button/control from stable source point;
- show thread lineage/source point;
- show pending/resolved/failed transfers;
- show native vs portable resolution.
Do not build debugger controls before the backend projection is authoritative.
## Tests
Use `bun run test`, not `bun test`.
Required backend tests:
- `thread.fork` from latest completed checkpoint creates target thread and pending transfer.
- fork command is idempotent through command receipts.
- fork does not create provider session/thread eagerly.
- first run on same-provider fork invokes native resolution path when capability exists.
- unsupported native fork falls back or fails according to explicit policy.
- active-run fork policy is deterministic.
- replay/recovery preserves target thread lineage and pending transfer.
Add test provider layers only at external service boundaries. Do not mock core orchestration policy.
## Implementation Order
1. Add contract schemas and ids for context transfers/source points.
2. Add migration/projection table for context transfers.
3. Add event store/projection handling for transfer events.
4. Add `thread.fork` command policy and orchestrator path.
5. Add tests for cheap idle fork creation and recovery.
6. Add start-context resolver interface.
7. Wire resolver into run startup with no-op behavior.
8. Add Codex native fork capability investigation and adapter path.
9. Add tests for same-provider native fork resolution.
10. Add debug projection surface after backend behavior is stable.
## Validation
Before considering the slice complete:
- `bun fmt`
- `bun lint`
- `bun typecheck`
- targeted backend tests with `bun run test`
If backend code changes are included, tests must cover the new orchestration behavior before the task is considered done.
## Implementation Status
Implemented in this slice:
- context transfer ids, schemas, JSON codecs, events, and projection storage
- app-thread lineage on thread creation and fork creation
- `thread.fork` command using `latest_stable`, explicit run, or explicit checkpoint source points
- cheap idle fork creation with no eager provider session/thread/run
- Codex same-provider native `thread/fork` resolution on first target dispatch
- Codex native fork-from-earlier-run resolution with `thread/fork` plus fork-local `thread/rollback`
- transfer status progression through `pending`, `resolved_native`, and `consumed`
- command receipt idempotency for duplicate fork commands
- replay-backed integration coverage for lazy fork creation and native Codex fork consumption
Explicitly deferred:
- portable `ContextHandoff` materialization for cross-provider forks/provider handoff
- merge-back command/runtime
- subagent spawn/result runtime
- debugger controls for creating/inspecting transfers
File diff suppressed because it is too large. Load diff
+1
View File
@@ -12,3 +12,4 @@
10. `10-unify-process-session-abstraction.md`
19. `19-version-control-phase-1-vcs-driver-foundation.md`
20. `20-version-control-phase-2-source-control-provider-foundation.md`
21. `21-orchestration-v2-application-integration.md`
+1
View File
@@ -79,6 +79,7 @@ Full docs live in [docs/](./docs). There's no docs site yet.
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Customize a project icon](./docs/user/project-settings.md)
- [Appearance preferences](./docs/user/appearance.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
@@ -96,6 +96,8 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
assert.equal(environment.userDataDirName, "t3code");
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha)");
}),
);
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed(() => null),
Effect.orElseSucceed((): string | null => null),
);
const dnsName =
input.statusJson === undefined
@@ -31,6 +31,7 @@ const clientSettings: ClientSettings = {
fontSmoothing: true,
glassOpacity: 80,
planModeEnabled: false,
persistComposerContextStrip: true,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarAutoSettleOnMerge: true,
+1 -1
View File
@@ -218,7 +218,7 @@ const mobileEndorsementRows = [
<div class="harness-mark"><img src="/harnesses/cursor_light.svg" alt="" /></div>
<div class="harness-meta">
<div class="harness-name">Cursor</div>
<div class="harness-tag">cursor-agent</div>
<div class="harness-tag">@cursor/sdk</div>
</div>
</div>
<div class="harness">
+2 -7
View File
@@ -3,14 +3,9 @@ import { Image } from "expo-image";
import { View } from "react-native";
import { AppText as Text } from "./AppText";
import { T3_CODE_BRAND_MARK_SOURCE } from "./brandAssets";
const appVariant = Constants.expoConfig?.extra?.appVariant;
const BRAND_MARK_SOURCE =
appVariant === "development"
? require("../../../../assets/dev/blueprint-ios-1024.png")
: appVariant === "preview"
? require("../../../../assets/nightly/nightly-ios-1024.png")
: require("../../../../assets/prod/black-ios-1024.png");
const DEFAULT_STAGE_LABEL =
appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha";
@@ -22,7 +17,7 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
return (
<View className="flex-row items-center gap-3">
<Image
source={BRAND_MARK_SOURCE}
source={T3_CODE_BRAND_MARK_SOURCE}
accessibilityIgnoresInvertColors
style={{
width: iconSize,
+10
View File
@@ -0,0 +1,10 @@
import Constants from "expo-constants";
const appVariant = Constants.expoConfig?.extra?.appVariant;
export const T3_CODE_BRAND_MARK_SOURCE =
appVariant === "development"
? require("../../../../assets/dev/blueprint-ios-1024.png")
: appVariant === "preview"
? require("../../../../assets/nightly/nightly-ios-1024.png")
: require("../../../../assets/prod/black-ios-1024.png");
@@ -1,5 +1,16 @@
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
import { ORCHESTRATION_CACHE_SCHEMA_VERSION } from "@t3tools/client-runtime/platform";
import {
CommandId,
EnvironmentId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ThreadDetailSnapshot,
type VcsListRefsResult,
} from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -7,6 +18,124 @@ import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-data
import { make } from "./environment-cache-store";
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
const PROJECT_ID = ProjectId.make("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
schemaVersion: 1,
snapshotSequence: 3,
projects: [
{
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-29T12:00:00.000Z",
updatedAt: "2026-07-29T12:00:00.000Z",
},
],
threads: [
{
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Thread",
providerInstanceId: PROVIDER_INSTANCE_ID,
modelSelection: {
instanceId: PROVIDER_INSTANCE_ID,
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: {
rootThreadId: THREAD_ID,
parentThreadId: null,
relationshipToParent: null,
},
forkedFrom: null,
createdBy: "user",
creationSource: "mobile",
latestRunId: null,
activeRunId: null,
status: "idle",
pendingRuntimeRequest: null,
latestVisibleMessage: null,
latestUserMessageAt: NOW,
hasActionableProposedPlan: false,
itemCount: 0,
visibleItemCount: 0,
createdAt: NOW,
updatedAt: NOW,
archivedAt: null,
settledOverride: null,
settledAt: NOW,
lastVisitedAt: null,
titleRegeneration: {
requestId: CommandId.make("title-regeneration-1"),
startedAt: NOW,
},
deletedAt: null,
},
],
archivedThreads: [],
};
const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
snapshotSequence: 4,
projection: {
thread: {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Thread",
providerInstanceId: PROVIDER_INSTANCE_ID,
modelSelection: {
instanceId: PROVIDER_INSTANCE_ID,
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: {
rootThreadId: THREAD_ID,
parentThreadId: null,
relationshipToParent: null,
},
forkedFrom: null,
createdBy: "user",
creationSource: "mobile",
createdAt: NOW,
updatedAt: NOW,
archivedAt: null,
settledOverride: null,
settledAt: NOW,
lastVisitedAt: null,
deletedAt: null,
},
runs: [],
attempts: [],
nodes: [],
subagents: [],
providerSessions: [],
providerThreads: [],
providerTurns: [],
runtimeRequests: [],
messages: [],
plans: [],
turnItems: [],
checkpointScopes: [],
checkpoints: [],
contextHandoffs: [],
contextTransfers: [],
visibleTurnItems: [],
updatedAt: NOW,
},
};
const REFS: VcsListRefsResult = {
refs: [
{
@@ -28,13 +157,16 @@ function cacheId(environmentId: EnvironmentId, kind: ClientCacheKind, cacheKey:
function makeDatabase() {
const values = new Map<string, string>();
const schemaVersions = new Map<string, number>();
const removed: Array<string> = [];
const database = MobileDatabase.of({
loadCache: (environmentId, kind, cacheKey) =>
Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
saveCache: (environmentId, kind, cacheKey, _schemaVersion, payload) =>
saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
Effect.sync(() => {
values.set(cacheId(environmentId, kind, cacheKey), payload);
const id = cacheId(environmentId, kind, cacheKey);
values.set(id, payload);
schemaVersions.set(id, schemaVersion);
}),
removeCache: (environmentId, kind, cacheKey) =>
Effect.sync(() => {
@@ -59,10 +191,40 @@ function makeDatabase() {
loadPreferencesJson: Effect.succeed(Option.none()),
savePreferencesJson: () => Effect.void,
});
return { database, removed, values };
return { database, removed, schemaVersions, values };
}
describe("mobile SQLite environment cache store", () => {
it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
"2026-07-29T12:00:00.000Z",
);
expect(DateTime.formatIso(shell.threads[0]!.titleRegeneration!.startedAt)).toBe(
"2026-07-29T12:00:00.000Z",
);
expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
"2026-07-29T12:00:00.000Z",
);
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
ORCHESTRATION_CACHE_SCHEMA_VERSION,
);
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
ORCHESTRATION_CACHE_SCHEMA_VERSION,
);
}),
);
it.effect("round-trips schema-validated VCS refs", () =>
Effect.gen(function* () {
const memory = makeDatabase();
@@ -1,14 +1,11 @@
import {
ConnectionPersistenceError,
EnvironmentCacheStore,
ORCHESTRATION_CACHE_SCHEMA_VERSION,
StoredOrchestrationShellSnapshot,
StoredOrchestrationThreadSnapshot,
} from "@t3tools/client-runtime/platform";
import {
type EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
ServerConfig,
VcsListRefsResult,
} from "@t3tools/contracts";
import { type EnvironmentId, ServerConfig, VcsListRefsResult } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -16,25 +13,9 @@ import * as Schema from "effect/Schema";
import * as MobileDatabase from "../persistence/mobile-database";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
// makes pre-pagination clients discard the record instead of decoding a
// partial thread as complete (rollback safety).
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
threadId: Schema.String,
snapshot: OrchestrationThreadDetailSnapshot,
});
const StoredServerConfig = Schema.Struct({
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
@@ -48,13 +29,17 @@ const StoredVcsRefs = Schema.Struct({
});
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredShellSnapshot),
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
);
const encodeStoredShellSnapshot = Schema.encodeEffect(
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
);
const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot));
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredThreadSnapshot),
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
);
const encodeStoredThreadSnapshot = Schema.encodeEffect(
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
);
const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot));
const decodeStoredServerConfig = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredServerConfig),
);
@@ -130,12 +115,12 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
),
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
const payload = yield* encodeStoredShellSnapshot({
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
yield* database
.saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
.saveCache(environmentId, "shell", "snapshot", ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-shell")));
}),
loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
@@ -153,15 +138,15 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
}),
),
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
const threadId = snapshot.thread.id;
const threadId = snapshot.projection.thread.id;
const payload = yield* encodeStoredThreadSnapshot({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
environmentId,
threadId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
yield* database
.saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
.saveCache(environmentId, "thread", threadId, ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-thread")));
}),
removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
+9 -2
View File
@@ -1,6 +1,9 @@
import { Connection } from "@t3tools/client-runtime/connection";
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
import {
boundedThreadSnapshotLoaderLayer,
threadHistoryControllerLayer,
} from "@t3tools/client-runtime/state/threads";
import * as Layer from "effect/Layer";
import { Atom } from "effect/unstable/reactivity";
@@ -15,7 +18,11 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
Layer.provide(runtimeContextLayer),
);
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
const snapshotLoaderLayer = Layer.mergeAll(
boundedThreadSnapshotLoaderLayer,
shellSnapshotLoaderLayer,
threadHistoryControllerLayer,
);
type ConnectionLayerSource =
| typeof Connection.layer
+1
View File
@@ -17,6 +17,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as CatalogStore from "./catalog-store";
function targetPersistenceError(
@@ -1,9 +1,11 @@
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell } from "@t3tools/contracts";
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import * as DateTime from "effect/DateTime";
import { buildArchivedThreadGroups } from "./archivedThreadList";
import { makeRawThreadShell } from "../../test-fixtures";
const environmentId = EnvironmentId.make("environment-1");
@@ -22,42 +24,30 @@ function makeProject(
}
function makeThread(
input: Partial<OrchestrationThreadShell> &
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
): OrchestrationThreadShell {
return {
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: "2026-06-02T00:00:00.000Z",
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
input: Pick<OrchestrationV2ThreadShell, "id" | "projectId" | "title"> & {
readonly branch?: string | null;
readonly archivedAt?: string | null;
},
): OrchestrationV2ThreadShell {
const archivedAt = input.archivedAt === undefined ? "2026-06-02T00:00:00.000Z" : input.archivedAt;
return makeRawThreadShell({
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
archivedAt: archivedAt === null ? null : DateTime.makeUnsafe(archivedAt),
});
}
function makeSnapshot(
projects: ReadonlyArray<OrchestrationProjectShell>,
threads: ReadonlyArray<OrchestrationThreadShell>,
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
targetEnvironmentId = environmentId,
): ArchivedSnapshotEntry {
return {
environmentId: targetEnvironmentId,
snapshot: {
schemaVersion: 1,
snapshotSequence: 1,
projects,
threads,
updatedAt: "2026-06-04T00:00:00.000Z",
},
};
}
+3 -3
View File
@@ -190,7 +190,7 @@ function deriveEmptyState(props: {
return {
title: "No threads yet",
detail: "Create a task to start a new coding session in one of your connected projects.",
detail: "Create a task to start a new coding runtime in one of your connected projects.",
loading: false,
};
}
@@ -814,7 +814,7 @@ export function HomeScreen(props: HomeScreenProps) {
?.providers.find(
(provider) =>
provider.instanceId ===
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
@@ -1101,7 +1101,7 @@ export function HomeScreen(props: HomeScreenProps) {
detail="Choose another environment or create a new task."
/>
) : (
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
<EmptyState title="No threads yet" detail="Create a task to start a new coding runtime." />
)
) : null;
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
@@ -1,8 +1,10 @@
import type {
EnvironmentProject,
EnvironmentThreadShell,
import {
presentThreadShell,
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
import {
@@ -32,29 +34,41 @@ function makeProject(id: string, title: string): EnvironmentProject {
};
}
const threadTimestamp = DateTime.makeUnsafe("2026-06-01T00:00:00.000Z");
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
return {
environmentId,
id: ThreadId.make(id),
const threadId = ThreadId.make(id);
return presentThreadShell(environmentId, {
id: threadId,
projectId,
title: `Thread ${id}`,
providerInstanceId: ProviderInstanceId.make("codex"),
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
activeProviderThreadId: null,
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
forkedFrom: null,
createdBy: "user",
creationSource: "mobile",
latestRunId: null,
activeRunId: null,
status: "idle",
pendingRuntimeRequest: null,
latestVisibleMessage: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
};
itemCount: 0,
visibleItemCount: 0,
createdAt: threadTimestamp,
updatedAt: threadTimestamp,
archivedAt: null,
deletedAt: null,
});
}
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
@@ -11,6 +11,7 @@ import {
buildHomeThreadGroups,
sortHomeProjectScopes,
} from "./homeThreadList";
import { makeThreadShellFixture } from "../../test-fixtures";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
@@ -30,25 +31,21 @@ function makeThread(
input: Partial<EnvironmentThreadShell> &
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
): EnvironmentThreadShell {
return {
return makeThreadShellFixture({
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
});
}
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
@@ -0,0 +1,40 @@
import { ProviderInstanceId, RunId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
import { threadCanArchive } from "./threadArchive";
function runtime(
status: ThreadRuntimeSummary["status"],
activeRunId: ThreadRuntimeSummary["activeRunId"],
): ThreadRuntimeSummary {
return {
status,
activeRunId,
providerInstanceId: ProviderInstanceId.make("codex"),
providerName: "codex",
lastError: null,
updatedAt: "2026-07-28T10:00:00.000Z",
};
}
describe("threadCanArchive", () => {
it("blocks provider-active work", () => {
const activeRunId = RunId.make("run-live");
expect(threadCanArchive(runtime("preparing", activeRunId))).toBe(false);
expect(threadCanArchive(runtime("starting", activeRunId))).toBe(false);
expect(threadCanArchive(runtime("running", activeRunId))).toBe(false);
});
it("only allows queued work when no provider run remains active", () => {
const activeRunId = RunId.make("run-live");
expect(threadCanArchive(runtime("queued", null))).toBe(true);
expect(threadCanArchive(runtime("queued", activeRunId))).toBe(false);
});
it("allows post-provider waiting work despite a retained active run id", () => {
const staleActiveRunId = RunId.make("run-finished");
expect(threadCanArchive(runtime("waiting", null))).toBe(true);
expect(threadCanArchive(runtime("waiting", staleActiveRunId))).toBe(true);
});
});
@@ -0,0 +1,16 @@
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
/**
* Archiving may discard queued work, but it must not detach a provider while
* that provider is still executing a turn.
*/
export function threadCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
if (runtime?.status === "queued") {
return runtime.activeRunId === null;
}
return (
runtime?.status !== "preparing" &&
runtime?.status !== "starting" &&
runtime?.status !== "running"
);
}
@@ -17,6 +17,7 @@ import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { threadCanArchive } from "./threadArchive";
/** Version skew: never send settle/unsettle to a server that predates them
(capability defaults false on decode for older servers). */
@@ -128,13 +129,9 @@ function useThreadActionExecutor(
);
return false;
}
// Archive keeps its original, narrower guard: never interrupt a
// thread mid-turn.
if (
action === "archive" &&
thread.session?.status === "running" &&
thread.session.activeTurnId != null
) {
// The server cancels queued runs on archive. Only an actual provider
// turn still needs the user to interrupt it first.
if (action === "archive" && !threadCanArchive(thread.runtime)) {
Alert.alert(
actionFailureTitle(action),
"This thread is working. Interrupt it first, then try again.",
@@ -55,7 +55,10 @@ export function subscribeToHardwareKeyboardCommandRegistrations(listener: () =>
export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
const commandHandlers = handlers.get(command);
if (!commandHandlers) return false;
for (const handler of [...commandHandlers].toReversed()) {
const handlersInRegistrationOrder = Array.from(commandHandlers);
for (let index = handlersInRegistrationOrder.length - 1; index >= 0; index -= 1) {
const handler = handlersInRegistrationOrder[index];
if (!handler) continue;
if (handler() !== false) return true;
}
return false;
@@ -604,7 +604,6 @@ function useCreateProject(environment: EnvironmentOption | null) {
commandId: CommandId.make(uuidv4()),
projectId,
workspaceRoot,
createdAt: new Date().toISOString(),
});
const result = await createProject({
environmentId: environment.environmentId,
@@ -1,11 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import {
MessageId,
TurnId,
type OrchestrationCheckpointSummary,
type ReviewDiffPreviewSource,
} from "@t3tools/contracts";
import { MessageId, RunId, type ReviewDiffPreviewSource } from "@t3tools/contracts";
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import {
buildReviewListItems,
@@ -18,9 +14,9 @@ import {
} from "./reviewModel";
function makeCheckpoint(
input: Partial<OrchestrationCheckpointSummary> &
Pick<OrchestrationCheckpointSummary, "turnId" | "checkpointTurnCount" | "completedAt">,
): OrchestrationCheckpointSummary {
input: Partial<ThreadCheckpointSummary> &
Pick<ThreadCheckpointSummary, "runId" | "checkpointTurnCount" | "completedAt">,
): ThreadCheckpointSummary {
return {
checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any,
status: "ready",
@@ -52,12 +48,12 @@ describe("buildReviewSectionItems", () => {
it("keeps one chip per checkpoint and appends git sources", () => {
const checkpoints = [
makeCheckpoint({
turnId: TurnId.make("turn-1"),
runId: RunId.make("run-1"),
checkpointTurnCount: 1,
completedAt: "2026-04-01T00:00:00.000Z",
}),
makeCheckpoint({
turnId: TurnId.make("turn-2"),
runId: RunId.make("run-2"),
checkpointTurnCount: 2,
completedAt: "2026-04-02T00:00:00.000Z",
}),
+11 -10
View File
@@ -1,6 +1,7 @@
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Order from "effect/Order";
@@ -128,11 +129,11 @@ export type ReviewParsedDiff =
readonly notice: string | null;
};
function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string {
function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
return `Turn ${checkpoint.checkpointTurnCount}`;
}
function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string {
function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
const fileCount = checkpoint.files.length;
if (checkpoint.status !== "ready") {
return `Diff ${checkpoint.status}`;
@@ -141,8 +142,8 @@ function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string
}
function compareCheckpointTurnCountDescending(
left: OrchestrationCheckpointSummary,
right: OrchestrationCheckpointSummary,
left: ThreadCheckpointSummary,
right: ThreadCheckpointSummary,
): -1 | 0 | 1 {
if (left.checkpointTurnCount === right.checkpointTurnCount) {
return 0;
@@ -151,7 +152,7 @@ function compareCheckpointTurnCountDescending(
return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
}
const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
compareCheckpointTurnCountDescending,
);
@@ -510,14 +511,14 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
}
export function getReviewSectionIdForCheckpoint(
checkpoint: Pick<OrchestrationCheckpointSummary, "checkpointTurnCount">,
checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
): string {
return `turn:${checkpoint.checkpointTurnCount}`;
}
export function getReadyReviewCheckpoints(
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
): ReadonlyArray<OrchestrationCheckpointSummary> {
checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
): ReadonlyArray<ThreadCheckpointSummary> {
return pipe(
checkpoints,
Arr.filter((checkpoint) => checkpoint.status === "ready"),
@@ -526,7 +527,7 @@ export function getReadyReviewCheckpoints(
}
export function buildReviewSectionItems(input: {
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
@@ -1,11 +1,15 @@
import { useCallback, useEffect, useMemo } from "react";
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
import {
deriveThreadCheckpointSummaries,
type ThreadCheckpointSummary,
} from "@t3tools/client-runtime/state/thread-checkpoints";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useCheckpointDiff } from "../../state/queries";
import { useEnvironmentQuery } from "../../state/query";
import { reviewEnvironment } from "../../state/review";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import {
buildReviewSectionItems,
@@ -30,7 +34,7 @@ export function useReviewSections(input: {
}) {
const { environmentId, reviewCache, threadId } = input;
const enabled = input.enabled ?? true;
const selectedThread = useSelectedThreadDetail();
const selectedThread = useSelectedThreadProjection();
const { selectedThreadCwd } = useSelectedThreadWorktree();
const diffPreview = useEnvironmentQuery(
enabled && environmentId !== undefined && selectedThreadCwd !== null
@@ -49,8 +53,11 @@ export function useReviewSections(input: {
}, [diffPreview.data, reviewCache.threadKey]);
const readyCheckpoints = useMemo(
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
[selectedThread?.checkpoints],
() =>
getReadyReviewCheckpoints(
selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
),
[selectedThread],
);
const checkpointBySectionId = useMemo(
() =>
@@ -59,7 +66,7 @@ export function useReviewSections(input: {
getReviewSectionIdForCheckpoint(checkpoint),
checkpoint,
]),
) as Record<string, OrchestrationCheckpointSummary>,
) as Record<string, ThreadCheckpointSummary>,
[readyCheckpoints],
);
const reviewSections = useMemo(
@@ -40,7 +40,7 @@ import {
useKnownTerminalSessions,
} from "../../state/use-terminal-session";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { TerminalSurface } from "./NativeTerminalSurface";
@@ -172,7 +172,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
const params = props.route.params;
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const selectedThreadDetail = useSelectedThreadProjection();
const selectedThreadDetailWorktreePath =
selectedThreadDetail?.projection.thread.worktreePath ?? null;
const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
const routeThreadIdRaw = firstRouteParam(params.threadId);
const routeEnvironmentId = routeEnvironmentIdRaw
@@ -283,13 +285,13 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
activeSessionLocation: activeKnownSession?.state.summary ?? null,
workspaceRoot: selectedThreadProject.workspaceRoot,
threadShellWorktreePath: selectedThread.worktreePath ?? null,
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
threadDetailWorktreePath: selectedThreadDetailWorktreePath,
});
}, [
activeKnownSession?.state.summary,
pendingLaunch,
selectedThread,
selectedThreadDetail?.worktreePath,
selectedThreadDetailWorktreePath,
selectedThreadProject?.workspaceRoot,
]);
const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
@@ -20,6 +20,7 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import {
@@ -50,7 +51,7 @@ import {
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
@@ -717,7 +718,10 @@ export function NewTaskDraftScreen(props: {
// finds no work and ends the card within seconds.
armAgentAwarenessLiveActivityForLocalWork({
environmentId: selectedProject.environmentId,
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
threadTitle: deriveThreadTitleSeed({
text: initialMessageText,
attachments: draft.attachments,
}),
projectTitle: selectedProject.title,
});
const creationBranch = resolveProjectThreadCreationBranch({
@@ -1,4 +1,4 @@
import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
import type { ProviderApprovalDecision, RuntimeRequestId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
@@ -6,9 +6,9 @@ import type { PendingApproval } from "../../lib/threadActivity";
export interface PendingApprovalCardProps {
readonly approval: PendingApproval;
readonly respondingApprovalId: ApprovalRequestId | null;
readonly respondingApprovalId: RuntimeRequestId | null;
readonly onRespond: (
requestId: ApprovalRequestId,
requestId: RuntimeRequestId,
decision: ProviderApprovalDecision,
) => Promise<unknown>;
}
@@ -16,6 +16,8 @@ export interface PendingApprovalCardProps {
export function PendingApprovalCard(props: PendingApprovalCardProps) {
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
// behind this card, so a translucent surface bleeds messages through it.
const canRespond = props.approval.responseCapability === "live";
const disabled = !canRespond || props.respondingApprovalId === props.approval.requestId;
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
@@ -29,17 +31,23 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
{props.approval.detail}
</Text>
) : null}
{!canRespond ? (
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
The provider process for this request is no longer available. Interrupt or restart the run
to continue.
</Text>
) : null}
<View className="flex-row flex-wrap gap-2.5">
<Pressable
className="items-center justify-center rounded-[14px] bg-blue-500 px-3.5 py-3"
disabled={props.respondingApprovalId === props.approval.requestId}
disabled={disabled}
onPress={() => void props.onRespond(props.approval.requestId, "accept")}
>
<Text className="font-t3-extrabold text-sm text-white">Allow once</Text>
</Pressable>
<Pressable
className="items-center justify-center rounded-[14px] bg-neutral-200 px-3.5 py-3 dark:bg-neutral-800"
disabled={props.respondingApprovalId === props.approval.requestId}
disabled={disabled}
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
>
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
@@ -48,7 +56,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
</Pressable>
<Pressable
className="items-center justify-center rounded-[14px] bg-rose-100 px-3.5 py-3 dark:bg-rose-500/18"
disabled={props.respondingApprovalId === props.approval.requestId}
disabled={disabled}
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
>
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
@@ -1,4 +1,5 @@
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
import type { RuntimeRequestId } from "@t3tools/contracts";
import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
import { useCallback, useRef } from "react";
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
import Animated, {
@@ -55,14 +56,14 @@ export interface PendingUserInputCardProps {
readonly onInputFocusChange?: (focused: boolean) => void;
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly respondingUserInputId: RuntimeRequestId | null;
readonly onSelectOption: (
requestId: ApprovalRequestId,
question: UserInputQuestion,
requestId: RuntimeRequestId,
question: ThreadUserInputQuestion,
label: string,
) => void;
readonly onChangeCustomAnswer: (
requestId: ApprovalRequestId,
requestId: RuntimeRequestId,
questionId: string,
customAnswer: string,
) => void;
@@ -89,6 +90,9 @@ const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
export function PendingUserInputCard(props: PendingUserInputCardProps) {
const iconSubtle = useThemeColor("--color-icon-subtle");
const questionCount = props.pendingUserInput.questions.length;
// V2 runtime requests carry response capability: a dead provider process
// cannot accept answers, so the card reads-only until the run restarts.
const canRespond = props.pendingUserInput.responseCapability === "live";
const cardCoverage = props.cardCoverage;
const barHeightRef = useRef(0);
@@ -247,6 +251,12 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
showsVerticalScrollIndicator
style={{ flexShrink: 1 }}
>
{!canRespond ? (
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
The provider process for this request is no longer available. Interrupt or restart the
run to continue.
</Text>
) : null}
{props.pendingUserInput.questions.map((question) => {
const draft = props.drafts[question.id];
return (
@@ -263,6 +273,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
return (
<Pressable
key={option.label}
disabled={!canRespond}
className={cn(
"rounded-full border px-3 py-2.5 ",
selected
@@ -292,6 +303,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
})}
</View>
<TextInput
editable={canRespond}
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
@@ -311,7 +323,9 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
)}
disabled={
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
!canRespond ||
props.answers === null ||
props.respondingUserInputId === props.pendingUserInput.requestId
}
onPress={() => void props.onSubmit()}
>
@@ -0,0 +1,203 @@
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useNavigation } from "@react-navigation/native";
import { useMemo, useState } from "react";
import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
import { buildThreadActivityInspector } from "../../lib/threadActivityInspector";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useV2ItemSupport } from "../../state/v2-item-support";
import { buildThreadActivityFileParams } from "./threadActivityFileNavigation";
export function ThreadActivityInspector(props: {
readonly activity: ThreadFeedActivity;
readonly currentThreadId: ThreadId;
readonly environmentId: EnvironmentId;
readonly iconColor: ColorValue;
readonly workspaceRoot?: string | null;
}) {
const navigation = useNavigation();
const row = props.activity.projectedItem;
const support = useV2ItemSupport({
environmentId: props.environmentId,
sourceThreadId: row.sourceThreadId,
sourceItemId: row.sourceItemId,
});
const model = useMemo(
() => buildThreadActivityInspector(props.activity, support, props.currentThreadId),
[props.activity, props.currentThreadId, support],
);
const revertCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, {
label: "checkpoint rollback",
reportFailure: true,
});
const [rollingBack, setRollingBack] = useState(false);
return (
<View className="gap-3">
<View className="flex-row flex-wrap gap-x-4 gap-y-2 rounded-lg border border-neutral-300/50 bg-black/[0.025] p-2.5 dark:border-white/[0.1] dark:bg-white/[0.025]">
{model.fields.map((field) => (
<View key={`${field.label}:${field.value}`} className="min-w-[42%] flex-1 gap-0.5">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
{field.label}
</Text>
<Text selectable className="text-2xs leading-4 text-foreground">
{field.value}
</Text>
</View>
))}
</View>
{model.blocks.map((block) => (
<View key={`${block.label}:${block.value}`} className="gap-1">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
{block.label}
</Text>
<ScrollView
nestedScrollEnabled
directionalLockEnabled
showsVerticalScrollIndicator
style={{ maxHeight: 240 }}
contentContainerStyle={{ paddingRight: 8 }}
>
<Text
selectable
className="text-2xs leading-[17px] text-foreground-muted"
style={block.monospaced ? { fontFamily: "ui-monospace" } : undefined}
>
{block.value}
</Text>
</ScrollView>
</View>
))}
{model.fileLinks.length > 0 ? (
<View className="gap-1">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
Files
</Text>
{model.fileLinks.map((link) => {
const relativePath =
resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??
(link.path.startsWith("/") ? null : link.path);
return (
<Pressable
key={`${link.path}:${link.line ?? 0}:${link.label}`}
accessibilityRole={relativePath ? "link" : undefined}
disabled={relativePath === null}
onPress={() => {
if (!relativePath) return;
void Haptics.selectionAsync();
navigation.navigate(
"ThreadFile",
buildThreadActivityFileParams({
environmentId: props.environmentId,
currentThreadId: props.currentThreadId,
activitySourceThreadId: row.sourceThreadId,
relativePath,
line: link.line,
}),
);
}}
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
>
<SymbolView
name="doc.text"
size={13}
tintColor={props.iconColor}
type="monochrome"
/>
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
{link.label}
</Text>
</Pressable>
);
})}
</View>
) : null}
{model.webLinks.length > 0 ? (
<View className="gap-1">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
Sources
</Text>
{model.webLinks.map((link) => (
<Pressable
key={link.url}
accessibilityRole="link"
onPress={() => void Linking.openURL(link.url)}
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
>
<SymbolView
name="arrow.up.right.square"
size={13}
tintColor={props.iconColor}
type="monochrome"
/>
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
{link.label}
</Text>
</Pressable>
))}
</View>
) : null}
{model.rollbackTarget ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Roll back to this checkpoint"
disabled={rollingBack}
onPress={() => {
setRollingBack(true);
void Haptics.selectionAsync();
void revertCheckpoint({
environmentId: props.environmentId,
input: {
threadId: model.rollbackTarget!.threadId,
checkpointId: model.rollbackTarget!.checkpointId,
scopeId: model.rollbackTarget!.scopeId,
},
}).finally(() => setRollingBack(false));
}}
className="min-h-10 flex-row items-center justify-center gap-2 rounded-lg border border-neutral-300/60 px-3 py-2 dark:border-white/[0.12]"
>
<SymbolView
name={rollingBack ? "hourglass" : "arrow.counterclockwise"}
size={14}
tintColor={props.iconColor}
type="monochrome"
/>
<Text className="font-t3-medium text-xs text-foreground">
{rollingBack ? "Rolling back…" : "Roll back to checkpoint"}
</Text>
</Pressable>
) : null}
<View className="gap-1 border-t border-neutral-300/50 pt-2 dark:border-white/[0.1]">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
Structured details
</Text>
<ScrollView
nestedScrollEnabled
directionalLockEnabled
showsVerticalScrollIndicator
style={{ maxHeight: 280 }}
contentContainerStyle={{ paddingRight: 8 }}
>
<Text
selectable
className="text-2xs leading-[17px] text-foreground-muted"
style={{ fontFamily: "ui-monospace" }}
>
{model.structuredDetails}
</Text>
</ScrollView>
</View>
</View>
);
}
@@ -1,8 +1,9 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderInteractionMode,
RuntimeMode,
ServerConfig as T3ServerConfig,
@@ -102,9 +103,11 @@ export interface ThreadComposerProps {
* are on screen while they reconcile with the server.
*/
readonly threadSyncPhase?: "loading" | "syncing" | null;
readonly selectedThread: OrchestrationThreadShell;
readonly selectedThread: EnvironmentThreadShell;
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
readonly canStopThread: boolean;
readonly environmentId: EnvironmentId;
readonly projectCwd: string | null;
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
@@ -321,9 +324,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
setIsFocused(false);
onEditorFocusChange?.(false);
}, [onEditorFocusChange]);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting";
const showStopAction = props.canStopThread;
const sendLabel =
props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
@@ -1,21 +1,21 @@
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import type { LegendListRef } from "@legendapp/list/react-native";
import { HeaderHeightContext } from "@react-navigation/elements";
import type {
ApprovalRequestId,
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderApprovalDecision,
ProviderInteractionMode,
RuntimeMode,
RuntimeRequestId,
ServerConfig as T3ServerConfig,
ThreadId,
UserInputQuestion,
} from "@t3tools/contracts";
import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
import * as Haptics from "expo-haptics";
import {
memo,
@@ -57,13 +57,15 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import type {
PendingApproval,
PendingUserInput,
PendingUserInputDraftAnswer,
ThreadFeedEntry,
ThreadFeedLatestRun,
} from "../../lib/threadActivity";
import { PendingApprovalCard } from "./PendingApprovalCard";
import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -77,30 +79,35 @@ import {
COMPOSER_EXPANDED_CHROME,
ThreadComposer,
} from "./ThreadComposer";
import { ThreadFeed } from "./ThreadFeed";
import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
import { ThreadRelationshipsBanner } from "./ThreadRelationshipsBanner";
import { ThreadQueueControl } from "./ThreadQueueControl";
import type { ThreadContentPresentation } from "./threadContentPresentation";
export interface ThreadDetailScreenProps {
readonly selectedThread: OrchestrationThreadShell;
readonly selectedThread: EnvironmentThreadShell;
readonly contentPresentation: ThreadContentPresentation;
readonly screenTone: StatusTone;
readonly connectionError: string | null;
readonly environmentLabel: string | null;
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
readonly activityRun: ThreadFeedLatestRun | null;
readonly activeWorkStartedAt: string | null;
readonly activePendingApproval: PendingApproval | null;
readonly respondingApprovalId: ApprovalRequestId | null;
readonly respondingApprovalId: RuntimeRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly respondingUserInputId: RuntimeRequestId | null;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly connectionStateLabel: EnvironmentConnectionPhase;
/** Message sync status for the selected thread (drives the composer status pill). */
readonly threadSyncStatus?: EnvironmentThreadStatus;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
/** Progressive history controls for oversized mobile thread opens. */
readonly historyControls?: ThreadFeedHistoryControls;
readonly activeThreadBusy: boolean;
readonly canStopThread: boolean;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
readonly threadCwd: string | null;
@@ -121,16 +128,16 @@ export interface ThreadDetailScreenProps {
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onRespondToApproval: (
requestId: ApprovalRequestId,
requestId: RuntimeRequestId,
decision: ProviderApprovalDecision,
) => Promise<unknown>;
readonly onSelectUserInputOption: (
requestId: ApprovalRequestId,
question: UserInputQuestion,
requestId: RuntimeRequestId,
question: ThreadUserInputQuestion,
label: string,
) => void;
readonly onChangeUserInputCustomAnswer: (
requestId: ApprovalRequestId,
requestId: RuntimeRequestId,
questionId: string,
customAnswer: string,
) => void;
@@ -249,7 +256,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
}
}, []);
const windowHeight = useWindowDimensions().height;
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + IOS_NAV_BAR_HEIGHT;
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
@@ -298,7 +305,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
// keyboard animations coherent. Collapse state is keyed by request id so a
// new request re-expands automatically.
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
useState<ApprovalRequestId | null>(null);
useState<RuntimeRequestId | null>(null);
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
const userInputCollapsed =
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
@@ -456,6 +463,39 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
selectedThreadKeyRef.current = selectedThreadKey;
}, [selectedThreadKey]);
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
const lastDispatchedVisitRef = useRef<string | null>(null);
const selectedThreadId = props.selectedThread.id;
const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
useEffect(() => {
// Records the server-side visited watermark while the thread is on
// screen (mirror of web ChatView), so the "Done" marker clears on every
// device. Field absent → the server predates visited tracking.
if (selectedThreadLastVisitedAt === undefined) return;
const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
if (Number.isNaN(threadUpdatedAtMs)) return;
const lastVisitedAtMs = selectedThreadLastVisitedAt
? Date.parse(selectedThreadLastVisitedAt)
: NaN;
if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
// Dedupe per watermark — the effect re-runs before the command echo lands.
const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
if (lastDispatchedVisitRef.current === dispatchKey) return;
lastDispatchedVisitRef.current = dispatchKey;
void visitThread({
environmentId: props.environmentId,
input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
});
}, [
props.environmentId,
selectedThreadId,
selectedThreadKey,
selectedThreadLastVisitedAt,
selectedThreadUpdatedAt,
visitThread,
]);
useEffect(() => {
setAnchorMessageId(null);
lastScrolledAnchorMessageIdRef.current = null;
@@ -589,7 +629,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
latestTurn={props.selectedThread.latestTurn}
threadTitle={props.selectedThread.title}
latestRun={props.activityRun}
activeWorkStartedAt={props.activeWorkStartedAt}
listRef={listRef}
freeze={freeze}
@@ -598,12 +639,18 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
historyControls={props.historyControls}
topAccessory={
<ThreadRelationshipsBanner
environmentId={props.environmentId}
threadId={props.selectedThread.id}
/>
}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
onEndFollowEnabledChange={setEndFollowEnabled}
skills={selectedProviderSkills}
loadEarlier={props.loadEarlier ?? null}
/>
</View>
) : (
@@ -668,6 +715,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
</Animated.View>
) : null}
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
<ThreadQueueControl
environmentId={props.environmentId}
threadId={props.selectedThread.id}
/>
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
@@ -726,6 +778,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
canStopThread={props.canStopThread}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
+259 -88
View File
@@ -1,7 +1,15 @@
import * as Haptics from "expo-haptics";
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
import { type LegendListRef } from "@legendapp/list/react-native";
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
import {
ThreadId,
type EnvironmentId,
type MessageId,
type OrchestrationV2ProjectedTurnItem,
type RunId,
} from "@t3tools/contracts";
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
import { SymbolView } from "../../components/AppSymbol";
@@ -27,6 +35,7 @@ import {
} from "react-native-nitro-markdown";
import {
ActivityIndicator,
Alert,
Image,
Platform,
type LayoutChangeEvent,
@@ -75,6 +84,7 @@ import {
import { buildReviewParsedDiff } from "../review/reviewModel";
import { cn } from "../../lib/cn";
import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout";
import { uuidv4 } from "../../lib/uuid";
import {
resolveMarkdownFontSizes,
resolveNativeMarkdownTypography,
@@ -87,8 +97,9 @@ import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
import {
deriveThreadFeedPresentation,
threadFeedRunIsUnsettled,
type ThreadFeedEntry,
type ThreadFeedLatestTurn,
type ThreadFeedLatestRun,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import {
@@ -103,7 +114,13 @@ import {
} from "./thread-work-log";
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useV2ItemSupport } from "../../state/v2-item-support";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
import { waitForThreadShellReady } from "./threadForkNavigation";
import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
includeOrderedLists: Platform.OS === "android",
@@ -140,14 +157,22 @@ function isFreshTimestamp(input: string): boolean {
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ENTRY_WINDOW_MS;
}
export interface ThreadFeedHistoryControls {
readonly hasMoreHistory: boolean;
readonly loading: boolean;
readonly error: string | null;
readonly onLoadEarlier: () => void;
}
export interface ThreadFeedProps {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly threadTitle: string;
readonly workspaceRoot?: string | null;
readonly feed: ReadonlyArray<ThreadFeedEntry>;
readonly contentPresentation: ThreadContentPresentation;
readonly agentLabel: string;
readonly latestTurn: ThreadFeedLatestTurn | null;
readonly latestRun: ThreadFeedLatestRun | null;
readonly activeWorkStartedAt: string | null;
readonly listRef: RefObject<LegendListRef | null>;
readonly freeze: SharedValue<boolean>;
@@ -155,17 +180,98 @@ export interface ThreadFeedProps {
readonly contentInsetEndAdjustment: SharedValue<number>;
readonly contentTopInset?: number;
readonly contentBottomInset?: number;
readonly historyControls?: ThreadFeedHistoryControls;
readonly topAccessory?: ReactNode;
readonly contentMaxWidth?: number;
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: {
readonly loading: boolean;
readonly onLoadEarlier: () => void;
} | null;
}
async function waitForThreadShell(
environmentId: EnvironmentId,
threadId: ThreadId,
): Promise<boolean> {
const atom = environmentThreadShells.threadShellAtom(scopeThreadRef(environmentId, threadId));
return waitForThreadShellReady({
read: () => appAtomRegistry.get(atom) !== null,
});
}
function AssistantForkButton(props: {
readonly environmentId: EnvironmentId;
readonly iconColor: ColorValue;
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
readonly sourceTitle: string;
}) {
const support = useV2ItemSupport({
environmentId: props.environmentId,
sourceThreadId: props.projectedItem.sourceThreadId,
sourceItemId: props.projectedItem.sourceItemId,
});
const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
const navigation = useNavigation();
const [busy, setBusy] = useState(false);
const canFork = canForkProjectedAssistantItem({
projectedItem: props.projectedItem,
capabilities: support.providerSession?.capabilities,
});
const runId = props.projectedItem.item.runId;
if (!canFork || runId === null) return null;
return (
<Pressable
accessibilityRole="button"
accessibilityLabel="Fork from this response"
disabled={busy}
onPress={() => {
const targetThreadId = ThreadId.make(uuidv4());
setBusy(true);
void Haptics.selectionAsync();
void forkFromRun({
environmentId: props.environmentId,
input: {
sourceThreadId: props.projectedItem.sourceThreadId,
targetThreadId,
runId,
title: `${props.sourceTitle} fork`,
creationSource: "mobile",
},
})
.then(async (result) => {
if (result._tag !== "Success") return;
const targetThreadReady = await waitForThreadShell(props.environmentId, targetThreadId);
if (!targetThreadReady) {
Alert.alert(
"Fork created",
"Its thread data did not reach this client. Reconnect and try opening it from the thread list.",
);
return;
}
navigation.navigate("Thread", {
environmentId: props.environmentId,
threadId: targetThreadId,
});
})
.finally(() => setBusy(false));
}}
className="h-7 w-7 items-center justify-center disabled:opacity-40"
>
{busy ? (
<ActivityIndicator size="small" />
) : (
<SymbolView
name="arrow.triangle.branch"
size={13}
tintColor={props.iconColor}
type="monochrome"
/>
)}
</Pressable>
);
}
function MessageAttachmentImage(props: {
@@ -821,15 +927,16 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
function renderFeedEntry(
info: { item: ThreadFeedEntry; index: number },
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
props: Pick<ThreadFeedProps, "environmentId" | "skills" | "threadId" | "workspaceRoot"> & {
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
readonly expandedWorkRows: Record<string, boolean>;
readonly terminalAssistantMessageIds: ReadonlySet<string>;
readonly unsettledTurnId: TurnId | null;
readonly unsettledTurnId: RunId | null;
readonly onCopyWorkRow: (rowId: string, value: string) => void;
readonly onToggleWorkGroup: (groupId: string) => void;
readonly onToggleWorkRow: (rowId: string) => void;
readonly onToggleTurnFold: (turnId: TurnId) => void;
readonly onToggleWorkRow: (rowId: string, anchorKey?: string) => void;
readonly onToggleTurnFold: (runId: RunId) => void;
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
readonly onMarkdownLinkPress: (href: string) => void;
readonly iconSubtleColor: string | import("react-native").ColorValue;
@@ -838,6 +945,7 @@ function renderFeedEntry(
readonly reviewCommentColors: ReviewCommentColors;
readonly reviewCommentBubbleWidth: number;
readonly userBubbleMaxWidth: number;
readonly threadTitle: string;
},
) {
const entry = info.item;
@@ -847,12 +955,12 @@ function renderFeedEntry(
return <WorkingTimelineRow startedAt={entry.createdAt} />;
}
if (entry.type === "turn-fold") {
if (entry.type === "run-fold") {
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: entry.expanded }}
onPress={() => props.onToggleTurnFold(entry.turnId)}
onPress={() => props.onToggleTurnFold(entry.runId)}
hitSlop={4}
className="mb-3 min-h-11 flex-row items-center gap-2 border-b border-neutral-200/80 px-2 dark:border-white/[0.08]"
>
@@ -897,7 +1005,7 @@ function renderFeedEntry(
const assistantTurnStillInProgress =
message.role === "assistant" &&
props.unsettledTurnId !== null &&
message.turnId === props.unsettledTurnId;
message.runId === props.unsettledTurnId;
const showAssistantMeta =
message.role === "assistant" &&
props.terminalAssistantMessageIds.has(message.id) &&
@@ -906,11 +1014,17 @@ function renderFeedEntry(
if (isUser) {
const enterAnimated = isFreshTimestamp(message.createdAt);
const intentBadge = resolveUserMessageIntentBadge(message.inputIntent);
return (
<Animated.View
className="mb-5 items-end"
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
>
{message.createdBy === "agent" ? (
<Text className="mb-1 pr-1 font-t3-medium text-2xs text-foreground-muted opacity-60">
Sent by another agent
</Text>
) : null}
<View
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
style={{
@@ -945,6 +1059,30 @@ function renderFeedEntry(
})}
</View>
<View className="mt-1 flex-row items-center justify-end gap-1 pr-0.5">
{intentBadge ? (
<View
accessible
accessibilityRole="text"
accessibilityLabel={intentBadge.accessibilityLabel}
className={cn(
"rounded-full border px-1.5 py-0.5",
intentBadge.tone === "queued"
? "border-amber-500/25 bg-amber-500/10 dark:border-amber-400/25 dark:bg-amber-400/10"
: "border-sky-500/25 bg-sky-500/10 dark:border-sky-400/25 dark:bg-sky-400/10",
)}
>
<Text
className={cn(
"font-t3-medium text-2xs tracking-wide",
intentBadge.tone === "queued"
? "text-amber-700 dark:text-amber-300"
: "text-sky-700 dark:text-sky-300",
)}
>
{intentBadge.label}
</Text>
</View>
) : null}
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
{timestampLabel}
</Text>
@@ -1006,6 +1144,12 @@ function renderFeedEntry(
})}
{showAssistantMeta ? (
<View className="mt-1 flex-row items-center gap-1">
<AssistantForkButton
environmentId={props.environmentId}
iconColor={iconSubtleColor}
projectedItem={message.projectedItem}
sourceTitle={props.threadTitle}
/>
<CopyTextButton
accessibilityLabel="Copy message"
text={message.text}
@@ -1026,10 +1170,15 @@ function renderFeedEntry(
<ThreadWorkLog
activities={entry.activities}
copiedRowId={props.copiedRowId}
currentThreadId={props.threadId}
environmentId={props.environmentId}
expanded={props.expandedWorkGroups[entry.id] ?? false}
expandedRows={props.expandedWorkRows}
iconSubtleColor={iconSubtleColor}
onCopyRow={props.onCopyWorkRow}
onToggleRow={props.onToggleWorkRow}
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
onToggleRow={(rowId) => props.onToggleWorkRow(rowId, entry.id)}
workspaceRoot={props.workspaceRoot}
/>
);
}
@@ -1298,6 +1447,41 @@ function compactFileName(filePath: string): string {
return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized;
}
function ThreadFeedLoadEarlierControl(props: ThreadFeedHistoryControls) {
const mutedColor = useThemeColor("--color-icon-subtle");
const accentColor = useThemeColor("--color-primary");
if (!props.hasMoreHistory && props.error === null) {
return null;
}
return (
<View className="mb-3 items-center gap-1.5 px-2">
{props.hasMoreHistory ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Load earlier activity"
disabled={props.loading}
onPress={props.onLoadEarlier}
className="min-h-9 flex-row items-center justify-center gap-2 rounded-full border border-border/60 bg-surface/80 px-4 py-2 disabled:opacity-50"
>
{props.loading ? (
<ActivityIndicator size="small" color={accentColor} />
) : (
<SymbolView name="chevron.up" size={12} tintColor={accentColor} type="monochrome" />
)}
<Text className="text-sm font-medium text-foreground">
{props.loading ? "Loading earlier activity…" : "Load earlier activity"}
</Text>
</Pressable>
) : null}
{props.error !== null ? (
<Text className="text-center text-xs" style={{ color: mutedColor }}>
{props.error}
</Text>
) : null}
</View>
);
}
function ThreadFeedPlaceholder(props: {
readonly bottomInset: number;
readonly detail: string;
@@ -1332,10 +1516,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const foldSettleFrameRef = useRef<number | null>(null);
const foldSettleSecondFrameRef = useRef<number | null>(null);
const previousLatestTurnRef = useRef(props.latestRun);
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const disclosureAnchorKeyRef = useRef<string | null>(null);
const headerMaterialVisibleRef = useRef(false);
const previousLatestTurnRef = useRef(props.latestTurn);
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const { width: windowWidth } = useWindowDimensions();
const { appearance } = useAppearancePreferences();
const [viewportWidth, setViewportWidth] = useState(() =>
@@ -1343,11 +1527,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
const [viewportHeight, setViewportHeight] = useState(0);
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
// Live-follow latch. LegendList's maintainScrollAtEnd alone re-pins the feed
// whenever the viewport drifts back inside its geometric threshold, which
// yanked users off history they were reading every time a stream chunk grew
// a row. Follow breaks when the user scrolls up and away, and re-arms only
// when the list actually returns to the end (or on send / thread switch).
// Live-follow latch (#5566). LegendList's maintainScrollAtEnd alone re-pins
// the feed whenever the viewport drifts back inside its geometric threshold,
// which yanked users off history they were reading every time a stream chunk
// grew a row. Follow breaks when the user scrolls up and away, and re-arms
// only when the list actually returns to the end (or on send / thread switch).
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
const endFollowEnabledRef = useRef(true);
// A "user scroll session" spans from drag start through the end of its
@@ -1375,7 +1559,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
readonly expandedWorkRows: Record<string, boolean>;
readonly expandedTurnIds: ReadonlySet<TurnId>;
readonly expandedTurnIds: ReadonlySet<RunId>;
}>({
copiedRowId: null,
expandedWorkGroups: {},
@@ -1448,6 +1632,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listAppearanceData = useMemo(
() => ({
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1457,6 +1642,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}),
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1549,22 +1735,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
const nextHeight = Math.round(event.nativeEvent.layout.height);
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
}, []);
// Thread identity is env-scoped: two environments can hold the same
// ThreadId, and keying resets (or the list mount) on the bare id would
// carry stale scroll/follow state across an environment switch.
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
useEffect(() => {
reportHeaderMaterialVisibility(false);
}, [feedThreadKey, reportHeaderMaterialVisibility]);
// A thread switch opens pinned to the end; a send explicitly returns to the
// live edge (ThreadDetailScreen scrolls the new message into place). Both
// re-arm follow regardless of where the user had scrolled before.
@@ -1581,31 +1755,31 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
if (expanded) {
ids.add(groupId);
}
}
return ids;
}, [expandedWorkGroups]);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
const nextHeight = Math.round(event.nativeEvent.layout.height);
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
}, []);
useEffect(() => {
reportHeaderMaterialVisibility(false);
}, [feedThreadKey, reportHeaderMaterialVisibility]);
const presentedFeed = useMemo(
() =>
deriveThreadFeedPresentation(
props.feed,
props.latestTurn,
props.latestRun,
expandedTurnIds,
expandedWorkGroupIds,
new Set(
Object.entries(expandedWorkGroups)
.filter(([, expanded]) => expanded)
.map(([groupId]) => groupId),
),
props.activeWorkStartedAt,
),
[
expandedTurnIds,
expandedWorkGroupIds,
props.activeWorkStartedAt,
props.feed,
props.latestTurn,
],
[expandedTurnIds, expandedWorkGroups, props.activeWorkStartedAt, props.feed, props.latestRun],
);
// The empty↔filled key below remounts the list, which resets its imperative
@@ -1634,29 +1808,25 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
[presentedFeed, props.anchorMessageId, anchorTopInset],
);
const terminalAssistantMessageIds = useMemo(() => {
const terminalIdsByTurn = new Map<TurnId, string>();
const terminalIdsByTurn = new Map<RunId, string>();
for (const entry of props.feed) {
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
terminalIdsByTurn.set(entry.message.turnId, entry.message.id);
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
terminalIdsByTurn.set(entry.message.runId, entry.message.id);
}
}
return new Set(terminalIdsByTurn.values());
}, [props.feed]);
const unsettledTurnId =
props.latestTurn &&
(props.latestTurn.completedAt === null || props.latestTurn.state === "running")
? props.latestTurn.turnId
: null;
const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
useEffect(() => {
const previous = previousLatestTurnRef.current;
previousLatestTurnRef.current = props.latestTurn;
if (!props.latestTurn || !previous) {
previousLatestTurnRef.current = props.latestRun;
if (!props.latestRun || !previous) {
return;
}
if (props.latestTurn.turnId === previous.turnId) {
if (previous.state === "running" && props.latestTurn.state === "interrupted") {
const interruptedTurnId = props.latestTurn.turnId;
if (props.latestRun.runId === previous.runId) {
if (previous.status === "running" && props.latestRun.status === "interrupted") {
const interruptedTurnId = props.latestRun.runId;
setInteractionState((current) => ({
...current,
expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
@@ -1665,14 +1835,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
return;
}
setInteractionState((current) => {
if (!current.expandedTurnIds.has(previous.turnId)) {
if (!current.expandedTurnIds.has(previous.runId)) {
return current;
}
const next = new Set(current.expandedTurnIds);
next.delete(previous.turnId);
next.delete(previous.runId);
return { ...current, expandedTurnIds: next };
});
}, [props.latestTurn]);
}, [props.latestRun]);
useEffect(() => {
return () => {
@@ -1753,8 +1923,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
const onToggleWorkRow = useCallback(
(rowId: string) => {
suspendEndScrollMaintenanceForDisclosure(rowId);
(rowId: string, anchorKey?: string) => {
suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null);
setInteractionState((current) => ({
...current,
expandedWorkRows: {
@@ -1767,14 +1937,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
const onToggleTurnFold = useCallback(
(turnId: TurnId) => {
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
(runId: RunId) => {
suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`);
setInteractionState((current) => {
const next = new Set(current.expandedTurnIds);
if (next.has(turnId)) {
next.delete(turnId);
if (next.has(runId)) {
next.delete(runId);
} else {
next.add(turnId);
next.add(runId);
}
return { ...current, expandedTurnIds: next };
});
@@ -1799,7 +1969,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const getFixedItemSize = useCallback(
(entry: ThreadFeedEntry) => {
switch (entry.type) {
case "turn-fold":
case "run-fold":
return TURN_FOLD_HEIGHT;
case "work-toggle":
return WORK_GROUP_TOGGLE_HEIGHT;
@@ -1822,7 +1992,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
(info: { item: ThreadFeedEntry; index: number }) =>
renderFeedEntry(info, {
environmentId: props.environmentId,
threadId: props.threadId,
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
unsettledTurnId,
@@ -1838,10 +2010,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
reviewCommentColors,
reviewCommentBubbleWidth,
userBubbleMaxWidth,
threadTitle: props.threadTitle,
skills: props.skills,
workspaceRoot: props.workspaceRoot,
}),
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
unsettledTurnId,
@@ -1858,7 +2033,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleWorkGroup,
onToggleWorkRow,
props.environmentId,
props.threadId,
props.threadTitle,
props.skills,
props.workspaceRoot,
],
);
@@ -1988,17 +2166,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
ListHeaderComponent={
<>
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
{props.loadEarlier != null ? (
<Pressable
onPress={props.loadEarlier.onLoadEarlier}
disabled={props.loadEarlier.loading}
className="items-center py-2"
>
<Text className="text-xs text-foreground-secondary">
{props.loadEarlier.loading ? "Loading earlier turns…" : "Load earlier turns"}
</Text>
</Pressable>
{props.historyControls ? (
<ThreadFeedLoadEarlierControl {...props.historyControls} />
) : null}
{props.topAccessory}
</>
}
contentContainerStyle={{
@@ -945,7 +945,7 @@ function ThreadNavigationSidebarPane(
?.providers.find(
(provider) =>
provider.instanceId ===
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
@@ -0,0 +1,149 @@
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
import { useMemo, useState } from "react";
import { Pressable, ScrollView, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useThreadProjection } from "../../state/use-thread-detail";
import {
buildCancelQueuedRunCommand,
resolveThreadQueueRowControls,
} from "./threadQueueControlPresentation";
export function ThreadQueueControl(props: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
}) {
const scoped = useThreadProjection(props);
const workflow = useMemo(
() => (scoped ? deriveThreadQueueWorkflowState(scoped.projection) : null),
[scoped],
);
const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun, "reorder queued message");
const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "cancel queued message");
const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
const iconColor = useThemeColor("--color-icon-subtle");
if (!workflow || workflow.queuedRuns.length === 0) return null;
const move = async (runId: RunId, beforeRunId: RunId | null) => {
setBusyRunId(runId);
void Haptics.selectionAsync();
await reorder({
environmentId: props.environmentId,
input: { threadId: props.threadId, runId, beforeRunId },
});
setBusyRunId(null);
};
const steer = async (queuedRunId: RunId) => {
if (!workflow.activeRun || !workflow.canPromoteToSteer) return;
setBusyRunId(queuedRunId);
void Haptics.selectionAsync();
await promote({
environmentId: props.environmentId,
input: {
threadId: props.threadId,
queuedRunId,
targetRunId: workflow.activeRun.id,
},
});
setBusyRunId(null);
};
const dismiss = async (runId: RunId) => {
setBusyRunId(runId);
void Haptics.selectionAsync();
await cancel(
buildCancelQueuedRunCommand({
environmentId: props.environmentId,
runId,
threadId: props.threadId,
}),
);
setBusyRunId(null);
};
return (
<View className="mx-4 mb-3 overflow-hidden rounded-2xl border border-neutral-300/60 bg-card dark:border-white/[0.1]">
<View className="flex-row items-center gap-2 border-b border-neutral-300/50 px-3 py-2 dark:border-white/[0.08]">
<SymbolView name="list.number" size={13} tintColor={iconColor} type="monochrome" />
<Text className="font-t3-medium text-xs text-foreground">Queue</Text>
<Text className="ml-auto text-2xs tabular-nums text-foreground-muted">
{workflow.queuedRuns.length}
</Text>
</View>
<ScrollView style={{ maxHeight: 156 }} contentContainerStyle={{ paddingVertical: 4 }}>
{workflow.queuedRuns.map(({ run, text }, index) => {
const controls = resolveThreadQueueRowControls({
busy: busyRunId !== null,
canPromoteToSteer: workflow.canPromoteToSteer,
canReorder: workflow.canReorder,
index,
queuedCount: workflow.queuedRuns.length,
text,
});
return (
<View key={run.id} className="min-h-11 flex-row items-center gap-1.5 px-2">
<Text className="w-5 text-right text-3xs tabular-nums text-foreground-muted">
{index + 1}
</Text>
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
{controls.displayText}
</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Move queued message up"
disabled={!controls.canMoveUp}
onPress={() => void move(run.id, workflow.queuedRuns[index - 1]?.run.id ?? null)}
className="h-9 w-9 items-center justify-center disabled:opacity-30"
>
<SymbolView name="arrow.up" size={13} tintColor={iconColor} type="monochrome" />
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Move queued message down"
disabled={!controls.canMoveDown}
onPress={() => void move(run.id, workflow.queuedRuns[index + 2]?.run.id ?? null)}
className="h-9 w-9 items-center justify-center disabled:opacity-30"
>
<SymbolView name="arrow.down" size={13} tintColor={iconColor} type="monochrome" />
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel="Promote queued message to steer"
disabled={!controls.canSteer}
onPress={() => void steer(run.id)}
className="min-h-8 flex-row items-center gap-1 rounded-lg border border-neutral-300/60 px-2 disabled:opacity-30 dark:border-white/[0.1]"
>
<SymbolView
name="arrow.turn.left.up"
size={12}
tintColor={iconColor}
type="monochrome"
/>
<Text className="font-t3-medium text-2xs text-foreground">Steer</Text>
</Pressable>
<Pressable
accessibilityRole="button"
accessibilityLabel={controls.dismissAccessibilityLabel}
disabled={!controls.canDismiss}
onPress={() => void dismiss(run.id)}
className="h-9 w-9 items-center justify-center disabled:opacity-30"
>
<SymbolView name="xmark" size={13} tintColor={iconColor} type="monochrome" />
</Pressable>
</View>
);
})}
</ScrollView>
</View>
);
}
@@ -0,0 +1,306 @@
import * as Haptics from "expo-haptics";
import { SymbolView, type SFSymbol } from "expo-symbols";
import {
deriveThreadRelationshipGraph,
immediateThreadRelationships,
resolveMergeBackTargetThreadId,
type ThreadRelationshipEdge,
} from "@t3tools/client-runtime/state/thread-relationships";
import {
canDetachThreadProviderSession,
resolveLatestMergeBackRun,
} from "@t3tools/client-runtime/state/thread-workflows";
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import { copySorted } from "@t3tools/shared/Array";
import { useNavigation } from "@react-navigation/native";
import { useMemo, useState } from "react";
import { ActivityIndicator, Modal, Pressable, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadShells } from "../../state/entities";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useThreadProjection } from "../../state/use-thread-detail";
import { useArchivedThreadSnapshots } from "../archive/useArchivedThreadSnapshots";
function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId): string {
if (edge.kind === "transfer") {
return edge.sourceThreadId === currentThreadId ? "Context sent to" : "Context received from";
}
if (edge.kind === "subagent") {
return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
}
return edge.sourceThreadId === currentThreadId ? "Fork" : "Forked from";
}
function relationshipSymbol(edge: ThreadRelationshipEdge): SFSymbol {
if (edge.kind === "subagent") return "person.2";
if (edge.kind === "transfer") return "arrow.left.arrow.right";
return "arrow.triangle.branch";
}
function threadAvailability(
thread: OrchestrationV2ThreadShell | null,
missing: boolean,
): string | null {
if (missing) return "Unavailable";
if (thread?.deletedAt !== null && thread?.deletedAt !== undefined) return "Deleted";
if (thread?.archivedAt !== null && thread?.archivedAt !== undefined) return "Archived";
return null;
}
const EMPTY_THREAD_SHELLS: ReadonlyArray<OrchestrationV2ThreadShell> = [];
export function ThreadRelationshipsBanner(props: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
}) {
const scopedProjection = useThreadProjection(props);
const projection = scopedProjection?.projection ?? null;
const threadShells = useThreadShells();
const environmentIds = useMemo(() => [props.environmentId], [props.environmentId]);
const archived = useArchivedThreadSnapshots(environmentIds);
const archivedShells =
archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot
.threads ?? EMPTY_THREAD_SHELLS;
const shells = useMemo<ReadonlyArray<OrchestrationV2ThreadShell>>(() => {
const environmentShells: OrchestrationV2ThreadShell[] = [];
for (const thread of threadShells) {
if (thread.environmentId === props.environmentId) {
environmentShells.push(thread.source);
}
}
environmentShells.push(...archivedShells);
return environmentShells;
}, [archivedShells, props.environmentId, threadShells]);
const graph = useMemo(
() => deriveThreadRelationshipGraph({ threads: shells, projection }),
[projection, shells],
);
const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
const rows = useMemo(
() =>
copySorted(
immediateThreadRelationships(graph, props.threadId),
(left, right) =>
Number(right.threadId === mergeTargetThreadId) -
Number(left.threadId === mergeTargetThreadId),
),
[graph, mergeTargetThreadId, props.threadId],
);
const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
const [visible, setVisible] = useState(false);
const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
const navigation = useNavigation();
const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
const insets = useSafeAreaInsets();
const backdropColor = useThemeColor("--color-backdrop");
const sheetColor = useThemeColor("--color-sheet");
const iconColor = useThemeColor("--color-icon-subtle");
if (rows.length === 0 && !canDetach) return null;
const primaryParent = rows.find(({ edge }) => edge.targetThreadId === props.threadId) ?? rows[0];
const primaryNode = primaryParent ? graph.nodes.get(primaryParent.threadId) : null;
const summary = primaryParent
? `${relationshipLabel(primaryParent.edge, props.threadId)}: ${primaryNode?.thread?.title ?? "related thread"}`
: "Agent session connected";
const openThread = (threadId: ThreadId, archivedThread: boolean) => {
setVisible(false);
void Haptics.selectionAsync();
if (archivedThread) {
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsArchive" },
});
return;
}
navigation.navigate("Thread", {
environmentId: props.environmentId,
threadId,
});
};
const merge = async () => {
if (!canMerge || mergeTargetThreadId === null || latestMergeBackRun === null) return;
setBusyAction("merge");
const result = await mergeBack({
environmentId: props.environmentId,
input: {
sourceThreadId: props.threadId,
targetThreadId: mergeTargetThreadId,
runId: latestMergeBackRun.id,
creationSource: "mobile",
},
});
setBusyAction(null);
if (result._tag === "Success") openThread(mergeTargetThreadId, false);
};
const detach = async () => {
if (!canDetach) return;
setBusyAction("detach");
await stopSession({
environmentId: props.environmentId,
input: { threadId: props.threadId },
});
setBusyAction(null);
};
return (
<>
<Pressable
accessibilityRole="button"
accessibilityLabel={`${summary}. Show thread relationships`}
onPress={() => {
void Haptics.selectionAsync();
setVisible(true);
}}
className="mb-4 min-h-11 flex-row items-center gap-2 rounded-xl border border-neutral-300/60 bg-card px-3 py-2.5 dark:border-white/[0.1]"
>
<SymbolView
name={primaryParent ? relationshipSymbol(primaryParent.edge) : "link"}
size={14}
tintColor={iconColor}
type="monochrome"
/>
<Text className="min-w-0 flex-1 font-t3-medium text-xs text-foreground" numberOfLines={1}>
{summary}
</Text>
{rows.length > 1 ? (
<Text className="text-2xs tabular-nums text-foreground-muted">+{rows.length - 1}</Text>
) : null}
<SymbolView name="chevron.right" size={12} tintColor={iconColor} type="monochrome" />
</Pressable>
<Modal
transparent
animationType="fade"
visible={visible}
statusBarTranslucent
onRequestClose={() => setVisible(false)}
>
<View className="flex-1 justify-end">
<View
pointerEvents="none"
className="absolute inset-0"
style={{ backgroundColor: backdropColor }}
/>
<Pressable className="absolute inset-0" onPress={() => setVisible(false)} />
<View
className="max-h-[78%] rounded-t-[28px] px-4 pt-3"
style={{ backgroundColor: sheetColor, paddingBottom: Math.max(insets.bottom, 16) }}
>
<View className="mb-4 h-1 w-10 self-center rounded-full bg-neutral-400/40" />
<View className="mb-3 flex-row items-center justify-between px-1">
<View>
<Text className="font-t3-bold text-lg text-foreground">Thread lineage</Text>
<Text className="text-xs text-foreground-muted">
{rows.length} related {rows.length === 1 ? "thread" : "threads"}
</Text>
</View>
<Pressable
accessibilityRole="button"
accessibilityLabel="Close thread lineage"
onPress={() => setVisible(false)}
className="h-10 w-10 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/[0.07]"
>
<SymbolView name="xmark" size={14} tintColor={iconColor} type="monochrome" />
</Pressable>
</View>
<ScrollView contentContainerStyle={{ gap: 8 }} showsVerticalScrollIndicator={false}>
{rows.map(({ threadId, edge }) => {
const node = graph.nodes.get(threadId);
const availability = threadAvailability(
node?.thread ?? null,
node?.missing ?? true,
);
const archivedThread = availability === "Archived";
const disabled = availability === "Unavailable" || availability === "Deleted";
return (
<Pressable
key={`${edge.kind}:${threadId}`}
accessibilityRole={disabled ? undefined : "link"}
accessibilityState={{ disabled }}
disabled={disabled}
onPress={() => openThread(threadId, archivedThread)}
className="min-h-14 flex-row items-center gap-3 rounded-2xl border border-neutral-300/50 bg-card px-3 py-2.5 dark:border-white/[0.08]"
>
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/60 dark:bg-white/[0.06]">
<SymbolView
name={relationshipSymbol(edge)}
size={14}
tintColor={iconColor}
type="monochrome"
/>
</View>
<View className="min-w-0 flex-1">
<Text className="text-3xs uppercase tracking-wide text-foreground-muted">
{relationshipLabel(edge, props.threadId)}
</Text>
<Text className="font-t3-medium text-sm text-foreground" numberOfLines={1}>
{node?.thread?.title ?? threadId}
</Text>
</View>
{availability ? (
<Text className="text-2xs text-foreground-muted">{availability}</Text>
) : (
<SymbolView
name="chevron.right"
size={12}
tintColor={iconColor}
type="monochrome"
/>
)}
</Pressable>
);
})}
</ScrollView>
{canMerge || canDetach ? (
<View className="mt-4 gap-2 border-t border-neutral-300/50 pt-4 dark:border-white/[0.08]">
{canMerge ? (
<Pressable
accessibilityRole="button"
disabled={busyAction !== null}
onPress={() => void merge()}
className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl bg-primary px-3"
>
{busyAction === "merge" ? (
<ActivityIndicator color="white" />
) : (
<SymbolView name="arrow.triangle.merge" size={14} tintColor="white" />
)}
<Text className="font-t3-medium text-sm text-primary-foreground">
Merge back to source
</Text>
</Pressable>
) : null}
{canDetach ? (
<Pressable
accessibilityRole="button"
disabled={busyAction !== null}
onPress={() => void detach()}
className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl border border-neutral-300/60 px-3 dark:border-white/[0.1]"
>
{busyAction === "detach" ? <ActivityIndicator /> : null}
<Text className="font-t3-medium text-sm text-foreground">
Disconnect agent session
</Text>
</Pressable>
) : null}
</View>
) : null}
</View>
</View>
</Modal>
</>
);
}
@@ -8,10 +8,6 @@ import {
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import * as Option from "effect/Option";
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
import {
requestOlderThreadTurns,
threadHasOlderTurns,
} from "@t3tools/client-runtime/state/threads";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -194,26 +190,36 @@ function ThreadRouteContent(
useThreadSelection();
const selectedThreadDetailState = props.selectedThreadDetailState;
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
// "Load earlier turns" header state for windowed (paginated) thread loads.
const loadEarlierTurns = useMemo(() => {
if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
return null;
}
return {
loading:
selectedThreadDetailState.page._tag === "Some" &&
selectedThreadDetailState.page.value.loadingOlder,
onLoadEarlier: () => {
requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
},
};
}, [selectedThread, selectedThreadDetailState]);
const { selectedThreadCwd } = useSelectedThreadWorktree();
const composer = useThreadComposerState();
const gitState = useSelectedThreadGitState();
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
label: "load earlier thread history",
reportFailure: false,
});
const historyControls = useMemo(() => {
const history = selectedThreadDetailState.history;
if (!selectedThread) {
return undefined;
}
if (!history.hasMoreHistory && history.error === null) {
return undefined;
}
return {
hasMoreHistory: history.hasMoreHistory,
loading: history.loading,
error: history.error,
onLoadEarlier: () => {
void loadEarlierHistory({
environmentId: selectedThread.environmentId,
input: { threadId: selectedThread.id },
});
},
};
}, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]);
const navigation = useNavigation();
const params = props.route.params;
const environmentIdRaw = firstRouteParam(params.environmentId);
@@ -325,7 +331,7 @@ function ThreadRouteContent(
}),
[knownTerminalSessions, selectedThreadProject?.workspaceRoot],
);
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
const handleReconnectEnvironment = useCallback(() => {
if (!environmentId) {
return;
@@ -479,23 +485,17 @@ function ThreadRouteContent(
void navigation.navigate("Connections");
}, [navigation]);
const handleStopThread = useCallback(() => {
if (
!selectedThread ||
(selectedThread.session?.status !== "running" &&
selectedThread.session?.status !== "starting")
) {
if (!selectedThread || composer.interruptibleRunId === null) {
return;
}
return interruptThreadTurn({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
...(selectedThread.session.activeTurnId
? { turnId: selectedThread.session.activeTurnId }
: {}),
runId: composer.interruptibleRunId,
},
});
}, [interruptThreadTurn, selectedThread]);
}, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
const handleOpenTerminal = useCallback(
(nextTerminalId?: string | null) => {
@@ -773,6 +773,7 @@ function ThreadRouteContent(
connectionError={routeConnectionError}
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
selectedThreadFeed={composer.selectedThreadFeed}
activityRun={composer.selectedThreadActivityRun}
activeWorkStartedAt={composer.activeWorkStartedAt}
activePendingApproval={requests.activePendingApproval}
respondingApprovalId={requests.respondingApprovalId}
@@ -784,7 +785,9 @@ function ThreadRouteContent(
draftAttachments={composer.draftAttachments}
connectionStateLabel={routeConnectionState}
threadSyncStatus={selectedThreadDetailState.status}
loadEarlier={loadEarlierTurns}
historyControls={historyControls}
activeThreadBusy={composer.activeThreadBusy}
canStopThread={composer.interruptibleRunId !== null}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
threadCwd={selectedThreadCwd}
@@ -29,10 +29,11 @@ import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2Status,
resolveThreadListV2SwipeActions,
threadHasUnseenCompletion,
type ThreadListV2Status,
} from "./threadListV2";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
@@ -59,6 +60,8 @@ const STATUS_LABEL_BY_STATUS: Partial<
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
input: { label: "Input", className: "text-indigo-600 dark:text-indigo-300" },
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
// Colorless like the web sidebar: parked on background work, not "act now".
waiting: { label: "Waiting", className: "text-foreground-tertiary" },
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
};
@@ -418,7 +421,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const selected = props.selected === true;
const status = resolveThreadListV2Status(thread);
const statusLabel = STATUS_LABEL_BY_STATUS[status];
// "Done" marks a completion the user has not opened yet — same emerald
// label as the web sidebar, sourced from the server-side visited watermark
// so checking a thread on any device clears it everywhere.
const isUnread = status === "ready" && threadHasUnseenCompletion(thread);
const statusLabel =
STATUS_LABEL_BY_STATUS[status] ??
(isUnread ? { label: "Done", className: "text-emerald-700 dark:text-emerald-300" } : undefined);
const timeLabel = threadTimeLabel(thread);
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
@@ -714,7 +723,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
</View>
) : null}
<View className="mt-1 flex-row items-center gap-2">
{status === "failed" && thread.session?.lastError ? (
{status === "failed" && thread.runtime?.lastError ? (
<Text
className={cn(
"flex-1 text-xs",
@@ -724,7 +733,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
)}
numberOfLines={1}
>
{thread.session.lastError}
{thread.runtime.lastError}
</Text>
) : thread.branch || props.environmentLabel ? (
/* "branch · machine" share one truncating line. The machine sits
@@ -0,0 +1,15 @@
import { describe, expect, it } from "vite-plus/test";
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
describe("thread work log overflow labels", () => {
it("describes tool-only groups as tool calls", () => {
expect(threadWorkLogOverflowNoun(true, 1)).toBe("tool call");
expect(threadWorkLogOverflowNoun(true, 2)).toBe("tool calls");
});
it("describes mixed groups as log entries", () => {
expect(threadWorkLogOverflowNoun(false, 1)).toBe("log entry");
expect(threadWorkLogOverflowNoun(false, 2)).toBe("log entries");
});
});
@@ -0,0 +1,9 @@
export function threadWorkLogOverflowNoun(
onlyToolRows: boolean,
count: number,
): "tool call" | "tool calls" | "log entry" | "log entries" {
if (onlyToolRows) {
return count === 1 ? "tool call" : "tool calls";
}
return count === 1 ? "log entry" : "log entries";
}
@@ -1,14 +1,22 @@
import * as Haptics from "expo-haptics";
import { Image } from "expo-image";
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useNavigation } from "@react-navigation/native";
import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { T3_CODE_BRAND_MARK_SOURCE } from "../../components/brandAssets";
import { scaledTypographyLineHeight } from "../../lib/appearancePreferences";
import { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import Animated, { FadeIn } from "react-native-reanimated";
import { useV2ItemSupport } from "../../state/v2-item-support";
import { ThreadActivityInspector } from "./ThreadActivityInspector";
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const WORK_LOG_LAYOUT_ANIMATION = {
duration: 180,
create: {
@@ -71,6 +79,87 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName {
}
}
function WorkRowIcon(props: {
readonly row: ThreadFeedActivity;
readonly iconSubtleColor: import("react-native").ColorValue;
}) {
const iconIsDestructive = props.row.icon === "alert" || props.row.icon === "warning";
if (props.row.logo === "t3-code") {
return (
<Image
source={T3_CODE_BRAND_MARK_SOURCE}
accessibilityIgnoresInvertColors
style={{
width: 16,
height: 16,
borderRadius: 4,
}}
/>
);
}
return (
<SymbolView
name={workRowSymbolName(props.row.icon)}
size={14}
weight="medium"
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
/>
);
}
function ThreadActivityThreadLink(props: {
readonly activity: ThreadFeedActivity;
readonly environmentId: EnvironmentId;
readonly iconColor: import("react-native").ColorValue;
}) {
const row = props.activity.projectedItem;
const support = useV2ItemSupport({
environmentId: props.environmentId,
sourceThreadId: row.sourceThreadId,
sourceItemId: row.sourceItemId,
});
const navigation = useNavigation();
const item = row.item;
let targetThreadId: ThreadId | null = null;
let label = "Open related thread";
if (item.type === "thread_created") {
targetThreadId = item.targetThreadId;
label = "Open created thread";
} else if (item.type === "subagent") {
targetThreadId = support.subagent?.childThreadId ?? item.childThreadId;
label = "Open subagent thread";
} else if (item.type === "fork") {
targetThreadId =
item.targetThreadId === row.sourceThreadId && item.source.type === "run"
? item.source.threadId
: item.targetThreadId;
label = targetThreadId === item.targetThreadId ? "Open forked thread" : "Open parent thread";
}
if (targetThreadId === null) return null;
return (
<Pressable
accessibilityRole="link"
accessibilityLabel={label}
onPress={() => {
void Haptics.selectionAsync();
navigation.navigate("Thread", {
environmentId: props.environmentId,
threadId: targetThreadId,
});
}}
className="mx-2 mb-2 min-h-9 flex-row items-center justify-center gap-1.5 rounded-lg border border-neutral-300/50 px-2 dark:border-white/[0.08]"
>
<Text className="font-t3-medium text-2xs text-foreground">{label}</Text>
<SymbolView name="arrow.right" size={11} tintColor={props.iconColor} type="monochrome" />
</Pressable>
);
}
// Entering fades only for rows created moments ago: rows remount whenever the
// list scrolls them back into view, and old rows must not replay an entrance.
const FRESH_ROW_WINDOW_MS = 3_000;
@@ -122,10 +211,15 @@ export function collapsedWorkLogHeight(
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
readonly currentThreadId: ThreadId;
readonly environmentId: EnvironmentId;
readonly expanded: boolean;
readonly expandedRows: Readonly<Record<string, boolean>>;
readonly iconSubtleColor: import("react-native").ColorValue;
readonly onCopyRow: (rowId: string, value: string) => void;
readonly onToggleGroup: () => void;
readonly onToggleRow: (rowId: string) => void;
readonly workspaceRoot?: string | null;
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
@@ -138,10 +232,15 @@ export function ThreadWorkLog(props: {
return null;
}
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
const visibleRows =
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
const hiddenCount = rows.length - visibleRows.length;
const onlyToolRows = rows.every((row) => row.toolLike);
const overflowNoun = threadWorkLogOverflowNoun(onlyToolRows, hiddenCount);
return (
<View className="-mx-1 mb-1 px-1 py-0">
<View className="-mx-1 mb-3 px-1 py-0.5">
{!onlyToolRows ? (
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
work log
@@ -149,17 +248,21 @@ export function ThreadWorkLog(props: {
) : null}
<View className="gap-px">
{rows.map((row) => {
{visibleRows.map((row) => {
const expanded = props.expandedRows[row.id] ?? false;
const canExpand = row.canExpand;
const fullDetail = expanded ? row.getFullDetail() : null;
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
const detail = compactActivityDetail(row.detail);
const displayText = detail ? `${row.summary} ${detail}` : row.summary;
const textIsDestructive = row.icon === "alert" || row.icon === "warning";
return (
<Animated.View
key={row.id}
{...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
className={cn(
row.prominent &&
"mb-2 overflow-hidden rounded-xl border border-neutral-300/60 bg-card dark:border-white/[0.1]",
)}
>
<Pressable
accessibilityRole={canExpand ? "button" : undefined}
@@ -181,30 +284,24 @@ export function ThreadWorkLog(props: {
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="rounded-md px-0.5 py-0"
className="rounded-md px-0.5 py-0.5"
>
<View className="min-h-8 flex-row items-center gap-1.5">
<View className="h-[18px] w-5 shrink-0 items-center justify-center">
<SymbolView
name={workRowSymbolName(row.icon)}
size={13}
weight="medium"
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
/>
<View className="min-h-9 flex-row items-center gap-1.5">
<View className="h-5 w-5 shrink-0 items-center justify-center">
<WorkRowIcon row={row} iconSubtleColor={props.iconSubtleColor} />
</View>
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
<Text
className={cn(
"font-t3-medium text-foreground",
iconIsDestructive && "text-rose-600 dark:text-rose-400",
textIsDestructive && "text-rose-600 dark:text-rose-400",
)}
>
{row.summary}
</Text>
{row.detail ? (
<Text className="text-foreground-muted opacity-60"> {row.detail}</Text>
{detail ? (
<Text className="text-foreground-muted opacity-60"> {detail}</Text>
) : null}
</Text>
@@ -248,28 +345,63 @@ export function ThreadWorkLog(props: {
</View>
</Pressable>
{fullDetail ? (
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
<ScrollView
nestedScrollEnabled
directionalLockEnabled
showsVerticalScrollIndicator
className="max-h-60"
contentContainerStyle={{ paddingRight: 8 }}
>
<Text
selectable
className="font-mono text-2xs leading-normal text-foreground-muted"
>
{fullDetail}
</Text>
</ScrollView>
{expanded && canExpand ? (
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
<ThreadActivityInspector
activity={row}
currentThreadId={props.currentThreadId}
environmentId={props.environmentId}
iconColor={props.iconSubtleColor}
workspaceRoot={props.workspaceRoot}
/>
</View>
) : null}
{row.prominent ? (
<ThreadActivityThreadLink
activity={row}
environmentId={props.environmentId}
iconColor={props.iconSubtleColor}
/>
) : null}
</Animated.View>
);
})}
</View>
{hasOverflow ? (
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={
props.expanded
? `Show fewer ${overflowNoun}`
: `Show ${hiddenCount} previous ${overflowNoun}`
}
hitSlop={4}
onPress={() => {
triggerDisclosureFeedback();
props.onToggleGroup();
}}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
>
<View className="h-5 w-5 items-center justify-center">
<SymbolView
name={props.expanded ? "chevron.up" : "chevron.down"}
size={13}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text className="font-t3-medium text-xs text-foreground opacity-80">
{props.expanded
? `Show fewer ${overflowNoun}`
: `+${hiddenCount} previous ${overflowNoun}`}
</Text>
</Pressable>
) : null}
</View>
);
}
@@ -283,48 +415,36 @@ export function ThreadWorkGroupToggle(props: {
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
const noun = props.onlyToolActivities
? props.hiddenCount === 1
? "tool call"
: "tool calls"
: props.hiddenCount === 1
? "log entry"
: "log entries";
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
const expandedLabel = props.onlyToolActivities
? "Show fewer tool calls"
: "Show fewer log entries";
const noun = threadWorkLogOverflowNoun(props.onlyToolActivities, props.hiddenCount);
return (
<View className="-mx-1 mb-1 px-1 py-0">
<View className="-mx-1 mb-1 px-1">
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
accessibilityLabel={
props.expanded ? `Show fewer ${noun}` : `Show ${props.hiddenCount} previous ${noun}`
}
hitSlop={4}
onPress={() => {
void Haptics.selectionAsync();
triggerDisclosureFeedback();
props.onToggle();
}}
style={({ pressed }) => ({
backgroundColor: pressed ? pressedBackground : "transparent",
})}
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5"
>
<View className="h-[18px] w-5 items-center justify-center">
<SymbolView
name={
props.expanded
? { ios: "chevron.up", android: "keyboard_arrow_up" }
: { ios: "chevron.down", android: "keyboard_arrow_down" }
}
name={props.expanded ? "chevron.up" : "chevron.down"}
size={12}
tintColor={props.iconSubtleColor}
type="monochrome"
/>
</View>
<Text className="font-t3-medium text-xs text-foreground opacity-80">
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
{props.expanded ? `Show fewer ${noun}` : `+${props.hiddenCount} previous ${noun}`}
</Text>
</Pressable>
</View>
@@ -0,0 +1,26 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import { buildThreadActivityFileParams } from "./threadActivityFileNavigation";
describe("thread activity file navigation", () => {
it("keeps inherited activity file links on the currently selected thread", () => {
const sourceThreadId = ThreadId.make("source-thread");
const currentThreadId = ThreadId.make("current-thread");
const params = buildThreadActivityFileParams({
environmentId: EnvironmentId.make("environment"),
currentThreadId,
activitySourceThreadId: sourceThreadId,
relativePath: "apps/mobile/src/index.ts",
line: 12,
});
expect(params).toEqual({
environmentId: "environment",
threadId: "current-thread",
path: ["apps", "mobile", "src", "index.ts"],
line: "12",
});
});
});
@@ -0,0 +1,22 @@
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
interface ThreadActivityFileContext {
readonly environmentId: EnvironmentId;
readonly currentThreadId: ThreadId;
readonly activitySourceThreadId: ThreadId;
readonly relativePath: string;
readonly line?: number | null;
}
export function buildThreadActivityFileParams(input: ThreadActivityFileContext) {
// Activity provenance may come from a parent thread, but file routes stay scoped
// to the thread whose workspace is currently selected.
return {
environmentId: String(input.environmentId),
threadId: String(input.currentThreadId),
path: input.relativePath.split("/").filter((segment) => segment.length > 0),
...(Number.isFinite(input.line) && Number(input.line) > 0
? { line: String(Math.floor(Number(input.line))) }
: {}),
};
}
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vite-plus/test";
import { waitForThreadShellReady } from "./threadForkNavigation";
describe("waitForThreadShellReady", () => {
it("returns true when the forked thread shell arrives before the deadline", async () => {
let elapsedMs = 0;
const ready = await waitForThreadShellReady({
read: () => elapsedMs >= 80,
timeoutMs: 120,
pollIntervalMs: 40,
now: () => elapsedMs,
delay: async (durationMs) => {
elapsedMs += durationMs;
},
});
expect(ready).toBe(true);
});
it("returns false instead of navigating when the shell never arrives", async () => {
let elapsedMs = 0;
const ready = await waitForThreadShellReady({
read: () => false,
timeoutMs: 80,
pollIntervalMs: 40,
now: () => elapsedMs,
delay: async (durationMs) => {
elapsedMs += durationMs;
},
});
expect(ready).toBe(false);
expect(elapsedMs).toBe(80);
});
});
@@ -0,0 +1,26 @@
const DEFAULT_TIMEOUT_MS = 2_000;
const DEFAULT_POLL_INTERVAL_MS = 40;
export async function waitForThreadShellReady(input: {
readonly read: () => boolean;
readonly timeoutMs?: number;
readonly pollIntervalMs?: number;
readonly now?: () => number;
readonly delay?: (durationMs: number) => Promise<void>;
}): Promise<boolean> {
const now = input.now ?? Date.now;
const delay =
input.delay ??
((durationMs: number) =>
new Promise<void>((resolve) => {
setTimeout(resolve, durationMs);
}));
const deadline = now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS);
const pollIntervalMs = input.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
while (!input.read() && now() < deadline) {
await delay(Math.min(pollIntervalMs, deadline - now()));
}
return input.read();
}
@@ -7,12 +7,13 @@ import {
MessageId,
ProjectId,
ProviderInstanceId,
RunId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { makeThreadShellFixture } from "../../test-fixtures";
import {
buildThreadListV2Items,
buildThreadListV2ListItems,
@@ -29,27 +30,10 @@ const environmentId = EnvironmentId.make("environment-1");
function makeThread(
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
): EnvironmentThreadShell {
return {
return makeThreadShellFixture({
environmentId,
projectId: ProjectId.make("project-1"),
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
};
});
}
const NOW = "2026-06-02T00:00:00.000Z";
@@ -126,18 +110,16 @@ describe("resolveThreadListV2Enabled", () => {
});
describe("resolveThreadListV2Status", () => {
it("prioritizes approval over a running session", () => {
it("prioritizes approval over a running runtime", () => {
const thread = makeThread({
id: ThreadId.make("t"),
title: "t",
hasPendingApprovals: true,
session: {
threadId: ThreadId.make("t"),
runtime: {
status: "running",
activeRunId: RunId.make("run-t"),
providerName: "Codex",
providerInstanceId: ProviderInstanceId.make("codex"),
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: NOW,
},
@@ -145,6 +127,26 @@ describe("resolveThreadListV2Status", () => {
expect(resolveThreadListV2Status(thread)).toBe("approval");
});
it("reports waiting when presentation parks runtime idle for background tasks", () => {
expect(
resolveThreadListV2Status(
makeThread({
id: ThreadId.make("t"),
title: "t",
pendingBackgroundTasks: [{ taskId: "bg-1", description: "Run Codex review" }],
runtime: {
status: "idle",
activeRunId: null,
providerInstanceId: ProviderInstanceId.make("codex"),
providerName: "Codex",
lastError: null,
updatedAt: NOW,
},
}),
),
).toBe("waiting");
});
it("resolves ready for quiescent threads", () => {
expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe(
"ready",
@@ -263,6 +265,68 @@ describe("sortThreadsForListV2", () => {
});
describe("buildThreadListV2Items", () => {
it("excludes subagent child threads from top-level rows and counts", () => {
const rootThreadId = ThreadId.make("root");
const activeChildId = ThreadId.make("active-child");
const forkId = ThreadId.make("fork");
const settledChildId = ThreadId.make("settled-child");
const snoozedChildId = ThreadId.make("snoozed-child");
const layout = buildThreadListV2Items({
threads: [
makeThread({ id: rootThreadId, title: "Root" }),
makeThread({
id: forkId,
title: "Fork",
lineage: {
rootThreadId,
parentThreadId: rootThreadId,
relationshipToParent: "fork",
},
}),
makeThread({
id: activeChildId,
title: "Active child",
lineage: {
rootThreadId,
parentThreadId: rootThreadId,
relationshipToParent: "subagent",
},
}),
makeThread({
id: settledChildId,
title: "Settled child",
lineage: {
rootThreadId,
parentThreadId: rootThreadId,
relationshipToParent: "subagent",
},
settledOverride: "settled",
settledAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: snoozedChildId,
title: "Snoozed child",
lineage: {
rootThreadId,
parentThreadId: rootThreadId,
relationshipToParent: "subagent",
},
snoozedUntil: "2026-06-03T09:00:00.000Z",
snoozedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
now: NOW,
settledLimit: 0,
});
expect(layout.items.map((item) => item.thread.id)).toEqual([forkId, rootThreadId]);
expect(layout.hiddenSettledCount).toBe(0);
expect(layout.snoozedCount).toBe(0);
expect(layout.nextSnoozeWakeAt).toBeNull();
});
it("keeps a merged thread active when auto-settle on merge is off", () => {
const merged = makeThread({ id: ThreadId.make("merged"), title: "Merged" });
const layout = buildThreadListV2Items({
@@ -645,10 +709,11 @@ describe("buildThreadListV2Items", () => {
});
it("scopes the flat list to one project", () => {
const projectId = ProjectId.make("project-1");
const otherProjectId = ProjectId.make("project-2");
const { items } = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("included"), title: "Included" }),
makeThread({ id: ThreadId.make("included"), projectId, title: "Included" }),
makeThread({
id: ThreadId.make("excluded"),
projectId: otherProjectId,
@@ -656,7 +721,7 @@ describe("buildThreadListV2Items", () => {
}),
],
environmentId: null,
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
projectRefs: [{ environmentId, projectId }],
searchQuery: "",
now: NOW,
});
@@ -666,19 +731,21 @@ describe("buildThreadListV2Items", () => {
it("scopes the flat list to every environment member of a logical project", () => {
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const projectId = ProjectId.make("project-1");
const { items } = buildThreadListV2Items({
threads: [
makeThread({ id: ThreadId.make("local"), title: "Local" }),
makeThread({ id: ThreadId.make("local"), projectId, title: "Local" }),
makeThread({
environmentId: remoteEnvironmentId,
id: ThreadId.make("remote"),
projectId,
title: "Remote",
}),
],
environmentId: null,
projectRefs: [
{ environmentId, projectId: ProjectId.make("project-1") },
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
{ environmentId, projectId },
{ environmentId: remoteEnvironmentId, projectId },
],
searchQuery: "",
now: NOW,
@@ -701,9 +768,9 @@ describe("buildThreadListV2Items settled paging", () => {
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
// A turn adopted the message (same requestedAt): without it the
// thread reads as a queued turn start, which never settles.
latestTurn: {
turnId: TurnId.make(`turn-${index}`),
state: "completed",
latestRun: {
runId: RunId.make(`run-${index}`),
status: "completed",
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
startedAt: `2026-06-01T0${index}:00:00.000Z`,
completedAt: `2026-06-01T0${index}:10:00.000Z`,
@@ -20,11 +20,13 @@ export { snoozeWakeLabel };
* Thread List v2 model, ported from the web sidebar v2
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
*
* Four visual states, three colors: color is reserved for "act now"
* (approval), "in motion" (working), and "broken" (failed). Ready is the
* unlabeled resting state.
* Six visual states. Color distinguishes approval, input, active work, and
* failures. Ready is the unlabeled resting state; waiting (runtime status "idle") is the agent
* parked on open background tasks, grey like working rather than a false Done.
* The orchestrator v2 presentation bridge parks runtime at idle when the
* post-settlement background roster is nonempty.
*/
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
export type ThreadListV2Status = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
export function resolveThreadListV2SnoozeMenuSelection(input: {
@@ -85,7 +87,7 @@ export function resolveThreadListV2SwipeActions(input: {
export function resolveThreadListV2SnoozeGateExpiryMs(
thread: Pick<
EnvironmentThreadShell,
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
"hasPendingApprovals" | "hasPendingUserInput" | "latestRun" | "latestUserMessageAt" | "runtime"
>,
options: { readonly now: string },
): number | null {
@@ -122,8 +124,29 @@ export function resolveThreadListV2Enabled(input: {
return input.legacyPreference !== true;
}
/**
* Completed-but-not-yet-seen, mirroring the web sidebar's
* hasUnseenCompletion. The visited watermark is server state
* (thread.lastVisitedAt), so the marker agrees across web and mobile.
* Never-visited threads count as read — a fresh environment must not light
* up its whole history — and pre-tracking servers (field absent) never
* report unread.
*/
export function threadHasUnseenCompletion(
thread: Pick<EnvironmentThreadShell, "latestRun" | "lastVisitedAt">,
): boolean {
const completedAt = thread.latestRun?.completedAt;
if (!completedAt) return false;
const completedAtMs = Date.parse(completedAt);
if (Number.isNaN(completedAtMs)) return false;
if (!thread.lastVisitedAt) return false;
const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAtMs)) return true;
return completedAtMs > lastVisitedAtMs;
}
export function resolveThreadListV2Status(
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "runtime">,
): ThreadListV2Status {
if (thread.hasPendingApprovals) {
return "approval";
@@ -131,10 +154,16 @@ export function resolveThreadListV2Status(
if (thread.hasPendingUserInput) {
return "input";
}
if (thread.session?.status === "running" || thread.session?.status === "starting") {
if (
thread.runtime !== null &&
["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
) {
return "working";
}
if (thread.session?.status === "error") {
if (thread.runtime?.status === "idle") {
return "waiting";
}
if (thread.runtime?.status === "failed") {
return "failed";
}
return "ready";
@@ -361,6 +390,7 @@ export function buildThreadListV2Items(input: {
const snoozed: EnvironmentThreadShell[] = [];
let nextSnoozeWakeAt: string | null = null;
for (const thread of input.threads) {
if (thread.lineage.relationshipToParent === "subagent") continue;
// Callers pass live (unarchived) shells; settled threads are among them
// and partition into the tail via effectiveSettled.
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
@@ -1,6 +1,8 @@
import type { StatusTone } from "../../components/StatusPill";
import type { OrchestrationLatestTurn, OrchestrationSession } from "@t3tools/contracts";
import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
threadRuntimeIsActive,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
export function threadSortValue(thread: EnvironmentThreadShell): number {
const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
@@ -31,14 +33,10 @@ export const THREAD_STATUS_NEUTRAL_ICON = {
iconBackground: "rgba(142,142,147,0.22)",
} as const;
function isLatestTurnSettled(
latestTurn: OrchestrationLatestTurn | null,
session: OrchestrationSession | null,
): boolean {
if (!latestTurn?.startedAt) return false;
if (!latestTurn.completedAt) return false;
if (!session) return true;
return session.status !== "running";
function isLatestRunSettled(thread: EnvironmentThreadShell): boolean {
if (!thread.latestRun?.startedAt) return false;
if (!thread.latestRun.completedAt) return false;
return !threadRuntimeIsActive(thread.runtime);
}
/**
@@ -73,7 +71,9 @@ export function resolveThreadStatus(
};
}
if (thread.session?.status === "running") {
const runtimeStatus = thread.runtime?.status;
if (runtimeStatus === "running" || runtimeStatus === "waiting") {
return {
kind: "working",
label: "Working",
@@ -85,7 +85,7 @@ export function resolveThreadStatus(
};
}
if (thread.session?.status === "starting") {
if (runtimeStatus === "preparing" || runtimeStatus === "queued" || runtimeStatus === "starting") {
return {
kind: "connecting",
label: "Connecting",
@@ -97,7 +97,7 @@ export function resolveThreadStatus(
};
}
if (thread.session?.status === "error" || thread.latestTurn?.state === "error") {
if (runtimeStatus === "failed" || thread.latestRun?.status === "failed") {
return {
kind: "error",
label: "Error",
@@ -111,7 +111,7 @@ export function resolveThreadStatus(
const hasPlanReadyPrompt =
thread.interactionMode === "plan" &&
isLatestTurnSettled(thread.latestTurn, thread.session) &&
isLatestRunSettled(thread) &&
thread.hasActionableProposedPlan;
if (hasPlanReadyPrompt) {
return {
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vite-plus/test";
import {
REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
buildCancelQueuedRunCommand,
resolveThreadQueueRowControls,
} from "./threadQueueControlPresentation";
describe("threadQueueControlPresentation", () => {
it("preserves queue reorder and steer controls with removal", () => {
const controls = resolveThreadQueueRowControls({
busy: false,
canPromoteToSteer: true,
canReorder: true,
index: 1,
queuedCount: 3,
text: "Please review the follow-up change.",
});
expect(controls.displayText).toBe("Please review the follow-up change.");
expect(controls.canMoveUp).toBe(true);
expect(controls.canMoveDown).toBe(true);
expect(controls.canSteer).toBe(true);
expect(controls.canDismiss).toBe(true);
expect(controls.dismissAccessibilityLabel).toBe(REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL);
});
it("disables edge reorder controls and busy dismissal", () => {
const first = resolveThreadQueueRowControls({
busy: false,
canPromoteToSteer: false,
canReorder: true,
index: 0,
queuedCount: 2,
text: "First",
});
const busy = resolveThreadQueueRowControls({
busy: true,
canPromoteToSteer: true,
canReorder: true,
index: 0,
queuedCount: 1,
text: "Queued message",
});
expect(first.canMoveUp).toBe(false);
expect(first.canMoveDown).toBe(true);
expect(first.canSteer).toBe(false);
expect(busy.canDismiss).toBe(false);
expect(busy.canMoveUp).toBe(false);
expect(busy.canSteer).toBe(false);
});
it("builds cancelQueuedRun command arguments for removal", () => {
expect(
buildCancelQueuedRunCommand({
environmentId: "environment:test" as never,
runId: "run:queued" as never,
threadId: "thread:test" as never,
}),
).toEqual({
environmentId: "environment:test",
input: {
runId: "run:queued",
threadId: "thread:test",
},
});
});
});
@@ -0,0 +1,52 @@
import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
export const REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL = "Remove queued message";
export interface ThreadQueueRowControls {
readonly canDismiss: boolean;
readonly canMoveDown: boolean;
readonly canMoveUp: boolean;
readonly canSteer: boolean;
readonly dismissAccessibilityLabel: string;
readonly displayText: string;
}
export function resolveThreadQueueRowControls(input: {
readonly busy: boolean;
readonly canPromoteToSteer: boolean;
readonly canReorder: boolean;
readonly index: number;
readonly queuedCount: number;
readonly text: string;
}): ThreadQueueRowControls {
const mutationEnabled = !input.busy;
return {
canDismiss: !input.busy,
canMoveDown: mutationEnabled && input.canReorder && input.index < input.queuedCount - 1,
canMoveUp: mutationEnabled && input.canReorder && input.index > 0,
canSteer: mutationEnabled && input.canPromoteToSteer,
dismissAccessibilityLabel: REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
displayText: input.text,
};
}
export function buildCancelQueuedRunCommand(input: {
readonly environmentId: EnvironmentId;
readonly runId: RunId;
readonly threadId: ThreadId;
}): {
readonly environmentId: EnvironmentId;
readonly input: {
readonly runId: RunId;
readonly threadId: ThreadId;
};
} {
return {
environmentId: input.environmentId,
input: {
runId: input.runId,
threadId: input.threadId,
},
};
}
@@ -0,0 +1,34 @@
import { describe, expect, it } from "@effect/vitest";
import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
describe("user message intent badge", () => {
it("does not label ordinary turn-start messages", () => {
expect(resolveUserMessageIntentBadge(undefined)).toBeNull();
expect(resolveUserMessageIntentBadge("turn_start")).toBeNull();
});
it("labels messages waiting behind the active turn", () => {
expect(resolveUserMessageIntentBadge("queued_turn")).toEqual({
label: "queued",
accessibilityLabel: "Queued behind the active turn",
tone: "queued",
});
});
it("labels messages that steer the active turn", () => {
expect(resolveUserMessageIntentBadge("steer")).toEqual({
label: "steer",
accessibilityLabel: "Steered the active turn",
tone: "steer",
});
});
it("preserves the queued origin after promotion to steer", () => {
expect(resolveUserMessageIntentBadge("promoted_queued_to_steer")).toEqual({
label: "queued → steer",
accessibilityLabel: "Originally queued, then promoted to steer the active turn",
tone: "steer",
});
});
});
@@ -0,0 +1,35 @@
import type { OrchestrationV2UserMessageInputIntent } from "@t3tools/contracts";
export interface UserMessageIntentBadgePresentation {
readonly label: string;
readonly accessibilityLabel: string;
readonly tone: "queued" | "steer";
}
export function resolveUserMessageIntentBadge(
intent: OrchestrationV2UserMessageInputIntent | undefined,
): UserMessageIntentBadgePresentation | null {
switch (intent) {
case "queued_turn":
return {
label: "queued",
accessibilityLabel: "Queued behind the active turn",
tone: "queued",
};
case "steer":
return {
label: "steer",
accessibilityLabel: "Steered the active turn",
tone: "steer",
};
case "promoted_queued_to_steer":
return {
label: "queued → steer",
accessibilityLabel: "Originally queued, then promoted to steer the active turn",
tone: "steer",
};
case "turn_start":
case undefined:
return null;
}
}
+51
View File
@@ -1,3 +1,4 @@
import type { MenuAction } from "@react-native-menu/menu";
import type {
ModelCapabilities,
ModelSelection,
@@ -187,3 +188,53 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
models: group.models,
}));
}
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
return {
id: `model:${option.key}`,
title: option.label,
state:
option.selection.instanceId === selectedModel?.instanceId &&
option.selection.model === selectedModel.model
? "on"
: undefined,
};
}
export function buildModelMenuActions(
groups: ReadonlyArray<ProviderGroup>,
selectedModel: ModelSelection | null,
): MenuAction[] {
return groups.flatMap((group) => {
const currentModels = group.models.filter((model) => !model.isLegacy);
const legacyModels = group.models.filter((model) => model.isLegacy);
const selected = group.models.find(
(model) =>
model.selection.instanceId === selectedModel?.instanceId &&
model.selection.model === selectedModel.model,
);
return [
...(currentModels.length > 0
? [
{
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: selected && !selected.isLegacy ? selected.label : undefined,
subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
...(legacyModels.length > 0
? [
{
id: `legacy-models:${group.providerKey}`,
title: `${group.providerLabel} legacy models`,
subtitle: selected?.isLegacy ? selected.label : undefined,
subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
];
});
}
+13 -11
View File
@@ -7,19 +7,10 @@ import {
type ProviderInteractionMode,
type RuntimeMode,
} from "@t3tools/contracts";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
export function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
if (trimmed.length === 0) {
return "New thread";
}
const compact = trimmed.replace(/\s+/g, " ");
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
}
export interface ProjectThreadStartTurnSpec {
readonly projectId: ProjectId;
readonly projectCwd: string;
@@ -46,10 +37,11 @@ export interface ProjectThreadStartTurnSpec {
* offline outbox drain so both deliver identical commands.
*/
export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpec) {
const title = deriveThreadTitleFromPrompt(spec.text);
const title = deriveThreadTitleSeed({ text: spec.text, attachments: spec.attachments });
const isWorktree = spec.workspaceMode === "worktree";
return {
commandId: CommandId.make(spec.commandId),
creationSource: "mobile" as const,
threadId: ThreadId.make(spec.threadId),
message: {
messageId: MessageId.make(spec.messageId),
@@ -87,3 +79,13 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
createdAt: spec.createdAt,
};
}
export function deriveThreadTitleFromPrompt(value: string): string {
const trimmed = value.trim();
if (trimmed.length === 0) {
return "New thread";
}
const compact = trimmed.replace(/\s+/g, " ");
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
}
+2 -2
View File
@@ -1,4 +1,4 @@
import { ApprovalRequestId, EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
import { EnvironmentId, ProjectId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
export function scopedProjectKey(environmentId: EnvironmentId, projectId: ProjectId): string {
return `${environmentId}:${projectId}`;
@@ -10,7 +10,7 @@ export function scopedThreadKey(environmentId: EnvironmentId, threadId: ThreadId
export function scopedRequestKey(
environmentId: EnvironmentId,
requestId: ApprovalRequestId,
requestId: RuntimeRequestId,
): string {
return `${environmentId}:${requestId}`;
}
+407 -566
View File
@@ -1,27 +1,419 @@
import {
MessageId,
RunId,
ThreadId,
TurnItemId,
type OrchestrationV2ProjectedTurnItem,
type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
import {
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
type OrchestrationThread,
type OrchestrationThreadActivity,
} from "@t3tools/contracts";
import {
buildPendingUserInputAnswers,
buildThreadFeed,
deriveThreadFeedPresentation,
isPendingUserInputOptionSelected,
setPendingUserInputCustomAnswer,
togglePendingUserInputOptionSelection,
threadFeedRunIsUnsettled,
type ThreadFeedActivity,
type ThreadFeedEntry,
togglePendingUserInputOptionSelection,
setPendingUserInputCustomAnswer,
isPendingUserInputOptionSelected,
buildPendingUserInputAnswers,
} from "./threadActivity";
const threadId = ThreadId.make("thread-1");
const sourceThreadId = ThreadId.make("thread-source");
const runId = RunId.make("run-1");
function base(id: string, updatedAt: string, ordinal: number) {
const timestamp = DateTime.makeUnsafe(updatedAt);
return {
id: TurnItemId.make(id),
threadId,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal,
status: "completed" as const,
title: null,
startedAt: timestamp,
completedAt: timestamp,
updatedAt: timestamp,
};
}
function projected(
item: OrchestrationV2TurnItem,
position: number,
visibility: OrchestrationV2ProjectedTurnItem["visibility"] = "local",
): OrchestrationV2ProjectedTurnItem {
return {
position,
visibility,
sourceThreadId: visibility === "local" ? threadId : sourceThreadId,
sourceItemId: item.id,
item,
};
}
function userMessage(updatedAt = "2026-06-20T00:00:01.000Z") {
return {
...base("item-user", updatedAt, 0),
type: "user_message" as const,
messageId: MessageId.make("message-user"),
createdBy: "user" as const,
creationSource: "mobile" as const,
inputIntent: "turn_start" as const,
text: "Run checks",
attachments: [],
};
}
function command(updatedAt = "2026-06-20T00:00:02.000Z") {
return {
...base("item-command", updatedAt, 1),
type: "command_execution" as const,
input: "vp check",
output: "ok",
exitCode: 0,
};
}
function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") {
return {
...base("item-assistant", updatedAt, 2),
type: "assistant_message" as const,
messageId: MessageId.make("message-assistant"),
text: "Done",
streaming: false,
};
}
describe("buildThreadFeed", () => {
it("hides synthetic workspace preparation activity", () => {
const workspacePreparation = projected(
{
...command(),
title: "Workspace ready",
input: "Preparing workspace",
output: "Workspace preparation completed.",
},
0,
);
expect(buildThreadFeed([workspacePreparation])).toEqual([]);
});
it("does not treat a queued-only run as live feed activity", () => {
expect(
threadFeedRunIsUnsettled({
runId,
status: "queued",
startedAt: null,
completedAt: null,
}),
).toBe(false);
expect(
threadFeedRunIsUnsettled({
runId,
status: "running",
startedAt: "2026-06-20T00:00:01.000Z",
completedAt: null,
}),
).toBe(true);
});
it("adds queued input only after dispatch creates its turn item", () => {
const dispatchedRunId = RunId.make("run-dispatched-queued");
const dispatchedMessageId = MessageId.make("message-dispatched-queued");
expect(buildThreadFeed([])).toEqual([]);
const promotedEntries = buildThreadFeed([
projected(
{
...userMessage(),
id: TurnItemId.make("item-dispatched-queued"),
runId: dispatchedRunId,
messageId: dispatchedMessageId,
inputIntent: "turn_start",
},
0,
),
]);
expect(promotedEntries.map((entry) => entry.id)).toEqual([dispatchedMessageId]);
expect(
promotedEntries[0]?.type === "message" ? promotedEntries[0].message.inputIntent : undefined,
).toBe("turn_start");
});
it("hides the interruption request and keeps the terminal result", () => {
const request = projected(
{
...base("item-interrupt-request", "2026-06-20T00:00:02.000Z", 1),
type: "run_interrupt_request",
message: "Interrupt requested",
},
0,
);
const result = projected(
{
...base("item-interrupt-result", "2026-06-20T00:00:03.000Z", 2),
type: "run_interrupt_result",
message: "Run interrupted before provider start",
},
1,
);
const activities = buildThreadFeed([request, result]).flatMap((entry) =>
entry.type === "activity-group" ? entry.activities : [],
);
expect(activities).toHaveLength(1);
expect(activities[0]?.summary).toBe("Run interrupted");
expect(activities[0]?.detail).toBe("Run interrupted before provider start");
});
it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
const rows = [
projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
projected(command("2026-06-20T00:00:01.000Z"), 1),
projected(assistantMessage("2026-06-20T00:00:02.000Z"), 2),
];
const feed = buildThreadFeed(rows);
expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
expect(feed.map((entry) => entry.id)).toEqual([
"message-user",
"local:thread-1:item-command",
"message-assistant",
]);
const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
expect(activity?.projectedItem).toBe(rows[1]);
expect(activity?.getFullDetail()).toContain('"input": "vp check"');
});
it("retains inherited and synthetic rows with their original projected identity", () => {
const inherited = projected(command(), 0, "inherited");
const { providerThreadId: _providerThreadId, ...forkBase } = base(
"item-fork",
"2026-06-20T00:00:03.000Z",
2,
);
const synthetic = projected(
{
...forkBase,
type: "fork",
source: { type: "run", threadId: sourceThreadId, runId },
targetThreadId: threadId,
},
1,
"synthetic",
);
const feed = buildThreadFeed([inherited, synthetic]);
const activities = feed.flatMap((entry) =>
entry.type === "activity-group" ? entry.activities : [],
);
expect(activities.map((activity) => activity.projectedItem)).toEqual([inherited, synthetic]);
expect(activities.map((activity) => activity.projectedItem.visibility)).toEqual([
"inherited",
"synthetic",
]);
expect(activities.at(-1)?.prominent).toBe(true);
});
it("keeps orchestration relationship cards visible when a completed run is folded", () => {
const { providerThreadId: _providerThreadId, ...forkBase } = base(
"item-fork",
"2026-06-20T00:00:02.500Z",
2,
);
const feed = buildThreadFeed([
projected(userMessage(), 0),
projected(command(), 1),
projected(
{
...forkBase,
type: "fork",
source: { type: "run", threadId, runId },
targetThreadId: sourceThreadId,
},
2,
),
projected(assistantMessage(), 3),
]);
const collapsed = deriveThreadFeedPresentation(
feed,
{
runId,
status: "completed",
startedAt: "2026-06-20T00:00:01.000Z",
completedAt: "2026-06-20T00:00:03.000Z",
},
new Set(),
);
expect(
collapsed.some(
(entry) =>
entry.type === "activity-group" &&
entry.activities.some((activity) => activity.projectedItem.item.type === "fork"),
),
).toBe(true);
expect(
collapsed.some(
(entry) =>
entry.type === "activity-group" &&
entry.activities.some(
(activity) => activity.projectedItem.item.type === "command_execution",
),
),
).toBe(false);
});
it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
const feed = buildThreadFeed([
projected(userMessage(), 0),
projected(command(), 1),
projected(assistantMessage(), 2),
]);
const latestRun = {
runId,
status: "completed" as const,
startedAt: "2026-06-20T00:00:01.000Z",
completedAt: "2026-06-20T00:00:03.000Z",
};
const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
expect(collapsed.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
expect(expanded.map((entry) => entry.type)).toEqual([
"message",
"run-fold",
"activity-group",
"message",
]);
});
it("keeps an active run expanded and marks failed tools as failures", () => {
const failedCommand: OrchestrationV2TurnItem = {
...command(),
status: "failed",
completedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
};
const feed = buildThreadFeed([projected(userMessage(), 0), projected(failedCommand, 1)]);
const presented = deriveThreadFeedPresentation(
feed,
{
runId,
status: "running",
startedAt: "2026-06-20T00:00:01.000Z",
completedAt: null,
},
new Set(),
);
expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
expect(presented.find((entry) => entry.type === "activity-group")?.activities[0]?.status).toBe(
"failure",
);
});
it("appends active work as a normal timeline row", () => {
const startedAt = "2026-04-01T00:00:01.000Z";
const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
expect(presented).toEqual([
{
type: "working",
id: "working-indicator-row",
createdAt: startedAt,
},
]);
expect(deriveThreadFeedPresentation(presented, null, new Set())).toEqual([]);
});
it("models work-log overflow as list rows", () => {
const activity = (
id: string,
createdAt: string,
status: ThreadFeedActivity["status"] = "success",
): ThreadFeedActivity => ({
id,
createdAt,
runId: null,
summary: `Tool ${id}`,
detail: null,
canExpand: false,
getFullDetail: () => null,
getCopyText: () => id,
icon: "command",
logo: null,
toolLike: true,
prominent: false,
status,
projectedItem: projected(command(createdAt), 0),
});
const feed: ThreadFeedEntry[] = [
{
type: "activity-group",
id: "work-group-1",
createdAt: "2026-04-01T00:00:01.000Z",
runId: null,
activities: [
activity("activity-1", "2026-04-01T00:00:01.000Z"),
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
activity("activity-2", "2026-04-01T00:00:03.000Z"),
activity("activity-3", "2026-04-01T00:00:04.000Z"),
],
},
];
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
expect(collapsed[1]).toMatchObject({
type: "work-toggle",
groupId: "work-group-1",
hiddenCount: 2,
expanded: false,
});
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
expect(expanded.map((entry) => entry.id)).toEqual([
"activity-1",
"activity-2",
"activity-3",
"work-toggle:work-group-1",
]);
expect(expanded.at(-1)).toMatchObject({
type: "work-toggle",
expanded: true,
});
});
it("pretty prints T3 MCP dynamic tool activities and attaches the product logo", () => {
const toolItem: OrchestrationV2TurnItem = {
...base("item-t3-tool", "2026-06-20T00:00:04.000Z", 3),
type: "dynamic_tool",
toolName: "mcp__t3-code__t3_thread_read",
input: { threadId: "thread-child" },
output: { messages: [] },
};
const feed = buildThreadFeed([projected(toolItem, 0)]);
const activity = feed[0]?.type === "activity-group" ? feed[0].activities[0] : null;
expect(activity?.summary).toBe("Read a T3 thread");
expect(activity?.logo).toBe("t3-code");
expect(activity?.getCopyText().split("\n")[0]).toBe("Read a T3 thread");
});
});
const singleSelectQuestion = {
id: "runtime",
header: "Runtime",
@@ -112,554 +504,3 @@ describe("pending user input answers", () => {
).toBe(false);
});
});
function makeActivity(
input: Partial<OrchestrationThreadActivity> &
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
): OrchestrationThreadActivity {
return {
tone: "info",
payload: {},
turnId: null,
...input,
};
}
function makeThread(
input: Partial<OrchestrationThread> & Pick<OrchestrationThread, "id" | "projectId" | "title">,
): OrchestrationThread {
return {
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
describe("buildThreadFeed", () => {
it("keeps historic work entries attributed to their turns", () => {
const thread = makeThread({
id: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Runtime warning thread",
latestTurn: {
turnId: TurnId.make("turn-latest"),
state: "running",
requestedAt: "2026-04-01T00:00:00.000Z",
startedAt: "2026-04-01T00:00:01.000Z",
completedAt: null,
assistantMessageId: null,
},
activities: [
makeActivity({
id: EventId.make("activity-old"),
kind: "runtime.warning",
summary: "Runtime warning",
createdAt: "2026-04-01T00:00:02.000Z",
turnId: TurnId.make("turn-old"),
payload: {
message: "Old warning",
},
}),
makeActivity({
id: EventId.make("activity-latest"),
kind: "runtime.warning",
summary: "Runtime warning",
createdAt: "2026-04-01T00:00:03.000Z",
turnId: TurnId.make("turn-latest"),
payload: {
message: "Latest warning",
},
}),
],
});
const feed = buildThreadFeed(thread);
expect(feed).toMatchObject([
{
type: "activity-group",
turnId: "turn-old",
activities: [{ id: "activity-old", turnId: "turn-old" }],
},
{
type: "activity-group",
turnId: "turn-latest",
activities: [{ id: "activity-latest", turnId: "turn-latest" }],
},
]);
});
it("collapses matching tool lifecycle rows like desktop", () => {
const thread = makeThread({
id: ThreadId.make("thread-2"),
projectId: ProjectId.make("project-1"),
title: "Collapsed tools",
latestTurn: {
turnId: TurnId.make("turn-1"),
state: "completed",
requestedAt: "2026-04-01T00:00:00.000Z",
startedAt: "2026-04-01T00:00:01.000Z",
completedAt: "2026-04-01T00:00:03.000Z",
assistantMessageId: null,
},
activities: [
makeActivity({
id: EventId.make("tool-updated"),
kind: "tool.updated",
tone: "tool",
summary: "Run tests",
createdAt: "2026-04-01T00:00:01.000Z",
turnId: TurnId.make("turn-1"),
payload: {
title: "Run tests",
itemType: "command_execution",
detail: "/bin/zsh -lc 'bun run test'",
},
}),
makeActivity({
id: EventId.make("tool-completed"),
kind: "tool.completed",
tone: "tool",
summary: "Run tests completed",
createdAt: "2026-04-01T00:00:02.000Z",
turnId: TurnId.make("turn-1"),
payload: {
title: "Run tests",
itemType: "command_execution",
detail: "/bin/zsh -lc 'bun run test'",
},
}),
],
});
const feed = buildThreadFeed(thread);
const group = feed[0];
expect(group).toMatchObject({
type: "activity-group",
});
if (!group || group.type !== "activity-group") {
return;
}
expect(group.activities).toHaveLength(1);
expect(group.activities[0]).toMatchObject({
id: "tool-completed",
createdAt: "2026-04-01T00:00:02.000Z",
turnId: "turn-1",
summary: "Run tests",
detail: "bun run test",
canExpand: true,
icon: "command",
toolLike: true,
status: "success",
});
expect(group.activities[0]?.getFullDetail()).toBe("/bin/zsh -lc 'bun run test'");
expect(group.activities[0]?.getCopyText()).toBe(
"Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
);
});
it("keeps MCP inputs available to expanded mobile work rows", () => {
const turnId = TurnId.make("turn-mcp");
const thread = makeThread({
id: ThreadId.make("thread-mcp"),
projectId: ProjectId.make("project-1"),
title: "Expandable MCP call",
latestTurn: {
turnId,
state: "completed",
requestedAt: "2026-04-01T00:00:00.000Z",
startedAt: "2026-04-01T00:00:01.000Z",
completedAt: "2026-04-01T00:00:03.000Z",
assistantMessageId: null,
},
activities: [
makeActivity({
id: EventId.make("mcp-completed"),
kind: "tool.completed",
tone: "tool",
summary: "Call repository tool",
createdAt: "2026-04-01T00:00:02.000Z",
turnId,
payload: {
title: "Call repository tool",
itemType: "mcp_tool_call",
detail: "repository.search",
status: "completed",
data: {
item: {
server: "repository",
tool: "search",
arguments: { query: "work log" },
},
},
},
}),
],
});
const group = buildThreadFeed(thread)[0];
expect(group).toMatchObject({ type: "activity-group" });
if (!group || group.type !== "activity-group") {
return;
}
expect(group.activities[0]?.icon).toBe("wrench");
expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"');
expect(group.activities[0]?.getFullDetail()).toContain("repository.search");
});
it("defers large tool output expansion until a work row is opened or copied", () => {
let serializedToolOutputs = 0;
const activities = Array.from({ length: 5_000 }, (_, index) =>
makeActivity({
id: EventId.make(`large-tool-${index}`),
kind: "tool.completed",
tone: "tool",
summary: `Tool ${index}`,
createdAt: new Date(Date.UTC(2026, 3, 1, 0, 0, index)).toISOString(),
payload: {
title: `Tool ${index}`,
itemType: "mcp_tool_call",
status: "completed",
data: {
item: {
toJSON: () => {
serializedToolOutputs += 1;
return { output: "x".repeat(32_768) };
},
},
},
},
}),
);
const thread = makeThread({
id: ThreadId.make("thread-large-tools"),
projectId: ProjectId.make("project-1"),
title: "Large tools",
activities,
});
const feed = buildThreadFeed(thread);
expect(serializedToolOutputs).toBe(0);
const group = feed[0];
expect(group).toMatchObject({ type: "activity-group" });
if (!group || group.type !== "activity-group") {
return;
}
expect(group.activities).toHaveLength(5_000);
expect(group.activities[0]?.getFullDetail()).toContain('"output"');
expect(serializedToolOutputs).toBe(1);
expect(group.activities[0]?.getCopyText()).toContain('"output"');
expect(serializedToolOutputs).toBe(1);
});
it("folds settled turn work while leaving the terminal answer visible", () => {
const turnId = TurnId.make("turn-1");
const thread = makeThread({
id: ThreadId.make("thread-3"),
projectId: ProjectId.make("project-1"),
title: "Folded work",
latestTurn: {
turnId,
state: "completed",
requestedAt: "2026-04-01T00:00:00.000Z",
startedAt: "2026-04-01T00:00:01.000Z",
completedAt: "2026-04-01T00:00:18.000Z",
assistantMessageId: MessageId.make("assistant-final"),
},
messages: [
{
id: MessageId.make("assistant-commentary"),
role: "assistant",
text: "I am checking.",
turnId,
streaming: false,
createdAt: "2026-04-01T00:00:02.000Z",
updatedAt: "2026-04-01T00:00:03.000Z",
},
{
id: MessageId.make("assistant-final"),
role: "assistant",
text: "Done.",
turnId,
streaming: false,
createdAt: "2026-04-01T00:00:17.000Z",
updatedAt: "2026-04-01T00:00:18.000Z",
},
],
activities: [
makeActivity({
id: EventId.make("tool-completed"),
kind: "tool.completed",
tone: "tool",
summary: "Read files",
createdAt: "2026-04-01T00:00:05.000Z",
turnId,
payload: {
title: "Read files",
itemType: "file_read",
status: "completed",
},
}),
],
});
const feed = buildThreadFeed(thread);
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
expect(collapsed[0]).toMatchObject({
type: "turn-fold",
label: "Worked for 17s",
expanded: false,
});
const expanded = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set([turnId]));
expect(expanded.map((entry) => entry.id)).toEqual([
"turn-fold:turn-1",
"assistant-commentary",
"tool-completed",
"assistant-final",
]);
});
it("measures a steer-superseded turn from its user boundary through trailing work", () => {
const firstTurnId = TurnId.make("turn-1");
const secondTurnId = TurnId.make("turn-2");
const thread = makeThread({
id: ThreadId.make("thread-steered"),
projectId: ProjectId.make("project-1"),
title: "Steered work",
latestTurn: {
turnId: secondTurnId,
state: "running",
requestedAt: "2026-04-01T00:00:14.000Z",
startedAt: "2026-04-01T00:00:14.000Z",
completedAt: null,
assistantMessageId: MessageId.make("assistant-next"),
},
messages: [
{
id: MessageId.make("user-1"),
role: "user",
text: "Do it once more.",
turnId: null,
streaming: false,
createdAt: "2026-04-01T00:00:00.000Z",
updatedAt: "2026-04-01T00:00:00.000Z",
},
{
id: MessageId.make("assistant-commentary"),
role: "assistant",
text: "Kicking off call 1.",
turnId: firstTurnId,
streaming: false,
createdAt: "2026-04-01T00:00:09.000Z",
updatedAt: "2026-04-01T00:00:09.000Z",
},
{
id: MessageId.make("user-2"),
role: "user",
text: "Actually do 15.",
turnId: null,
streaming: false,
createdAt: "2026-04-01T00:00:14.000Z",
updatedAt: "2026-04-01T00:00:14.000Z",
},
{
id: MessageId.make("assistant-next"),
role: "assistant",
text: "One down - adjusting.",
turnId: secondTurnId,
streaming: true,
createdAt: "2026-04-01T00:00:17.000Z",
updatedAt: "2026-04-01T00:00:17.000Z",
},
],
activities: [
makeActivity({
id: EventId.make("work-1"),
kind: "tool.completed",
tone: "tool",
summary: "Ran command",
createdAt: "2026-04-01T00:00:12.000Z",
turnId: firstTurnId,
payload: {
title: "Ran command",
itemType: "command_execution",
status: "completed",
},
}),
],
});
const feed = buildThreadFeed(thread);
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
turnId: firstTurnId,
label: "Worked for 12s",
});
});
it("keeps an active turn expanded and classifies error-shaped tool output", () => {
const turnId = TurnId.make("turn-running");
const thread = makeThread({
id: ThreadId.make("thread-4"),
projectId: ProjectId.make("project-1"),
title: "Running work",
latestTurn: {
turnId,
state: "running",
requestedAt: "2026-04-01T00:00:00.000Z",
startedAt: "2026-04-01T00:00:01.000Z",
completedAt: null,
assistantMessageId: null,
},
activities: [
makeActivity({
id: EventId.make("tool-failed"),
kind: "tool.completed",
tone: "tool",
summary: "Run command",
createdAt: "2026-04-01T00:00:05.000Z",
turnId,
payload: {
title: "Run command",
itemType: "command_execution",
detail: "zsh: command not found: nope",
status: "completed",
},
}),
],
});
const feed = buildThreadFeed(thread);
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
expect(feed[0]).toMatchObject({
type: "activity-group",
activities: [{ status: "failure" }],
});
});
it("appends active work as a normal timeline row", () => {
const startedAt = "2026-04-01T00:00:01.000Z";
const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
expect(presented).toEqual([
{
type: "working",
id: "working-indicator-row",
createdAt: startedAt,
},
]);
expect(deriveThreadFeedPresentation(presented, null, new Set())).toEqual([]);
});
it("models work-log overflow as list rows", () => {
const activity = (
id: string,
createdAt: string,
status: ThreadFeedActivity["status"] = "success",
): ThreadFeedActivity => ({
id,
createdAt,
turnId: null,
summary: `Tool ${id}`,
detail: null,
canExpand: false,
getFullDetail: () => null,
getCopyText: () => id,
icon: "command",
toolLike: true,
status,
});
const feed: ThreadFeedEntry[] = [
{
type: "activity-group",
id: "work-group-1",
createdAt: "2026-04-01T00:00:01.000Z",
turnId: null,
activities: [
activity("activity-1", "2026-04-01T00:00:01.000Z"),
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
activity("activity-2", "2026-04-01T00:00:03.000Z"),
activity("activity-3", "2026-04-01T00:00:04.000Z"),
],
},
];
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
expect(collapsed[1]).toMatchObject({
type: "work-toggle",
groupId: "work-group-1",
hiddenCount: 2,
expanded: false,
});
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
expect(expanded.map((entry) => entry.id)).toEqual([
"activity-1",
"activity-2",
"activity-3",
"work-toggle:work-group-1",
]);
expect(expanded.at(-1)).toMatchObject({
type: "work-toggle",
expanded: true,
});
});
});
describe("quiet timeline: nested agents", () => {
it("keeps a nested agent's terminal row but hides its background work", () => {
const thread = makeThread({
id: ThreadId.make("thread-nested"),
projectId: ProjectId.make("project-1"),
title: "Nested agents",
activities: [
// A subagent's own shell: internal, covered by the owner's liveness.
makeActivity({
id: EventId.make("shell-done"),
kind: "task.completed",
summary: "Task completed",
createdAt: "2026-04-01T00:00:02.000Z",
payload: { taskId: "sh-1", agentId: "owner", agentKind: "background" },
}),
// A nested AGENT's completion: mobile has no Agents sheet, so this
// terminal row is the only signal it ever finished.
makeActivity({
id: EventId.make("nested-done"),
kind: "task.completed",
summary: "Task completed",
createdAt: "2026-04-01T00:00:03.000Z",
payload: { taskId: "n-1", agentId: "owner", agentKind: "agent" },
}),
],
});
const feed = buildThreadFeed(thread);
const ids = feed.flatMap((entry) =>
entry.type === "activity-group" ? entry.activities.map((row) => row.id) : [],
);
expect(ids).toContain("nested-done");
expect(ids).not.toContain("shell-done");
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,257 @@
import { EMPTY_V2_ITEM_SUPPORT } from "@t3tools/client-runtime/state/item-support";
import {
CheckpointId,
CheckpointScopeId,
NodeId,
ProviderDriverKind,
ProviderInstanceId,
RunId,
ThreadId,
TurnItemId,
type OrchestrationV2ProjectedTurnItem,
type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
import { buildThreadFeed, type ThreadFeedActivity } from "./threadActivity";
import { buildThreadActivityInspector } from "./threadActivityInspector";
const threadId = ThreadId.make("thread-1");
const sourceThreadId = ThreadId.make("thread-source");
const runId = RunId.make("run-1");
const nodeId = NodeId.make("node-1");
const startedAt = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
const completedAt = DateTime.makeUnsafe("2026-06-20T00:00:02.000Z");
function itemBase(id: string) {
return {
id: TurnItemId.make(id),
threadId,
runId,
nodeId,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "completed" as const,
title: null,
startedAt,
completedAt,
updatedAt: completedAt,
};
}
function activityFor(item: OrchestrationV2TurnItem): ThreadFeedActivity {
const row: OrchestrationV2ProjectedTurnItem = {
position: 0,
visibility: "inherited",
sourceThreadId,
sourceItemId: item.id,
item,
};
const group = buildThreadFeed([row])[0];
if (group?.type !== "activity-group" || !group.activities[0]) {
throw new Error("Expected an activity group");
}
return group.activities[0];
}
describe("buildThreadActivityInspector", () => {
it("presents command lifecycle, execution support, output, and exit state", () => {
const item: OrchestrationV2TurnItem = {
...itemBase("command"),
type: "command_execution",
input: "vp check",
output: "all checks passed",
exitCode: 0,
};
const support = {
...EMPTY_V2_ITEM_SUPPORT,
item,
run: { status: "completed" } as never,
attempts: [
{
id: "attempt-1",
attemptOrdinal: 1,
status: "superseded",
reason: "initial",
},
{
id: "attempt-2",
attemptOrdinal: 2,
status: "completed",
reason: "steering_restart",
},
] as never,
node: { kind: "tool_call", status: "completed" } as never,
providerSession: {
status: "ready",
model: "gpt-5.4",
cwd: "/workspace/project",
} as never,
};
const model = buildThreadActivityInspector(activityFor(item), support, sourceThreadId);
expect(model.fields).toEqual(
expect.arrayContaining([
{ label: "Duration", value: "2.0s" },
{ label: "Run", value: "completed" },
{ label: "Working directory", value: "/workspace/project" },
{ label: "Visibility", value: "inherited" },
]),
);
expect(model.blocks).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: "Command", value: "vp check" }),
expect.objectContaining({ label: "Output", value: "all checks passed" }),
expect.objectContaining({ label: "Exit", value: "Process exited with code 0" }),
expect.objectContaining({ label: "Attempt history" }),
]),
);
});
it("exposes file and web result provenance plus dynamic structured data", () => {
const fileSearch: OrchestrationV2TurnItem = {
...itemBase("file-search"),
type: "file_search",
pattern: "resolveSession",
results: [{ fileName: "src/session.ts", line: 42, preview: "function resolveSession()" }],
};
const fileModel = buildThreadActivityInspector(
activityFor(fileSearch),
EMPTY_V2_ITEM_SUPPORT,
sourceThreadId,
);
expect(fileModel.fileLinks).toEqual([
{
label: "src/session.ts — function resolveSession()",
path: "src/session.ts",
line: 42,
},
]);
const webSearch: OrchestrationV2TurnItem = {
...itemBase("web-search"),
type: "web_search",
patterns: ["Effect Schema docs"],
results: [
{ title: "Schema", url: "https://effect.website/docs/schema", snippet: "Typed schemas" },
],
};
const webModel = buildThreadActivityInspector(
activityFor(webSearch),
EMPTY_V2_ITEM_SUPPORT,
sourceThreadId,
);
expect(webModel.webLinks).toEqual([
{ label: "Schema", url: "https://effect.website/docs/schema" },
]);
expect(webModel.blocks).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: "Schema", value: "Typed schemas" }),
]),
);
const dynamicTool: OrchestrationV2TurnItem = {
...itemBase("dynamic"),
type: "dynamic_tool",
toolName: "custom",
input: { nested: { value: 1 } },
output: { ok: true },
};
const dynamicModel = buildThreadActivityInspector(
activityFor(dynamicTool),
EMPTY_V2_ITEM_SUPPORT,
sourceThreadId,
);
expect(dynamicModel.blocks).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: "Input", value: expect.stringContaining('"nested"') }),
expect.objectContaining({ label: "Output", value: expect.stringContaining('"ok"') }),
]),
);
expect(dynamicModel.structuredDetails).toContain('"type": "dynamic_tool"');
});
it("enables rollback only for the matching ready checkpoint", () => {
const checkpointId = CheckpointId.make("checkpoint-1");
const scopeId = CheckpointScopeId.make("scope-1");
const item: OrchestrationV2TurnItem = {
...itemBase("checkpoint"),
type: "checkpoint",
checkpointId,
scopeId,
files: [{ path: "src/main.ts", kind: "modified", additions: 2, deletions: 1 }],
};
const checkpoint = { id: checkpointId, scopeId, status: "ready" } as never;
const model = buildThreadActivityInspector(
activityFor(item),
{
...EMPTY_V2_ITEM_SUPPORT,
item,
checkpoint,
},
sourceThreadId,
);
expect(model.canRollback).toBe(true);
expect(model.rollbackTarget).toEqual({
threadId: sourceThreadId,
checkpointId,
scopeId,
});
const inheritedModel = buildThreadActivityInspector(
activityFor(item),
{
...EMPTY_V2_ITEM_SUPPORT,
item,
checkpoint,
},
ThreadId.make("child-thread"),
);
expect(inheritedModel.canRollback).toBe(false);
expect(inheritedModel.rollbackTarget).toBeNull();
});
it("prefers live subagent progress from supporting state", () => {
const item: OrchestrationV2TurnItem = {
...itemBase("subagent"),
type: "subagent",
subagentId: nodeId,
origin: "provider_native",
driver: ProviderDriverKind.make("claude"),
providerInstanceId: ProviderInstanceId.make("claude"),
childThreadId: null,
prompt: "Audit the reducer",
progress: "Starting",
result: null,
};
const model = buildThreadActivityInspector(
activityFor(item),
{
...EMPTY_V2_ITEM_SUPPORT,
item,
subagent: {
origin: "provider_native",
status: "running",
progress: "Reading projection tests",
result: null,
} as never,
},
sourceThreadId,
);
expect(model.fields).toContainEqual({
label: "Delegated task",
value: "provider native · running",
});
expect(model.blocks).toContainEqual({
label: "Progress",
value: "Reading projection tests",
monospaced: false,
});
});
});
@@ -0,0 +1,308 @@
import type { V2ItemSupport } from "@t3tools/client-runtime/state/item-support";
import type { ThreadId } from "@t3tools/contracts";
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
import * as DateTime from "effect/DateTime";
import type { ThreadFeedActivity } from "./threadActivity";
export interface ThreadActivityInspectorField {
readonly label: string;
readonly value: string;
}
export interface ThreadActivityInspectorBlock {
readonly label: string;
readonly value: string;
readonly monospaced: boolean;
}
export interface ThreadActivityFileLink {
readonly label: string;
readonly path: string;
readonly line?: number;
}
export interface ThreadActivityWebLink {
readonly label: string;
readonly url: string;
}
export interface ThreadActivityInspectorModel {
readonly fields: ReadonlyArray<ThreadActivityInspectorField>;
readonly blocks: ReadonlyArray<ThreadActivityInspectorBlock>;
readonly fileLinks: ReadonlyArray<ThreadActivityFileLink>;
readonly webLinks: ReadonlyArray<ThreadActivityWebLink>;
readonly canRollback: boolean;
readonly rollbackTarget: {
readonly threadId: ThreadId;
readonly checkpointId: string;
readonly scopeId: string;
} | null;
readonly structuredDetails: string;
}
function formatStructured(value: unknown): string {
if (typeof value === "string") return value;
try {
return JSON.stringify(value, null, 2) ?? String(value);
} catch {
return String(value);
}
}
function durationLabel(
startedAt: DateTime.Utc | null,
completedAt: DateTime.Utc | null,
): string | null {
if (startedAt === null) return null;
const start = DateTime.toEpochMillis(startedAt);
const end = completedAt === null ? Date.now() : DateTime.toEpochMillis(completedAt);
return formatDuration(Math.max(0, end - start));
}
function addBlock(
blocks: ThreadActivityInspectorBlock[],
label: string,
value: unknown,
monospaced = true,
): void {
if (value === undefined || value === null || value === "") return;
blocks.push({ label, value: formatStructured(value), monospaced });
}
export function buildThreadActivityInspector(
activity: ThreadFeedActivity,
support: V2ItemSupport,
currentThreadId: ThreadId,
): ThreadActivityInspectorModel {
const row = activity.projectedItem;
const item = row.item;
const fields: ThreadActivityInspectorField[] = [
{ label: "Item", value: item.type.replaceAll("_", " ") },
{ label: "Status", value: item.status.replaceAll("_", " ") },
];
const duration = durationLabel(item.startedAt, item.completedAt);
if (duration) fields.push({ label: "Duration", value: duration });
if (row.visibility !== "local") fields.push({ label: "Visibility", value: row.visibility });
if (support.run) fields.push({ label: "Run", value: support.run.status });
const latestAttempt = support.attempts.at(-1);
if (latestAttempt) {
fields.push({
label: "Attempt",
value: `${latestAttempt.attemptOrdinal} · ${latestAttempt.status} · ${latestAttempt.reason.replaceAll("_", " ")}`,
});
}
if (support.node) {
fields.push({
label: "Node",
value: `${support.node.kind.replaceAll("_", " ")} · ${support.node.status}`,
});
}
if (support.providerThread) {
fields.push({
label: "Provider thread",
value: `${support.providerThread.providerInstanceId} · ${support.providerThread.status}`,
});
}
if (support.providerTurn) {
fields.push({ label: "Provider turn", value: support.providerTurn.status });
}
if (support.providerSession) {
fields.push({
label: "Session",
value: `${support.providerSession.status} · ${support.providerSession.model ?? "default model"}`,
});
fields.push({ label: "Working directory", value: support.providerSession.cwd });
}
if (support.runtimeRequest) {
fields.push({
label: "Request",
value: `${support.runtimeRequest.status} · ${support.runtimeRequest.responseCapability.type.replaceAll("_", " ")}`,
});
}
const blocks: ThreadActivityInspectorBlock[] = [];
const fileLinks: ThreadActivityFileLink[] = [];
const webLinks: ThreadActivityWebLink[] = [];
if (support.attempts.length > 1) {
addBlock(
blocks,
"Attempt history",
support.attempts
.map(
(attempt) =>
`Attempt ${attempt.attemptOrdinal} · ${attempt.status} · ${attempt.reason.replaceAll("_", " ")}`,
)
.join("\n"),
);
}
switch (item.type) {
case "reasoning":
addBlock(blocks, "Reasoning", item.text, false);
break;
case "command_execution":
addBlock(blocks, "Command", item.input);
addBlock(blocks, "Output", item.output);
if (item.exitCode !== undefined) {
addBlock(blocks, "Exit", `Process exited with code ${item.exitCode}`);
}
break;
case "file_change":
fileLinks.push({ label: item.fileName, path: item.fileName });
if (item.additions !== undefined || item.deletions !== undefined) {
fields.push({
label: "Changes",
value: `+${item.additions ?? 0} −${item.deletions ?? 0}`,
});
}
addBlock(blocks, "Patch", item.diffStr);
addBlock(blocks, "Before", item.oldStr);
addBlock(blocks, "After", item.newStr);
break;
case "file_search":
addBlock(blocks, "Query", item.pattern);
for (const result of item.results ?? []) {
fileLinks.push({
label: result.preview ? `${result.fileName} — ${result.preview}` : result.fileName,
path: result.fileName,
...(result.line === undefined ? {} : { line: result.line }),
});
}
break;
case "web_search":
addBlock(blocks, "Queries", item.patterns?.join("\n"));
for (const result of item.results ?? []) {
if (result.url) {
webLinks.push({
label: result.title ?? result.url,
url: result.url,
});
}
if (result.snippet)
addBlock(blocks, result.title ?? "Search result", result.snippet, false);
}
break;
case "dynamic_tool":
addBlock(blocks, "Input", item.input);
addBlock(blocks, "Output", item.output);
break;
case "approval_request":
addBlock(blocks, "Prompt", item.prompt, false);
break;
case "user_input_request":
addBlock(
blocks,
"Questions",
item.questions.map((question) => question.question).join("\n"),
false,
);
break;
case "checkpoint":
addBlock(
blocks,
"Files",
item.files
.map((file) => `${file.path} +${file.additions} −${file.deletions} ${file.kind}`)
.join("\n"),
);
break;
case "subagent":
addBlock(blocks, "Prompt", item.prompt, false);
addBlock(blocks, "Progress", support.subagent?.progress ?? item.progress, false);
addBlock(blocks, "Result", support.subagent?.result ?? item.result, false);
if (support.subagent) {
fields.push({
label: "Delegated task",
value: `${support.subagent.origin.replaceAll("_", " ")} · ${support.subagent.status}`,
});
}
break;
case "handoff":
addBlock(blocks, "Summary", item.summary, false);
fields.push({
label: "Handoff",
value: `${item.strategy.replaceAll("_", " ")} · ${support.contextHandoff?.status ?? item.status}`,
});
if (support.contextTransfer) {
fields.push({
label: "Transfer",
value: `${support.contextTransfer.type.replaceAll("_", " ")} · ${support.contextTransfer.status}`,
});
if (support.contextTransfer.resolution) {
fields.push({
label: "Context",
value: support.contextTransfer.resolution.strategy.replaceAll("_", " "),
});
}
}
break;
case "error":
addBlock(blocks, "Error", item.failure.message, false);
if (item.failure.code) fields.push({ label: "Code", value: item.failure.code });
if (item.failure.retryable !== null) {
fields.push({ label: "Retryable", value: item.failure.retryable ? "yes" : "no" });
}
break;
case "proposed_plan":
addBlock(blocks, "Plan", item.markdown, false);
break;
case "todo_list":
addBlock(
blocks,
"Tasks",
item.steps
.map((step) => `${step.status === "completed" ? "✓" : "○"} ${step.text}`)
.join("\n"),
false,
);
addBlock(blocks, "Explanation", item.explanation, false);
break;
case "compaction":
addBlock(blocks, "Summary", item.summary, false);
if (item.beforeTokenCount !== undefined || item.afterTokenCount !== undefined) {
fields.push({
label: "Context tokens",
value: `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"}`,
});
}
break;
case "run_interrupt_request":
case "run_interrupt_result":
addBlock(blocks, "Message", item.message, false);
break;
case "fork":
case "thread_created":
case "user_message":
case "assistant_message":
break;
}
const checkpoint =
item.type === "checkpoint" && row.sourceThreadId === currentThreadId
? support.checkpoint
: null;
return {
fields,
blocks,
fileLinks,
webLinks,
canRollback: checkpoint?.status === "ready",
rollbackTarget:
checkpoint?.status === "ready"
? {
threadId: row.sourceThreadId,
checkpointId: checkpoint.id,
scopeId: checkpoint.scopeId,
}
: null,
structuredDetails: formatStructured({
visibility: row.visibility,
sourceThreadId: row.sourceThreadId,
sourceItemId: row.sourceItemId,
item,
}),
};
}
+1 -28
View File
@@ -1,11 +1,5 @@
import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
import type {
EnvironmentId,
OrchestrationThread,
ThreadId,
VcsListRefsResult,
VcsRef,
} from "@t3tools/contracts";
import type { EnvironmentId, ThreadId, VcsListRefsResult, VcsRef } from "@t3tools/contracts";
import {
createThreadSearchResultsAtomFamily,
makeThreadSearchKey,
@@ -21,7 +15,6 @@ import { appAtomRegistry } from "./atom-registry";
import { orchestrationEnvironment } from "./orchestration";
import { projectEnvironment } from "./projects";
import { useEnvironmentQuery } from "./query";
import { useEnvironmentThread } from "./threads";
import { vcsEnvironment } from "./vcs";
import {
buildCheckpointDiffTargets,
@@ -50,13 +43,6 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
labelPrefix: "mobile:thread-search",
});
export interface ThreadDetailView {
readonly data: OrchestrationThread | null;
readonly error: string | null;
readonly isPending: boolean;
readonly isDeleted: boolean;
}
export interface ComposerPathSearchTarget {
readonly environmentId: EnvironmentId | null;
readonly cwd: string | null;
@@ -103,19 +89,6 @@ export function useThreadSearch(
};
}
export function useThreadDetail(
environmentId: EnvironmentId | null,
threadId: ThreadId | null,
): ThreadDetailView {
const state = useEnvironmentThread(environmentId, threadId);
return {
data: Option.getOrNull(state.data),
error: Option.getOrNull(state.error),
isPending: state.status === "synchronizing",
isDeleted: state.status === "deleted",
};
}
export function useBranches(input: {
readonly environmentId: EnvironmentId | null;
readonly cwd: string | null;
+2 -1
View File
@@ -38,8 +38,9 @@ export function useEnvironmentThread(
? environmentThreads.stateAtom(environmentId, threadId)
: EMPTY_THREAD_STATE_ATOM,
);
return Option.getOrElse(
const state = Option.getOrElse(
AsyncResult.value(result),
() => EMPTY_ENVIRONMENT_THREAD_STATE,
) as EnvironmentThreadState;
return state;
}
@@ -1,6 +1,6 @@
import { useMemo } from "react";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
import {
flattenQueuedThreadMessages,
type QueuedThreadCreation,
@@ -26,7 +26,7 @@ export function usePendingNewTasks(): ReadonlyArray<PendingNewTask> {
tasks.push({
message,
creation: message.creation,
title: deriveThreadTitleFromPrompt(message.text),
title: deriveThreadTitleSeed({ text: message.text, attachments: message.attachments }),
});
}
tasks.sort((left, right) => right.message.createdAt.localeCompare(left.message.createdAt));
@@ -1,26 +1,23 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useMemo, useState } from "react";
import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";
import {
ApprovalRequestId,
type ProviderApprovalDecision,
type UserInputQuestion,
} from "@t3tools/contracts";
derivePendingThreadRequests,
type ThreadUserInputQuestion,
} from "@t3tools/client-runtime/state/thread-requests";
import { Atom } from "effect/unstable/reactivity";
import { threadEnvironment } from "../state/threads";
import { scopedRequestKey } from "../lib/scopedEntities";
import {
buildPendingUserInputAnswers,
derivePendingApprovals,
derivePendingUserInputs,
setPendingUserInputCustomAnswer,
sortThreadActivities,
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../lib/threadActivity";
import { appAtomRegistry } from "./atom-registry";
import { useSelectedThreadDetail } from "./use-thread-detail";
import { useSelectedThreadProjection } from "./use-thread-detail";
import { useThreadSelection } from "./use-thread-selection";
import { useAtomCommand } from "./use-atom-command";
@@ -30,7 +27,7 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
function setUserInputDraftOption(
requestKey: string,
question: UserInputQuestion,
question: ThreadUserInputQuestion,
label: string,
): void {
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
@@ -75,27 +72,21 @@ export function useSelectedThreadRequests() {
"thread user input response",
);
const { selectedThread: selectedThreadShell } = useThreadSelection();
const selectedThread = useSelectedThreadDetail();
const selectedThread = useSelectedThreadProjection();
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
null,
);
const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
// Sort once; both derivations expect the same lifecycle ordering.
const sortedActivities = useMemo(
() => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
const pendingRequests = useMemo(
() =>
selectedThread === null
? { approvals: [], userInputs: [] }
: derivePendingThreadRequests(selectedThread.projection),
[selectedThread],
);
const activePendingApprovals = useMemo(
() => derivePendingApprovals(sortedActivities),
[sortedActivities],
);
const activePendingApprovals = pendingRequests.approvals;
const activePendingApproval = activePendingApprovals[0] ?? null;
const activePendingUserInputs = useMemo(
() => derivePendingUserInputs(sortedActivities),
[sortedActivities],
);
const activePendingUserInputs = pendingRequests.userInputs;
const activePendingUserInput = activePendingUserInputs[0] ?? null;
const activePendingUserInputDrafts =
activePendingUserInput && selectedThreadShell
@@ -108,7 +99,7 @@ export function useSelectedThreadRequests() {
: null;
const onSelectUserInputOption = useCallback(
(requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => {
(requestId: RuntimeRequestId, question: ThreadUserInputQuestion, label: string) => {
if (!selectedThreadShell) {
return;
}
@@ -120,7 +111,7 @@ export function useSelectedThreadRequests() {
);
const onChangeUserInputCustomAnswer = useCallback(
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
(requestId: RuntimeRequestId, questionId: string, customAnswer: string) => {
if (!selectedThreadShell) {
return;
}
@@ -132,10 +123,16 @@ export function useSelectedThreadRequests() {
);
const onRespondToApproval = useCallback(
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
if (!selectedThreadShell) {
return;
}
if (
activePendingApprovals.find((approval) => approval.requestId === requestId)
?.responseCapability !== "live"
) {
return;
}
setRespondingApprovalId(requestId);
const result = await respondToApproval({
@@ -149,11 +146,16 @@ export function useSelectedThreadRequests() {
setRespondingApprovalId((current) => (current === requestId ? null : current));
return result;
},
[respondToApproval, selectedThreadShell],
[activePendingApprovals, respondToApproval, selectedThreadShell],
);
const onSubmitUserInput = useCallback(async () => {
if (!selectedThreadShell || !activePendingUserInput || !activePendingUserInputAnswers) {
if (
!selectedThreadShell ||
!activePendingUserInput ||
activePendingUserInput.responseCapability !== "live" ||
!activePendingUserInputAnswers
) {
return;
}
@@ -1,20 +1,21 @@
import { useMemo } from "react";
import { useSelectedThreadDetail } from "./use-thread-detail";
import { useSelectedThreadProjection } from "./use-thread-detail";
import { useThreadSelection } from "./use-thread-selection";
import { resolvePreferredThreadWorktreePath } from "../features/terminal/terminalLaunchContext";
export function useSelectedThreadWorktree() {
const { selectedThread, selectedThreadProject } = useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const selectedThreadDetail = useSelectedThreadProjection();
const detailWorktreePath = selectedThreadDetail?.projection.thread.worktreePath ?? null;
const selectedThreadWorktreePath = useMemo(
() =>
resolvePreferredThreadWorktreePath({
threadShellWorktreePath: selectedThread?.worktreePath ?? null,
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
threadDetailWorktreePath: detailWorktreePath,
}),
[selectedThread?.worktreePath, selectedThreadDetail?.worktreePath],
[detailWorktreePath, selectedThread?.worktreePath],
);
return {
@@ -1,4 +1,10 @@
import { useAtomValue } from "@effect/atom-react";
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
import {
deriveThreadActivityRun,
deriveThreadRuntime,
threadRuntimeHasInterruptibleRun,
} from "@t3tools/client-runtime/state/thread-execution";
import { useCallback, useEffect, useMemo } from "react";
import {
@@ -37,7 +43,10 @@ import {
useComposerDraft,
} from "./use-composer-drafts";
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
import { useSelectedThreadDetail } from "../state/use-thread-detail";
import {
useSelectedThreadProjection,
useSelectedThreadVisibleTurnItems,
} from "../state/use-thread-detail";
import { useThreadSelection } from "../state/use-thread-selection";
import { enqueueThreadOutboxMessage } from "./thread-outbox";
import { useThreadOutboxMessages } from "./use-thread-outbox";
@@ -75,7 +84,8 @@ export function useThreadDraftForThread(input: {
export function useThreadComposerState() {
const { selectedThread: selectedThreadShell } = useThreadSelection();
const selectedThreadDetail = useSelectedThreadDetail();
const selectedThreadProjection = useSelectedThreadProjection();
const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems();
const composerDrafts = useAtomValue(composerDraftsAtom);
const queuedMessagesByThreadKey = useThreadOutboxMessages();
@@ -91,43 +101,59 @@ export function useThreadComposerState() {
[queuedMessagesByThreadKey, selectedThreadKey],
);
const selectedThreadFeed = useMemo(
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
[selectedThreadDetail],
() => buildThreadFeed(selectedThreadVisibleTurnItems),
[selectedThreadVisibleTurnItems],
);
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
const draftMessage = selectedDraft?.text ?? "";
const draftAttachments = selectedDraft?.attachments ?? [];
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
const selectedThread = selectedThreadShell;
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
const selectedThreadRuntime = useMemo(
() =>
selectedThreadProjection
? deriveThreadRuntime(selectedThreadProjection.projection)
: (selectedThreadShell?.runtime ?? null),
[selectedThreadProjection, selectedThreadShell?.runtime],
);
const selectedThreadActivityRun = useMemo(
() =>
selectedThreadProjection
? deriveThreadActivityRun(selectedThreadProjection.projection)
: (selectedThreadShell?.latestRun ?? null),
[selectedThreadProjection, selectedThreadShell?.latestRun],
);
const selectedThreadSessionActivity = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
if (!selectedThread?.session) {
if (!selectedThreadRuntime) {
return null;
}
return {
orchestrationStatus: selectedThread.session.status,
activeTurnId: selectedThread.session.activeTurnId ?? undefined,
orchestrationStatus: selectedThreadRuntime.status,
activeRunId: selectedThreadRuntime.activeRunId ?? undefined,
};
}, [selectedThreadDetail, selectedThreadShell]);
}, [selectedThreadRuntime]);
const activeWorkStartedAt = useMemo(() => {
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
if (!selectedThread) {
if (!selectedThreadShell) {
return null;
}
return deriveActiveWorkStartedAt(
selectedThread.latestTurn,
selectedThreadActivityRun,
selectedThreadSessionActivity,
null,
);
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
}, [selectedThreadActivityRun, selectedThreadSessionActivity, selectedThreadShell]);
const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
? (selectedThreadRuntime?.activeRunId ?? null)
: null;
const onSendMessage = useCallback(async () => {
if (!selectedThreadShell) {
@@ -136,7 +162,7 @@ export function useThreadComposerState() {
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
const draft = getComposerDraftSnapshot(threadKey);
const thread = selectedThreadDetail ?? selectedThreadShell;
const thread = selectedThreadShell;
const text = draft.text.trim();
const attachments = draft.attachments;
if (text.length === 0 && attachments.length === 0) {
@@ -175,7 +201,7 @@ export function useThreadComposerState() {
);
});
return messageId;
}, [selectedThreadDetail, selectedThreadShell]);
}, [selectedThreadShell]);
const onChangeDraftMessage = useCallback(
(value: string) => {
@@ -297,6 +323,7 @@ export function useThreadComposerState() {
return {
selectedThreadFeed,
selectedThreadActivityRun,
selectedThreadQueueCount,
activeWorkStartedAt,
draftMessage,
@@ -304,6 +331,8 @@ export function useThreadComposerState() {
modelSelection,
runtimeMode,
interactionMode,
activeThreadBusy,
interruptibleRunId,
onChangeDraftMessage,
onPickDraftImages,
onPasteIntoDraft,
+50 -5
View File
@@ -1,9 +1,18 @@
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { useEnvironmentThread } from "./threads";
import { environmentThreadDetails, useEnvironmentThread } from "./threads";
import { useThreadSelection } from "./use-thread-selection";
const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
Atom.withLabel("mobile-thread-projection:empty"),
);
const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make<
OrchestrationV2ThreadProjection["visibleTurnItems"]
>(Object.freeze([])).pipe(Atom.withLabel("mobile-thread-visible-turn-items:empty"));
export interface ThreadDetailTarget {
readonly environmentId: EnvironmentId | null;
readonly threadId: ThreadId | null;
@@ -21,6 +30,42 @@ export function useSelectedThreadDetailState() {
});
}
export function useSelectedThreadDetail() {
return Option.getOrNull(useSelectedThreadDetailState().data);
export function useThreadProjection(target: ThreadDetailTarget): EnvironmentThread | null {
return useAtomValue(
target.environmentId === null || target.threadId === null
? EMPTY_THREAD_PROJECTION_ATOM
: environmentThreadDetails.threadAtom({
environmentId: target.environmentId,
threadId: target.threadId,
}),
);
}
export function useSelectedThreadProjection(): EnvironmentThread | null {
const { selectedThread } = useThreadSelection();
return useThreadProjection({
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
});
}
export function useThreadVisibleTurnItems(
target: ThreadDetailTarget,
): OrchestrationV2ThreadProjection["visibleTurnItems"] {
return useAtomValue(
target.environmentId === null || target.threadId === null
? EMPTY_VISIBLE_TURN_ITEMS_ATOM
: environmentThreadDetails.visibleTurnItemsAtom({
environmentId: target.environmentId,
threadId: target.threadId,
}),
);
}
export function useSelectedThreadVisibleTurnItems(): OrchestrationV2ThreadProjection["visibleTurnItems"] {
const { selectedThread } = useThreadSelection();
return useThreadVisibleTurnItems({
environmentId: selectedThread?.environmentId ?? null,
threadId: selectedThread?.id ?? null,
});
}
@@ -1,9 +1,11 @@
import { useAtomValue } from "@effect/atom-react";
import type {
EnvironmentProject,
EnvironmentThreadShell,
import {
threadRuntimeIsActive,
type EnvironmentProject,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import {
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
@@ -221,6 +223,7 @@ export function useThreadOutboxDrain(): void {
environmentId: queuedMessage.environmentId,
input: {
commandId: queuedMessage.commandId,
creationSource: "mobile",
threadId: queuedMessage.threadId,
message: {
messageId: queuedMessage.messageId,
@@ -229,9 +232,14 @@ export function useThreadOutboxDrain(): void {
attachments: toUploadChatImageAttachments(queuedMessage.attachments),
},
modelSelection: settings.modelSelection,
titleSeed: deriveThreadTitleSeed({
text: queuedMessage.text,
attachments: queuedMessage.attachments,
}),
runtimeMode: settings.runtimeMode,
interactionMode: settings.interactionMode,
createdAt: queuedMessage.createdAt,
dispatchMode: "start",
},
});
return completeDelivery(deliveryResult);
@@ -314,7 +322,7 @@ export function useThreadOutboxDrain(): void {
threadExists: thread !== undefined,
shellStatus,
environmentConnected: environment?.connectionState === "connected",
threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting",
threadBusy: threadRuntimeIsActive(thread?.runtime),
});
if (deliveryAction === "wait") {
continue;
+47 -15
View File
@@ -2,12 +2,20 @@ import { useRoute, type RouteProp } from "@react-navigation/native";
import { useMemo, useRef } from "react";
import {
EnvironmentId,
type OrchestrationThread,
ThreadId,
type OrchestrationV2ThreadProjection,
type OrchestrationV2ThreadShell,
type ScopedProjectRef,
type ScopedThreadRef,
} from "@t3tools/contracts";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
presentThreadShell,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import {
deriveLatestThreadRun,
deriveThreadRuntime,
} from "@t3tools/client-runtime/state/thread-execution";
import * as Option from "effect/Option";
import { useProject, useThreadShell } from "../state/entities";
@@ -29,9 +37,11 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
return value ?? null;
}
function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["updatedAt"] | null {
for (let index = thread.messages.length - 1; index >= 0; index -= 1) {
const message = thread.messages[index];
function latestUserMessageAt(
projection: OrchestrationV2ThreadProjection,
): OrchestrationV2ThreadShell["latestUserMessageAt"] {
for (let index = projection.messages.length - 1; index >= 0; index -= 1) {
const message = projection.messages[index];
if (message?.role === "user") {
return message.createdAt;
}
@@ -40,21 +50,47 @@ function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["
return null;
}
/**
* Builds an optimistic thread shell from the detail projection for the window
* where the shell list has not materialized the thread yet (e.g. a thread that
* was just created from this device).
*/
function threadDetailToShell(
environmentId: EnvironmentId,
thread: OrchestrationThread,
projection: OrchestrationV2ThreadProjection,
): EnvironmentThreadShell {
return {
environmentId,
const thread = projection.thread;
const latestRun = deriveLatestThreadRun(projection);
const runtime = deriveThreadRuntime(projection);
const pendingRequest =
projection.runtimeRequests.find((request) => request.status === "pending") ?? null;
return presentThreadShell(environmentId, {
id: thread.id,
projectId: thread.projectId,
title: thread.title,
providerInstanceId: thread.providerInstanceId,
modelSelection: thread.modelSelection,
runtimeMode: thread.runtimeMode,
interactionMode: thread.interactionMode,
branch: thread.branch,
worktreePath: thread.worktreePath,
latestTurn: thread.latestTurn,
activeProviderThreadId: thread.activeProviderThreadId,
lineage: thread.lineage,
forkedFrom: thread.forkedFrom,
createdBy: thread.createdBy,
creationSource: thread.creationSource,
latestRunId: latestRun?.runId ?? null,
activeRunId: runtime?.activeRunId ?? null,
status: runtime?.status ?? "idle",
pendingRuntimeRequest:
pendingRequest === null
? null
: { id: pendingRequest.id, kind: pendingRequest.kind, createdAt: pendingRequest.createdAt },
latestVisibleMessage: null,
latestUserMessageAt: latestUserMessageAt(projection),
hasActionableProposedPlan: false,
itemCount: projection.turnItems.length,
visibleItemCount: projection.visibleTurnItems.length,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
archivedAt: thread.archivedAt,
@@ -62,12 +98,8 @@ function threadDetailToShell(
settledAt: thread.settledAt,
snoozedUntil: thread.snoozedUntil ?? null,
snoozedAt: thread.snoozedAt ?? null,
session: thread.session,
latestUserMessageAt: latestUserMessageAt(thread),
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
};
deletedAt: thread.deletedAt,
});
}
function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
+56
View File
@@ -0,0 +1,56 @@
import { useAtomValue } from "@effect/atom-react";
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
EMPTY_V2_ITEM_SUPPORT,
resolveV2ItemSupport,
v2ItemSupportEqual,
type V2ItemSupport,
} from "@t3tools/client-runtime/state/item-support";
import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { environmentThreadDetails } from "./threads";
interface ItemSupportTarget {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly itemId: TurnItemId;
}
function supportKey(target: ItemSupportTarget): string {
return JSON.stringify(target);
}
function parseSupportKey(key: string): ItemSupportTarget {
return JSON.parse(key) as ItemSupportTarget;
}
const itemSupportAtomFamily = Atom.family((key: string) => {
const target = parseSupportKey(key);
const ref = scopeThreadRef(target.environmentId, target.threadId);
let previous = EMPTY_V2_ITEM_SUPPORT;
return Atom.make((get): V2ItemSupport => {
const scoped = get(environmentThreadDetails.threadAtom(ref));
if (scoped === null) return EMPTY_V2_ITEM_SUPPORT;
const next = resolveV2ItemSupport(scoped.projection, target.itemId);
if (v2ItemSupportEqual(previous, next)) return previous;
previous = next;
return next;
}).pipe(Atom.withLabel(`mobile-v2-item-support:${key}`));
});
export function useV2ItemSupport(target: {
readonly environmentId: EnvironmentId;
readonly sourceThreadId: ThreadId;
readonly sourceItemId: TurnItemId;
}): V2ItemSupport {
return useAtomValue(
itemSupportAtomFamily(
supportKey({
environmentId: target.environmentId,
threadId: target.sourceThreadId,
itemId: target.sourceItemId,
}),
),
);
}
+72
View File
@@ -0,0 +1,72 @@
import {
presentThreadShell,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import {
EnvironmentId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationV2ThreadShell,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
const DEFAULT_TIMESTAMP = "2026-01-01T00:00:00.000Z";
export function makeRawThreadShell(
input: Partial<OrchestrationV2ThreadShell> = {},
): OrchestrationV2ThreadShell {
const id = input.id ?? ThreadId.make("thread-test");
const providerInstanceId = input.providerInstanceId ?? ProviderInstanceId.make("codex");
const now = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
return {
id,
projectId: ProjectId.make("project-test"),
title: "Thread",
providerInstanceId,
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: { rootThreadId: id, parentThreadId: null, relationshipToParent: null },
forkedFrom: null,
createdBy: "user",
creationSource: "mobile",
latestRunId: null,
activeRunId: null,
status: "idle",
pendingRuntimeRequest: null,
latestVisibleMessage: null,
latestUserMessageAt: null,
hasActionableProposedPlan: false,
itemCount: 0,
visibleItemCount: 0,
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
deletedAt: null,
...input,
};
}
export function makeThreadShellFixture(
overrides: Partial<EnvironmentThreadShell> = {},
): EnvironmentThreadShell {
const environmentId = overrides.environmentId ?? EnvironmentId.make("environment-test");
const raw = makeRawThreadShell({
id: overrides.id,
projectId: overrides.projectId,
title: overrides.title,
providerInstanceId: overrides.providerInstanceId,
modelSelection: overrides.modelSelection,
runtimeMode: overrides.runtimeMode,
interactionMode: overrides.interactionMode,
branch: overrides.branch,
worktreePath: overrides.worktreePath,
});
return { ...presentThreadShell(environmentId, raw), ...overrides };
}
+3
View File
@@ -0,0 +1,3 @@
# Server
Node.js WebSocket server for the T3 Code app.
@@ -1,177 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - Measures the real Node HTTP and WebSocket transports.
import * as NodeHttp from "node:http";
import * as NodeZlib from "node:zlib";
import * as NodeSocket from "@effect/platform-node/NodeSocket";
import { WsRpcGroup } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
export class TransferHttpRequestError extends Schema.TaggedErrorClass<TransferHttpRequestError>()(
"TransferHttpRequestError",
{
url: Schema.String,
cause: Schema.Defect(),
},
) {}
export interface HttpTransferMeasurement {
readonly status: number;
readonly contentEncoding: string | null;
readonly encodedBody: Uint8Array;
readonly encodedBodyBytes: number;
readonly decodedBody: Uint8Array;
readonly decodedBodyBytes: number;
/** HTTP response bytes read from the socket, including status line and headers. */
readonly wireBytes: number;
}
export const measureHttpGet = Effect.fn("TransferBudget.measureHttpGet")(function* (input: {
readonly url: string;
readonly headers?: Readonly<Record<string, string>>;
}) {
return yield* Effect.tryPromise({
try: () =>
new Promise<HttpTransferMeasurement>((resolve, reject) => {
let socketBytesBeforeResponse = 0;
const request = NodeHttp.get(
input.url,
{
agent: false,
headers: {
"accept-encoding": "gzip",
connection: "close",
...input.headers,
},
},
(response) => {
const chunks: Buffer[] = [];
response.on("data", (chunk: Buffer) => chunks.push(chunk));
response.once("error", reject);
response.once("end", () => {
try {
const encodedBody = Buffer.concat(chunks);
const header = response.headers["content-encoding"];
const contentEncoding = Array.isArray(header)
? (header[0] ?? null)
: (header ?? null);
const decodedBody =
contentEncoding === "gzip" ? NodeZlib.gunzipSync(encodedBody) : encodedBody;
resolve({
status: response.statusCode ?? 0,
contentEncoding,
encodedBody,
encodedBodyBytes: encodedBody.byteLength,
decodedBody,
decodedBodyBytes: decodedBody.byteLength,
wireBytes: Math.max(0, response.socket.bytesRead - socketBytesBeforeResponse),
});
} catch (cause) {
reject(cause);
}
});
},
);
request.once("socket", (socket) => {
socketBytesBeforeResponse = socket.bytesRead;
});
request.once("error", reject);
request.setTimeout(10_000, () => {
request.destroy(new Error(`Timed out reading ${input.url}`));
});
}),
catch: (cause) => new TransferHttpRequestError({ url: input.url, cause }),
});
});
export interface WebSocketTransferTotals {
readonly wireBytes: number;
readonly decodedBytes: number;
readonly messages: number;
}
export interface WebSocketTransferRecorder {
readonly connect: (
url: string,
protocols: string | string[] | undefined,
cookie: string,
) => globalThis.WebSocket;
readonly totals: () => WebSocketTransferTotals;
readonly negotiatedExtensions: () => string;
}
interface NodeWebSocketWithTransport extends NodeSocket.NodeWS.WebSocket {
readonly _socket?: {
readonly bytesRead: number;
};
}
function rawDataBytes(data: NodeSocket.NodeWS.RawData): number {
if (Array.isArray(data)) {
return data.reduce((total, chunk) => total + chunk.byteLength, 0);
}
return data.byteLength;
}
export function makeWebSocketTransferRecorder(): WebSocketTransferRecorder {
let socket: NodeWebSocketWithTransport | null = null;
let decodedBytes = 0;
let messages = 0;
return {
connect: (url, protocols, cookie) => {
const nextSocket = new NodeSocket.NodeWS.WebSocket(url, protocols, {
headers: { cookie },
perMessageDeflate: true,
}) as NodeWebSocketWithTransport;
socket = nextSocket;
nextSocket.on("message", (data) => {
const bytes = rawDataBytes(data);
decodedBytes += bytes;
messages += 1;
});
return nextSocket as unknown as globalThis.WebSocket;
},
totals: () => ({
wireBytes: socket?._socket?.bytesRead ?? 0,
decodedBytes,
messages,
}),
negotiatedExtensions: () => socket?.extensions ?? "",
};
}
export function transferDelta(
start: WebSocketTransferTotals,
end: WebSocketTransferTotals,
): WebSocketTransferTotals {
return {
wireBytes: Math.max(0, end.wireBytes - start.wireBytes),
decodedBytes: Math.max(0, end.decodedBytes - start.decodedBytes),
messages: Math.max(0, end.messages - start.messages),
};
}
export function countingWsRpcProtocolLayer(input: {
readonly url: string;
readonly cookie: string;
readonly recorder: WebSocketTransferRecorder;
}) {
const webSocketConstructorLayer = Layer.succeed(Socket.WebSocketConstructor, (url, protocols) =>
input.recorder.connect(url, protocols, input.cookie),
);
return RpcClient.layerProtocolSocket().pipe(
Layer.provide(
Socket.layerWebSocket(input.url, { openTimeout: "10 seconds" }).pipe(
Layer.provide(webSocketConstructorLayer),
),
),
Layer.provide(RpcSerialization.layerJson),
);
}
export const makeCountingWsRpcClient = RpcClient.make(WsRpcGroup);
export type CountingWsRpcClient = Effect.Success<typeof makeCountingWsRpcClient>;
@@ -1,578 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
CodexSettings,
ProviderDriverKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as CheckpointStore from "../src/checkpointing/CheckpointStore.ts";
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../src/orchestration/ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../src/orchestration/ThreadPlanProgress.ts";
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
import { CheckpointReactor } from "../src/orchestration/Services/CheckpointReactor.ts";
import { ProviderRuntimeIngestionService } from "../src/orchestration/Services/ProviderRuntimeIngestion.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../src/orchestration/Services/OrchestrationEngine.ts";
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
import {
RuntimeReceiptBus,
type OrchestrationRuntimeReceipt,
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import * as WorkspaceEntries from "../src/workspace/WorkspaceEntries.ts";
import * as WorkspacePaths from "../src/workspace/WorkspacePaths.ts";
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
import * as AgentAwarenessRelay from "../src/relay/AgentAwarenessRelay.ts";
const decodeCodexSettings = Schema.decodeEffect(CodexSettings);
function runGit(cwd: string, args: ReadonlyArray<string>) {
return NodeChildProcess.execFileSync("git", args, {
cwd,
stdio: ["ignore", "pipe", "pipe"],
encoding: "utf8",
});
}
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "Test User"]);
const fileSystem = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
});
export function gitRefExists(cwd: string, ref: string): boolean {
try {
runGit(cwd, ["show-ref", "--verify", "--quiet", ref]);
return true;
} catch {
return false;
}
}
export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
return runGit(cwd, ["show", `${ref}:${filePath}`]);
}
class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
"WaitForTimeoutError",
{
description: Schema.String,
},
) {}
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs?: number,
): Effect.Effect<A, never>;
function waitFor<A, B extends A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => value is B,
description: string,
timeoutMs?: number,
): Effect.Effect<B, never>;
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 40_000,
): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
const retrySchedule = Schedule.spaced(`${retryIntervalMs} millis`);
return read.pipe(
Effect.filterOrFail(predicate, () => RETRY_SIGNAL),
Effect.retry({
schedule: retrySchedule,
times: maxRetries,
while: (error) => error === RETRY_SIGNAL,
}),
Effect.mapError((error) =>
error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
),
Effect.orDie,
);
}
class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
"OrchestrationHarnessRuntimeError",
{
operation: Schema.String,
cause: Schema.optional(Schema.Defect()),
},
) {}
const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
Effect.tryPromise({
try: run,
catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
});
export interface OrchestrationIntegrationHarness {
readonly rootDir: string;
readonly workspaceDir: string;
readonly dbPath: string;
readonly adapterHarness: TestProviderAdapterHarness | null;
readonly engine: OrchestrationEngineShape;
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
readonly providerService: ProviderService["Service"];
readonly checkpointStore: CheckpointStore.CheckpointStore["Service"];
readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
readonly waitForThread: (
threadId: string,
predicate: (thread: OrchestrationThread) => boolean,
timeoutMs?: number,
) => Effect.Effect<OrchestrationThread, never>;
readonly waitForDomainEvent: (
predicate: (event: OrchestrationEvent) => boolean,
timeoutMs?: number,
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
readonly waitForPendingApproval: (
requestId: string,
predicate: (row: {
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
}) => boolean,
timeoutMs?: number,
) => Effect.Effect<
{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
},
never
>;
readonly waitForReceipt: {
(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
};
readonly drainProviderRuntime: Effect.Effect<void>;
readonly drainCheckpointReactor: Effect.Effect<void>;
readonly dispose: Effect.Effect<void, never>;
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderDriverKind;
readonly realCodex?: boolean;
}
export const makeOrchestrationIntegrationHarness = (
options?: MakeOrchestrationIntegrationHarnessOptions,
) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
? null
: yield* makeTestProviderAdapterHarness({
provider,
});
const fakeRegistry = adapterHarness
? Layer.succeed(
ProviderAdapterRegistry,
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
});
const workspaceDir = path.join(rootDir, "workspace");
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
Effect.provideService(Path.Path, path),
);
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
yield* initializeGitWorkspace(workspaceDir);
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
);
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
const realCodexRegistry = Layer.effect(
ProviderAdapterRegistry,
Effect.gen(function* () {
const codexSettings = yield* decodeCodexSettings({});
const codexAdapter = yield* makeCodexAdapter(codexSettings);
return makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: codexAdapter,
});
}),
).pipe(
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
const providerLayer = useRealCodex
? makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(realCodexRegistry),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
)
: makeProviderServiceLive().pipe(
Layer.provide(providerSessionDirectoryLayer),
Layer.provide(fakeRegistry!),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
);
const providerRegistryLayer = makeProviderRegistryLayer();
const checkpointStoreLayer = CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
projectionSnapshotQueryLayer,
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
providerLayer,
RuntimeReceiptBusTest,
).pipe(
Layer.provideMerge(ThreadBackgroundLiveness.layer),
Layer.provideMerge(ThreadPlanProgress.layer),
);
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(serverSettingsLayer),
);
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
renameBranch: (input: {
readonly cwd: string;
readonly oldBranch: string;
readonly newBranch: string;
}) => Effect.succeed({ branch: input.newBranch }),
});
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: "update" }),
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitWorkflowLayer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
Layer.succeed(VcsStatusBroadcaster, {
getStatus: () => Effect.die("getStatus should not be called in this test"),
refreshLocalStatus: () =>
Effect.succeed({
isRepo: true,
hasPrimaryRemote: false,
isDefaultRef: true,
refName: "main",
hasWorkingTreeChanges: false,
workingTree: { files: [], insertions: 0, deletions: 0 },
}),
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
streamStatus: () => Stream.empty,
}),
),
Layer.provideMerge(
WorkspaceEntries.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provideMerge(VcsDriverRegistry.layer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePaths.layer),
Layer.provideMerge(VcsProcess.layer),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
Layer.provideMerge(
Layer.succeed(ThreadDeletionReactor, {
start: () => Effect.void,
drain: Effect.void,
}),
),
Layer.provideMerge(
Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, {
publishThread: () => Effect.void,
start: () => Effect.void,
}),
),
);
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
Layer.provideMerge(providerRegistryLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(layer);
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
runtime.runPromise(Effect.service(OrchestrationEngineService)),
).pipe(Effect.orDie);
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
runtime.runPromise(Effect.service(OrchestrationReactor)),
).pipe(Effect.orDie);
const providerRuntimeIngestion = yield* tryRuntimePromise(
"load ProviderRuntimeIngestion service",
() => runtime.runPromise(Effect.service(ProviderRuntimeIngestionService)),
).pipe(Effect.orDie);
const checkpointReactor = yield* tryRuntimePromise("load CheckpointReactor service", () =>
runtime.runPromise(Effect.service(CheckpointReactor)),
).pipe(Effect.orDie);
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
).pipe(Effect.orDie);
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
runtime.runPromise(Effect.service(ProviderService)),
).pipe(Effect.orDie);
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
runtime.runPromise(Effect.service(CheckpointStore.CheckpointStore)),
).pipe(Effect.orDie);
const checkpointRepository = yield* tryRuntimePromise(
"load ProjectionCheckpointRepository service",
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
).pipe(Effect.orDie);
const pendingApprovalRepository = yield* tryRuntimePromise(
"load ProjectionPendingApprovalRepository service",
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
).pipe(Effect.orDie);
const runtimeReceiptBus = yield* tryRuntimePromise("load RuntimeReceiptBus service", () =>
runtime.runPromise(Effect.service(RuntimeReceiptBus)),
).pipe(Effect.orDie);
const scope = yield* Scope.make("sequential");
yield* tryRuntimePromise("start OrchestrationReactor", () =>
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* Effect.sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
threadId,
predicate,
timeoutMs,
) =>
waitFor(
snapshotQuery
.getSnapshot()
.pipe(
Effect.map(
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
),
),
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
`projected thread '${threadId}'`,
timeoutMs,
) as Effect.Effect<OrchestrationThread, never>;
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
predicate,
timeoutMs,
) =>
waitFor(
Stream.runCollect(engine.readEvents(0)).pipe(
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
),
(events) => events.some(predicate),
"domain event",
timeoutMs,
);
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
requestId,
predicate,
timeoutMs,
) =>
waitFor(
pendingApprovalRepository
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
.pipe(
Effect.map((row) =>
Option.match(row, {
onNone: () => null,
onSome: (value) => ({
status: value.status,
decision: value.decision,
resolvedAt: value.resolvedAt,
}),
}),
),
),
(
row,
): row is {
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
} => row !== null && predicate(row),
`pending approval '${requestId}'`,
timeoutMs,
) as Effect.Effect<
{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
},
never
>;
function waitForReceipt(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
function waitForReceipt(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
) {
const readMatchingReceipt = Ref.get(receiptHistory).pipe(
Effect.map((history) => history.find(predicate)),
);
return waitFor(
readMatchingReceipt,
(receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
"runtime receipt",
timeoutMs,
);
}
let disposed = false;
const dispose = Effect.gen(function* () {
if (disposed) {
return;
}
disposed = true;
const shutdown = Effect.gen(function* () {
const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
const failureCause = Exit.isFailure(closeScopeExit)
? closeScopeExit.cause
: Exit.isFailure(disposeRuntimeExit)
? disposeRuntimeExit.cause
: null;
if (failureCause) {
return yield* Effect.failCause(failureCause);
}
});
yield* shutdown;
});
return {
rootDir,
workspaceDir,
dbPath,
adapterHarness,
engine,
snapshotQuery,
providerService,
checkpointStore,
checkpointRepository,
pendingApprovalRepository,
waitForThread,
waitForDomainEvent,
waitForPendingApproval,
waitForReceipt,
drainProviderRuntime: providerRuntimeIngestion.drain,
drainCheckpointReactor: checkpointReactor.drain,
dispose,
} satisfies OrchestrationIntegrationHarness;
});
@@ -1,568 +0,0 @@
import {
ApprovalRequestId,
EventId,
ProviderApprovalDecision,
ProviderRuntimeEvent,
RuntimeSessionId,
ProviderSession,
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderDriverKind,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import {
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../src/provider/Errors.ts";
import type {
ProviderAdapterShape,
ProviderThreadSnapshot,
ProviderThreadTurnSnapshot,
} from "../src/provider/Services/ProviderAdapter.ts";
export interface TestTurnResponse {
readonly events: ReadonlyArray<FixtureProviderRuntimeEvent>;
readonly mutateWorkspace?: (input: {
readonly cwd: string;
readonly turnCount: number;
}) => Effect.Effect<void, never>;
}
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderDriverKind;
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
readonly itemId?: string | undefined;
readonly requestId?: string | undefined;
readonly payload?: unknown | undefined;
readonly [key: string]: unknown;
};
// Temporary alias while fixtures migrate to the new name.
export type LegacyProviderRuntimeEvent = FixtureProviderRuntimeEvent;
interface SessionState {
readonly session: ProviderSession;
snapshot: ProviderThreadSnapshot;
turnCount: number;
readonly queuedResponses: Array<TestTurnResponse>;
readonly rollbackCalls: Array<number>;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupted" | "cancelled" {
if (
value === "completed" ||
value === "failed" ||
value === "interrupted" ||
value === "cancelled"
) {
return value;
}
return "completed";
}
function mapRequestType(
requestKind: unknown,
): "command_execution_approval" | "file_change_approval" | "unknown" {
if (requestKind === "command") {
return "command_execution_approval";
}
if (requestKind === "file-change") {
return "file_change_approval";
}
return "unknown";
}
function mapItemType(toolKind: unknown): "command_execution" | "file_change" | "unknown" {
if (toolKind === "command") {
return "command_execution";
}
if (toolKind === "file-change") {
return "file_change";
}
return "unknown";
}
function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRuntimeEvent {
const type = typeof rawEvent.type === "string" ? rawEvent.type : "";
switch (type) {
case "turn.started":
return {
...rawEvent,
type: "turn.started",
payload: isRecord(rawEvent.payload) ? rawEvent.payload : {},
} as ProviderRuntimeEvent;
case "turn.completed":
return {
...rawEvent,
type: "turn.completed",
payload: isRecord(rawEvent.payload)
? rawEvent.payload
: {
state: normalizeTurnState(rawEvent.status),
},
} as ProviderRuntimeEvent;
case "message.delta":
return {
...rawEvent,
type: "content.delta",
payload: {
streamKind: "assistant_text",
delta: typeof rawEvent.delta === "string" ? rawEvent.delta : "",
},
} as ProviderRuntimeEvent;
case "message.completed":
return {
...rawEvent,
type: "item.completed",
payload: {
itemType: "assistant_message",
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
},
} as ProviderRuntimeEvent;
case "tool.started":
return {
...rawEvent,
type: "item.started",
payload: {
itemType: mapItemType(rawEvent.toolKind),
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
},
} as ProviderRuntimeEvent;
case "tool.completed":
return {
...rawEvent,
type: "item.completed",
payload: {
itemType: mapItemType(rawEvent.toolKind),
status: "completed",
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
},
} as ProviderRuntimeEvent;
case "approval.requested":
return {
...rawEvent,
type: "request.opened",
payload: {
requestType: mapRequestType(rawEvent.requestKind),
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
},
} as ProviderRuntimeEvent;
case "approval.resolved":
return {
...rawEvent,
type: "request.resolved",
payload: {
requestType: mapRequestType(rawEvent.requestKind),
...(typeof rawEvent.decision === "string" ? { decision: rawEvent.decision } : {}),
},
} as ProviderRuntimeEvent;
default:
return rawEvent as ProviderRuntimeEvent;
}
}
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: ProviderDriverKind;
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
readonly queueTurnResponseForNextSession: (
response: TestTurnResponse,
) => Effect.Effect<void, never>;
readonly getStartCount: () => number;
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
readonly listActiveSessionIds: () => ReadonlyArray<ThreadId>;
readonly getApprovalResponses: (threadId: ThreadId) => ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}>;
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: ProviderDriverKind;
}
function nowIso(): string {
return "2026-01-01T00:00:00.000Z";
}
function sessionNotFound(
provider: ProviderDriverKind,
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
provider,
threadId: String(threadId),
});
}
function missingSessionEffect(
provider: ProviderDriverKind,
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
}
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
Effect.gen(function* () {
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
let eventCount = 0;
const sessions = new Map<ThreadId, SessionState>();
const queuedResponsesForNextSession: TestTurnResponse[] = [];
const interruptCallsBySession = new Map<ThreadId, Array<TurnId | undefined>>();
const approvalResponsesBySession = new Map<
ThreadId,
Array<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}>
>();
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const nextEventId = (threadId: ThreadId) => {
eventCount += 1;
return EventId.make(`test-provider:${provider}:${threadId}:${eventCount}`);
};
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== provider) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "startSession",
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
});
}
sessionCount += 1;
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
provider,
...(input.providerInstanceId !== undefined
? { providerInstanceId: input.providerInstanceId }
: {}),
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(threadId, {
session,
snapshot: {
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
});
return session;
});
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.make(`turn-${turnCount}`);
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
const assistantDeltas: string[] = [];
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: nextEventId(input.threadId),
provider,
sessionId: RuntimeSessionId.make(String(input.threadId)),
};
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
const runtimeEvent = normalizeFixtureEvent(rawEvent);
const runtimeType = (runtimeEvent as { type: string }).type;
if (runtimeType === "content.delta") {
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta);
}
} else if (runtimeType === "message.delta") {
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
if (typeof legacyDelta === "string") {
assistantDeltas.push(legacyDelta);
}
}
if (runtimeEvent.type === "turn.completed") {
deferredTurnCompletedEvents.push(runtimeEvent);
continue;
}
yield* emit(runtimeEvent);
}
if (response.mutateWorkspace && state.session.cwd) {
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
}
const userItem = {
type: "userMessage",
content: [{ type: "text", text: input.input }],
} as const;
const assistantText = assistantDeltas.join("");
const nextItems: Array<unknown> =
assistantText.length > 0
? [userItem, { type: "agentMessage", text: assistantText }]
: [userItem];
const nextTurn: ProviderThreadTurnSnapshot = {
id: turnId,
items: nextItems,
};
state.snapshot = {
threadId: state.snapshot.threadId,
turns: [...state.snapshot.turns, nextTurn],
};
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: nextEventId(input.threadId),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
turnId,
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
}
return {
threadId: state.snapshot.threadId,
turnId,
} satisfies ProviderTurnStartResult;
});
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
);
}
return Effect.sync(() => {
state.rollbackCalls.push(numTurns);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
};
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
};
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const queueTurnResponse = (
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const getStartCount = (): number => sessionCount;
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
Array.from(sessions.values(), (state) => state.session.threadId);
const getApprovalResponses = (
threadId: ThreadId,
): ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
@@ -1,212 +0,0 @@
import type { ProviderDriverKind } from "@t3tools/contracts";
import type {
HttpTransferMeasurement,
WebSocketTransferTotals,
} from "./NetworkTransferMeasurement.integration.ts";
import {
TRANSFER_HISTORY_MCP_RESULT_BYTES,
TRANSFER_HISTORY_TOOLS_PER_TURN,
TRANSFER_HISTORY_TURN_COUNT,
TRANSFER_MEASURED_MCP_RESULT_BYTES,
TRANSFER_MEASURED_TOOLS,
} from "./fixtures/transferBudget.ts";
export interface TransferBudgetRun {
readonly provider: ProviderDriverKind;
readonly threadSnapshot: HttpTransferMeasurement;
readonly measuredTurnWebSocket: WebSocketTransferTotals;
}
interface ProviderTransferBudget {
readonly totalWireBytes: number;
readonly threadSnapshotWireBytes: number;
readonly measuredTurnWebSocketWireBytes: number;
readonly measuredTurnWebSocketDecodedBytes: number;
readonly measuredTurnWebSocketMessages: number;
}
// These caps leave roughly 30% headroom above the client projection of the
// deterministic 9 MB retained-result fixture. Full MCP results stay in
// persistence, so accidentally shipping them again exceeds these caps by
// orders of magnitude. The CI report preserves exact values for review.
const TRANSFER_BUDGET = {
totalWireBytes: 15_500,
threadSnapshotWireBytes: 7_500,
measuredTurnWebSocketWireBytes: 8_000,
measuredTurnWebSocketDecodedBytes: 68_000,
measuredTurnWebSocketMessages: 21,
} satisfies ProviderTransferBudget;
export const TRANSFER_BUDGETS: Readonly<Record<string, ProviderTransferBudget>> = {
codex: TRANSFER_BUDGET,
claudeAgent: TRANSFER_BUDGET,
};
function totalWireBytes(run: TransferBudgetRun): number {
return run.threadSnapshot.wireBytes + run.measuredTurnWebSocket.wireBytes;
}
function observedTransfer(run: TransferBudgetRun) {
return {
totalWireBytes: totalWireBytes(run),
threadSnapshotWireBytes: run.threadSnapshot.wireBytes,
threadSnapshotDecodedBytes: run.threadSnapshot.decodedBodyBytes,
measuredTurnWebSocketWireBytes: run.measuredTurnWebSocket.wireBytes,
measuredTurnWebSocketDecodedBytes: run.measuredTurnWebSocket.decodedBytes,
measuredTurnWebSocketMessages: run.measuredTurnWebSocket.messages,
};
}
/** Machine-readable input for the trusted PR comment publisher. */
export function formatTransferBudgetResult(runs: ReadonlyArray<TransferBudgetRun>): string {
const providers = Object.fromEntries(
runs.flatMap((run) => {
const ceiling = TRANSFER_BUDGETS[run.provider];
return ceiling ? [[run.provider, { observed: observedTransfer(run), ceiling }]] : [];
}),
);
return `${JSON.stringify(
{
schemaVersion: 1,
scenario: {
id: "thread-transfer-v1",
historyTurns: TRANSFER_HISTORY_TURN_COUNT,
historyCommandToolsPerTurn: TRANSFER_HISTORY_TOOLS_PER_TURN,
historyMcpResultBytes: TRANSFER_HISTORY_MCP_RESULT_BYTES,
measuredCommandTools: TRANSFER_MEASURED_TOOLS,
measuredMcpResultBytes: TRANSFER_MEASURED_MCP_RESULT_BYTES,
},
providers,
},
null,
2,
)}\n`;
}
function formatBytes(bytes: number): string {
if (bytes < 1_024) return `${bytes} B`;
if (bytes >= 1_024 * 1_024) {
return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB (${bytes.toLocaleString("en-US")} B)`;
}
return `${(bytes / 1_024).toFixed(1)} KiB (${bytes.toLocaleString("en-US")} B)`;
}
function row(
provider: ProviderDriverKind,
phase: string,
metric: string,
observed: number,
maximum: number,
format: (value: number) => string = formatBytes,
): string {
const status = observed <= maximum ? "PASS" : "FAIL";
return `| ${provider} | ${phase} | ${metric} | ${format(observed)} | ${format(maximum)} | ${status} |`;
}
export function transferBudgetViolations(runs: ReadonlyArray<TransferBudgetRun>): string[] {
const violations: string[] = [];
for (const run of runs) {
const budget = TRANSFER_BUDGETS[run.provider];
if (!budget) {
violations.push(`${run.provider}: no transfer budget is configured`);
continue;
}
const checks = [
["total thread wire bytes", totalWireBytes(run), budget.totalWireBytes],
["thread snapshot wire bytes", run.threadSnapshot.wireBytes, budget.threadSnapshotWireBytes],
[
"measured-turn WebSocket wire bytes",
run.measuredTurnWebSocket.wireBytes,
budget.measuredTurnWebSocketWireBytes,
],
[
"measured-turn WebSocket decoded bytes",
run.measuredTurnWebSocket.decodedBytes,
budget.measuredTurnWebSocketDecodedBytes,
],
[
"measured-turn WebSocket messages",
run.measuredTurnWebSocket.messages,
budget.measuredTurnWebSocketMessages,
],
] as const;
for (const [metric, observed, maximum] of checks) {
if (observed > maximum) {
violations.push(`${run.provider}: ${metric} was ${observed}, maximum ${maximum}`);
}
}
}
return violations;
}
export function formatTransferBudgetReport(runs: ReadonlyArray<TransferBudgetRun>): string {
const lines = [
"# T3 Code thread transfer budget",
"",
"Wire values are thread data bytes read from local HTTP and WebSocket sockets. HTTP includes response headers; WebSocket measurement starts after the resumed thread subscription synchronizes. TCP/IP, TLS framing, and the WebSocket upgrade are excluded. WebSocket permessage-deflate is negotiated.",
`Scenario: ${TRANSFER_HISTORY_TURN_COUNT} historical turns with ${TRANSFER_HISTORY_TOOLS_PER_TURN} command tools and one retained ${formatBytes(TRANSFER_HISTORY_MCP_RESULT_BYTES)} MCP result each, followed by one measured turn with ${TRANSFER_MEASURED_TOOLS} command tools and a retained ${formatBytes(TRANSFER_MEASURED_MCP_RESULT_BYTES)} MCP result. Payload sizes are calibrated from heavy local Codex and Claude histories and contain no user data.`,
"",
"| Provider | Total thread wire | Budget | Result |",
"| --- | ---: | ---: | --- |",
...runs.flatMap((run) => {
const budget = TRANSFER_BUDGETS[run.provider];
if (!budget) return [];
const observed = observedTransfer(run).totalWireBytes;
return [
`| ${run.provider} | ${formatBytes(observed)} | ${formatBytes(budget.totalWireBytes)} | ${observed <= budget.totalWireBytes ? "PASS" : "FAIL"} |`,
];
}),
"",
"## Detailed measurements",
"",
"| Provider | Phase | Metric | Observed | Budget | Result |",
"| --- | --- | --- | ---: | ---: | --- |",
];
for (const run of runs) {
const budget = TRANSFER_BUDGETS[run.provider];
if (!budget) continue;
lines.push(
row(
run.provider,
"thread snapshot",
"HTTP wire",
run.threadSnapshot.wireBytes,
budget.threadSnapshotWireBytes,
),
row(
run.provider,
"measured turn",
"WebSocket wire",
run.measuredTurnWebSocket.wireBytes,
budget.measuredTurnWebSocketWireBytes,
),
row(
run.provider,
"measured turn",
"WebSocket decoded",
run.measuredTurnWebSocket.decodedBytes,
budget.measuredTurnWebSocketDecodedBytes,
),
row(
run.provider,
"measured turn",
"WebSocket messages",
run.measuredTurnWebSocket.messages,
budget.measuredTurnWebSocketMessages,
String,
),
);
}
lines.push("", "## Compression diagnostics", "");
for (const run of runs) {
lines.push(
`- ${run.provider}: thread snapshot ${formatBytes(run.threadSnapshot.decodedBodyBytes)} decoded to ${formatBytes(run.threadSnapshot.encodedBodyBytes)} gzip.`,
);
}
return `${lines.join("\n")}\n`;
}
@@ -1,128 +0,0 @@
import {
CommandId,
defaultInstanceIdForDriver,
DEFAULT_MODEL,
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_PROVIDER_INTERACTION_MODE,
MessageId,
ProjectId,
ProviderDriverKind,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import type { TurnProcessingQuiescedReceipt } from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import type { OrchestrationIntegrationHarness } from "./OrchestrationEngineHarness.integration.ts";
import {
expectedRecordedAssistantText,
makeRecordedTransferTurn,
TRANSFER_HISTORY_TURN_COUNT,
} from "./fixtures/transferBudget.ts";
export const TRANSFER_PROJECT_ID = ProjectId.make("transfer-budget-project");
export const TRANSFER_THREAD_ID = ThreadId.make("transfer-budget-thread");
export const TRANSFER_MEASURED_TURN_INDEX = TRANSFER_HISTORY_TURN_COUNT;
export function transferModelSelection(provider: ProviderDriverKind) {
return {
instanceId: defaultInstanceIdForDriver(provider),
model: DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL,
};
}
function turnTimestamp(turnIndex: number): string {
return `2026-06-01T00:${String(turnIndex).padStart(2, "0")}:00.000Z`;
}
export const TRANSFER_MEASURED_TURN_CREATED_AT = turnTimestamp(TRANSFER_MEASURED_TURN_INDEX);
const waitForTurnQuiesced = Effect.fn("TransferBudget.waitForTurnQuiesced")(function* (
harness: OrchestrationIntegrationHarness,
checkpointTurnCount: number,
) {
const receipt = yield* harness.waitForReceipt(
(receipt): receipt is TurnProcessingQuiescedReceipt =>
receipt.type === "turn.processing.quiesced" &&
receipt.threadId === TRANSFER_THREAD_ID &&
receipt.checkpointTurnCount === checkpointTurnCount,
);
yield* harness.drainProviderRuntime;
yield* harness.drainCheckpointReactor;
return receipt;
});
export const seedTransferBudgetHistory = Effect.fn("TransferBudget.seedHistory")(function* (
harness: OrchestrationIntegrationHarness,
provider: ProviderDriverKind,
) {
if (!harness.adapterHarness) {
return yield* Effect.die(new Error("Transfer budget history requires the replay adapter."));
}
const modelSelection = transferModelSelection(provider);
yield* harness.engine.dispatch({
type: "project.create",
commandId: CommandId.make(`transfer:${provider}:project-create`),
projectId: TRANSFER_PROJECT_ID,
title: "Transfer Budget Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: modelSelection,
createdAt: turnTimestamp(0),
});
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make(`transfer:${provider}:thread-create`),
threadId: TRANSFER_THREAD_ID,
projectId: TRANSFER_PROJECT_ID,
title: `${provider} transfer history`,
modelSelection,
runtimeMode: "approval-required",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
branch: "main",
worktreePath: harness.workspaceDir,
createdAt: turnTimestamp(0),
});
for (let turnIndex = 0; turnIndex < TRANSFER_HISTORY_TURN_COUNT; turnIndex += 1) {
const response = makeRecordedTransferTurn(provider, turnIndex);
if (turnIndex === 0) {
yield* harness.adapterHarness.queueTurnResponseForNextSession(response);
} else {
yield* harness.adapterHarness.queueTurnResponse(TRANSFER_THREAD_ID, response);
}
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make(`transfer:${provider}:turn:${turnIndex + 1}`),
threadId: TRANSFER_THREAD_ID,
message: {
messageId: MessageId.make(`transfer-user-${turnIndex + 1}`),
role: "user",
text: `Inspect transfer behavior for historical turn ${turnIndex + 1}.`,
attachments: [],
},
modelSelection,
runtimeMode: "approval-required",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
createdAt: turnTimestamp(turnIndex),
});
yield* waitForTurnQuiesced(harness, turnIndex + 1);
}
});
export const queueMeasuredTransferTurn = Effect.fn("TransferBudget.queueMeasuredTurn")(function* (
harness: OrchestrationIntegrationHarness,
provider: ProviderDriverKind,
) {
if (!harness.adapterHarness) {
return yield* Effect.die(new Error("Transfer budget measurement requires the replay adapter."));
}
const response = makeRecordedTransferTurn(provider, TRANSFER_MEASURED_TURN_INDEX);
yield* harness.adapterHarness.queueTurnResponse(TRANSFER_THREAD_ID, response);
});
export function expectedMeasuredAssistantText(provider: ProviderDriverKind): string {
return expectedRecordedAssistantText(provider, TRANSFER_MEASURED_TURN_INDEX);
}
export { TRANSFER_HISTORY_TURN_COUNT, waitForTurnQuiesced };
@@ -1,162 +0,0 @@
import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
const PROVIDER = ProviderDriverKind.make("codex");
const SESSION_ID = "fixture-session";
const THREAD_ID = "fixture-thread";
const TURN_ID = "fixture-turn";
const REQUEST_ID = RuntimeRequestId.make("req-1");
function baseEvent(
eventId: string,
createdAt: string,
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
return {
eventId: EventId.make(eventId),
provider: PROVIDER,
sessionId: SESSION_ID,
createdAt,
};
}
export const codexTurnTextFixture = [
{
type: "turn.started",
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {},
},
{
type: "content.delta",
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {
streamKind: "assistant_text",
delta: "I will make a small update.\n",
},
},
{
type: "content.delta",
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {
streamKind: "assistant_text",
delta: "Done.\n",
},
},
{
type: "turn.completed",
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {
state: "completed",
},
},
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
export const codexTurnToolFixture = [
{
type: "turn.started",
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {},
},
{
type: "item.started",
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {
itemType: "command_execution",
title: "Ran command",
detail: "echo integration",
},
},
{
type: "item.completed",
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
detail: "echo integration",
},
},
{
type: "content.delta",
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {
streamKind: "assistant_text",
delta: "Applied the requested edit.\n",
},
},
{
type: "turn.completed",
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {
state: "completed",
},
},
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
export const codexTurnApprovalFixture = [
{
type: "turn.started",
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {},
},
{
type: "request.opened",
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
requestId: REQUEST_ID,
payload: {
requestType: "command_execution_approval",
detail: "Please approve command",
},
},
{
type: "request.resolved",
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
requestId: REQUEST_ID,
payload: {
requestType: "command_execution_approval",
decision: "accept",
},
},
{
type: "content.delta",
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {
streamKind: "assistant_text",
delta: "Approval received and command executed.\n",
},
},
{
type: "turn.completed",
...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"),
threadId: THREAD_ID,
turnId: TURN_ID,
payload: {
state: "completed",
},
},
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
@@ -1,372 +0,0 @@
import { EventId, ProviderDriverKind } from "@t3tools/contracts";
import type {
FixtureProviderRuntimeEvent,
TestTurnResponse,
} from "../TestProviderAdapter.integration.ts";
const FIXTURE_THREAD_ID = "transfer-budget-thread";
const FIXTURE_TURN_ID = "transfer-budget-turn";
export const TRANSFER_HISTORY_TURN_COUNT = 10;
export const TRANSFER_HISTORY_TOOLS_PER_TURN = 5;
export const TRANSFER_MEASURED_TOOLS = 20;
export const TRANSFER_HISTORY_MCP_RESULT_BYTES = 900_000;
export const TRANSFER_MEASURED_MCP_RESULT_BYTES = 1_100_000;
const sourceModules = [
"connection/session.ts",
"connection/supervisor.ts",
"rpc/client.ts",
"rpc/protocol.ts",
"state/threads.ts",
"state/threadReducer.ts",
"state/threadSnapshotHttp.ts",
"orchestration/http.ts",
"orchestration/Normalizer.ts",
"orchestration/ActivityPayloadProjection.ts",
"provider/ProviderService.ts",
"provider/ProviderRuntimeIngestion.ts",
"persistence/ProjectionSnapshotQuery.ts",
"persistence/OrchestrationEventStore.ts",
"checkpointing/CheckpointStore.ts",
"checkpointing/CheckpointDiffQuery.ts",
"server.ts",
] as const;
function fixtureTimestamp(turnIndex: number, eventIndex: number): string {
const minute = String(turnIndex).padStart(2, "0");
const second = String(Math.floor(eventIndex / 1_000)).padStart(2, "0");
const millisecond = String(eventIndex % 1_000).padStart(3, "0");
return `2026-06-01T00:${minute}:${second}.${millisecond}Z`;
}
function mix(value: number): number {
let mixed = value | 0;
mixed ^= mixed >>> 16;
mixed = Math.imul(mixed, 0x7feb352d);
mixed ^= mixed >>> 15;
mixed = Math.imul(mixed, 0x846ca68b);
mixed ^= mixed >>> 16;
return mixed >>> 0;
}
function digest(seed: number): string {
return [0, 1, 2, 3]
.map((offset) =>
mix(seed + offset * 0x9e3779b9)
.toString(16)
.padStart(8, "0"),
)
.join("");
}
/** Produces safe, deterministic output with enough entropy to exercise gzip. */
function diagnosticOutput(input: {
readonly provider: ProviderDriverKind;
readonly turnIndex: number;
readonly toolIndex: number;
readonly targetBytes: number;
}): string {
const chunks: string[] = [];
const providerSeed = input.provider === "codex" ? 0x43_4f_44_45 : 0x43_4c_41_55;
let length = 0;
let lineIndex = 0;
while (length < input.targetBytes) {
const modulePath = sourceModules[(input.toolIndex + lineIndex) % sourceModules.length];
const seed =
providerSeed + input.turnIndex * 100_003 + input.toolIndex * 10_007 + lineIndex * 101;
const line =
`${String(lineIndex + 1).padStart(6, "0")} ${modulePath} ` +
`operation=project-transfer-${input.turnIndex + 1}-${input.toolIndex + 1} ` +
`cursor=${mix(seed)} digest=${digest(seed)} status=completed\n`;
chunks.push(line);
length += line.length;
lineIndex += 1;
}
return chunks.join("").slice(0, input.targetBytes);
}
function assistantChunks(provider: ProviderDriverKind, turnIndex: number): ReadonlyArray<string> {
const providerName = provider === "codex" ? "Codex" : "Claude";
const paragraphs: string[] = [
`I traced the ${providerName} request through the environment connection and orchestration layers. `,
];
let paragraphIndex = 0;
while (paragraphs.join("").length < 4_096) {
const modulePath = sourceModules[paragraphIndex % sourceModules.length];
paragraphs.push(
`Pass ${paragraphIndex + 1} reviewed ${modulePath} for turn ${turnIndex + 1}. ` +
"The shell cursor stayed monotonic, the thread snapshot remained resumable, and the client received only incremental events. ",
);
paragraphIndex += 1;
}
const text = paragraphs.join("").slice(0, 4_096);
return Array.from({ length: Math.ceil(text.length / 256) }, (_, index) =>
text.slice(index * 256, (index + 1) * 256),
);
}
export function expectedRecordedAssistantText(
provider: ProviderDriverKind,
turnIndex: number,
): string {
return assistantChunks(provider, turnIndex).join("");
}
function unifiedDiff(provider: ProviderDriverKind, turnIndex: number): string {
const lines = sourceModules
.slice(0, 8)
.flatMap((modulePath, index) => [
`diff --git a/${modulePath} b/${modulePath}`,
`--- a/${modulePath}`,
`+++ b/${modulePath}`,
`@@ -${index + 1},2 +${index + 1},3 @@`,
` const provider = "${provider}";`,
`+const transferTurn = ${turnIndex + 1};`,
`+const transferSample = ${1_500 + index * 97};`,
]);
return lines.join("\n");
}
function baseEvent(
provider: ProviderDriverKind,
turnIndex: number,
eventIndex: number,
): Pick<FixtureProviderRuntimeEvent, "eventId" | "provider" | "createdAt" | "threadId"> {
return {
eventId: EventId.make(`recorded:${provider}:${turnIndex}:${eventIndex}`),
provider,
createdAt: fixtureTimestamp(turnIndex, eventIndex),
threadId: FIXTURE_THREAD_ID,
};
}
/**
* Synthetic canonical events calibrated from heavy local Codex and Claude
* threads. Ten historical turns produce 9 MB of retained MCP results without
* committing user content. Command output is intentionally modest because the
* client projection strips it.
*/
export function makeRecordedTransferTurn(
provider: ProviderDriverKind,
turnIndex: number,
): TestTurnResponse {
const measuredTurn = turnIndex >= TRANSFER_HISTORY_TURN_COUNT;
const toolCount = measuredTurn ? TRANSFER_MEASURED_TOOLS : TRANSFER_HISTORY_TOOLS_PER_TURN;
const turnId = `${FIXTURE_TURN_ID}-${turnIndex + 1}`;
const events: FixtureProviderRuntimeEvent[] = [];
let eventIndex = 0;
events.push({
type: "turn.started",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
payload: {
model: provider === "codex" ? "gpt-5.4" : "claude-opus-4-1",
effort: provider === "codex" ? "high" : "default",
},
});
for (let toolIndex = 0; toolIndex < toolCount; toolIndex += 1) {
const itemId = `tool-${turnIndex + 1}-${toolIndex + 1}`;
const command =
provider === "codex"
? `vp test transfer-budget-${toolIndex + 1}`
: `review transfer budget ${toolIndex + 1}`;
events.push(
{
type: "item.started",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId,
payload: {
itemType: "command_execution",
status: "inProgress",
title: `Inspect transfer path ${toolIndex + 1}`,
detail: "Inspecting the HTTP snapshot and WebSocket projection boundaries.",
data: {
threadId: FIXTURE_THREAD_ID,
turnId,
startedAtMs: turnIndex * 60_000 + eventIndex,
item: {
id: itemId,
type: "commandExecution",
command,
cwd: "/workspace/transfer-budget",
processId: String(toolIndex + 1),
status: "inProgress",
commandActions: [],
aggregatedOutput: "",
},
},
},
},
{
type: "item.completed",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId,
payload: {
itemType: "command_execution",
status: "completed",
title: `Inspected transfer path ${toolIndex + 1}`,
detail: "Collected a deterministic multi-module transfer diagnostic.",
data: {
threadId: FIXTURE_THREAD_ID,
turnId,
completedAtMs: turnIndex * 60_000 + eventIndex,
item: {
id: itemId,
type: "commandExecution",
command,
cwd: "/workspace/transfer-budget",
processId: String(toolIndex + 1),
status: "completed",
commandActions: [],
aggregatedOutput: diagnosticOutput({
provider,
turnIndex,
toolIndex,
targetBytes: 1_000,
}),
exitCode: 0,
durationMs: 500 + toolIndex,
},
},
},
},
);
}
const mcpItemId = `mcp-${turnIndex + 1}`;
const mcpResultBytes = measuredTurn
? TRANSFER_MEASURED_MCP_RESULT_BYTES
: TRANSFER_HISTORY_MCP_RESULT_BYTES;
events.push(
{
type: "item.started",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId: mcpItemId,
payload: {
itemType: "mcp_tool_call",
status: "inProgress",
title: "fixture-history · inspect_transfer_log",
detail: "Reading a retained diagnostic result from the provider history.",
data: {
startedAtMs: turnIndex * 60_000 + eventIndex,
threadId: FIXTURE_THREAD_ID,
turnId,
item: {
type: "mcpToolCall",
id: mcpItemId,
server: "fixture-history",
tool: "inspect_transfer_log",
arguments: { turn: turnIndex + 1 },
status: "inProgress",
},
},
},
},
{
type: "item.completed",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId: mcpItemId,
payload: {
itemType: "mcp_tool_call",
status: "completed",
title: "fixture-history · inspect_transfer_log",
detail: "Retained a deterministic diagnostic result in the thread history.",
data: {
completedAtMs: turnIndex * 60_000 + eventIndex,
threadId: FIXTURE_THREAD_ID,
turnId,
item: {
type: "mcpToolCall",
id: mcpItemId,
server: "fixture-history",
tool: "inspect_transfer_log",
arguments: { turn: turnIndex + 1 },
durationMs: 1_000 + turnIndex,
error: null,
result: {
content: [
{
type: "text",
text: diagnosticOutput({
provider,
turnIndex,
toolIndex: toolCount,
targetBytes: mcpResultBytes,
}),
},
],
},
status: "completed",
},
},
},
},
);
const chunks = assistantChunks(provider, turnIndex);
for (const [contentIndex, delta] of chunks.entries()) {
events.push({
type: "content.delta",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId: `assistant-${turnIndex + 1}`,
payload: {
streamKind: "assistant_text",
delta,
contentIndex,
},
});
}
events.push(
{
type: "thread.token-usage.updated",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
payload: {
usage: {
usedTokens: 18_000 + turnIndex * 1_900,
maxTokens: 200_000,
inputTokens: 15_000 + turnIndex * 1_700,
cachedInputTokens: 9_000 + turnIndex * 1_100,
outputTokens: 3_000 + turnIndex * 200,
toolUses: toolCount,
durationMs: 4_000 + turnIndex * 250,
},
},
},
{
type: "turn.diff.updated",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
payload: {
unifiedDiff: unifiedDiff(provider, turnIndex),
},
},
{
type: "turn.completed",
...baseEvent(provider, turnIndex, eventIndex),
turnId,
payload: {
state: "completed",
stopReason: "end_turn",
usage: {
inputTokens: 15_000 + turnIndex * 1_700,
outputTokens: 3_000 + turnIndex * 200,
},
},
},
);
return { events };
}
File diff suppressed because it is too large. Load diff
@@ -1,386 +0,0 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../src/provider/Layers/ProviderEventLoggers.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import * as ServerConfig from "../src/config.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";
import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
type TestTurnResponse,
} from "./TestProviderAdapter.integration.ts";
import {
codexTurnApprovalFixture,
codexTurnToolFixture,
codexTurnTextFixture,
} from "./fixtures/providerRuntime.ts";
const codexInstanceId = ProviderInstanceId.make("codex");
const makeWorkspaceDirectory = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const cwd = yield* fs.makeTempDirectory();
yield* fs.writeFileString(pathService.join(cwd, "README.md"), "v1\n");
return cwd;
}).pipe(Effect.provide(NodeServices.layer));
interface IntegrationFixture {
readonly cwd: string;
readonly harness: TestProviderAdapterHarness;
readonly layer: Layer.Layer<ProviderService, unknown, never>;
}
interface RecordedAnalyticsEvent {
readonly event: string;
readonly properties: Readonly<Record<string, unknown>> | undefined;
}
/**
* Analytics layer that keeps captured events in memory so tests can assert on
* telemetry payloads. `AnalyticsService.layerTest` discards them.
*/
const makeRecordingAnalytics = Effect.gen(function* () {
const recorded = yield* Ref.make<ReadonlyArray<RecordedAnalyticsEvent>>([]);
const layer = Layer.succeed(
AnalyticsService,
AnalyticsService.of({
record: (event, properties) =>
Ref.update(recorded, (current) => [...current, { event, properties }]),
flush: Effect.void,
}),
);
return { layer, get: Ref.get(recorded) } as const;
});
const makeIntegrationFixture = (options?: { readonly analytics?: Layer.Layer<AnalyticsService> }) =>
Effect.gen(function* () {
const cwd = yield* makeWorkspaceDirectory;
const harness = yield* makeTestProviderAdapterHarness();
const registry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntime.layer),
);
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerConfig.layerTest(cwd, cwd).pipe(Layer.provide(NodeServices.layer)),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
options?.analytics ?? AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
return {
cwd,
harness,
layer,
} satisfies IntegrationFixture;
});
const collectEventsDuring = <A, E, R>(
stream: Stream.Stream<ProviderRuntimeEvent>,
count: number,
action: Effect.Effect<A, E, R>,
) =>
Effect.gen(function* () {
const queue = yield* Queue.unbounded<ProviderRuntimeEvent>();
yield* Stream.runForEach(stream, (event) => Queue.offer(queue, event).pipe(Effect.asVoid)).pipe(
Effect.forkScoped,
);
yield* Effect.sleep("50 millis");
yield* action;
return yield* Effect.forEach(
Array.from({ length: count }, () => undefined),
() => Queue.take(queue),
{ discard: false },
);
});
const runTurn = (input: {
readonly provider: ProviderServiceShape;
readonly harness: TestProviderAdapterHarness;
readonly threadId: ThreadId;
readonly userText: string;
readonly response: TestTurnResponse;
}) =>
Effect.gen(function* () {
yield* input.harness.queueTurnResponse(input.threadId, input.response);
return yield* collectEventsDuring(
input.provider.streamEvents,
input.response.events.length,
input.provider.sendTurn({
threadId: input.threadId,
input: input.userText,
attachments: [],
}),
);
});
it.live("replays typed runtime fixture events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
threadId: ThreadId.make("thread-integration-typed"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "hello",
response: { events: codexTurnTextFixture },
});
assert.deepEqual(
observedEvents.map((event) => event.type),
codexTurnTextFixture.map((event) => event.type),
);
assert.deepEqual(
observedEvents.map((event) => event.providerInstanceId),
codexTurnTextFixture.map(() => codexInstanceId),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("replays file-changing fixture turn events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const { join } = yield* Path.Path;
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
threadId: ThreadId.make("thread-integration-tools"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
const observedEvents = yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "make a small change",
response: {
events: codexTurnToolFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
},
});
assert.deepEqual(
observedEvents.map((event) => event.type),
codexTurnToolFixture.map((event) => event.type),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("runs multi-turn tool/approval flow", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const { join } = yield* Path.Path;
const { writeFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
threadId: ThreadId.make("thread-integration-multi"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
const firstTurnEvents = yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "turn 1",
response: {
events: codexTurnToolFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
},
});
assert.deepEqual(
firstTurnEvents.map((event) => event.type),
codexTurnToolFixture.map((event) => event.type),
);
const secondTurnEvents = yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "turn 2 approval",
response: {
events: codexTurnApprovalFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
},
});
assert.deepEqual(
secondTurnEvents.map((event) => event.type),
codexTurnApprovalFixture.map((event) => event.type),
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("rolls back provider conversation state only", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const { join } = yield* Path.Path;
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
threadId: ThreadId.make("thread-integration-rollback"),
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode: "full-access",
});
assert.equal((session.threadId ?? "").length > 0, true);
yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "turn 1",
response: {
events: codexTurnToolFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
},
});
yield* runTurn({
provider,
harness: fixture.harness,
threadId: session.threadId,
userText: "turn 2 approval",
response: {
events: codexTurnApprovalFixture,
mutateWorkspace: ({ cwd }) =>
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
},
});
yield* provider.rollbackConversation({
threadId: session.threadId,
numTurns: 1,
});
const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId);
assert.deepEqual(rollbackCalls, [1]);
const readme = yield* readFileString(join(fixture.cwd, "README.md"));
assert.equal(readme, "v3\n");
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("reports runtime mode per turn and on mode transitions", () =>
Effect.gen(function* () {
const analytics = yield* makeRecordingAnalytics;
const fixture = yield* makeIntegrationFixture({ analytics: analytics.layer });
const threadId = ThreadId.make("thread-integration-runtime-mode");
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const startSession = (runtimeMode: "approval-required" | "full-access") =>
provider.startSession(threadId, {
threadId,
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode,
});
yield* startSession("approval-required");
yield* runTurn({
provider,
harness: fixture.harness,
threadId,
userText: "supervised turn",
response: { events: codexTurnTextFixture },
});
// Toggling the mode restarts the session, which is the only place the
// transition is observable.
yield* startSession("full-access");
yield* runTurn({
provider,
harness: fixture.harness,
threadId,
userText: "full access turn",
response: { events: codexTurnTextFixture },
});
const recorded = yield* analytics.get;
assert.deepEqual(
recorded
.filter((entry) => entry.event === "provider.turn.sent")
.map((entry) => entry.properties?.runtimeMode),
["approval-required", "full-access"],
);
assert.deepEqual(
recorded
.filter((entry) => entry.event === "provider.runtime_mode.changed")
.map((entry) => [entry.properties?.from, entry.properties?.to]),
[["approval-required", "full-access"]],
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
+8 -2
View File
@@ -16,13 +16,19 @@
"type": "module",
"scripts": {
"dev": "node --watch src/bin.ts",
"build:bundle": "vp pack && vp pack src/service-launcher.ts --out-dir dist --no-clean",
"record:codex-replay": "bun scripts/record-codex-app-server-replay-fixture.ts",
"record:claude-replay": "bun scripts/record-claude-agent-sdk-replay-fixture.ts",
"record:cursor-replay": "node --env-file-if-exists=../../.env --experimental-strip-types scripts/record-cursor-agent-sdk-replay-fixture.ts",
"build:bundle": "vp pack",
"start": "node dist/bin.mjs",
"typecheck": "tsgo --noEmit",
"test": "vp test run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
"@anthropic-ai/claude-agent-sdk": "^0.3.205",
"@connectrpc/connect": "1.7.0",
"@connectrpc/connect-node": "1.7.0",
"@cursor/sdk": "1.0.22",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
+537 -43
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env node
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as Effect from "effect/Effect";
@@ -11,19 +12,44 @@ import * as EffectAcpAgent from "effect-acp/agent";
import * as AcpError from "effect-acp/errors";
import type * as AcpSchema from "effect-acp/schema";
import { beginAcpMockPrompt } from "./acpMockCancellationState.ts";
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitPostSettleMonitorFlow = process.env.T3_ACP_EMIT_POST_SETTLE_MONITOR_FLOW === "1";
const emitInTurnTaskOutputThenLateDuplicate =
process.env.T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE === "1";
const injectedReportTriggerPath = process.env.T3_ACP_INJECTED_REPORT_TRIGGER_PATH;
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const emitElicitation = process.env.T3_ACP_EMIT_ELICITATION === "1";
const emitUrlElicitation = process.env.T3_ACP_EMIT_URL_ELICITATION === "1";
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
const hangAfterPermission = process.env.T3_ACP_HANG_AFTER_PERMISSION === "1";
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
const emitTaskBackgroundedAfterCancel =
process.env.T3_ACP_EMIT_TASK_BACKGROUNDED_AFTER_CANCEL === "1";
const residualCallbackResponseLogPath = process.env.T3_ACP_RESIDUAL_CALLBACK_RESPONSE_LOG_PATH;
const residualCallbackTriggerPath = process.env.T3_ACP_RESIDUAL_CALLBACK_TRIGGER_PATH;
const exitAfterResidualCallbacks = process.env.T3_ACP_EXIT_AFTER_RESIDUAL_CALLBACKS === "1";
const emitRunningCommandThenHang = process.env.T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG === "1";
const emitRunningCommandThenHangOnFirstPrompt =
process.env.T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG_FIRST_PROMPT === "1";
const emitEmptySuccessfulBash = process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH === "1";
const emitEmptySuccessfulBashThenHang =
process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG === "1";
const exitOnCancel = process.env.T3_ACP_EXIT_ON_CANCEL === "1";
const runningCommandIgnoresTerm = process.env.T3_ACP_RUNNING_COMMAND_IGNORE_TERM === "1";
const runningCommandPidPath = process.env.T3_ACP_RUNNING_COMMAND_PID_PATH;
const runningCommandSeparateSession = process.env.T3_ACP_RUNNING_COMMAND_SEPARATE_SESSION === "1";
const exitAfterRunningCommandLaunch = process.env.T3_ACP_EXIT_AFTER_RUNNING_COMMAND_LAUNCH === "1";
const omitXAiPromptCompleteStopReason =
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
@@ -40,6 +66,9 @@ const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
const supportsSessionLifecycle = process.env.T3_ACP_SESSION_LIFECYCLE === "1";
const advertisedAuthMethodId = process.env.T3_ACP_AUTH_METHOD_ID?.trim();
const requiresAuthentication = process.env.T3_ACP_REQUIRE_AUTH === "1";
const permissionOptionIds = {
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
@@ -53,6 +82,7 @@ let parameterizedModelPicker = false;
let currentReasoning = "medium";
let currentContext = "272k";
let currentFast = false;
let authenticated = !requiresAuthentication;
let promptCount = 0;
let overlappingFirstPromptId: string | undefined;
const cancelledSessions = new Set<string>();
@@ -79,6 +109,11 @@ function writeJsonRpcNotification(method: string, params: unknown): void {
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
}
function logResidualCallbackResponse(kind: string): void {
if (!residualCallbackResponseLogPath) return;
NodeFS.appendFileSync(residualCallbackResponseLogPath, `${kind}\n`, "utf8");
}
process.once("SIGTERM", () => {
logExit("SIGTERM");
process.exit(0);
@@ -224,35 +259,6 @@ function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
];
}
function modelConfigOptionsFor(modelId: string): ReadonlyArray<AcpSchema.SessionConfigOption> {
const previousModelId = currentModelId;
try {
currentModelId = modelId;
return configOptions().filter(
(option) => option.category !== "mode" && option.category !== "model",
);
} finally {
currentModelId = previousModelId;
}
}
function availableModels(): ReadonlyArray<{
readonly value: string;
readonly name: string;
readonly configOptions: ReadonlyArray<AcpSchema.SessionConfigOption>;
}> {
return [
{ value: "default", name: "Auto" },
{ value: "composer-2", name: "Composer 2" },
{ value: "gpt-5.4", name: "GPT-5.4" },
{ value: "claude-opus-4-6", name: "Opus 4.6" },
].map((model) => ({
value: model.value,
name: model.name,
configOptions: modelConfigOptionsFor(model.value),
}));
}
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
{
id: "ask",
@@ -302,19 +308,60 @@ const program = Effect.gen(function* () {
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
return {
protocolVersion: 1,
agentCapabilities: { loadSession: true },
agentCapabilities: {
loadSession: true,
...(supportsSessionLifecycle
? {
sessionCapabilities: {
list: {},
fork: {},
resume: {},
close: {},
},
}
: {}),
},
...(advertisedAuthMethodId
? {
authMethods: [
{
id: advertisedAuthMethodId,
name: "Mock agent authentication",
},
],
}
: {}),
};
}),
);
yield* agent.handleAuthenticate(() => Effect.succeed({}));
yield* agent.handleAuthenticate((request) =>
Effect.gen(function* () {
if (advertisedAuthMethodId && request.methodId !== advertisedAuthMethodId) {
return yield* AcpError.AcpRequestError.invalidParams(
`Unknown mock authentication method: ${request.methodId}`,
);
}
authenticated = true;
return {};
}),
);
const requireAuthentication = Effect.fn("acpMockAgent.requireAuthentication")(function* () {
if (!authenticated) {
return yield* AcpError.AcpRequestError.authRequired();
}
});
yield* agent.handleCreateSession(() =>
Effect.succeed({
sessionId,
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
Effect.gen(function* () {
yield* requireAuthentication();
return {
sessionId,
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}),
);
@@ -380,6 +427,52 @@ const program = Effect.gen(function* () {
}),
);
yield* agent.handleListSessions((request) =>
Effect.gen(function* () {
yield* requireAuthentication();
return {
sessions: [
{
sessionId,
cwd: request.cwd ?? process.cwd(),
title: "Mock session",
updatedAt: "1970-01-01T00:00:00.000Z",
},
],
};
}),
);
yield* agent.handleForkSession((request) =>
Effect.gen(function* () {
yield* requireAuthentication();
return {
sessionId: `${request.sessionId}-fork`,
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}),
);
yield* agent.handleResumeSession(() =>
Effect.gen(function* () {
yield* requireAuthentication();
return {
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}),
);
yield* agent.handleCloseSession(() =>
Effect.gen(function* () {
yield* requireAuthentication();
return {};
}),
);
yield* agent.handleSetSessionModel((request) =>
Effect.gen(function* () {
if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
@@ -437,6 +530,9 @@ const program = Effect.gen(function* () {
Effect.gen(function* () {
const cancelledSessionId = String(sessionId ?? "mock-session-1");
cancelledSessions.add(cancelledSessionId);
if (exitOnCancel) {
return yield* Effect.sync(() => process.exit(0));
}
if (emitLateUpdateAfterCancel) {
yield* Effect.sleep("50 millis");
yield* Effect.sync(() => {
@@ -449,14 +545,119 @@ const program = Effect.gen(function* () {
});
});
}
if (emitTaskBackgroundedAfterCancel) {
// Grok cancel-as-detach: the foreground command is re-run as a
// background task that later completes on its own.
yield* Effect.sync(() => {
writeJsonRpcNotification("_x.ai/task_backgrounded", {
sessionId: cancelledSessionId,
update: {
sessionUpdate: "task_backgrounded",
tool_call_id: "task-bg-1",
task_id: "task-bg-1",
command: "sleep 30",
},
});
});
yield* Effect.sleep("1200 millis")
.pipe(
Effect.andThen(
Effect.sync(() => {
writeJsonRpcNotification("_x.ai/task_completed", {
sessionId: cancelledSessionId,
update: {
sessionUpdate: "task_completed",
task_snapshot: { task_id: "task-bg-1", command: "sleep 30" },
},
});
}),
),
)
.pipe(Effect.forkDetach);
}
}),
);
yield* agent.handlePrompt((request) =>
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
beginAcpMockPrompt(cancelledSessions, requestedSessionId);
promptCount += 1;
if (residualCallbackTriggerPath !== undefined) {
yield* Effect.gen(function* () {
while (!(yield* Effect.sync(() => NodeFS.existsSync(residualCallbackTriggerPath)))) {
yield* Effect.sleep("20 millis");
}
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "residual assistant callback" },
},
});
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "residual-tool-call",
title: "Residual tool callback",
kind: "other",
status: "pending",
rawInput: {},
},
});
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "plan",
entries: [
{ content: "Residual plan callback", priority: "high", status: "pending" },
],
},
});
});
yield* agent.client
.requestPermission({
sessionId: requestedSessionId,
toolCall: {
toolCallId: "residual-permission",
title: "Residual permission callback",
},
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
})
.pipe(
Effect.exit,
Effect.tap(() => Effect.sync(() => logResidualCallbackResponse("permission"))),
Effect.ignore,
Effect.forkDetach,
);
yield* agent.client
.elicit({
sessionId: requestedSessionId,
message: "Residual elicitation callback",
mode: "form",
requestedSchema: {
type: "object",
properties: {
approved: { type: "boolean", title: "Approved" },
},
},
})
.pipe(
Effect.exit,
Effect.tap(() => Effect.sync(() => logResidualCallbackResponse("elicitation"))),
Effect.ignore,
Effect.forkDetach,
);
if (exitAfterResidualCallbacks) {
yield* Effect.sleep("100 millis");
return yield* Effect.sync(() => process.exit(0));
}
}).pipe(Effect.forkDetach);
}
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
yield* Effect.sleep(`${promptDelayMs} millis`);
}
@@ -518,10 +719,126 @@ const program = Effect.gen(function* () {
return yield* Effect.never;
}
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
if (
hangPromptForever ||
(hangFirstPromptForever && promptCount === 1) ||
(emitEmptySuccessfulBashThenHang && promptCount === 2)
) {
return yield* Effect.never;
}
if (
emitRunningCommandThenHang ||
(emitRunningCommandThenHangOnFirstPrompt && promptCount === 1)
) {
const toolCallId = "tool-call-running-1";
if (runningCommandPidPath !== undefined) {
const command = runningCommandIgnoresTerm
? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s\\n" "$$" "$child" > "$1"; wait "$child"'
: 'sleep 120 & child=$!; printf "%s %s\\n" "$$" "$child" > "$1"; wait "$child"';
if (runningCommandSeparateSession) {
const launcher = [
'const { spawn } = require("node:child_process");',
"const child = spawn(process.argv[1], process.argv.slice(2), { stdio: 'ignore' });",
"child.once('exit', (code, signal) => process.exitCode = code ?? (signal ? 1 : 0));",
].join(" ");
const detachedCommand = runningCommandIgnoresTerm
? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s %s\\n" "$PPID" "$$" "$child" > "$1"; wait "$child"'
: 'sleep 120 & child=$!; printf "%s %s %s\\n" "$PPID" "$$" "$child" > "$1"; wait "$child"';
// Nested bash publishes "$PPID $$ $child" once it starts. Do not
// write the launcher PID alone here: that races with bash and can
// clobber the triple that interrupt tests wait for.
const detachedLauncher = NodeChildProcess.spawn(
process.execPath,
["-e", launcher, "bash", "-c", detachedCommand, "bash", runningCommandPidPath],
{ detached: true, stdio: "ignore" },
);
detachedLauncher.unref();
} else {
NodeChildProcess.spawn("bash", ["-c", command, "bash", runningCommandPidPath], {
stdio: "ignore",
});
}
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId,
title: "Terminal",
kind: "execute",
status: "pending",
rawInput: {
command: ["sleep", "120"],
},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId,
title: "Terminal",
kind: "execute",
status: "in_progress",
rawInput: {
command: ["sleep", "120"],
},
// Grok-like mid-stream Bash re-report: exit_code 0 while still running.
rawOutput: { type: "Bash", exit_code: 0 },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-call-output-1",
title: "get_command_or_subagent_output",
kind: "other",
status: "pending",
rawInput: { task_id: "task-running-1" },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-output-1",
status: "in_progress",
rawOutput: { task_id: "task-running-1", status: "running" },
},
});
if (exitAfterRunningCommandLaunch) {
yield* Effect.sleep("100 millis");
return yield* Effect.sync(() => process.exit(0));
}
// Stay open until session/cancel so interrupt tests can observe a running tool.
while (!cancelledSessions.has(requestedSessionId)) {
yield* Effect.sleep("25 millis");
}
cancelledSessions.delete(requestedSessionId);
return { stopReason: "cancelled" };
}
if (emitEmptySuccessfulBash || (emitEmptySuccessfulBashThenHang && promptCount === 1)) {
const update = {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-empty-success-1",
title: "Terminal",
kind: "execute",
status: "completed",
rawInput: { command: "true" },
rawOutput: { type: "Bash", exit_code: 0 },
},
} as const;
yield* agent.client.sessionUpdate(update);
yield* Effect.sleep("25 millis");
yield* agent.client.sessionUpdate(update);
return { stopReason: "end_turn" };
}
if (emitXAiPromptCompleteThenHang) {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
@@ -630,6 +947,32 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
if (emitElicitation) {
yield* agent.client.elicit({
sessionId: requestedSessionId,
message: "Approve this request?",
mode: "form",
requestedSchema: {
type: "object",
properties: {
approved: { type: "boolean", title: "Approved" },
},
},
});
return { stopReason: "end_turn" };
}
if (emitUrlElicitation) {
yield* agent.client.elicit({
sessionId: requestedSessionId,
message: "Open authentication page",
mode: "url",
url: "https://example.com/auth",
elicitationId: "url-elicitation-1",
});
return { stopReason: "end_turn" };
}
if (emitToolCalls) {
const toolCallId = "tool-call-1";
@@ -688,6 +1031,10 @@ const program = Effect.gen(function* () {
cancelledSessions.delete(requestedSessionId) ||
permission.outcome.outcome === "cancelled";
if (hangAfterPermission) {
return yield* Effect.never;
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
@@ -754,6 +1101,159 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
// In-turn monitor + TaskOutput hydrate, then a late post-finalize
// duplicate terminal TaskOutput for the same task. Exercises the
// already-handled short-circuit: must not pin hasPendingBackgroundWork.
if (emitInTurnTaskOutputThenLateDuplicate) {
const monitorToolCallId = "tool-call-monitor-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: monitorToolCallId,
title: "Monitor: mock background task",
kind: "execute",
status: "pending",
rawInput: {},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: monitorToolCallId,
status: "in_progress",
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-call-fetch-1",
title: "get_command_or_subagent_output",
kind: "other",
status: "pending",
rawInput: { task_id: "task-monitor-1" },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-fetch-1",
status: "completed",
rawOutput: { output: "MONITOR_LISTING_TOKEN" },
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Monitor listing ready in-turn." },
},
});
// After deferred finalize (~2s) clears activeTurn, re-emit a terminal
// TaskOutput for the same task so bufferPostSettleWake sees
// alreadyHandledToolUpdate with a non-empty wake path.
yield* Effect.gen(function* () {
yield* Effect.sleep("2500 millis");
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-fetch-1",
title: "get_command_or_subagent_output",
kind: "other",
status: "completed",
rawOutput: { output: "MONITOR_LISTING_TOKEN_LATE" },
},
});
});
}).pipe(Effect.forkDetach);
return { stopReason: "end_turn" };
}
if (emitPostSettleMonitorFlow) {
const monitorToolCallId = "tool-call-monitor-1";
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: monitorToolCallId,
title: "Monitor: mock background task",
kind: "execute",
status: "pending",
rawInput: {},
},
});
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: monitorToolCallId,
status: "in_progress",
},
});
// After the prompt settles, replay the CLI-injected monitor-event
// turn: end notice, TaskOutput hydration, then (once the trigger
// file exists) the report chunk. Detached fiber on the real clock;
// it outlives the prompt handler.
yield* Effect.gen(function* () {
yield* Effect.sleep("150 millis");
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "user_message_chunk",
content: {
type: "text",
text: 'Monitor "task-monitor-1" ended: [monitor ended: exit 0]',
},
},
});
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call",
toolCallId: "tool-call-fetch-1",
title: "get_command_or_subagent_output",
kind: "other",
status: "pending",
rawInput: { task_id: "task-monitor-1" },
},
});
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "tool_call_update",
toolCallId: "tool-call-fetch-1",
status: "completed",
rawOutput: { output: "MONITOR_LISTING_TOKEN" },
},
});
});
if (injectedReportTriggerPath === undefined) return;
while (!(yield* Effect.sync(() => NodeFS.existsSync(injectedReportTriggerPath)))) {
yield* Effect.sleep("20 millis");
}
yield* Effect.sync(() => {
writeJsonRpcNotification("session/update", {
sessionId: requestedSessionId,
update: {
sessionUpdate: "agent_message_chunk",
content: { type: "text", text: "Monitor finished. MONITOR_REPORT_TOKEN" },
},
});
});
}).pipe(Effect.forkDetach);
return { stopReason: "end_turn" };
}
if (emitAskQuestion) {
yield* agent.client.extRequest("cursor/ask_question", {
toolCallId: "ask-question-tool-call-1",
@@ -878,12 +1378,6 @@ const program = Effect.gen(function* () {
);
yield* agent.handleUnknownExtRequest((method, params) => {
if (method === "cursor/list_available_models") {
return Effect.succeed({
models: availableModels(),
});
}
if (method !== "session/mode/set") {
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
}
@@ -0,0 +1,78 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeChildProcess from "node:child_process";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
import { expect, it } from "vite-plus/test";
import { acpReplayAgentArgs } from "../src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts";
const replayAgentPath = NodeURL.fileURLToPath(new URL("./acp-replay-agent.ts", import.meta.url));
async function runRuntimeExit(status: "success" | "error" | "cancelled") {
const scratch = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-acp-replay-agent-"));
const statusPath = NodePath.join(scratch, "status.json");
const transcript = {
scenario: `${status}-runtime-exit`,
entries: [{ type: "runtime_exit", status }],
};
const args = acpReplayAgentArgs(replayAgentPath);
const child = NodeChildProcess.spawn(process.execPath, args, {
env: {
...process.env,
T3_ACP_REPLAY_STATUS_PATH: statusPath,
T3_ACP_REPLAY_TRANSCRIPT: Buffer.from(JSON.stringify(transcript), "utf8").toString("base64"),
T3_ACP_REPLAY_WORKSPACE: scratch,
},
stdio: ["pipe", "pipe", "pipe"],
});
let stderr = "";
child.stderr.setEncoding("utf8");
child.stderr.on("data", (chunk: string) => {
stderr += chunk;
});
child.stdin.end();
try {
const code = await new Promise<number | null>((resolve, reject) => {
child.once("error", reject);
child.once("exit", resolve);
});
return {
code,
status: JSON.parse(NodeFS.readFileSync(statusPath, "utf8")) as unknown,
stderr,
transcript,
args,
};
} finally {
NodeFS.rmSync(scratch, { recursive: true, force: true });
}
}
it("accepts a recorded cancelled runtime exit", async () => {
const result = await runRuntimeExit("cancelled");
expect(result.code, result.stderr).toBe(0);
expect(result.args).toEqual(["--experimental-strip-types", replayAgentPath]);
expect(result.status).toEqual({
scenario: result.transcript.scenario,
cursor: 1,
total: 1,
});
});
it("still rejects a recorded error runtime exit", async () => {
const result = await runRuntimeExit("error");
expect(result.code).toBe(1);
expect(result.status).toMatchObject({
scenario: result.transcript.scenario,
cursor: 0,
total: 1,
failure: {
detail: "Recorded runtime exit was error",
cursor: 0,
},
});
});
+285
View File
@@ -0,0 +1,285 @@
#!/usr/bin/env node
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeReadline from "node:readline";
interface ReplayEntry {
readonly type: "emit_inbound" | "expect_outbound" | "runtime_exit";
readonly label?: string;
readonly frame?: unknown;
readonly status?: "success" | "error" | "cancelled";
readonly error?: unknown;
}
interface ReplayTranscript {
readonly scenario: string;
readonly entries: ReadonlyArray<ReplayEntry>;
}
interface LogicalFrame {
readonly kind: "notification" | "request" | "response";
readonly method: string;
readonly params?: unknown;
readonly result?: unknown;
readonly error?: unknown;
}
interface JsonRpcMessage {
readonly jsonrpc?: string;
readonly id?: string | number | null;
readonly method?: string;
readonly params?: unknown;
readonly result?: unknown;
readonly error?: unknown;
readonly headers?: ReadonlyArray<unknown>;
}
const encodedTranscript = process.env.T3_ACP_REPLAY_TRANSCRIPT;
const statusPath = process.env.T3_ACP_REPLAY_STATUS_PATH;
const replayWorkspace = process.env.T3_ACP_REPLAY_WORKSPACE ?? process.cwd();
if (encodedTranscript === undefined || statusPath === undefined) {
process.stderr.write("ACP replay requires transcript and status environment variables.\n");
process.exit(2);
}
const replayStatusPath = statusPath;
const transcript = JSON.parse(
Buffer.from(encodedTranscript, "base64").toString("utf8"),
) as ReplayTranscript;
let cursor = 0;
let stopped = false;
let nextAgentRequestId = 1;
const pendingClientRequestIds = new Map<string, string | number>();
const pendingAgentRequestMethods = new Map<string, string>();
function writeStatus(failure?: unknown): void {
NodeFS.writeFileSync(
replayStatusPath,
JSON.stringify({
scenario: transcript.scenario,
cursor,
total: transcript.entries.length,
...(failure === undefined ? {} : { failure }),
}),
"utf8",
);
}
function stableStringify(value: unknown): string {
if (Array.isArray(value)) {
return `[${value.map(stableStringify).join(",")}]`;
}
if (typeof value === "object" && value !== null) {
const record = value as Record<string, unknown>;
return `{${Object.keys(record)
.toSorted()
.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
.join(",")}}`;
}
return JSON.stringify(value);
}
function expandExpectedString(value: string): string {
return value.replaceAll("<workspace>", replayWorkspace);
}
function matchesExpected(expected: unknown, actual: unknown): boolean {
if (expected === "<any>") return true;
if (typeof expected === "string" && typeof actual === "string") {
const expanded = expandExpectedString(expected);
if (!expanded.includes("<any>")) return expanded === actual;
const parts = expanded.split("<any>");
let offset = 0;
for (const part of parts) {
const index = actual.indexOf(part, offset);
if (index === -1) return false;
offset = index + part.length;
}
return true;
}
if (Array.isArray(expected)) {
return (
Array.isArray(actual) &&
expected.length === actual.length &&
expected.every((entry, index) => matchesExpected(entry, actual[index]))
);
}
if (typeof expected === "object" && expected !== null) {
if (typeof actual !== "object" || actual === null || Array.isArray(actual)) return false;
const expectedRecord = expected as Record<string, unknown>;
const actualRecord = actual as Record<string, unknown>;
const expectedKeys = Object.keys(expectedRecord).toSorted();
const actualKeys = Object.keys(actualRecord).toSorted();
return (
stableStringify(expectedKeys) === stableStringify(actualKeys) &&
expectedKeys.every((key) => matchesExpected(expectedRecord[key], actualRecord[key]))
);
}
return Object.is(expected, actual);
}
function stopWithFailure(detail: string, actual?: unknown): void {
if (stopped) return;
stopped = true;
const entry = transcript.entries[cursor];
const failure = {
detail,
cursor,
expected: entry,
...(actual === undefined ? {} : { actual }),
};
writeStatus(failure);
process.stderr.write(`ACP replay mismatch: ${JSON.stringify(failure)}\n`);
process.exitCode = 1;
process.stdin.pause();
}
function advance(): void {
cursor += 1;
writeStatus();
}
function send(message: JsonRpcMessage): void {
process.stdout.write(`${JSON.stringify(message)}\n`);
}
function pendingClientRequestId(method: string): string | number | undefined {
return pendingClientRequestIds.get(method);
}
function logicalIncoming(message: JsonRpcMessage): LogicalFrame | undefined {
if (typeof message.method === "string") {
return {
kind:
message.id === undefined || message.id === null || message.id === ""
? "notification"
: "request",
method: message.method,
...(message.params === undefined ? {} : { params: message.params }),
};
}
if (message.id === undefined || message.id === null) return undefined;
const method = pendingAgentRequestMethods.get(String(message.id));
if (method === undefined) return undefined;
return {
kind: "response",
method,
...(message.result === undefined ? {} : { result: message.result }),
...(message.error === undefined ? {} : { error: message.error }),
};
}
function emitInbound(frame: LogicalFrame): void {
switch (frame.kind) {
case "notification":
send({
jsonrpc: "2.0",
method: frame.method,
...(frame.params === undefined ? {} : { params: frame.params }),
});
return;
case "request": {
const id = nextAgentRequestId;
nextAgentRequestId += 1;
pendingAgentRequestMethods.set(String(id), frame.method);
send({
jsonrpc: "2.0",
id,
method: frame.method,
...(frame.params === undefined ? {} : { params: frame.params }),
headers: [],
});
return;
}
case "response": {
const id = pendingClientRequestId(frame.method);
if (id === undefined) {
stopWithFailure(`No pending client request for ${frame.method}`, frame);
return;
}
pendingClientRequestIds.delete(frame.method);
send({
jsonrpc: "2.0",
id,
...(frame.result === undefined ? {} : { result: frame.result }),
...(frame.error === undefined ? {} : { error: frame.error }),
});
}
}
}
function flushInbound(): void {
while (!stopped) {
const entry = transcript.entries[cursor];
if (entry === undefined || entry.type === "expect_outbound") return;
if (entry.type === "runtime_exit") {
if (entry.status !== "success" && entry.status !== "cancelled") {
stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error);
return;
}
advance();
continue;
}
const frame = entry.frame as LogicalFrame;
if (
typeof frame !== "object" ||
frame === null ||
!["notification", "request", "response"].includes(frame.kind) ||
typeof frame.method !== "string"
) {
stopWithFailure("Invalid emit_inbound logical ACP frame", entry.frame);
return;
}
emitInbound(frame);
if (stopped) return;
advance();
}
}
function handleMessage(message: JsonRpcMessage): void {
if (stopped) return;
const actual = logicalIncoming(message);
if (actual === undefined) {
stopWithFailure("Could not identify outbound ACP frame", message);
return;
}
const entry = transcript.entries[cursor];
if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {
if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
send({
jsonrpc: "2.0",
id: message.id,
error: { code: -32603, message: "ACP replay frame mismatch" },
});
}
stopWithFailure("Unexpected outbound ACP frame", actual);
return;
}
if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
pendingClientRequestIds.set(actual.method, message.id);
} else if (actual.kind === "response" && message.id !== undefined && message.id !== null) {
pendingAgentRequestMethods.delete(String(message.id));
}
advance();
flushInbound();
}
writeStatus();
flushInbound();
const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
input.on("line", (line) => {
if (stopped || line.trim().length === 0) return;
try {
handleMessage(JSON.parse(line) as JsonRpcMessage);
} catch (cause) {
stopWithFailure("Failed to decode outbound ACP JSON-RPC", String(cause));
}
});
input.on("close", () => {
if (!stopped && cursor !== transcript.entries.length) {
stopWithFailure("ACP replay input closed before transcript completion");
}
});
@@ -0,0 +1,37 @@
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
static const char *pid_path;
static void *spawn_child(void *unused) {
(void)unused;
pid_t child = fork();
if (child == 0) {
execlp("sleep", "sleep", "120", NULL);
_exit(127);
}
if (child < 0) return NULL;
FILE *file = fopen(pid_path, "w");
if (file != NULL) {
fprintf(file, "%ld %d\n", syscall(SYS_gettid), child);
fclose(file);
}
waitpid(child, NULL, 0);
return NULL;
}
int main(int argc, char **argv) {
if (argc != 2) return 2;
pid_path = argv[1];
pthread_t worker;
if (pthread_create(&worker, NULL, spawn_child, NULL) != 0) return 3;
if (pthread_join(worker, NULL) != 0) return 4;
return 0;
}
@@ -0,0 +1,12 @@
import { assert, it } from "@effect/vitest";
import { beginAcpMockPrompt } from "./acpMockCancellationState.ts";
it("does not carry an idle cancellation into the next prompt", () => {
const cancelledSessions = new Set(["session:cancelled-while-idle", "session:other"]);
beginAcpMockPrompt(cancelledSessions, "session:cancelled-while-idle");
assert.isFalse(cancelledSessions.has("session:cancelled-while-idle"));
assert.isTrue(cancelledSessions.has("session:other"));
});
@@ -0,0 +1,3 @@
export function beginAcpMockPrompt(cancelledSessions: Set<string>, sessionId: string): void {
cancelledSessions.delete(sessionId);
}
@@ -0,0 +1,43 @@
import { assert, it } from "@effect/vitest";
import { validateClaudeReplayRecordingSelection } from "./claudeReplayRecordingConfig.ts";
it("rejects a query mode that is incompatible with the selected scenario", () => {
assert.throws(
() =>
validateClaudeReplayRecordingSelection({
scenario: "simple",
configuredQueryMode: "streaming",
selectedQueryMode: "fork_session_siblings",
configuredPromptCount: 1,
selectedPromptCount: 1,
}),
"Select a scenario configured for the requested query mode",
);
});
it("rejects prompt overrides that do not preserve the scenario shape", () => {
assert.throws(
() =>
validateClaudeReplayRecordingSelection({
scenario: "thread_fork_native_siblings",
configuredQueryMode: "fork_session_siblings",
selectedQueryMode: "fork_session_siblings",
configuredPromptCount: 3,
selectedPromptCount: 1,
}),
"requires exactly 3 prompt(s)",
);
});
it("accepts the configured scenario mode and prompt shape", () => {
assert.doesNotThrow(() =>
validateClaudeReplayRecordingSelection({
scenario: "thread_fork_native_siblings",
configuredQueryMode: "fork_session_siblings",
selectedQueryMode: "fork_session_siblings",
configuredPromptCount: 3,
selectedPromptCount: 3,
}),
);
});
@@ -0,0 +1,32 @@
export type ClaudeRecordingQueryMode =
| "streaming"
| "restart"
| "resume_at_cursor"
| "fork_session"
| "fork_session_prior_turn"
| "fork_session_continue"
| "fork_session_siblings"
| "fork_session_merge_back"
| "fork_session_merge_back_siblings"
| "active_steering"
| "interrupt"
| "interrupt_restart";
export function validateClaudeReplayRecordingSelection(input: {
readonly scenario: string;
readonly configuredQueryMode: ClaudeRecordingQueryMode;
readonly selectedQueryMode: ClaudeRecordingQueryMode;
readonly configuredPromptCount: number;
readonly selectedPromptCount: number;
}): void {
if (input.selectedQueryMode !== input.configuredQueryMode) {
throw new Error(
`Claude replay fixture '${input.scenario}' uses query mode '${input.configuredQueryMode}', not '${input.selectedQueryMode}'. Select a scenario configured for the requested query mode.`,
);
}
if (input.selectedPromptCount !== input.configuredPromptCount) {
throw new Error(
`Claude replay fixture '${input.scenario}' requires exactly ${input.configuredPromptCount} prompt(s) for query mode '${input.configuredQueryMode}', but received ${input.selectedPromptCount}.`,
);
}
}
@@ -0,0 +1,35 @@
import { assert, it } from "@effect/vitest";
import { codexReplayRecordingOutputRecords } from "./codexReplayRecordingRecords.ts";
it("preserves monotonic request ids across native Codex forks", () => {
const records = [
{
type: "expect_outbound",
label: "initialize",
frame: { id: 1, method: "initialize" },
},
{
type: "expect_outbound",
label: "thread/fork",
frame: { id: 4, method: "thread/fork" },
},
{
type: "expect_outbound",
label: "turn/start",
frame: { id: 5, method: "turn/start" },
},
];
const output = codexReplayRecordingOutputRecords(records);
assert.deepEqual(output, records);
assert.deepEqual(
output.map((record) => record.label),
["initialize", "thread/fork", "turn/start"],
);
assert.deepEqual(
output.map((record) => (record.frame as { readonly id: number }).id),
[1, 4, 5],
);
});
@@ -0,0 +1,9 @@
/**
* Codex supports multiple provider threads in one app-server session, so native
* fork recording keeps the request ids emitted by that single client.
*/
export function codexReplayRecordingOutputRecords(
records: ReadonlyArray<Record<string, unknown>>,
): ReadonlyArray<Record<string, unknown>> {
return [...records];
}
@@ -1,442 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeChildProcess from "node:child_process";
import * as NodeProcess from "node:process";
import * as NodeReadline from "node:readline";
import * as NodeTimers from "node:timers";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Effect from "effect/Effect";
type JsonPrimitive = null | boolean | number | string;
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
type JsonRpcId = number | string;
type JsonRpcMessage = {
jsonrpc?: string;
id?: JsonRpcId;
method?: string;
params?: JsonValue;
result?: JsonValue;
error?: JsonValue;
headers?: JsonValue;
};
type SelectLeafOption = {
value: string;
label?: string;
name?: string;
};
type SelectGroupOption = {
label?: string;
name?: string;
options: SelectLeafOption[];
};
type SessionConfigOption = {
id: string;
name?: string;
category?: string;
type?: string;
options?: Array<SelectLeafOption | SelectGroupOption>;
};
type SessionNewResult = {
sessionId: string;
configOptions?: SessionConfigOption[];
};
type SetConfigResult = {
configOptions?: SessionConfigOption[];
};
type PendingRequest = {
method: string;
resolve: (value: JsonValue | undefined) => void;
reject: (error: Error) => void;
};
const targetCwd = NodeProcess.argv[2] ?? NodeProcess.cwd();
const targetModel = NodeProcess.argv[3] ?? "gpt-5.4";
const promptText = NodeProcess.argv[4] ?? "helo";
const targetReasoning = NodeProcess.env.CURSOR_REASONING ?? "";
const targetContext = NodeProcess.env.CURSOR_CONTEXT ?? "";
const targetFast = NodeProcess.env.CURSOR_FAST ?? "";
const agentBin = NodeProcess.env.CURSOR_AGENT_BIN ?? "cursor-agent";
const promptWaitMs = Number(NodeProcess.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
const requestTimeoutMs = Number(NodeProcess.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
function logSection(title: string, value: unknown) {
NodeProcess.stdout.write(`\n=== ${title} ===\n`);
NodeProcess.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
}
function fail(message: string): never {
throw new Error(message);
}
function asString(value: JsonValue | undefined): string | null {
return typeof value === "string" ? value : null;
}
function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
if (!option || option.type !== "select" || !Array.isArray(option.options)) {
return [];
}
const values: string[] = [];
for (const entry of option.options) {
if (!entry || typeof entry !== "object") {
continue;
}
if ("value" in entry && typeof entry.value === "string") {
values.push(entry.value);
continue;
}
if ("options" in entry && Array.isArray(entry.options)) {
for (const nested of entry.options) {
if (nested && typeof nested === "object" && typeof nested.value === "string") {
values.push(nested.value);
}
}
}
}
return values;
}
function findConfigOption(
configOptions: SessionConfigOption[],
predicate: (option: SessionConfigOption) => boolean,
): SessionConfigOption | undefined {
return configOptions.find(predicate);
}
function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
return haystack.includes(keyword.toLowerCase());
}
function sleep(ms: number) {
return new Promise<void>((resolve) => {
// @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script, not an Effect runtime test.
NodeTimers.setTimeout(resolve, ms);
});
}
class JsonRpcChild {
readonly child: NodeChildProcess.ChildProcessWithoutNullStreams;
readonly pending = new Map<JsonRpcId, PendingRequest>();
nextId = 1;
closed = false;
constructor(bin: string, args: string[], cwd: string) {
const spawnCommand = Effect.runSync(resolveSpawnCommand(bin, args));
this.child = NodeChildProcess.spawn(spawnCommand.command, spawnCommand.args, {
cwd,
shell: spawnCommand.shell,
stdio: ["pipe", "pipe", "pipe"],
env: NodeProcess.env,
});
this.child.on("exit", (code, signal) => {
this.closed = true;
const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
for (const pending of this.pending.values()) {
pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
}
this.pending.clear();
});
this.child.on("error", (error) => {
this.closed = true;
for (const pending of this.pending.values()) {
pending.reject(error);
}
this.pending.clear();
});
const stdout = NodeReadline.createInterface({ input: this.child.stdout });
stdout.on("line", (line) => {
void this.handleStdoutLine(line);
});
const stderr = NodeReadline.createInterface({ input: this.child.stderr });
stderr.on("line", (line) => {
NodeProcess.stdout.write(`[stderr] ${line}\n`);
});
}
write(message: JsonRpcMessage) {
if (this.closed) {
fail("ACP process is already closed.");
}
const payload = JSON.stringify({
jsonrpc: "2.0",
headers: [],
...message,
});
NodeProcess.stdout.write(`>>> ${payload}\n`);
this.child.stdin.write(`${payload}\n`);
}
async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
const id = this.nextId++;
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
// @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script request timeout.
const timeout = NodeTimers.setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
}, timeoutMs);
this.pending.set(id, {
method,
resolve: (value) => {
NodeTimers.clearTimeout(timeout);
resolve(value);
},
reject: (error) => {
NodeTimers.clearTimeout(timeout);
reject(error);
},
});
});
this.write({
id,
method,
params,
});
return responsePromise;
}
notify(method: string, params: JsonValue) {
this.write({
method,
params,
});
}
respond(id: JsonRpcId, result: JsonValue) {
this.write({
id,
result,
});
}
respondError(id: JsonRpcId, code: number, message: string) {
this.write({
id,
error: {
code,
message,
},
});
}
async handleStdoutLine(line: string) {
if (line.trim().length === 0) {
return;
}
NodeProcess.stdout.write(`<<< ${line}\n`);
let message: JsonRpcMessage;
try {
message = JSON.parse(line) as JsonRpcMessage;
} catch (error) {
NodeProcess.stdout.write(`[parse-error] ${(error as Error).message}\n`);
return;
}
if (typeof message.id !== "undefined" && !message.method) {
const pending = this.pending.get(message.id);
if (!pending) {
return;
}
this.pending.delete(message.id);
if (typeof message.error !== "undefined") {
pending.reject(
new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
);
return;
}
pending.resolve(message.result);
return;
}
if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
this.respond(message.id, {
outcome: {
outcome: "selected",
optionId: "allow",
},
});
return;
}
if (typeof message.id !== "undefined" && message.id !== "") {
this.respondError(
message.id,
-32601,
`Unhandled server request: ${message.method ?? "unknown"}`,
);
}
}
async close() {
if (this.closed) {
return;
}
this.child.kill("SIGTERM");
await sleep(250);
if (!this.closed) {
this.child.kill("SIGKILL");
}
}
}
async function setSelectOptionIfAdvertised(
rpc: JsonRpcChild,
sessionId: string,
configOptions: SessionConfigOption[],
predicate: (option: SessionConfigOption) => boolean,
value: string,
label: string,
) {
if (value.length === 0) {
return configOptions;
}
const option = findConfigOption(configOptions, predicate);
const values = flattenSelectValues(option);
if (!option || !values.includes(value)) {
logSection(`SKIP_${label}`, {
requestedValue: value,
availableValues: values,
});
return configOptions;
}
const response = (await rpc.request("session/set_config_option", {
sessionId,
configId: option.id,
value,
})) as SetConfigResult | null | undefined;
logSection(`SET_${label}_RESPONSE`, response);
return response?.configOptions ?? configOptions;
}
async function main() {
const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
try {
const initializeResponse = await rpc.request("initialize", {
protocolVersion: 1,
clientCapabilities: {
fs: { readTextFile: false, writeTextFile: false },
terminal: false,
_meta: {
parameterizedModelPicker: true,
},
},
clientInfo: {
name: "cursor-acp-model-mismatch-probe",
version: "0.0.0",
},
});
logSection("INITIALIZE_RESPONSE", initializeResponse);
const authenticateResponse = await rpc.request("authenticate", {
methodId: "cursor_login",
});
logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
const sessionResponse = (await rpc.request("session/new", {
cwd: targetCwd,
mcpServers: [],
})) as SessionNewResult;
logSection("SESSION_NEW_RESPONSE", sessionResponse);
const sessionId = asString(sessionResponse.sessionId);
if (!sessionId) {
fail("session/new did not return a sessionId.");
}
let configOptions = sessionResponse.configOptions ?? [];
const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
const advertisedModels = flattenSelectValues(modelConfig);
logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
if (!modelConfig || modelConfig.type !== "select") {
fail("Cursor ACP did not expose a select-type model config option.");
}
if (!advertisedModels.includes(targetModel)) {
fail(
`Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
);
}
const setModelResponse = (await rpc.request("session/set_config_option", {
sessionId,
configId: modelConfig.id,
value: targetModel,
})) as SetConfigResult | null | undefined;
logSection("SET_MODEL_RESPONSE", setModelResponse);
configOptions = setModelResponse?.configOptions ?? configOptions;
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "thought_level",
targetReasoning,
"REASONING",
);
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "model_config" && matchesKeyword(option, "context"),
targetContext,
"CONTEXT",
);
configOptions = await setSelectOptionIfAdvertised(
rpc,
sessionId,
configOptions,
(option) => option.category === "model_config" && matchesKeyword(option, "fast"),
targetFast,
"FAST",
);
const promptResponse = await rpc.request("session/prompt", {
sessionId,
prompt: [
{
type: "text",
text: promptText,
},
],
});
logSection("PROMPT_RESPONSE", promptResponse);
await sleep(promptWaitMs);
rpc.notify("session/cancel", { sessionId });
} finally {
await rpc.close();
}
}
void main().catch((error: unknown) => {
NodeProcess.stderr.write(
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
);
process.exitCode = 1;
});
@@ -0,0 +1,44 @@
import { assert, it } from "@effect/vitest";
import {
cursorReplayPromptsForWorkspace,
cursorReplayTranscriptCwd,
shouldSeedCursorReplayWorkspace,
} from "./cursorReplayRecordingWorkspace.ts";
it("points the read-only prompt at the unique recording workspace", () => {
assert.deepEqual(
cursorReplayPromptsForWorkspace({
scenario: "tool_call_read_only",
configuredPrompts: ["stale global path"],
packageJsonPath: "/tmp/t3-cursor-owned-abc123/package.json",
tsconfigPath: "/tmp/t3-cursor-owned-abc123/tsconfig.json",
}),
[
"Read /tmp/t3-cursor-owned-abc123/package.json and /tmp/t3-cursor-owned-abc123/tsconfig.json, then answer exactly: read only tool fixture complete",
],
);
});
it("never seeds files into an externally supplied workspace", () => {
assert.isFalse(
shouldSeedCursorReplayWorkspace({
scenario: "tool_call_read_only",
owned: false,
}),
);
assert.isTrue(
shouldSeedCursorReplayWorkspace({
scenario: "tool_call_read_only",
owned: true,
}),
);
});
it("canonicalizes read-only tool paths to the stable fixture workspace", () => {
assert.equal(
cursorReplayTranscriptCwd("tool_call_read_only"),
"/tmp/claude-replay-tool_call_read_only",
);
assert.equal(cursorReplayTranscriptCwd("simple"), undefined);
});
@@ -0,0 +1,29 @@
import { TOOL_CALL_READ_ONLY_WORKSPACE_ROOT } from "../src/orchestration-v2/testkit/fixtures/shared.ts";
const SEEDED_CURSOR_REPLAY_SCENARIOS = new Set(["subagent", "tool_call_read_only", "todo_list"]);
export function cursorReplayPromptsForWorkspace(input: {
readonly scenario: string;
readonly configuredPrompts: ReadonlyArray<string>;
readonly packageJsonPath: string;
readonly tsconfigPath: string;
}): ReadonlyArray<string> {
if (input.scenario !== "tool_call_read_only") {
return input.configuredPrompts;
}
return [
`Read ${input.packageJsonPath} and ${input.tsconfigPath}, then answer exactly: read only tool fixture complete`,
];
}
export function shouldSeedCursorReplayWorkspace(input: {
readonly scenario: string;
readonly owned: boolean;
}): boolean {
return input.owned && SEEDED_CURSOR_REPLAY_SCENARIOS.has(input.scenario);
}
export function cursorReplayTranscriptCwd(scenario: string): string | undefined {
return scenario === "tool_call_read_only" ? TOOL_CALL_READ_ONLY_WORKSPACE_ROOT : undefined;
}
@@ -0,0 +1,358 @@
import {
forkSession,
query,
type SDKAssistantMessage,
type SDKMessage,
} from "@anthropic-ai/claude-agent-sdk";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ProviderInstanceId, type ProviderReplayEntry } from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import {
makeClaudeQueryOptions,
makeClaudeUserMessage,
type ClaudeAgentSdkQueryOptions,
} from "../src/orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import { randomUuidV4 } from "../src/orchestration-v2/RandomUuid.ts";
import { makeCheckpointWorkspace } from "../src/orchestration-v2/testkit/ReplayFixtureWorkspace.ts";
const SCENARIO = "thread_fork_native_fork_local_rollback";
const DEFAULT_OUTPUT = new URL(
"../src/orchestration-v2/testkit/fixtures/thread_fork_native_fork_local_rollback/claude_transcript.ndjson",
import.meta.url,
).pathname;
const CLAUDE_PROVIDER = "claudeAgent" as const;
const PROTOCOL = "claude-agent-sdk.query" as const;
const MODEL_SELECTION = {
instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER),
model: process.env.T3_CLAUDE_REPLAY_MODEL ?? "claude-sonnet-4-6",
} as const;
const SOURCE_PROMPT =
"For this fork-local rollback fixture, respond with exactly: fork local source alpha";
const FORK_FIRST_PROMPT =
"For this fork-local rollback fixture, respond with exactly: fork local first";
const FORK_SECOND_PROMPT =
"For this fork-local rollback fixture, respond with exactly: fork local second";
const FORK_AFTER_ROLLBACK_PROMPT =
"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.";
class PromptQueue implements AsyncIterable<ReturnType<typeof makeClaudeUserMessage>> {
readonly #items: Array<ReturnType<typeof makeClaudeUserMessage>> = [];
readonly #waiters: Array<
(value: IteratorResult<ReturnType<typeof makeClaudeUserMessage>>) => void
> = [];
#closed = false;
offer(message: ReturnType<typeof makeClaudeUserMessage>): void {
const waiter = this.#waiters.shift();
if (waiter !== undefined) {
waiter({ done: false, value: message });
return;
}
this.#items.push(message);
}
close(): void {
this.#closed = true;
for (const waiter of this.#waiters.splice(0)) {
waiter({ done: true, value: undefined });
}
}
[Symbol.asyncIterator](): AsyncIterator<ReturnType<typeof makeClaudeUserMessage>> {
return {
next: () => {
const value = this.#items.shift();
if (value !== undefined) {
return Promise.resolve({ done: false, value });
}
if (this.#closed) {
return Promise.resolve({ done: true, value: undefined });
}
return new Promise((resolve) => this.#waiters.push(resolve));
},
};
}
}
function readArgValue(name: string): string | undefined {
const args = process.argv.slice(2);
const index = args.indexOf(name);
return index >= 0 ? args[index + 1] : undefined;
}
function dirname(filePath: string): string {
const normalized = filePath.replace(/\/+$/u, "");
const lastSlash = normalized.lastIndexOf("/");
if (lastSlash < 0) {
return ".";
}
return lastSlash === 0 ? "/" : normalized.slice(0, lastSlash);
}
function sanitizeValue(
value: unknown,
pathFragments: ReadonlyArray<readonly [string, string]>,
): unknown {
if (typeof value === "string") {
return pathFragments.reduce(
(sanitized, [actual, replacement]) =>
actual.length === 0 ? sanitized : sanitized.split(actual).join(replacement),
value,
);
}
if (Array.isArray(value)) {
return value.map((entry) => sanitizeValue(entry, pathFragments));
}
if (typeof value === "object" && value !== null) {
return Object.fromEntries(
Object.entries(value).map(([key, entry]) => [key, sanitizeValue(entry, pathFragments)]),
);
}
return value;
}
function stableOptions(options: ClaudeAgentSdkQueryOptions): ClaudeAgentSdkQueryOptions {
const stable = {
model: options.model,
tools: options.tools,
permissionMode: options.permissionMode,
...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
...(options.settings === undefined ? {} : { settings: options.settings }),
...(options.allowDangerouslySkipPermissions === true
? { allowDangerouslySkipPermissions: true }
: {}),
...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
...(options.forkSession === true ? { forkSession: true } : {}),
};
return options.resume === undefined
? { ...stable, sessionId: options.sessionId }
: { ...stable, resume: options.resume };
}
function queryOptions(input: {
readonly cwd: string;
readonly nativeThreadId: string;
readonly resume: boolean;
readonly resumeSessionAt?: string;
}): ClaudeAgentSdkQueryOptions {
return {
...makeClaudeQueryOptions({
modelSelection: MODEL_SELECTION,
cwd: input.cwd,
nativeThreadId: input.nativeThreadId,
resume: input.resume,
tools: { type: "preset", preset: "claude_code" },
permissionMode: "bypassPermissions",
allowDangerouslySkipPermissions: true,
}),
...(input.resumeSessionAt === undefined ? {} : { resumeSessionAt: input.resumeSessionAt }),
};
}
async function recordTurn(input: {
readonly entries: Array<ProviderReplayEntry>;
readonly iterator: AsyncIterator<SDKMessage>;
readonly promptQueue: PromptQueue;
readonly prompt: string;
readonly label: string;
readonly pathFragments: ReadonlyArray<readonly [string, string]>;
}): Promise<SDKAssistantMessage["uuid"]> {
const message = makeClaudeUserMessage({ text: input.prompt });
input.entries.push({
type: "expect_outbound",
label: input.label,
frame: { type: "prompt.offer", message },
});
input.promptQueue.offer(message);
let assistantMessageUuid: SDKAssistantMessage["uuid"] | null = null;
while (true) {
const next = await input.iterator.next();
if (next.done === true) {
throw new Error(`Claude query ended before ${input.label} completed.`);
}
const frame = sanitizeValue(next.value, input.pathFragments);
input.entries.push({
type: "emit_inbound",
label: next.value.type,
frame,
});
if (next.value.type === "assistant") {
assistantMessageUuid = next.value.uuid;
}
if (next.value.type === "result") {
if (assistantMessageUuid === null) {
throw new Error(`Claude query completed ${input.label} without assistant UUID.`);
}
return assistantMessageUuid;
}
}
}
function encodeTranscript(input: {
readonly entries: ReadonlyArray<ProviderReplayEntry>;
readonly metadata: Record<string, unknown>;
}): string {
return [
JSON.stringify({
type: "transcript_start",
provider: CLAUDE_PROVIDER,
protocol: PROTOCOL,
version: "0.2.111",
scenario: SCENARIO,
metadata: input.metadata,
}),
...input.entries.map((entry) => JSON.stringify(entry)),
"",
].join("\n");
}
const outputPath = readArgValue("--out") ?? DEFAULT_OUTPUT;
const cwd =
process.env.T3_CLAUDE_REPLAY_CWD ??
(await makeCheckpointWorkspace(`claude-agent-sdk-record-${SCENARIO}`));
const cwdRealPath = await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
return yield* fs.realPath(cwd);
}).pipe(Effect.provide(NodeServices.layer)),
);
const pathFragments = [
[cwd, `/tmp/claude-replay-${SCENARIO}`],
[cwdRealPath, `/tmp/claude-replay-${SCENARIO}`],
[process.env.HOME ?? "", "/home/replay-user"],
] as const;
const sessionId =
process.env.T3_CLAUDE_REPLAY_SESSION_ID ?? (await Effect.runPromise(randomUuidV4));
const entries: Array<ProviderReplayEntry> = [];
const metadata: Record<string, unknown> = {
prompts: [SOURCE_PROMPT, FORK_FIRST_PROMPT, FORK_SECOND_PROMPT, FORK_AFTER_ROLLBACK_PROMPT],
model: MODEL_SELECTION.model,
nativeSessionId: sessionId,
queryMode: "fork_session_resume_at_fork_cursor",
tools: "claude_code",
permissionMode: "bypassPermissions",
generatedBy: "probeClaudeForkLocalRollbackReplay",
};
const sourceQueue = new PromptQueue();
const sourceOptions = queryOptions({ cwd, nativeThreadId: sessionId, resume: false });
entries.push({
type: "expect_outbound",
label: "query.open:source",
frame: { type: "query.open", options: stableOptions(sourceOptions) },
});
const sourceRuntime = query({ prompt: sourceQueue, options: sourceOptions });
try {
const sourceCursor = await recordTurn({
entries,
iterator: sourceRuntime[Symbol.asyncIterator](),
promptQueue: sourceQueue,
prompt: SOURCE_PROMPT,
label: "prompt.offer:source",
pathFragments,
});
sourceQueue.close();
sourceRuntime.close();
entries.push({ type: "runtime_exit", status: "success" });
entries.push({
type: "expect_outbound",
label: "session.fork",
frame: {
type: "session.fork",
sessionId,
options: {
dir: `/tmp/claude-replay-${SCENARIO}`,
upToMessageId: sourceCursor,
},
},
});
const forked = await forkSession(sessionId, { dir: cwd, upToMessageId: sourceCursor });
metadata.sourceAssistantMessageUuids = [sourceCursor];
metadata.forkUpToMessageId = sourceCursor;
metadata.forkedNativeSessionId = forked.sessionId;
entries.push({
type: "emit_inbound",
label: "session.forked",
frame: { type: "session.forked", sessionId: forked.sessionId },
});
const forkQueue = new PromptQueue();
const forkOptions = queryOptions({ cwd, nativeThreadId: forked.sessionId, resume: true });
entries.push({
type: "expect_outbound",
label: "query.open:fork",
frame: { type: "query.open", options: stableOptions(forkOptions) },
});
const forkRuntime = query({ prompt: forkQueue, options: forkOptions });
const forkIterator = forkRuntime[Symbol.asyncIterator]();
const forkFirstCursor = await recordTurn({
entries,
iterator: forkIterator,
promptQueue: forkQueue,
prompt: FORK_FIRST_PROMPT,
label: "prompt.offer:fork-first",
pathFragments,
});
const forkSecondCursor = await recordTurn({
entries,
iterator: forkIterator,
promptQueue: forkQueue,
prompt: FORK_SECOND_PROMPT,
label: "prompt.offer:fork-second",
pathFragments,
});
forkQueue.close();
forkRuntime.close();
entries.push({ type: "runtime_exit", status: "success" });
metadata.forkAssistantMessageUuids = [forkFirstCursor, forkSecondCursor];
metadata.resumeSessionAt = forkFirstCursor;
const resumedQueue = new PromptQueue();
const resumedOptions = queryOptions({
cwd,
nativeThreadId: forked.sessionId,
resume: true,
resumeSessionAt: forkFirstCursor,
});
entries.push({
type: "expect_outbound",
label: "query.open:fork-resume-at-cursor",
frame: { type: "query.open", options: stableOptions(resumedOptions) },
});
const resumedRuntime = query({ prompt: resumedQueue, options: resumedOptions });
await recordTurn({
entries,
iterator: resumedRuntime[Symbol.asyncIterator](),
promptQueue: resumedQueue,
prompt: FORK_AFTER_ROLLBACK_PROMPT,
label: "prompt.offer:fork-after-rollback",
pathFragments,
});
resumedQueue.close();
resumedRuntime.close();
entries.push({ type: "runtime_exit", status: "success" });
} catch (error) {
sourceQueue.close();
sourceRuntime.close();
entries.push({
type: "runtime_exit",
status: "error",
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
await Effect.runPromise(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.makeDirectory(dirname(outputPath), { recursive: true });
yield* fs.writeFileString(outputPath, encodeTranscript({ entries, metadata }));
yield* Console.log(`Wrote ${entries.length} ${PROTOCOL} replay entries to ${outputPath}`);
}).pipe(Effect.provide(NodeServices.layer)),
);
Loaded 100 of 883 files, more files were not shown because too many files have changed in this diff. Show more