Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex 67ab204c23 fix(server): record retried legacy handoffs
Co-authored-by: codex <[email protected]>
2026-07-27 19:39:05 +02:00
Julius Marmingeandcodex 4600a83e98 fix(server): preserve imported history across retries and forks
Co-authored-by: codex <[email protected]>
2026-07-27 19:30:29 +02:00
Julius Marmingeandcodex 9fd6b628be fix(server): hydrate delegated wake-policy parents
Co-authored-by: codex <[email protected]>
2026-07-27 19:23:29 +02:00
Julius Marmingeandcodex a7495ac4ba fix(server): gate migrated thread commands on hydration
Co-authored-by: codex <[email protected]>
2026-07-27 19:23:29 +02:00
Julius Marmingeandcodex 6a2a78526b fix(server): retain imported shell history origin
Co-authored-by: codex <[email protected]>
2026-07-27 19:23:29 +02:00
Julius Marmingeandcodex 1c90d03cc6 fix(server): preserve legacy context attribution
Co-authored-by: codex <[email protected]>
2026-07-27 19:23:29 +02:00
Julius Marmingeandcodex 0d81444d7b fix(server): preserve migrated context across provider failure
Co-authored-by: codex <[email protected]>
2026-07-27 19:23:29 +02:00
Julius Marmingeandcodex 83d955ce3b feat(server): migrate v1 state into orchestrator v2
Co-authored-by: codex <[email protected]>
2026-07-27 19:23:29 +02:00
Julius Marmingeandcodex 5263ab1836 chore(orchestrator): refresh checks after main sync
Co-authored-by: codex <[email protected]>
2026-07-27 19:22:59 +02:00
Julius Marmingeandcodex 06f5aaee77 fix(web): restore checked-in project scripts
Co-authored-by: codex <[email protected]>
2026-07-27 18:55:04 +02:00
Julius Marminge d342dc3d98 Merge origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>

# Conflicts:
#	apps/web/src/components/BranchToolbarEnvModeSelector.tsx
#	apps/web/src/components/BranchToolbarEnvironmentSelector.tsx
2026-07-27 18:54:42 +02:00
Yusuf007Randcodex 13543cd065 fix: ignore subagents when sorting sidebar projects
Co-authored-by: codex <[email protected]>
2026-07-27 18:52:45 +02:00
Yusuf007Randcodex 97a04be613 fix: hide subagent threads from v2 lists
Co-authored-by: codex <[email protected]>
2026-07-27 18:52:45 +02:00
Mike Olsonandcodex 3b6251f2b5 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-07-27 18:36:31 +02:00
Mike Olsonandcodex 959a1a3bf8 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-07-27 18:36:31 +02:00
Mike Olson 82d7d408b5 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-07-27 18:23:07 +02:00
Mike Olson bf5ad780f0 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-07-27 18:23:07 +02:00
Julius Marmingeandcodex 3f3b8b4044 Merge latest origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-07-27 17:11:58 +02:00
Julius Marmingeandcodex 3cc075adb1 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-07-27 17:11:20 +02:00
Julius Marmingeandcodex 4e200e4de4 Merge latest origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-07-27 17:02:46 +02:00
Julius Marmingeandcodex 769534e337 Merge latest origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-07-27 17:01:55 +02:00
Julius Marmingeandcodex 7b6c4e71a4 Merge origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-07-27 16:59:33 +02:00
Julius Marmingeandcodex 408efa6374 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-07-24 17:59:31 +02:00
Julius Marmingeandcodex b2441819f0 fix(server): enforce ACP auth and preserve fork provenance
Co-authored-by: codex <[email protected]>
2026-07-24 17:58:30 +02:00
Julius Marmingeandcodex 6e9becab04 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-07-24 17:54:01 +02:00
Julius Marmingeandcodex bccaea5fcd fix(mobile): wait for fork shell before navigation
Co-authored-by: codex <[email protected]>
2026-07-24 17:45:09 +02:00
Julius Marmingeandcodex c841e2a160 Merge main into codex-turn-mapping
Resolve migration sequencing and carry snooze behavior through orchestration V2.

Co-authored-by: codex <[email protected]>
2026-07-24 17:20:02 +02:00
David Whatleyandcodex 4dffcad518 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-07-24 16:56:41 +02:00
Alexandcodex 8c3675c786 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-07-24 16:56:22 +02:00
Mike Olson aee7ff39d7 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-07-24 16:49:21 +02:00
Julius Marminge c6b0ceba5d 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-07-24 16:43:08 +02:00
Mike Olson 5c4d8b7745 fix(orchestrator): Preserve claude/codex post-interrupt recovery state (#4229) 2026-07-24 16:19:21 +02:00
Mike Olson 4ed2ccc9f8 test(orchestrator): Align post-merge CTM fixtures (#4193) 2026-07-24 16:18:56 +02:00
Julius Marmingeandcodex a286c60329 fix(web): contain thread details panel effects
Co-authored-by: codex <[email protected]>
2026-07-24 15:37:48 +02:00
Julius Marmingeandcodex 8c86f10c75 fix(web): layer nested panel popups correctly
Co-authored-by: codex <[email protected]>
2026-07-24 14:15:32 +02:00
Julius Marmingeandcodex f7817d1546 refactor(web): use shared glass surfaces
Co-authored-by: codex <[email protected]>
2026-07-24 14:05:13 +02:00
Julius Marmingeandcodex 1ef1eb61ce fix(web): remove stacked composer shadows
Co-authored-by: codex <[email protected]>
2026-07-24 13:52:24 +02:00
Julius Marmingeandcodex a8fb548145 fix(web): restore v2 composer chrome
Co-authored-by: codex <[email protected]>
2026-07-24 13:52:24 +02:00
Julius Marmingeandcodex 20a3519393 fix(server): preserve released migration ordering
Co-authored-by: codex <[email protected]>
2026-07-24 12:11:35 +02:00
Julius Marmingeandcodex 7732874f50 Merge origin/main into orchestrator v2
Port mainline lifecycle and backend fixes onto the v2 orchestration architecture while retaining the full v2 implementation.

Co-authored-by: codex <[email protected]>
2026-07-23 15:49:05 +02:00
Julius Marmingeandcodex f30673fea7 fix(orchestration): clarify agent delegation and scheduling
Co-authored-by: codex <[email protected]>
2026-07-22 14:05:56 +02:00
Julius Marminge 4fcf27f426 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-07-21 04:53:20 -07:00
Julius Marminge 956be77882 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-07-21 03:19:40 -07:00
Julius Marmingeandcodex 72e23341d9 fix(grok): align ACP extensions with open source runtime
Co-authored-by: codex <[email protected]>
2026-07-20 19:03:12 +02:00
Julius Marmingeandcodex 3abcb370ed 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-07-20 18:35:12 +02:00
Julius Marmingeandcodex d114005159 test(orchestrator): align integration fixtures
Co-authored-by: codex <[email protected]>
2026-07-20 18:35:11 +02:00
Julius Marminge 59a4f121b5 Merge PR #3578 into orchestrator v2
Co-authored-by: codex <[email protected]>

# Conflicts:
#	apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
#	apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts
#	apps/server/src/orchestration-v2/ProviderContinuationRequests.ts
#	apps/server/src/orchestration-v2/ProviderContinuationService.test.ts
#	apps/server/src/orchestration-v2/ProviderContinuationService.ts
2026-07-20 18:04:37 +02:00
Julius Marmingeandcodex af3fb6c3ab fix(orchestrator): dedupe Grok continuation dispatch
Co-authored-by: codex <[email protected]>
2026-07-20 18:02:12 +02:00
Mike Olson 542c87ba03 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-07-20 11:47:41 -04:00
Mike Olsonandcodex 365a854761 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-07-20 17:15:01 +02:00
Julius Marmingeandcodex b9fc3631c9 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-07-20 16:49:49 +02:00
Julius Marmingeandcodex 380845ba7a 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-07-20 16:47:44 +02:00
Julius Marmingeandcodex 57fca27e2f 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-07-20 16:45:26 +02:00
Julius Marmingeandcodex 7114c2ce4f 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-07-20 16:44:44 +02:00
Julius Marmingeandcodex 2daa6a59f4 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-07-20 16:44:19 +02:00
Julius Marmingeandcodex 9794f40e70 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-07-20 16:43:10 +02:00
Julius Marmingeandcodex 6216b3b779 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-07-20 16:42:29 +02:00
Julius Marmingeandcodex 496818d311 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-07-20 16:41:43 +02:00
Julius Marmingeandcodex 30b6b7ba54 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-07-20 16:41:04 +02:00
Julius Marmingeandcodex 3a78bf4711 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-07-20 16:40:40 +02:00
Julius Marmingeandcodex 0f3ceb5f57 fix(orchestrator): align Claude permission replay with SDK
Co-authored-by: codex <[email protected]>
2026-07-20 16:09:41 +02:00
Alex f54fe64238 feat(orchestrator): pass model options through MCP thread targets (#3872) 2026-07-20 16:08:10 +02:00
Alex 24ea17a2ff fix(orchestrator): scope Claude MCP tool pre-approval (#3862) 2026-07-20 16:08:10 +02:00
Mike Olson aaf69ecf7f [orchestrator-v2] fix(orchestrator): Codex background command completion and subagent resume (#3908) 2026-07-20 16:08:10 +02:00
0aebed2ca6 [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-07-20 16:08:10 +02:00
Mike Olson 90c6401268 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-07-20 16:08:10 +02:00
Julius Marmingeandcodex 309fcabe1f Merge origin/main into orchestrator v2
Port current mainline fixes onto the orchestrator v2 architecture.

Co-authored-by: codex <[email protected]>
2026-07-20 16:07:59 +02:00
Julius MarmingeandClaude Fable 5 dac514e6b6 feat: scheduled tasks (automations) (#3638)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-01 16:44:14 -07:00
Julius Marmingeandcodex 96b4071cdb Fix Claude task turn mapping
Co-authored-by: codex <[email protected]>
2026-07-01 09:43:43 -07:00
Julius Marminge 4ca3ff5191 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-06-30 17:38:12 -07:00
Julius Marminge 6d33dd25ca 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-06-30 11:14:40 -07:00
Julius Marminge c2132ee7dd 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-06-30 10:29:47 -07:00
maria 7bf0a2ce15 fix(web): align thread details panel controls and menus (#3606) 2026-06-30 09:38:04 -07:00
Julius Marminge 2f774f8e80 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-06-29 16:22:56 -07:00
Julius Marminge 73d8597e01 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-06-29 13:08:51 -07:00
Julius Marminge 30fa9443d6 Merge origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>

# Conflicts:
#	apps/web/src/components/ChatView.tsx
#	apps/web/src/components/chat/MessagesTimeline.tsx
#	pnpm-lock.yaml
2026-06-29 12:57:46 -07:00
Julius Marminge cc92acf77b 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-06-29 11:04:04 -07:00
Julius Marminge 57aa76ac14 Map nested Codex subagent threads correctly
- Preserve app-thread projection when spawning Codex subagents
- Add replay fixture coverage for nested provider-native subagents
2026-06-29 10:51:36 -07:00
Julius Marminge 3b864044c6 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-06-28 17:58:14 -07:00
Julius Marmingeandcodex b452303639 Merge origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-06-27 09:47:42 -07:00
Julius Marminge 706c819cf3 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-06-26 11:33:00 -07:00
Julius Marmingeandcodex 1467717c12 Merge main into orchestration v2
Carry forward the reusable ACP replay, drain, and xAI extension work from #3156 while retaining V2-owned adapters, presentation, and provider-acknowledged cancellation semantics.

Co-authored-by: codex <[email protected]>
2026-06-25 23:55:10 -07:00
Julius Marmingeandcodex 1603df97f5 Merge origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-06-25 19:30:11 -07:00
Julius Marminge 2c33e9f28c Add iOS associated domains for Clerk
- Configure applinks and webcredentials for all mobile variants
- Set the Clerk relying party used by app config
2026-06-25 10:44:14 -07:00
Julius Marmingeandcodex 89c752c2b8 Retire V1 client orchestration parity
Co-authored-by: codex <[email protected]>
2026-06-25 04:22:49 -07:00
Julius Marmingeandcodex 967193f737 Expose V2 thread workflows on mobile
Co-authored-by: codex <[email protected]>
2026-06-25 04:22:49 -07:00
Julius Marmingeandcodex e15026a12a 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-06-25 00:34:00 -07:00
Julius Marmingeandcodex 5df6529caa 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-06-25 00:32:19 -07:00
Julius Marminge 3a12575b05 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-06-24 23:10:56 -07:00
Julius Marminge 272e355ee9 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-06-24 19:35:40 -07:00
Julius Marminge e201350381 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-06-24 17:08:19 -07:00
Julius Marmingeandcodex 361df65ffb 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-06-24 16:48:28 -07:00
Julius Marminge fc23be8184 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-06-24 16:38:01 -07:00
Julius Marminge c529c610e3 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-06-24 16:36:49 -07:00
Julius Marminge 54a555c71b 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-06-24 16:35:40 -07:00
Julius Marminge 323ad3614f 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-06-24 16:33:56 -07:00
Julius Marminge 353acd9a27 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-06-24 16:22:45 -07:00
Julius Marminge d6e3326426 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-06-24 16:22:45 -07:00
Julius Marminge fb9764b8cb Guarantee MCP revocation during session release 2026-06-24 16:12:46 -07:00
Julius Marminge 6a295b93ea Remove MCP credential expiration 2026-06-24 16:12:46 -07:00
Julius Marminge 9f19b4f06c Require MCP registry for V2 provider sessions 2026-06-24 16:12:46 -07:00
Julius Marminge 84e1a91cab Complete orchestration V2 application services 2026-06-24 16:12:46 -07:00
Julius Marminge 170f3201e7 Start orchestration V2 application services 2026-06-24 16:12:46 -07:00
Julius Marminge 9711e6c879 Align orchestration V2 with Effect service conventions 2026-06-24 16:12:45 -07:00
Julius Marminge 42450d51f1 Merge origin/main into t3code/codex-turn-mapping 2026-06-24 16:12:45 -07:00
Julius Marminge 5ba299d715 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-06-20 17:06:29 -07:00
Julius Marminge 7fcc993eae 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-06-19 20:47:34 -07:00
Julius Marminge 6821946ccc Add Orchestration V2 application integration plan
- Define four implementation shapes for the V2-only migration
- Add the plan to the plans index
2026-06-19 19:05:19 -07:00
Julius Marminge 12259adb5d 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-06-19 15:18:17 -07:00
Julius Marmingeandcodex c7f7e8c38d Merge origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-06-18 21:35:52 -07:00
Julius Marminge 1161529645 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-06-18 20:55:08 -07:00
Julius Marminge 9d38de8628 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-06-18 02:18:01 -07:00
Julius Marminge 9198a64c3d 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-06-17 16:11:28 -07:00
Julius Marminge d62855cd7d 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-06-17 10:58:50 -07:00
Julius Marmingeandcodex c7539b92f5 refactor(orchestration-v2): adopt host process spawn policy
Co-authored-by: codex <[email protected]>
2026-06-17 00:29:48 -07:00
Julius Marmingeandcodex b7ff82862e Merge origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-06-17 00:29:48 -07:00
Julius Marminge dbb184bb8a wip 2026-06-13 22:46:37 -07:00
Julius Marmingeandcodex acc41f4742 merge: native subagent orchestration
Co-authored-by: codex <[email protected]>
2026-06-09 21:32:01 -07:00
Julius Marminge 6b6a9c4081 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-06-09 21:32:01 -07:00
Julius Marmingeandcodex ae922761c3 feat(orchestration-v2): model native subagents
Co-authored-by: codex <[email protected]>
2026-06-09 21:32:01 -07:00
Julius Marmingeandcodex 0425b5510d 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-06-09 21:32:01 -07:00
Julius Marmingeandcodex 0de927dfc6 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-06-09 21:32:01 -07:00
Julius Marmingeandcodex e39cfb89f8 merge: orchestration v2 merge-back fixtures
Co-authored-by: codex <[email protected]>
2026-06-09 21:32:01 -07:00
Julius Marmingeandcodex b14e89f11a fix(orchestration-v2): resolve cross-provider forks
Co-authored-by: codex <[email protected]>
2026-06-09 21:32:01 -07:00
Julius Marmingeandcodex 96073b6bac 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-06-09 21:31:51 -07:00
Julius Marmingeandcodex bf75071f40 feat(orchestration-v2): support cross-provider handoff
Co-authored-by: codex <[email protected]>
2026-06-09 21:31:36 -07:00
Julius Marmingeandcodex a1d2f75253 Merge origin/main into t3code/codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-06-09 21:31:36 -07:00
Julius Marmingeandcodex 6d1d513032 feat(orchestration-v2): wire claude adapter primitives
Co-authored-by: codex <[email protected]>
2026-05-27 12:50:10 -07:00
Julius Marmingeandcodex ff03673ff8 Merge origin/main into codex-turn-mapping
Co-authored-by: codex <[email protected]>
2026-05-08 18:50:31 -07:00
Julius Marminge 1b440329f4 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-05-07 14:37:38 -07:00
Julius Marminge 85f570a413 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-05-07 13:21:10 -07:00
Julius Marminge 26f3c80250 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-05-07 10:53:39 -07:00
Julius Marmingeandcodex ca835c2508 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-05-06 21:02:39 -07:00
Julius Marminge 7979036cd1 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-05-06 19:28:31 -07:00
Julius Marminge 2ea043e73b 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-05-06 14:39:42 -07:00
Julius Marmingeandcodex 9316b57f9f Merge origin/main into codex-turn-mapping
Port orchestration V2 provider adapter wiring to the provider-instance driver registry.

Co-authored-by: codex <[email protected]>
2026-05-06 12:16:15 -07:00
Julius Marminge d9c39e4d30 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-05-06 11:35:39 -07:00
Julius Marminge f3957fd473 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-05-06 11:12:37 -07:00
Julius Marmingeandcodex 59e9c647b7 Add V2 command capability policy
Co-authored-by: codex <[email protected]>
2026-05-03 19:46:57 -07:00
Julius Marminge 5e5ad3c7a7 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-05-01 18:08:56 -07:00
Julius Marminge 2769c2e42d 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-04-28 22:48:42 -07:00
Julius Marminge 334265e87b 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-04-28 21:46:22 -07:00
Julius Marmingeandcodex 969e8ea4fa Implement orchestration v2 runtime
Co-authored-by: codex <[email protected]>
2026-04-24 13:47:37 -04:00
Julius Marminge 7eefb2eb1d 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-04-20 19:32:35 -07:00
Julius Marmingeandcodex 3bc8508de8 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-04-20 17:28:52 -07:00
Julius Marminge 355eb2dade 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-04-20 14:26:09 -07:00
Julius Marmingeandcodex d138a0bc31 Fix Codex provider status test expectations
Co-authored-by: codex <[email protected]>
2026-04-18 10:29:36 -07:00
Julius Marmingeandcodex 11fa703852 Address Codex review feedback
Co-authored-by: codex <[email protected]>
2026-04-18 10:22:26 -07:00
Julius Marminge d53e02b981 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-04-18 00:46:57 -07:00
Julius Marminge 6e6bcd8450 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-04-17 20:14:02 -07:00
Julius Marminge 6164a937ae decoders 2026-04-17 19:54:49 -07:00
Julius Marminge c01b90a8fd 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-04-17 19:47:21 -07:00
Julius Marminge 047eb4e29a 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-04-17 19:32:18 -07:00
Julius Marminge 9c916d6caa 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-04-17 19:28:36 -07:00
Julius Marminge 35bc0902ae Delay Codex provider availability until checked
- Initialize provider as unchecked in a pending state
- Update initial probe message to reflect session-local status
2026-04-17 19:03:59 -07:00
Julius Marminge fa9bcbc053 resynclock 2026-04-17 18:57:24 -07:00
Julius Marminge a15194f649 revert more 2026-04-17 17:43:47 -07:00
Julius Marminge 2b623b54ff nit 2026-04-17 17:39:14 -07:00
Julius Marmingeandcodex 308dd659da Integrate Codex app-server support
Co-authored-by: codex <[email protected]>
2026-04-17 17:29:53 -07:00
757 changed files with 145143 additions and 73066 deletions

No files matched your search

+10
View File
@@ -48,6 +48,16 @@ jobs:
- name: Checkout
uses: actions/checkout@v6
# 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:
@@ -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`
@@ -95,6 +95,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
+1 -1
View File
@@ -207,7 +207,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 -2
View File
@@ -101,8 +101,8 @@
"expo-web-browser": "~56.0.5",
"expo-widgets": "~56.0.19",
"punycode": "^2.3.1",
"react": "19.2.6",
"react-dom": "19.2.6",
"react": "19.2.3",
"react-dom": "19.2.3",
"react-native": "0.85.3",
"react-native-gesture-handler": "~2.31.1",
"react-native-image-viewing": "^0.2.2",
+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");
@@ -4,8 +4,8 @@ import {
} from "@t3tools/client-runtime/platform";
import {
type EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
OrchestrationV2ShellSnapshot,
OrchestrationV2ThreadDetailSnapshot,
ServerConfig,
VcsListRefsResult,
} from "@t3tools/contracts";
@@ -24,13 +24,13 @@ const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
snapshot: OrchestrationShellSnapshot,
snapshot: OrchestrationV2ShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
threadId: Schema.String,
snapshot: OrchestrationThreadDetailSnapshot,
snapshot: OrchestrationV2ThreadDetailSnapshot,
});
const StoredServerConfig = Schema.Struct({
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
@@ -150,7 +150,7 @@ 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,
environmentId,
+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
@@ -165,7 +165,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,
};
}
@@ -571,7 +571,7 @@ export function HomeScreen(props: HomeScreenProps) {
?.providers.find(
(provider) =>
provider.instanceId ===
(item.thread.session?.providerInstanceId ?? item.thread.modelSelection.instanceId),
(item.thread.runtime?.providerInstanceId ?? item.thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
@@ -839,7 +839,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 {
@@ -10,6 +10,7 @@ import {
buildHomeThreadGroups,
sortHomeProjectScopes,
} from "./homeThreadList";
import { makeThreadShellFixture } from "../../test-fixtures";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
@@ -29,25 +30,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");
@@ -1,4 +1,7 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
threadRuntimeIsActive,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
import * as Cause from "effect/Cause";
import * as Haptics from "expo-haptics";
@@ -95,11 +98,7 @@ function useThreadActionExecutor(
}
// Archive keeps its original, narrower guard: never interrupt a
// thread mid-turn.
if (
action === "archive" &&
thread.session?.status === "running" &&
thread.session.activeTurnId != null
) {
if (action === "archive" && threadRuntimeIsActive(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;
@@ -469,7 +469,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(() => ({
@@ -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,14 +6,16 @@ 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>;
}
export function PendingApprovalCard(props: PendingApprovalCardProps) {
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/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
@@ -27,17 +29,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">
@@ -46,7 +54,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,4 @@
import type { ApprovalRequestId } from "@t3tools/contracts";
import type { RuntimeRequestId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
@@ -9,14 +9,10 @@ export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
readonly answers: Record<string, string> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly onSelectOption: (
requestId: ApprovalRequestId,
questionId: string,
label: string,
) => void;
readonly respondingUserInputId: RuntimeRequestId | null;
readonly onSelectOption: (requestId: RuntimeRequestId, questionId: string, label: string) => void;
readonly onChangeCustomAnswer: (
requestId: ApprovalRequestId,
requestId: RuntimeRequestId,
questionId: string,
customAnswer: string,
) => void;
@@ -24,6 +20,7 @@ export interface PendingUserInputCardProps {
}
export function PendingUserInputCard(props: PendingUserInputCardProps) {
const canRespond = props.pendingUserInput.responseCapability === "live";
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
@@ -32,6 +29,12 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
Fill in the pending answers
</Text>
{!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 (
@@ -49,6 +52,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
return (
<Pressable
key={option.label}
disabled={!canRespond}
className={cn(
"rounded-full border px-3 py-2.5 ",
selected
@@ -78,6 +82,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
})}
</View>
<TextInput
editable={canRespond}
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
@@ -94,7 +99,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,217 @@
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";
function buildThreadFileParams(
environmentId: EnvironmentId,
threadId: ThreadId,
relativePath: string,
line?: number | null,
) {
return {
environmentId: String(environmentId),
threadId: String(threadId),
path: relativePath.split("/").filter((segment) => segment.length > 0),
...(Number.isFinite(line) && Number(line) > 0
? { line: String(Math.floor(Number(line))) }
: {}),
};
}
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",
buildThreadFileParams(
props.environmentId,
row.sourceThreadId,
relativePath,
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,9 +1,12 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import {
threadRuntimeIsActive,
type EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderInteractionMode,
RuntimeMode,
ServerConfig as T3ServerConfig,
@@ -97,7 +100,7 @@ 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;
@@ -305,9 +308,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
setIsFocused(false);
onExpandedChange?.(false);
}, [onExpandedChange]);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting";
const showStopAction = threadRuntimeIsActive(props.selectedThread.runtime);
const sendLabel =
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
@@ -1,16 +1,16 @@
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 type {
ApprovalRequestId,
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderApprovalDecision,
ProviderInteractionMode,
RuntimeMode,
RuntimeRequestId,
ServerConfig as T3ServerConfig,
ThreadId,
} from "@t3tools/contracts";
@@ -40,10 +40,12 @@ import {
ThreadComposer,
} from "./ThreadComposer";
import { ThreadFeed } 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;
@@ -51,11 +53,11 @@ export interface ThreadDetailScreenProps {
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
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> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly respondingUserInputId: RuntimeRequestId | null;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly connectionStateLabel: EnvironmentConnectionPhase;
@@ -82,16 +84,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,
requestId: RuntimeRequestId,
questionId: string,
label: string,
) => void;
readonly onChangeUserInputCustomAnswer: (
requestId: ApprovalRequestId,
requestId: RuntimeRequestId,
questionId: string,
customAnswer: string,
) => void;
@@ -358,7 +360,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.selectedThread.latestRun}
activeWorkStartedAt={props.activeWorkStartedAt}
listRef={listRef}
freeze={freeze}
@@ -367,6 +370,12 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
topAccessory={
<ThreadRelationshipsBanner
environmentId={props.environmentId}
threadId={props.selectedThread.id}
/>
}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
@@ -388,6 +397,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
pushes the resting content floor up by the same amount. */}
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
<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"
+173 -53
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,
Linking,
Platform,
@@ -77,6 +86,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,
@@ -88,13 +98,18 @@ import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/l
import {
deriveThreadFeedPresentation,
type ThreadFeedEntry,
type ThreadFeedLatestTurn,
type ThreadFeedLatestRun,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import { ThreadWorkGroupToggle, ThreadWorkLog } 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";
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
@@ -124,11 +139,12 @@ function isFreshTimestamp(input: string): boolean {
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>;
@@ -136,6 +152,7 @@ export interface ThreadFeedProps {
readonly contentInsetEndAdjustment: SharedValue<number>;
readonly contentTopInset?: number;
readonly contentBottomInset?: number;
readonly topAccessory?: ReactNode;
readonly contentMaxWidth?: number;
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
@@ -143,6 +160,89 @@ export interface ThreadFeedProps {
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
}
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`,
},
})
.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: {
readonly environmentId: EnvironmentId;
readonly attachmentId: string;
@@ -796,15 +896,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;
@@ -813,6 +914,7 @@ function renderFeedEntry(
readonly reviewCommentColors: ReviewCommentColors;
readonly reviewCommentBubbleWidth: number;
readonly userBubbleMaxWidth: number;
readonly threadTitle: string;
},
) {
const entry = info.item;
@@ -822,12 +924,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]"
>
@@ -866,7 +968,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) &&
@@ -880,6 +982,11 @@ function renderFeedEntry(
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={{
@@ -971,6 +1078,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}
@@ -991,10 +1104,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}
/>
);
}
@@ -1297,9 +1415,9 @@ 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 disclosureAnchorKeyRef = useRef<string | null>(null);
const headerMaterialVisibleRef = useRef(false);
const previousLatestTurnRef = useRef(props.latestTurn);
const { width: windowWidth } = useWindowDimensions();
const [viewportWidth, setViewportWidth] = useState(() =>
props.layoutVariant === "split" ? 0 : windowWidth,
@@ -1310,7 +1428,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: {},
@@ -1383,6 +1501,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listAppearanceData = useMemo(
() => ({
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1392,6 +1511,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}),
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1431,31 +1551,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
reportHeaderMaterialVisibility(false);
}, [props.threadId, reportHeaderMaterialVisibility]);
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 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
@@ -1484,29 +1593,29 @@ 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
props.latestRun &&
(props.latestRun.completedAt === null || props.latestRun.status === "running")
? 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),
@@ -1515,14 +1624,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 () => {
@@ -1603,8 +1712,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: {
@@ -1617,14 +1726,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 };
});
@@ -1640,7 +1749,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,
@@ -1656,10 +1767,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,
@@ -1676,7 +1790,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleWorkGroup,
onToggleWorkRow,
props.environmentId,
props.threadId,
props.threadTitle,
props.skills,
props.workspaceRoot,
],
);
@@ -1792,7 +1909,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onScroll={handleScroll}
scrollEventThrottle={16}
ListHeaderComponent={
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
<>
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
{props.topAccessory}
</>
}
contentContainerStyle={{
paddingTop: 12,
@@ -782,7 +782,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,115 @@
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";
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 [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);
};
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) => (
<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}>
{text}
</Text>
<Pressable
accessibilityRole="button"
accessibilityLabel="Move queued message up"
disabled={busyRunId !== null || !workflow.canReorder || index === 0}
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={
busyRunId !== null ||
!workflow.canReorder ||
index === workflow.queuedRuns.length - 1
}
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={busyRunId !== null || !workflow.canPromoteToSteer}
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>
</View>
))}
</ScrollView>
</View>
);
}
@@ -0,0 +1,299 @@
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 } 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 latestCompletedRun = projection?.runs.findLast((run) => run.status === "completed") ?? null;
const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== 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: "SettingsArchive" });
return;
}
navigation.navigate("Thread", {
environmentId: props.environmentId,
threadId,
});
};
const merge = async () => {
if (!canMerge || mergeTargetThreadId === null || latestCompletedRun === null) return;
setBusyAction("merge");
const result = await mergeBack({
environmentId: props.environmentId,
input: {
sourceThreadId: props.threadId,
targetThreadId: mergeTargetThreadId,
runId: latestCompletedRun.id,
},
});
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>
</>
);
}
@@ -5,6 +5,7 @@ import {
useNavigation,
type StaticScreenProps,
} from "@react-navigation/native";
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import * as Option from "effect/Option";
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
@@ -307,7 +308,7 @@ function ThreadRouteContent(
}),
[knownTerminalSessions, selectedThreadProject?.workspaceRoot],
);
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
const handleReconnectEnvironment = useCallback(() => {
if (!environmentId) {
return;
@@ -461,20 +462,15 @@ function ThreadRouteContent(
void navigation.navigate("Connections");
}, [navigation]);
const handleStopThread = useCallback(() => {
if (
!selectedThread ||
(selectedThread.session?.status !== "running" &&
selectedThread.session?.status !== "starting")
) {
const runtime = selectedThread?.runtime;
if (!selectedThread || !runtime || !threadRuntimeIsActive(runtime)) {
return;
}
return interruptThreadTurn({
environmentId: selectedThread.environmentId,
input: {
threadId: selectedThread.id,
...(selectedThread.session.activeTurnId
? { turnId: selectedThread.session.activeTurnId }
: {}),
...(runtime.activeRunId ? { runId: runtime.activeRunId } : {}),
},
});
}, [interruptThreadTurn, selectedThread]);
@@ -252,7 +252,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
{thread.title}
</Text>
<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",
@@ -262,7 +262,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
@@ -1,12 +1,19 @@
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 { cn } from "../../lib/cn";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
import Animated, { FadeIn } from "react-native-reanimated";
import { useV2ItemSupport } from "../../state/v2-item-support";
import { ThreadActivityInspector } from "./ThreadActivityInspector";
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
const WORK_LOG_LAYOUT_ANIMATION = {
duration: 180,
create: {
@@ -69,6 +76,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;
@@ -80,25 +168,32 @@ function isFreshRow(createdAt: string): boolean {
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)";
const rows = props.activities
.filter((activity) => !(activity.toolLike && activity.status === "neutral"))
.map((activity) => ({ ...activity, detail: compactActivityDetail(activity.detail) }));
const rows = props.activities;
if (rows.length === 0) {
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);
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
@@ -106,17 +201,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}
@@ -138,30 +237,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>
@@ -205,28 +298,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 tool calls"
: `Show ${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`
}
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 tool calls"
: `+${hiddenCount} previous tool ${hiddenCount === 1 ? "call" : "calls"}`}
</Text>
</Pressable>
) : null}
</View>
);
}
@@ -247,41 +375,35 @@ export function ThreadWorkGroupToggle(props: {
: 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";
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,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();
}
@@ -1,7 +1,8 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
import { EnvironmentId, ProjectId, ProviderInstanceId, RunId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { makeThreadShellFixture } from "../../test-fixtures";
import {
buildThreadListV2Items,
resolveThreadListV2Status,
@@ -13,44 +14,25 @@ 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";
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,
},
@@ -77,6 +59,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("hides snoozed threads and counts them — visibility parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -234,10 +278,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,
@@ -245,7 +290,7 @@ describe("buildThreadListV2Items", () => {
}),
],
environmentId: null,
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
projectRefs: [{ environmentId, projectId }],
searchQuery: "",
now: NOW,
});
@@ -255,19 +300,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,
@@ -290,9 +337,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`,
@@ -19,7 +19,7 @@ export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
export function resolveThreadListV2Status(
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "runtime">,
): ThreadListV2Status {
if (thread.hasPendingApprovals) {
return "approval";
@@ -27,10 +27,13 @@ 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 === "failed") {
return "failed";
}
return "ready";
@@ -140,6 +143,7 @@ export function buildThreadListV2Items(input: {
let snoozedCount = 0;
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 {
@@ -50,6 +50,7 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
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),
+3 -6
View File
@@ -4,6 +4,7 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools
import { groupProjectsByRepository } from "./repositoryGroups";
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { makeThreadShellFixture } from "../test-fixtures";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
@@ -23,24 +24,20 @@ function makeThread(
input: Partial<EnvironmentThreadShell> &
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title" | "modelSelection">,
): EnvironmentThreadShell {
return {
return makeThreadShellFixture({
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,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
});
}
describe("groupProjectsByRepository", () => {
+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}`;
}
+226 -433
View File
@@ -1,15 +1,13 @@
import { describe, expect, it } from "vite-plus/test";
import {
EventId,
MessageId,
ProjectId,
ProviderInstanceId,
RunId,
ThreadId,
TurnId,
type OrchestrationThread,
type OrchestrationThreadActivity,
TurnItemId,
type OrchestrationV2ProjectedTurnItem,
type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
import {
buildThreadFeed,
@@ -18,449 +16,224 @@ import {
type ThreadFeedEntry,
} from "./threadActivity";
function makeActivity(
input: Partial<OrchestrationThreadActivity> &
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
): OrchestrationThreadActivity {
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 {
tone: "info",
payload: {},
turnId: null,
...input,
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 makeThread(
input: Partial<OrchestrationThread> & Pick<OrchestrationThread, "id" | "projectId" | "title">,
): OrchestrationThread {
function projected(
item: OrchestrationV2TurnItem,
position: number,
visibility: OrchestrationV2ProjectedTurnItem["visibility"] = "local",
): OrchestrationV2ProjectedTurnItem {
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,
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("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",
},
}),
],
});
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(thread);
expect(feed).toMatchObject([
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(
{
type: "activity-group",
turnId: "turn-old",
activities: [{ id: "activity-old", turnId: "turn-old" }],
...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,
{
type: "activity-group",
turnId: "turn-latest",
activities: [{ id: "activity-latest", turnId: "turn-latest" }],
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("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",
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,
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",
},
}),
],
});
new Set(),
);
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" }],
});
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", () => {
@@ -485,22 +258,25 @@ describe("buildThreadFeed", () => {
): ThreadFeedActivity => ({
id,
createdAt,
turnId: null,
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",
turnId: null,
runId: null,
activities: [
activity("activity-1", "2026-04-01T00:00:01.000Z"),
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
@@ -531,4 +307,21 @@ describe("buildThreadFeed", () => {
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");
});
});
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 -23
View File
@@ -1,11 +1,9 @@
import type { EnvironmentId, OrchestrationThread, ThreadId } from "@t3tools/contracts";
import * as Option from "effect/Option";
import type { EnvironmentId } from "@t3tools/contracts";
import { useEffect, useMemo, useState } from "react";
import { orchestrationEnvironment } from "./orchestration";
import { projectEnvironment } from "./projects";
import { useEnvironmentQuery } from "./query";
import { useEnvironmentThread } from "./threads";
import { vcsEnvironment } from "./vcs";
import {
buildCheckpointDiffTargets,
@@ -17,13 +15,6 @@ const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
const COMPOSER_PATH_SEARCH_LIMIT = 20;
const VCS_REF_LIST_LIMIT = 100;
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;
@@ -45,19 +36,6 @@ function useDebouncedValue<A>(value: A, delayMs: number): A {
return debounced;
}
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,20 +1,19 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useMemo, useState } from "react";
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";
import { derivePendingThreadRequests } 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,
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";
@@ -63,22 +62,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);
const activePendingApprovals = useMemo(
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
const pendingRequests = useMemo(
() =>
selectedThread === null
? { approvals: [], userInputs: [] }
: derivePendingThreadRequests(selectedThread.projection),
[selectedThread],
);
const activePendingApprovals = pendingRequests.approvals;
const activePendingApproval = activePendingApprovals[0] ?? null;
const activePendingUserInputs = useMemo(
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
[selectedThread],
);
const activePendingUserInputs = pendingRequests.userInputs;
const activePendingUserInput = activePendingUserInputs[0] ?? null;
const activePendingUserInputDrafts =
activePendingUserInput && selectedThreadShell
@@ -91,7 +89,7 @@ export function useSelectedThreadRequests() {
: null;
const onSelectUserInputOption = useCallback(
(requestId: ApprovalRequestId, questionId: string, label: string) => {
(requestId: RuntimeRequestId, questionId: string, label: string) => {
if (!selectedThreadShell) {
return;
}
@@ -103,7 +101,7 @@ export function useSelectedThreadRequests() {
);
const onChangeUserInputCustomAnswer = useCallback(
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
(requestId: RuntimeRequestId, questionId: string, customAnswer: string) => {
if (!selectedThreadShell) {
return;
}
@@ -115,10 +113,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({
@@ -132,11 +136,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,9 @@
import { useAtomValue } from "@effect/atom-react";
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
import {
deriveLatestThreadRun,
deriveThreadRuntime,
} from "@t3tools/client-runtime/state/thread-execution";
import { useCallback, useEffect, useMemo } from "react";
import {
@@ -36,7 +41,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";
@@ -74,7 +82,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();
@@ -90,47 +99,52 @@ 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 selectedThreadLatestRun = useMemo(
() =>
selectedThreadProjection
? deriveLatestThreadRun(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(selectedThreadLatestRun, selectedThreadSessionActivity, null);
}, [selectedThreadLatestRun, selectedThreadSessionActivity, selectedThreadShell]);
return deriveActiveWorkStartedAt(
selectedThread.latestTurn,
selectedThreadSessionActivity,
null,
);
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
const activeThreadBusy =
!!selectedThread &&
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
const onSendMessage = useCallback(async () => {
if (!selectedThreadShell) {
@@ -139,7 +153,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) {
@@ -169,7 +183,7 @@ export function useThreadComposerState() {
);
return null;
}
}, [selectedThreadDetail, selectedThreadShell]);
}, [selectedThreadShell]);
const onChangeDraftMessage = useCallback(
(value: string) => {
+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,7 +1,8 @@
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 {
@@ -217,6 +218,7 @@ export function useThreadOutboxDrain(): void {
environmentId: queuedMessage.environmentId,
input: {
commandId: queuedMessage.commandId,
creationSource: "mobile",
threadId: queuedMessage.threadId,
message: {
messageId: queuedMessage.messageId,
@@ -310,7 +312,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;
+53 -15
View File
@@ -2,13 +2,18 @@ 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 * as Option from "effect/Option";
import { copySorted } from "@t3tools/shared/Array";
import { useProject, useThreadShell } from "../state/entities";
import { useEnvironmentThread } from "../state/threads";
@@ -29,9 +34,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 +47,56 @@ 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 runsByOrdinal = copySorted(projection.runs, (left, right) => right.ordinal - left.ordinal);
const latestRun = runsByOrdinal[0] ?? null;
const activeRun =
runsByOrdinal.find(
(run) =>
run.status === "preparing" ||
run.status === "queued" ||
run.status === "starting" ||
run.status === "running" ||
run.status === "waiting",
) ?? null;
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?.id ?? null,
activeRunId: activeRun?.id ?? null,
status: activeRun?.status ?? latestRun?.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 +104,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,560 +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 { 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 {
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 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,
);
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 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,
dispose,
} satisfies OrchestrationIntegrationHarness;
});
@@ -1,577 +0,0 @@
import {
ApprovalRequestId,
EventId,
ProviderApprovalDecision,
ProviderRuntimeEvent,
RuntimeSessionId,
ProviderSession,
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderDriverKind,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
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 crypto = yield* Crypto.Crypto;
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 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 randomUUIDv4 = (threadId: ThreadId) =>
crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterValidationError({
provider,
operation: "crypto/randomUUIDv4",
issue: `Failed to generate test runtime identifier for thread '${threadId}'.`,
cause,
}),
),
);
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: yield* randomUUIDv4(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: EventId.make(yield* randomUUIDv4(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,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>;
File diff suppressed because it is too large. Load diff
@@ -1,304 +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 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 { 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>;
}
const makeIntegrationFixture = 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),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
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)),
);
+7 -1
View File
@@ -16,13 +16,19 @@
"type": "module",
"scripts": {
"dev": "node --watch src/bin.ts",
"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:",
+534 -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";
@@ -17,13 +18,36 @@ 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 +64,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 +80,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 +107,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 +257,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 +306,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 +425,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 +528,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,6 +543,36 @@ 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);
}
}),
);
@@ -457,6 +581,80 @@ const program = Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
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 +716,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 +944,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 +1028,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 +1098,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 +1375,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));
}
+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") {
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;
}
@@ -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,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)),
);
@@ -0,0 +1,444 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";
import {
recordClaudeAgentSdkReplayTranscript,
CLAUDE_AGENT_SDK_REPLAY_PROTOCOL,
} from "../src/orchestration-v2/Adapters/ClaudeAdapterV2.testkit.ts";
import { claudeRuntimeQueryPolicyForRuntimePolicy } from "../src/orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import {
ProviderAdapterV2RuntimePolicy,
type ProviderAdapterV2RuntimePolicy as ProviderAdapterV2RuntimePolicyType,
} from "../src/orchestration-v2/ProviderAdapter.ts";
import type { RuntimePolicyV2Override } from "../src/orchestration-v2/RuntimePolicy.ts";
import { makeCheckpointWorkspace } from "../src/orchestration-v2/testkit/ReplayFixtureWorkspace.ts";
import { CLAUDE_MODEL_SELECTION } from "../src/orchestration-v2/testkit/fixtures/shared.ts";
import {
MESSAGE_STEERING_INITIAL_PROMPT,
MULTI_TURN_FIRST_PROMPT,
MESSAGE_STEERING_STEER_PROMPT,
READ_ONLY_NEVER_POLICY,
READ_ONLY_ON_REQUEST_POLICY,
RESTRICTED_GRANULAR_POLICY,
MULTI_TURN_SECOND_PROMPT,
SIMPLE_PROMPT,
SUBAGENT_PROMPT,
THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT,
THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT,
THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT,
THREAD_FORK_NATIVE_CONTINUE_FIRST_PROMPT,
THREAD_FORK_NATIVE_CONTINUE_SECOND_PROMPT,
THREAD_FORK_NATIVE_CONTINUE_SOURCE_PROMPT,
THREAD_FORK_NATIVE_SIBLINGS_FIRST_PROMPT,
THREAD_FORK_NATIVE_SIBLINGS_SECOND_PROMPT,
THREAD_FORK_NATIVE_SIBLINGS_SOURCE_PROMPT,
THREAD_FORK_NATIVE_SOURCE_PROMPT,
THREAD_FORK_NATIVE_TARGET_PROMPT,
THREAD_MERGE_BACK_FORK_PROMPT,
THREAD_MERGE_BACK_HANDOFF_PROMPT,
THREAD_MERGE_BACK_RECALL_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_FIRST_FORK_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_FIRST_HANDOFF_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_RECALL_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_SECOND_FORK_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_SECOND_HANDOFF_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_SOURCE_PROMPT,
THREAD_MERGE_BACK_SOURCE_PROMPT,
THREAD_ROLLBACK_AFTER_PROMPT,
THREAD_ROLLBACK_FIRST_PROMPT,
THREAD_ROLLBACK_SECOND_PROMPT,
TOOL_CALL_READ_ONLY_PROMPT,
TOOL_CALL_READ_ONLY_WORKSPACE_ROOT,
TOOL_CALL_WRITE_PROMPT,
TURN_INTERRUPT_MID_TOOL_PROMPT,
TURN_INTERRUPT_PROMPT,
TURN_INTERRUPT_RECOVERY_PROMPT,
WORKSPACE_NEVER_POLICY,
WEB_SEARCH_PROMPT,
} from "../src/orchestration-v2/testkit/fixtures/shared.ts";
const CLAUDE_RECORDINGS = {
simple: {
prompts: [SIMPLE_PROMPT],
defaultTranscriptFile: "fixtures/simple/claude_transcript.ndjson",
queryMode: "streaming",
enableTools: true,
},
multi_turn: {
prompts: [MULTI_TURN_FIRST_PROMPT, MULTI_TURN_SECOND_PROMPT],
defaultTranscriptFile: "fixtures/multi_turn/claude_transcript.ndjson",
queryMode: "streaming",
enableTools: true,
},
multi_turn_restart: {
prompts: [MULTI_TURN_FIRST_PROMPT, MULTI_TURN_SECOND_PROMPT],
defaultTranscriptFile: "fixtures/multi_turn_restart/claude_transcript.ndjson",
queryMode: "restart",
enableTools: true,
},
queued_turn: {
prompts: [MULTI_TURN_FIRST_PROMPT, MULTI_TURN_SECOND_PROMPT],
defaultTranscriptFile: "fixtures/queued_turn/claude_transcript.ndjson",
queryMode: "streaming",
enableTools: true,
},
message_steering: {
prompts: [MESSAGE_STEERING_INITIAL_PROMPT, MESSAGE_STEERING_STEER_PROMPT],
defaultTranscriptFile: "fixtures/message_steering/claude_transcript.ndjson",
queryMode: "active_steering",
enableTools: true,
},
turn_interrupt_mid_tool: {
prompts: [TURN_INTERRUPT_MID_TOOL_PROMPT],
defaultTranscriptFile: "fixtures/turn_interrupt_mid_tool/claude_transcript.ndjson",
queryMode: "interrupt",
enableTools: true,
interruptAfter: "tool_use",
},
turn_interrupt: {
prompts: [TURN_INTERRUPT_PROMPT],
defaultTranscriptFile: "fixtures/turn_interrupt/claude_transcript.ndjson",
queryMode: "interrupt",
enableTools: true,
},
turn_interrupt_restart: {
prompts: [TURN_INTERRUPT_MID_TOOL_PROMPT, TURN_INTERRUPT_RECOVERY_PROMPT],
defaultTranscriptFile: "fixtures/turn_interrupt_restart/claude_transcript.ndjson",
queryMode: "interrupt_restart",
enableTools: true,
interruptAfter: "tool_use",
},
tool_call_read_only: {
prompts: [TOOL_CALL_READ_ONLY_PROMPT],
defaultTranscriptFile: "fixtures/tool_call_read_only/claude_transcript.ndjson",
queryMode: "streaming",
enableTools: true,
runtimePolicyOverride: READ_ONLY_NEVER_POLICY,
},
tool_call_read_only_on_request: {
prompts: [TOOL_CALL_WRITE_PROMPT],
defaultTranscriptFile: "fixtures/tool_call_read_only_on_request/claude_transcript.ndjson",
queryMode: "streaming",
enableTools: true,
runtimePolicyOverride: READ_ONLY_ON_REQUEST_POLICY,
},
tool_call_workspace_never: {
prompts: [TOOL_CALL_WRITE_PROMPT],
defaultTranscriptFile: "fixtures/tool_call_workspace_never/claude_transcript.ndjson",
queryMode: "streaming",
enableTools: true,
runtimePolicyOverride: WORKSPACE_NEVER_POLICY,
},
tool_call_restricted_granular: {
prompts: [TOOL_CALL_WRITE_PROMPT],
defaultTranscriptFile: "fixtures/tool_call_restricted_granular/claude_transcript.ndjson",
queryMode: "streaming",
enableTools: true,
runtimePolicyOverride: RESTRICTED_GRANULAR_POLICY,
},
web_search: {
prompts: [WEB_SEARCH_PROMPT],
defaultTranscriptFile: "fixtures/web_search/claude_transcript.ndjson",
queryMode: "streaming",
enableTools: true,
},
subagent: {
prompts: [SUBAGENT_PROMPT],
defaultTranscriptFile: "fixtures/subagent/claude_transcript.ndjson",
queryMode: "streaming",
enableTools: true,
},
thread_rollback: {
prompts: [
THREAD_ROLLBACK_FIRST_PROMPT,
THREAD_ROLLBACK_SECOND_PROMPT,
THREAD_ROLLBACK_AFTER_PROMPT,
],
defaultTranscriptFile: "fixtures/thread_rollback/claude_transcript.ndjson",
queryMode: "resume_at_cursor",
enableTools: true,
},
thread_fork_native: {
prompts: [THREAD_FORK_NATIVE_SOURCE_PROMPT, THREAD_FORK_NATIVE_TARGET_PROMPT],
defaultTranscriptFile: "fixtures/thread_fork_native/claude_transcript.ndjson",
queryMode: "fork_session",
enableTools: true,
},
thread_fork_native_prior_turn: {
prompts: [
THREAD_FORK_NATIVE_PRIOR_TURN_ALPHA_PROMPT,
THREAD_FORK_NATIVE_PRIOR_TURN_BETA_PROMPT,
THREAD_FORK_NATIVE_PRIOR_TURN_REPEAT_PROMPT,
],
defaultTranscriptFile: "fixtures/thread_fork_native_prior_turn/claude_transcript.ndjson",
queryMode: "fork_session_prior_turn",
enableTools: true,
},
thread_fork_native_continue: {
prompts: [
THREAD_FORK_NATIVE_CONTINUE_SOURCE_PROMPT,
THREAD_FORK_NATIVE_CONTINUE_FIRST_PROMPT,
THREAD_FORK_NATIVE_CONTINUE_SECOND_PROMPT,
],
defaultTranscriptFile: "fixtures/thread_fork_native_continue/claude_transcript.ndjson",
queryMode: "fork_session_continue",
enableTools: true,
},
thread_fork_native_siblings: {
prompts: [
THREAD_FORK_NATIVE_SIBLINGS_SOURCE_PROMPT,
THREAD_FORK_NATIVE_SIBLINGS_FIRST_PROMPT,
THREAD_FORK_NATIVE_SIBLINGS_SECOND_PROMPT,
],
defaultTranscriptFile: "fixtures/thread_fork_native_siblings/claude_transcript.ndjson",
queryMode: "fork_session_siblings",
enableTools: true,
},
thread_merge_back_continue: {
prompts: [
THREAD_MERGE_BACK_SOURCE_PROMPT,
THREAD_MERGE_BACK_FORK_PROMPT,
THREAD_MERGE_BACK_HANDOFF_PROMPT,
THREAD_MERGE_BACK_RECALL_PROMPT,
],
defaultTranscriptFile: "fixtures/thread_merge_back_continue/claude_transcript.ndjson",
queryMode: "fork_session_merge_back",
enableTools: true,
},
thread_merge_back_siblings: {
prompts: [
THREAD_MERGE_BACK_SIBLINGS_SOURCE_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_FIRST_FORK_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_SECOND_FORK_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_FIRST_HANDOFF_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_SECOND_HANDOFF_PROMPT,
THREAD_MERGE_BACK_SIBLINGS_RECALL_PROMPT,
],
defaultTranscriptFile: "fixtures/thread_merge_back_siblings/claude_transcript.ndjson",
queryMode: "fork_session_merge_back_siblings",
enableTools: true,
},
} as const;
function readArgValue(name: string): string | undefined {
const args = process.argv.slice(2);
const index = args.indexOf(name);
return index >= 0 ? args[index + 1] : undefined;
}
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";
function selectedQueryMode(defaultMode: ClaudeRecordingQueryMode): ClaudeRecordingQueryMode {
const raw = readArgValue("--query-mode") ?? process.env.T3_CLAUDE_REPLAY_QUERY_MODE;
if (raw === undefined) {
return defaultMode;
}
if (
raw === "streaming" ||
raw === "restart" ||
raw === "resume_at_cursor" ||
raw === "fork_session" ||
raw === "fork_session_prior_turn" ||
raw === "fork_session_continue" ||
raw === "fork_session_siblings" ||
raw === "fork_session_merge_back" ||
raw === "fork_session_merge_back_siblings" ||
raw === "active_steering" ||
raw === "interrupt" ||
raw === "interrupt_restart"
) {
return raw;
}
throw new Error(
`Unsupported Claude replay query mode '${raw}'. Use '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', or 'interrupt_restart'.`,
);
}
const scenario = readArgValue("--scenario") ?? process.env.T3_CLAUDE_REPLAY_SCENARIO ?? "simple";
const recording = CLAUDE_RECORDINGS[scenario as keyof typeof CLAUDE_RECORDINGS];
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
if (recording === undefined) {
throw new Error(
`Claude replay fixture '${scenario}' is not configured. ` +
"TODO: approval fixtures need permission callback recording before they can be generated.",
);
}
const positionalOutputPath = process.argv[2]?.startsWith("--") ? undefined : process.argv[2];
const outputPath =
readArgValue("--out") ??
positionalOutputPath ??
new URL(`../src/orchestration-v2/testkit/${recording.defaultTranscriptFile}`, import.meta.url)
.pathname;
function encodeTranscriptNdjson(
transcript: Awaited<ReturnType<typeof recordClaudeAgentSdkReplayTranscript>>,
): string {
const { entries, ...metadata } = transcript;
return [
JSON.stringify({ type: "transcript_start", ...metadata }),
...entries.map((entry) => JSON.stringify(entry)),
"",
].join("\n");
}
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 joinPath(directory: string, fileName: string): string {
return `${directory.replace(/\/+$/u, "")}/${fileName.replace(/^\/+/u, "")}`;
}
function runFileSystem<A, E>(effect: Effect.Effect<A, E, FileSystem.FileSystem>): Promise<A> {
return Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
}
function selectedPrompts(): ReadonlyArray<string> {
if (process.env.T3_CLAUDE_REPLAY_PROMPTS !== undefined) {
return process.env.T3_CLAUDE_REPLAY_PROMPTS.split("\n---\n").filter(
(prompt) => prompt.length > 0,
);
}
if (process.env.T3_CLAUDE_REPLAY_PROMPT !== undefined) {
return [process.env.T3_CLAUDE_REPLAY_PROMPT];
}
return recording.prompts;
}
function runtimePolicyForRecording(input: {
readonly cwd: string;
readonly override?: RuntimePolicyV2Override;
}): ProviderAdapterV2RuntimePolicyType {
return ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: input.override?.cwd ?? input.cwd,
...(input.override?.approvalPolicy === undefined
? {}
: { approvalPolicy: input.override.approvalPolicy }),
...(input.override?.sandboxPolicy === undefined
? {}
: { sandboxPolicy: input.override.sandboxPolicy }),
...(input.override?.reasoningEffort === undefined
? {}
: { reasoningEffort: input.override.reasoningEffort }),
});
}
async function makeToolCallReadOnlyRecordingWorkspace(): Promise<string> {
await runFileSystem(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, { recursive: true, force: true });
yield* fs.makeDirectory(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, { recursive: true });
}),
);
return TOOL_CALL_READ_ONLY_WORKSPACE_ROOT;
}
const cwd =
process.env.T3_CLAUDE_REPLAY_CWD ??
(scenario === "tool_call_read_only"
? await makeToolCallReadOnlyRecordingWorkspace()
: await makeCheckpointWorkspace(`claude-agent-sdk-record-${scenario}`));
const shouldRemoveCwd = process.env.T3_CLAUDE_REPLAY_CWD === undefined;
if (shouldRemoveCwd && (scenario === "tool_call_read_only" || scenario === "subagent")) {
await runFileSystem(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.writeFileString(
joinPath(cwd, "package.json"),
encodeUnknownJsonString({
name: "claude-read-only-fixture",
private: true,
scripts: { typecheck: "tsc --noEmit" },
}),
);
yield* fs.writeFileString(
joinPath(cwd, "tsconfig.json"),
encodeUnknownJsonString({
compilerOptions: {
module: "ESNext",
strict: true,
target: "ES2022",
},
}),
);
}),
);
}
try {
const runtimePolicy = runtimePolicyForRecording({
cwd,
...("runtimePolicyOverride" in recording ? { override: recording.runtimePolicyOverride } : {}),
});
const queryPolicy = claudeRuntimeQueryPolicyForRuntimePolicy(runtimePolicy);
const transcript = await recordClaudeAgentSdkReplayTranscript({
scenario,
prompts: selectedPrompts(),
modelSelection: {
...CLAUDE_MODEL_SELECTION,
model: process.env.T3_CLAUDE_REPLAY_MODEL ?? CLAUDE_MODEL_SELECTION.model,
},
cwd,
...(process.env.T3_CLAUDE_REPLAY_SESSION_ID === undefined
? {}
: { sessionId: process.env.T3_CLAUDE_REPLAY_SESSION_ID }),
queryMode: selectedQueryMode(recording.queryMode),
...("enableTools" in recording && recording.enableTools === true ? { enableTools: true } : {}),
...(queryPolicy.tools === undefined ? {} : { tools: queryPolicy.tools }),
permissionMode: queryPolicy.permissionMode,
...(queryPolicy.allowedTools === undefined ? {} : { allowedTools: queryPolicy.allowedTools }),
...(queryPolicy.allowDangerouslySkipPermissions === undefined
? {}
: { allowDangerouslySkipPermissions: queryPolicy.allowDangerouslySkipPermissions }),
...(queryPolicy.installPermissionCallback ? { enablePermissionCallback: true } : {}),
...("interruptAfter" in recording ? { interruptAfter: recording.interruptAfter } : {}),
});
await runFileSystem(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.makeDirectory(dirname(outputPath), { recursive: true });
yield* fs.writeFileString(outputPath, encodeTranscriptNdjson(transcript));
}),
);
await Effect.runPromise(
Console.log(
`Wrote ${transcript.entries.length} ${CLAUDE_AGENT_SDK_REPLAY_PROTOCOL} replay entries to ${outputPath}`,
),
);
} finally {
if (shouldRemoveCwd) {
await runFileSystem(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(cwd, { recursive: true, force: true });
}),
);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,222 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { recordCursorAgentSdkReplayTranscript } from "../src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts";
import { makeCheckpointWorkspace } from "../src/orchestration-v2/testkit/ReplayFixtureWorkspace.ts";
import {
CURSOR_MODEL_SELECTION,
MESSAGE_STEERING_INITIAL_PROMPT,
MESSAGE_STEERING_STEER_PROMPT,
MULTI_TURN_FIRST_PROMPT,
MULTI_TURN_SECOND_PROMPT,
PROVIDER_THREAD_RESUME_FIRST_PROMPT,
PROVIDER_THREAD_RESUME_SECOND_PROMPT,
PROPOSED_PLAN_PROMPT,
SIMPLE_PROMPT,
SUBAGENT_PROMPT,
TODO_LIST_PROMPT,
TOOL_CALL_READ_ONLY_PROMPT,
TOOL_CALL_READ_ONLY_WORKSPACE_ROOT,
TURN_INTERRUPT_MID_TOOL_PROMPT,
} from "../src/orchestration-v2/testkit/fixtures/shared.ts";
const RECORDINGS = {
simple: {
prompts: [SIMPLE_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/simple/cursor_transcript.ndjson",
},
multi_turn: {
prompts: [MULTI_TURN_FIRST_PROMPT, MULTI_TURN_SECOND_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/multi_turn/cursor_transcript.ndjson",
},
message_steering: {
prompts: [MESSAGE_STEERING_INITIAL_PROMPT, MESSAGE_STEERING_STEER_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/message_steering/cursor_transcript.ndjson",
interruptAfterRunStartPromptIndex: 0,
},
provider_thread_resume: {
prompts: [PROVIDER_THREAD_RESUME_FIRST_PROMPT, PROVIDER_THREAD_RESUME_SECOND_PROMPT],
output:
"../src/orchestration-v2/testkit/fixtures/provider_thread_resume/cursor_transcript.ndjson",
restartBeforePromptIndex: 1,
},
queued_turn: {
prompts: [MULTI_TURN_FIRST_PROMPT, MULTI_TURN_SECOND_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/queued_turn/cursor_transcript.ndjson",
},
proposed_plan: {
prompts: [PROPOSED_PLAN_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/proposed_plan/cursor_transcript.ndjson",
interactionMode: "plan",
},
todo_list: {
prompts: [TODO_LIST_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/todo_list/cursor_transcript.ndjson",
},
subagent: {
prompts: [SUBAGENT_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/subagent/cursor_transcript.ndjson",
},
tool_call_read_only: {
prompts: [TOOL_CALL_READ_ONLY_PROMPT],
output: "../src/orchestration-v2/testkit/fixtures/tool_call_read_only/cursor_transcript.ndjson",
},
turn_interrupt_mid_tool: {
prompts: [TURN_INTERRUPT_MID_TOOL_PROMPT],
output:
"../src/orchestration-v2/testkit/fixtures/turn_interrupt_mid_tool/cursor_transcript.ndjson",
interruptAfterToolStart: true,
},
} as const;
type RecordingName = keyof typeof RECORDINGS;
const encodeUnknownJsonString = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
function readArgValue(name: string): string | undefined {
const index = process.argv.indexOf(name);
return index === -1 ? undefined : process.argv[index + 1];
}
function encodeTranscriptNdjson(
transcript: Awaited<ReturnType<typeof recordCursorAgentSdkReplayTranscript>>,
): string {
const { entries, ...metadata } = transcript;
return [
encodeUnknownJsonString({ type: "transcript_start", ...metadata }),
...entries.map((entry) => encodeUnknownJsonString(entry)),
"",
].join("\n");
}
const runFileSystem = <A, E>(
effect: Effect.Effect<A, E, FileSystem.FileSystem | Path.Path>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
async function prepareWorkspace(scenario: RecordingName): Promise<{
readonly cwd: string;
readonly remove: boolean;
}> {
if (process.env.T3_CURSOR_REPLAY_CWD !== undefined) {
return {
cwd: process.env.T3_CURSOR_REPLAY_CWD,
remove: false,
};
}
if (scenario === "tool_call_read_only") {
await runFileSystem(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, {
recursive: true,
force: true,
});
yield* fs.makeDirectory(TOOL_CALL_READ_ONLY_WORKSPACE_ROOT, {
recursive: true,
});
}),
);
return {
cwd: TOOL_CALL_READ_ONLY_WORKSPACE_ROOT,
remove: true,
};
}
return {
cwd: await makeCheckpointWorkspace(`cursor-agent-sdk-record-${scenario}`),
remove: true,
};
}
async function writeFixtureFiles(cwd: string): Promise<void> {
await runFileSystem(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.writeFileString(
path.join(cwd, "package.json"),
encodeUnknownJsonString({
name: "cursor-read-only-fixture",
private: true,
scripts: { typecheck: "tsc --noEmit" },
}),
);
yield* fs.writeFileString(
path.join(cwd, "tsconfig.json"),
encodeUnknownJsonString({
compilerOptions: {
module: "ESNext",
strict: true,
target: "ES2022",
},
}),
);
}),
);
}
const scenario = (readArgValue("--scenario") ?? process.env.T3_CURSOR_REPLAY_SCENARIO) as
| RecordingName
| undefined;
if (scenario === undefined || RECORDINGS[scenario] === undefined) {
throw new Error(`Pass --scenario with one of: ${Object.keys(RECORDINGS).join(", ")}`);
}
const apiKey = process.env.CURSOR_API_KEY?.trim();
if (!apiKey) {
throw new Error("CURSOR_API_KEY is required to record Cursor SDK replay fixtures.");
}
const recording = RECORDINGS[scenario];
const workspace = await prepareWorkspace(scenario);
if (scenario === "subagent" || scenario === "tool_call_read_only" || scenario === "todo_list") {
await writeFixtureFiles(workspace.cwd);
}
const outputPath = readArgValue("--out") ?? new URL(recording.output, import.meta.url).pathname;
try {
const transcript = await recordCursorAgentSdkReplayTranscript({
scenario,
prompts: recording.prompts,
modelSelection: {
...CURSOR_MODEL_SELECTION,
model: process.env.T3_CURSOR_REPLAY_MODEL ?? CURSOR_MODEL_SELECTION.model,
},
cwd: workspace.cwd,
apiKey,
...("interactionMode" in recording ? { interactionMode: recording.interactionMode } : {}),
...("interruptAfterToolStart" in recording
? { interruptAfterToolStart: recording.interruptAfterToolStart }
: {}),
...("interruptAfterRunStartPromptIndex" in recording
? { interruptAfterRunStartPromptIndex: recording.interruptAfterRunStartPromptIndex }
: {}),
...("restartBeforePromptIndex" in recording
? { restartBeforePromptIndex: recording.restartBeforePromptIndex }
: {}),
});
await runFileSystem(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(outputPath), { recursive: true });
yield* fs.writeFileString(outputPath, encodeTranscriptNdjson(transcript));
}),
);
await Effect.runPromise(
Console.log(`Wrote ${transcript.entries.length} Cursor SDK replay entries to ${outputPath}`),
);
} finally {
if (workspace.remove) {
await runFileSystem(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(workspace.cwd, { recursive: true, force: true });
}),
);
}
}
+11
View File
@@ -7,11 +7,22 @@ import { describe, expect, it } from "vite-plus/test";
import {
createAttachmentId,
createDeterministicAttachmentId,
parseThreadSegmentFromAttachmentId,
resolveAttachmentPathById,
} from "./attachmentStore.ts";
describe("attachmentStore", () => {
it("derives stable attachment ids for idempotent message retries", () => {
const first = createDeterministicAttachmentId("thread-1", "message-1:0");
const retry = createDeterministicAttachmentId("thread-1", "message-1:0");
const next = createDeterministicAttachmentId("thread-1", "message-1:1");
expect(first).toBe(retry);
expect(next).not.toBe(first);
expect(first && parseThreadSegmentFromAttachmentId(first)).toBe("thread-1");
});
it("sanitizes thread ids when creating attachment ids", () => {
const attachmentId = createAttachmentId("thread.folder/unsafe space");
expect(attachmentId).toBeTruthy();
+11
View File
@@ -42,6 +42,17 @@ export function createAttachmentId(threadId: string): string | null {
return `${threadSegment}-${NodeCrypto.randomUUID()}`;
}
export function createDeterministicAttachmentId(
threadId: string,
stableKey: string,
): string | null {
const threadSegment = toSafeThreadAttachmentSegment(threadId);
if (!threadSegment) return null;
const hash = NodeCrypto.createHash("sha256").update(stableKey).digest("hex").slice(0, 32);
const uuid = `${hash.slice(0, 8)}-${hash.slice(8, 12)}-${hash.slice(12, 16)}-${hash.slice(16, 20)}-${hash.slice(20)}`;
return `${threadSegment}-${uuid}`;
}
export function parseThreadSegmentFromAttachmentId(attachmentId: string): string | null {
const normalizedId = normalizeAttachmentRelativePath(attachmentId);
if (!normalizedId || normalizedId.includes("/") || normalizedId.includes(".")) {
-602
View File
@@ -1,602 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - CLI integration exercises Node HTTP and filesystem boundaries.
import * as NodeHttp from "node:http";
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
CommandId,
EnvironmentOrchestrationHttpApi,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as DateTime from "effect/DateTime";
import * as Layer from "effect/Layer";
import * as HttpRouter from "effect/unstable/http/HttpRouter";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpApi from "effect/unstable/httpapi/HttpApi";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as CliError from "effect/unstable/cli/CliError";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli, makeCli } from "./bin.ts";
import * as ServerConfig from "./config.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
import {
makePersistedServerRuntimeState,
persistServerRuntimeState,
} from "./serverRuntimeState.ts";
import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
const connectCli = makeCli({ cloudEnabled: true });
const noConnectCli = makeCli({ cloudEnabled: false });
const runCli = (args: ReadonlyArray<string>, command = cli) =>
Command.runWith(command, { version: "0.0.0" })(args);
const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
Effect.gen(function* () {
const result = yield* effect;
const output =
(yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ??
"";
return { result, output };
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
const makeCliTestServerConfig = (baseDir: string) =>
Effect.gen(function* () {
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
return {
logLevel: "Info",
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
mode: "web",
port: 0,
host: "127.0.0.1",
cwd: process.cwd(),
baseDir,
...derivedPaths,
staticDir: undefined,
devUrl: undefined,
devAllowedOrigins: [],
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
} satisfies ServerConfig.ServerConfig["Service"];
});
const makeProjectPersistenceLayer = (config: ServerConfig.ServerConfig["Service"]) =>
Layer.mergeAll(
OrchestrationLayerLive.pipe(
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(SqlitePersistenceLayerLive),
),
WorkspacePaths.layer,
).pipe(Layer.provideMerge(NodeServices.layer), Layer.provide(ServerConfig.layer(config)));
const readPersistedSnapshot = (baseDir: string) =>
Effect.gen(function* () {
const config = yield* makeCliTestServerConfig(baseDir);
return yield* Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
return yield* projectionSnapshotQuery.getSnapshot();
}).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
});
const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
Effect.gen(function* () {
const config = yield* makeCliTestServerConfig(baseDir);
const routesLayer = HttpApiBuilder.layer(ProjectCliHttpApi).pipe(
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(environmentAuthenticatedAuthLayer),
);
const appLayer = HttpRouter.serve(routesLayer, {
disableListenLog: true,
disableLogger: true,
}).pipe(
Layer.provideMerge(
EnvironmentAuth.layer.pipe(
Layer.provideMerge(SqlitePersistenceLayerLive),
Layer.provide(ServerSecretStore.layer),
),
),
Layer.provideMerge(makeProjectPersistenceLayer(config)),
Layer.provideMerge(
NodeHttpServer.layer(NodeHttp.createServer, {
host: "127.0.0.1",
port: 0,
}),
),
Layer.provideMerge(NodeServices.layer),
Layer.provide(ServerConfig.layer(config)),
);
return yield* Effect.scoped(
Effect.gen(function* () {
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) {
assert.fail(`Expected TCP address, got ${address}`);
}
yield* persistServerRuntimeState({
path: config.serverRuntimeStatePath,
state: yield* makePersistedServerRuntimeState({
config,
port: address.port,
}),
});
return yield* run();
}).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
);
});
it.layer(NodeServices.layer)("bin cli parsing", (it) => {
it.effect("accepts the built-in lowercase log-level flag values", () =>
runCliWithRuntime(["--log-level", "debug", "--version"]),
);
it.effect("accepts canonical --no-<flag> boolean negation", () =>
runCliWithRuntime(["--no-log-websocket-events", "--version"]),
);
it.effect("rejects invalid log-level casing before launching the server", () =>
Effect.gen(function* () {
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
if (error._tag !== "InvalidValue") {
assert.fail(`Expected InvalidValue, got ${error._tag}`);
}
assert.equal(error.option, "log-level");
assert.equal(error.value, "Debug");
}),
);
it.effect("rejects connect commands when public configuration is missing", () =>
Effect.gen(function* () {
const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
if (error._tag !== "ShowHelp") {
assert.fail(`Expected ShowHelp, got ${error._tag}`);
}
assert.deepEqual(error.commandPath, ["t3", "connect"]);
assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration");
const output = (yield* TestConsole.errorLines).join("\n");
assert.include(output, "ERROR");
assert.include(output, "missing T3 Connect public configuration");
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
);
it.effect("exposes service lifecycle commands without T3 Connect configuration", () =>
Effect.gen(function* () {
const { output } = yield* captureStdout(runCli(["service", "--help"], noConnectCli));
assert.include(output, "Manage the T3 Code background service.");
assert.include(output, "install");
assert.include(output, "uninstall");
assert.include(output, "update");
assert.include(output, "status");
}),
);
it.effect("reports fresh headless connect state without requiring local configuration", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-test-"),
);
const { output } = yield* captureStdout(
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const status = JSON.parse(output) as {
readonly desired: boolean;
readonly authenticated: boolean;
readonly linked: boolean;
readonly cloudUserId: string | null;
readonly relayUrl: string | null;
};
assert.equal(status.desired, false);
assert.equal(status.authenticated, false);
assert.equal(status.linked, false);
assert.equal(status.cloudUserId, null);
assert.equal(status.relayUrl, null);
}),
);
it.effect("reports actionable human-readable headless connect state", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-status-human-test-"),
);
const { output } = yield* captureStdout(
runConnectCli(["connect", "status", "--base-dir", baseDir]),
);
assert.include(output, "T3 Connect\n Exposure: disabled");
assert.include(output, " Authorization: missing");
assert.include(output, " Environment link: not provisioned");
assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect.");
}),
);
it.effect("accepts the --headless login override without enabling access", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-login-test-"),
);
const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
NodeFS.mkdirSync(secretsDir, { recursive: true });
NodeFS.writeFileSync(
NodePath.join(secretsDir, "cloud-cli-oauth-token.bin"),
// @effect-diagnostics-next-line preferSchemaOverJson:off - Test fixture matches the persisted CLI token representation.
JSON.stringify({
accessToken: "access-token",
refreshToken: "refresh-token",
expiresAtEpochMs: Number.MAX_SAFE_INTEGER,
}),
);
const login = yield* captureStdout(
runConnectCli(["connect", "login", "--base-dir", baseDir, "--headless"]),
);
const status = yield* captureStdout(
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const decoded = JSON.parse(status.output) as {
readonly desired: boolean;
readonly authenticated: boolean;
};
assert.equal(login.output, "✓ Signed in");
assert.isFalse(decoded.desired);
assert.isTrue(decoded.authenticated);
}),
);
it.effect("disables headless connect without a running server", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-unlink-test-"),
);
const { output } = yield* captureStdout(
runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
);
assert.equal(output, "T3 Connect is disabled locally.");
}),
);
it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-cloud-logout-test-"),
);
const { secretsDir } = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
const tokenPath = NodePath.join(secretsDir, "cloud-cli-oauth-token.bin");
NodeFS.mkdirSync(secretsDir, { recursive: true });
NodeFS.writeFileSync(tokenPath, "invalid persisted token");
const { output } = yield* captureStdout(
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
);
assert.equal(
output,
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
);
assert.isFalse(NodeFS.existsSync(tokenPath));
}),
);
it.effect("executes auth pairing subcommands and redacts secrets from list output", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-pairing-test-"),
);
const createdOutput = yield* captureStdout(
runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
const created = JSON.parse(createdOutput.output) as {
readonly id: string;
readonly credential: string;
};
const listedOutput = yield* captureStdout(
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
readonly id: string;
readonly credential?: string;
}>;
assert.equal(typeof created.id, "string");
assert.equal(typeof created.credential, "string");
assert.equal(created.credential.length > 0, true);
assert.equal(listed.length, 1);
assert.equal(listed[0]?.id, created.id);
assert.equal("credential" in (listed[0] ?? {}), false);
}),
);
it.effect("executes auth session subcommands and redacts secrets from list output", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-auth-session-test-"),
);
const issuedOutput = yield* captureStdout(
runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
const issued = JSON.parse(issuedOutput.output) as {
readonly sessionId: string;
readonly token: string;
readonly scopes: ReadonlyArray<string>;
};
const listedOutput = yield* captureStdout(
runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
readonly sessionId: string;
readonly token?: string;
readonly scopes: ReadonlyArray<string>;
}>;
assert.equal(typeof issued.sessionId, "string");
assert.equal(typeof issued.token, "string");
assert.deepEqual(issued.scopes, [
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
"access:read",
"access:write",
"relay:write",
]);
assert.equal(listed.length, 1);
assert.equal(listed[0]?.sessionId, issued.sessionId);
assert.deepEqual(listed[0]?.scopes, [
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
"access:read",
"access:write",
"relay:write",
]);
assert.equal("token" in (listed[0] ?? {}), false);
}),
);
it.effect("rejects invalid ttl values before running auth commands", () =>
Effect.gen(function* () {
const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe(
Effect.flip,
);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
if (error._tag !== "ShowHelp") {
assert.fail(`Expected ShowHelp, got ${error._tag}`);
}
assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]);
const ttlError = error.errors[0] as CliError.CliError | undefined;
if (!ttlError || ttlError._tag !== "InvalidValue") {
assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`);
}
assert.equal(ttlError.option, "ttl");
assert.equal(ttlError.value, "soon");
assert.isTrue(ttlError.message.includes("Invalid duration"));
assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
}),
);
it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-offline-test-"),
);
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-workspace-"),
);
yield* runCliWithRuntime([
"project",
"add",
workspaceRoot,
"--title",
"Alpha",
"--base-dir",
baseDir,
]);
const afterAdd = yield* readPersistedSnapshot(baseDir);
const addedProject = afterAdd.projects.find(
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
);
assert.isTrue(addedProject !== undefined);
assert.equal(addedProject?.title, "Alpha");
yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
const afterRename = yield* readPersistedSnapshot(baseDir);
const renamedProject = afterRename.projects.find(
(project) => project.id === addedProject?.id,
);
assert.equal(renamedProject?.title, "Beta");
assert.equal(renamedProject?.deletedAt, null);
yield* runCliWithRuntime([
"project",
"remove",
addedProject?.id ?? "",
"--base-dir",
baseDir,
]);
const afterRemove = yield* readPersistedSnapshot(baseDir);
const removedProject = afterRemove.projects.find(
(project) => project.id === addedProject?.id,
);
assert.isTrue((removedProject?.deletedAt ?? null) !== null);
}),
);
it.effect("force removes projects that still contain threads", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-test-"),
);
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-force-remove-workspace-"),
);
yield* runCliWithRuntime(["project", "add", workspaceRoot, "--base-dir", baseDir]);
const afterAdd = yield* readPersistedSnapshot(baseDir);
const project = afterAdd.projects.find(
(candidate) => candidate.workspaceRoot === workspaceRoot && candidate.deletedAt === null,
);
assert.isTrue(project !== undefined);
const config = yield* makeCliTestServerConfig(baseDir);
yield* Effect.gen(function* () {
const engine = yield* OrchestrationEngine.OrchestrationEngineService;
yield* engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-cli-force-remove-thread"),
threadId: ThreadId.make("thread-cli-force-remove"),
projectId: project!.id,
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "default",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: DateTime.formatIso(yield* DateTime.now),
});
}).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
yield* runCliWithRuntime([
"project",
"remove",
project!.id,
"--force",
"--base-dir",
baseDir,
]);
const afterRemove = yield* readPersistedSnapshot(baseDir);
assert.isTrue(
(afterRemove.projects.find((candidate) => candidate.id === project!.id)?.deletedAt ??
null) !== null,
);
assert.isTrue(
(afterRemove.threads.find((thread) => thread.id === "thread-cli-force-remove")?.deletedAt ??
null) !== null,
);
}),
);
it.effect("routes project commands through a running server when runtime state is present", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-test-"),
);
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-live-workspace-"),
);
yield* withLiveProjectCliServer(baseDir, () =>
Effect.gen(function* () {
yield* runCliWithRuntime([
"project",
"add",
workspaceRoot,
"--title",
"Live Project",
"--base-dir",
baseDir,
]);
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const readModel = yield* projectionSnapshotQuery.getSnapshot();
const addedProject = readModel.projects.find(
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
);
assert.isTrue(addedProject !== undefined);
assert.equal(addedProject?.title, "Live Project");
}),
);
}),
);
it.effect("rejects dev-url on project commands", () =>
Effect.gen(function* () {
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
);
const error = yield* runCliWithRuntime([
"project",
"add",
workspaceRoot,
"--dev-url",
"http://127.0.0.1:5173",
]).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
if (error._tag !== "ShowHelp") {
assert.fail(`Expected ShowHelp, got ${error._tag}`);
}
assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
const optionError = error.errors[0] as CliError.CliError | undefined;
if (!optionError || optionError._tag !== "UnrecognizedOption") {
assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
}
assert.equal(optionError.option, "--dev-url");
}),
);
});
@@ -1,431 +1,158 @@
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { it } from "@effect/vitest";
import { assert, it, vi } from "@effect/vitest";
import {
CheckpointRef,
CheckpointScopeId,
RunId,
ThreadId,
type OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { describe, expect } from "vite-plus/test";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForThreadTurn } from "./Utils.ts";
import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts";
import { OrchestratorProjectionError } from "../orchestration-v2/Orchestrator.ts";
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
import * as CheckpointDiffQuery from "./CheckpointDiffQuery.ts";
import * as CheckpointStore from "./CheckpointStore.ts";
import { CheckpointThreadNotFoundError } from "./Errors.ts";
import {
CheckpointRefUnavailableError,
CheckpointThreadNotFoundError,
CheckpointTurnRangeUnavailableError,
} from "./Errors.ts";
function makeThreadCheckpointContext(input: {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpointTurnCount: number;
readonly checkpointRef: CheckpointRef;
}): ProjectionSnapshotQuery.ProjectionThreadCheckpointContext {
const threadId = ThreadId.make("thread:checkpoint-diff-v2");
const firstRunId = RunId.make("run:checkpoint-diff-v2:1");
const secondRunId = RunId.make("run:checkpoint-diff-v2:2");
const firstScopeId = CheckpointScopeId.make("scope:checkpoint-diff-v2:1");
const secondScopeId = CheckpointScopeId.make("scope:checkpoint-diff-v2:2");
const secondRef = CheckpointRef.make("refs/t3/test/second");
function makeProjection(): OrchestrationV2ThreadProjection {
return {
threadId: input.threadId,
projectId: input.projectId,
workspaceRoot: input.workspaceRoot,
worktreePath: input.worktreePath,
runs: [
{ id: firstRunId, ordinal: 1 },
{ id: secondRunId, ordinal: 2 },
],
checkpointScopes: [
{ id: firstScopeId, runId: firstRunId, kind: "root_run", cwd: "/repo" },
{ id: secondScopeId, runId: secondRunId, kind: "root_run", cwd: "/repo" },
],
checkpoints: [
{
turnId: TurnId.make("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
scopeId: secondScopeId,
appRunOrdinal: 2,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
ref: secondRef,
},
],
};
} as unknown as OrchestrationV2ThreadProjection;
}
describe("CheckpointDiffQuery.layer", () => {
it.effect("uses the narrow full-thread context lookup for all-turns diffs", () =>
Effect.gen(function* () {
const projectId = ProjectId.make("project-full-thread");
const threadId = ThreadId.make("thread-full-thread");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 4);
let getThreadCheckpointContextCalls = 0;
let getFullThreadDiffContextCalls = 0;
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
readonly ignoreWhitespace: boolean;
}> = [];
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({
fromCheckpointRef,
toCheckpointRef,
cwd,
ignoreWhitespace,
});
return "full thread diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQuery.layer.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () =>
Effect.sync(() => {
getThreadCheckpointContextCalls += 1;
return Option.none();
}),
getFullThreadDiffContext: () =>
Effect.sync(() => {
getFullThreadDiffContextCalls += 1;
return Option.some({
threadId,
projectId,
workspaceRoot: "/tmp/workspace",
worktreePath: "/tmp/worktree",
latestCheckpointTurnCount: 4,
toCheckpointRef,
});
}),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
const result = yield* Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
return yield* query.getFullThreadDiff({
threadId,
toTurnCount: 4,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer));
expect(getThreadCheckpointContextCalls).toBe(0);
expect(getFullThreadDiffContextCalls).toBe(1);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/worktree",
fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
toCheckpointRef,
ignoreWhitespace: true,
},
]);
expect(result).toEqual({
threadId,
fromTurnCount: 0,
toTurnCount: 4,
diff: "full thread diff patch",
});
}),
function makeLayer(input: {
readonly projection: Effect.Effect<OrchestrationV2ThreadProjection, OrchestratorProjectionError>;
readonly diffCheckpoints?: CheckpointStore.CheckpointStore["Service"]["diffCheckpoints"];
}) {
return CheckpointDiffQuery.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadProjection: () => input.projection,
}),
Layer.mock(CheckpointStore.CheckpointStore)({
diffCheckpoints: input.diffCheckpoints ?? (() => Effect.succeed("diff")),
}),
),
),
);
}
it.effect("computes diffs using canonical turn-0 checkpoint refs", () =>
Effect.gen(function* () {
const projectId = ProjectId.make("project-1");
const threadId = ThreadId.make("thread-1");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
readonly ignoreWhitespace: boolean;
}> = [];
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({
fromCheckpointRef,
toCheckpointRef,
cwd,
ignoreWhitespace,
});
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQuery.layer.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
const result = yield* Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer));
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/workspace",
fromCheckpointRef: expectedFromRef,
toCheckpointRef,
ignoreWhitespace: true,
},
]);
expect(result).toEqual({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
diff: "diff patch",
});
}),
it.effect("computes V2 run diffs from projected checkpoint scopes", () => {
const diffCheckpoints = vi.fn((_input: CheckpointStore.DiffCheckpointsInput) =>
Effect.succeed("diff --git a/file b/file"),
);
const layer = makeLayer({ projection: Effect.succeed(makeProjection()), diffCheckpoints });
it.effect("defaults to hide whitespace changes", () =>
Effect.gen(function* () {
const projectId = ProjectId.make("project-default-whitespace");
const threadId = ThreadId.make("thread-default-whitespace");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
return Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const result = yield* query.getFullThreadDiff({ threadId, toTurnCount: 2 });
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({ ignoreWhitespace });
return "diff patch";
}),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQuery.layer.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
yield* Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
}).pipe(Effect.provide(layer));
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
}),
);
it.effect("does not preflight checkpoint refs before diffing", () =>
Effect.gen(function* () {
const projectId = ProjectId.make("project-no-preflight");
const threadId = ThreadId.make("thread-no-preflight");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
let hasCheckpointRefCallCount = 0;
const threadCheckpointContext = makeThreadCheckpointContext({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
worktreePath: null,
checkpointTurnCount: 1,
checkpointRef: toCheckpointRef,
});
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () =>
Effect.sync(() => {
hasCheckpointRefCallCount += 1;
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed("diff patch"),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQuery.layer.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
yield* Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer));
expect(hasCheckpointRefCallCount).toBe(0);
}),
);
it.effect("fails when the thread is missing from the snapshot", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-missing");
const checkpointStore: CheckpointStore.CheckpointStore["Service"] = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed(""),
deleteCheckpointRefs: () => Effect.void,
};
const layer = CheckpointDiffQuery.layer.pipe(
Layer.provideMerge(Layer.succeed(CheckpointStore.CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {
getCommandReadModel: () =>
Effect.die("CheckpointDiffQuery should not request the command read model"),
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
getThreadDetailSnapshot: () => Effect.succeed(Option.none()),
}),
),
);
const error = yield* Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
return yield* query.getTurnDiff({
threadId,
fromTurnCount: 0,
toTurnCount: 1,
});
}).pipe(Effect.provide(layer), Effect.flip);
expect(error).toBeInstanceOf(CheckpointThreadNotFoundError);
expect(error).toMatchObject({
operation: "CheckpointDiffQuery.getTurnDiff",
threadId,
});
expect(error.message).toBe(
"Checkpoint invariant violation in CheckpointDiffQuery.getTurnDiff: Thread 'thread-missing' not found.",
);
}),
);
assert.deepEqual(result, {
threadId,
fromTurnCount: 0,
toTurnCount: 2,
diff: "diff --git a/file b/file",
});
assert.deepEqual(diffCheckpoints.mock.calls[0]?.[0], {
cwd: "/repo",
fromCheckpointRef: checkpointRefForScopeOrdinal({
scopeId: firstScopeId,
ordinalWithinScope: 0,
}),
toCheckpointRef: secondRef,
fallbackFromToHead: false,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer));
});
it.effect("preserves the typed missing-thread error contract", () => {
const layer = makeLayer({
projection: Effect.fail(new OrchestratorProjectionError({ threadId })),
});
return Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const error = yield* query
.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 1 })
.pipe(Effect.flip);
assert.instanceOf(error, CheckpointThreadNotFoundError);
assert.deepEqual(
{ operation: error.operation, threadId: error.threadId },
{ operation: "CheckpointDiffQuery.getTurnDiff", threadId },
);
}).pipe(Effect.provide(layer));
});
it.effect("preserves the typed unavailable-range error contract", () => {
const layer = makeLayer({ projection: Effect.succeed(makeProjection()) });
return Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const error = yield* query
.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 3 })
.pipe(Effect.flip);
assert.instanceOf(error, CheckpointTurnRangeUnavailableError);
assert.deepEqual(
{
requestedTurnCount: error.requestedTurnCount,
availableTurnCount: error.availableTurnCount,
},
{ requestedTurnCount: 3, availableTurnCount: 2 },
);
}).pipe(Effect.provide(layer));
});
it.effect("preserves the typed missing-baseline-ref error contract", () => {
const projection = makeProjection();
const layer = makeLayer({
projection: Effect.succeed({
...projection,
checkpointScopes: projection.checkpointScopes.filter((scope) => scope.id !== firstScopeId),
}),
});
return Effect.gen(function* () {
const query = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const error = yield* query
.getTurnDiff({ threadId, fromTurnCount: 0, toTurnCount: 2 })
.pipe(Effect.flip);
assert.instanceOf(error, CheckpointRefUnavailableError);
assert.deepEqual(
{ checkpoint: error.checkpoint, turnCount: error.turnCount },
{ checkpoint: "from", turnCount: 0 },
);
}).pipe(Effect.provide(layer));
});
@@ -7,7 +7,6 @@
* @module CheckpointDiffQuery
*/
import {
type CheckpointRef,
OrchestrationGetTurnDiffResult,
type OrchestrationGetFullThreadDiffInput,
type OrchestrationGetFullThreadDiffResult,
@@ -18,19 +17,18 @@ import {
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 Schema from "effect/Schema";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForScopeOrdinal } from "../orchestration-v2/CheckpointService.ts";
import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
import {
CheckpointDiffResultInvalidError,
CheckpointRefUnavailableError,
CheckpointThreadNotFoundError,
CheckpointTurnRangeUnavailableError,
CheckpointWorkspacePathMissingError,
type CheckpointServiceError,
} from "./Errors.ts";
import type { CheckpointServiceError } from "./Errors.ts";
import { checkpointRefForThreadTurn } from "./Utils.ts";
import * as CheckpointStore from "./CheckpointStore.ts";
/** Service tag for checkpoint diff queries. */
@@ -76,7 +74,7 @@ function buildTurnDiffResult(
}
export const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const threads = yield* ThreadManagement.ThreadManagementService;
const checkpointStore = yield* CheckpointStore.CheckpointStore;
const getTurnDiff: CheckpointDiffQuery["Service"]["getTurnDiff"] = Effect.fn("getTurnDiff")(
@@ -91,12 +89,7 @@ export const make = Effect.gen(function* () {
});
if (input.fromTurnCount === input.toTurnCount) {
const emptyDiff: OrchestrationGetTurnDiffResultType = {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff: "",
};
const emptyDiff = buildTurnDiffResult(input, "");
if (!isTurnDiffResult(emptyDiff)) {
return yield* new CheckpointDiffResultInvalidError({
operation,
@@ -106,18 +99,21 @@ export const make = Effect.gen(function* () {
return emptyDiff;
}
const threadContext = yield* projectionSnapshotQuery
.getThreadCheckpointContext(input.threadId)
.pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
if (Option.isNone(threadContext)) {
return yield* new CheckpointThreadNotFoundError({
operation,
threadId: input.threadId,
});
}
const maxTurnCount = threadContext.value.checkpoints.reduce(
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
const projection = yield* threads.getThreadProjection(input.threadId).pipe(
Effect.mapError(
() =>
new CheckpointThreadNotFoundError({
operation,
threadId: input.threadId,
}),
),
Effect.withSpan("checkpoint.turnDiff.lookupProjection"),
);
const readyCheckpoints = projection.checkpoints.filter(
(checkpoint) => checkpoint.status === "ready" && checkpoint.appRunOrdinal !== null,
);
const maxTurnCount = readyCheckpoints.reduce(
(max, checkpoint) => Math.max(max, checkpoint.appRunOrdinal ?? 0),
0,
);
if (input.toTurnCount > maxTurnCount) {
@@ -129,33 +125,10 @@ export const make = Effect.gen(function* () {
});
}
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointWorkspacePathMissingError({
operation,
threadId: input.threadId,
});
}
const fromCheckpointRef =
input.fromTurnCount === 0
? checkpointRefForThreadTurn(input.threadId, 0)
: threadContext.value.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
)?.checkpointRef;
if (!fromCheckpointRef) {
return yield* new CheckpointRefUnavailableError({
operation,
threadId: input.threadId,
turnCount: input.fromTurnCount,
checkpoint: "from",
});
}
const toCheckpointRef = threadContext.value.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
)?.checkpointRef;
if (!toCheckpointRef) {
const toCheckpoint = readyCheckpoints.find(
(checkpoint) => checkpoint.appRunOrdinal === input.toTurnCount,
);
if (toCheckpoint === undefined) {
return yield* new CheckpointRefUnavailableError({
operation,
threadId: input.threadId,
@@ -164,11 +137,46 @@ export const make = Effect.gen(function* () {
});
}
const toScope = projection.checkpointScopes.find(
(scope) => scope.id === toCheckpoint.scopeId,
);
if (toScope === undefined) {
return yield* new CheckpointWorkspacePathMissingError({
operation,
threadId: input.threadId,
});
}
const fromCheckpointRef =
input.fromTurnCount === 0
? (() => {
const firstRun = projection.runs.find((run) => run.ordinal === 1);
const firstScope = projection.checkpointScopes.find(
(scope) => scope.runId === firstRun?.id && scope.kind === "root_run",
);
return firstScope === undefined
? undefined
: checkpointRefForScopeOrdinal({
scopeId: firstScope.id,
ordinalWithinScope: 0,
});
})()
: readyCheckpoints.find((checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount)
?.ref;
if (fromCheckpointRef === undefined) {
return yield* new CheckpointRefUnavailableError({
operation,
threadId: input.threadId,
turnCount: input.fromTurnCount,
checkpoint: "from",
});
}
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
cwd: toScope.cwd,
fromCheckpointRef,
toCheckpointRef,
toCheckpointRef: toCheckpoint.ref,
fallbackFromToHead: false,
ignoreWhitespace,
})
@@ -217,61 +225,12 @@ export const make = Effect.gen(function* () {
return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
}
const threadContext = yield* projectionSnapshotQuery
.getFullThreadDiffContext(input.threadId, input.toTurnCount)
.pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
if (Option.isNone(threadContext)) {
return yield* new CheckpointThreadNotFoundError({
operation,
threadId: input.threadId,
});
}
if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
return yield* new CheckpointTurnRangeUnavailableError({
operation,
threadId: input.threadId,
requestedTurnCount: input.toTurnCount,
availableTurnCount: threadContext.value.latestCheckpointTurnCount,
});
}
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointWorkspacePathMissingError({
operation,
threadId: input.threadId,
});
}
if (!threadContext.value.toCheckpointRef) {
return yield* new CheckpointRefUnavailableError({
operation,
threadId: input.threadId,
turnCount: input.toTurnCount,
checkpoint: "to",
});
}
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
const turnDiff = buildTurnDiffResult(
{
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
},
diff,
);
const turnDiff = yield* getTurnDiff({
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
ignoreWhitespace,
});
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointDiffResultInvalidError({
operation,
@@ -0,0 +1,53 @@
import { describe, expect, it } from "@effect/vitest";
import { ProviderInstanceId, type ModelSelection } from "@t3tools/contracts";
import { compileClaudeModelSelection } from "./claudeModelOptions.ts";
const selection = (
model: string,
options: NonNullable<ModelSelection["options"]>,
): ModelSelection => ({
instanceId: ProviderInstanceId.make("claude_test"),
model,
options,
});
describe("compileClaudeModelSelection", () => {
it("compiles context, effort, and settings together", () => {
expect(
compileClaudeModelSelection(
selection("claude-fable-5", [
{ id: "contextWindow", value: "1m" },
{ id: "effort", value: "ultracode" },
]),
),
).toMatchObject({
apiModelId: "claude-fable-5[1m]",
effort: "xhigh",
settings: { ultracode: true },
});
});
it("compiles fast mode only for models that expose it", () => {
expect(
compileClaudeModelSelection(selection("claude-opus-4-6", [{ id: "fastMode", value: true }]))
.settings,
).toEqual({ fastMode: true });
});
it("uses the model default SDK effort alongside prompt-injected effort", () => {
expect(
compileClaudeModelSelection(
selection("claude-sonnet-4-6", [{ id: "effort", value: "ultrathink" }]),
),
).toMatchObject({ effort: "high", promptEffort: "ultrathink" });
});
it("compiles the thinking toggle for models that expose it", () => {
expect(
compileClaudeModelSelection(selection("claude-haiku-4-5", [{ id: "thinking", value: false }]))
.settings,
).toEqual({ alwaysThinkingEnabled: false });
});
});
+56
View File
@@ -0,0 +1,56 @@
import type { ModelSelection } from "@t3tools/contracts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
getProviderOptionDescriptors,
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
import {
getClaudeModelCapabilities,
isClaudeUltracodeEffort,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeEffort,
} from "./provider/Layers/ClaudeProvider.ts";
export interface CompiledClaudeModelSelection {
readonly apiModelId: string;
readonly effort: string | undefined;
readonly promptEffort: string | undefined;
readonly settings: Readonly<Record<string, boolean>>;
readonly queryIdentity: string;
}
/** Compile every Claude model option at the provider boundary. */
export function compileClaudeModelSelection(
selection: ModelSelection,
): CompiledClaudeModelSelection {
const capabilities = getClaudeModelCapabilities(selection.model);
const descriptors = getProviderOptionDescriptors({ caps: capabilities });
const supportsBoolean = (id: string) =>
descriptors.some((descriptor) => descriptor.type === "boolean" && descriptor.id === id);
const rawEffort = getModelSelectionStringOptionValue(selection, "effort");
const resolvedEffort = resolveClaudeEffort(capabilities, rawEffort);
const effort = normalizeClaudeCliEffort(resolvedEffort, selection.model);
const fastMode =
supportsBoolean("fastMode") &&
getModelSelectionBooleanOptionValue(selection, "fastMode") === true;
const thinking = supportsBoolean("thinking")
? getModelSelectionBooleanOptionValue(selection, "thinking")
: undefined;
const settings = {
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
...(fastMode ? { fastMode: true } : {}),
...(isClaudeUltracodeEffort(resolvedEffort) ? { ultracode: true } : {}),
};
const apiModelId = resolveClaudeApiModelId(selection);
const promptEffort = resolvePromptInjectedEffort(capabilities, rawEffort) ?? undefined;
return {
apiModelId,
effort,
promptEffort,
settings,
queryIdentity: JSON.stringify({ apiModelId, effort: effort ?? null, settings }),
};
}
+99 -2
View File
@@ -1,17 +1,94 @@
// @effect-diagnostics nodeBuiltinImport:off - CLI integration uses temporary Node paths.
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { EnvironmentInternalError } from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as References from "effect/References";
import { Command } from "effect/unstable/cli";
import { cli } from "../bin.ts";
import * as ServerConfig from "../config.ts";
import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
import {
ProjectLiveServerDeclaredResponseError,
ProjectLiveServerRequestError,
projectCommandErrorFromLiveServerRequest,
} from "./project.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const runCli = (args: ReadonlyArray<string>) =>
Command.runWith(cli, { version: "0.0.0" })(args).pipe(Effect.provide(CliRuntimeLayer));
const makeConfig = (baseDir: string) =>
Effect.gen(function* () {
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined);
return {
logLevel: "Info",
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
mode: "web",
port: 0,
host: "127.0.0.1",
cwd: process.cwd(),
baseDir,
...derivedPaths,
staticDir: undefined,
devUrl: undefined,
devAllowedOrigins: [],
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
tailscaleServePort: 443,
} satisfies ServerConfig.ServerConfig["Service"];
});
const readProjects = (baseDir: string) =>
Effect.gen(function* () {
const config = yield* makeConfig(baseDir);
const layer = ProjectServiceLayerLive.pipe(
Layer.provideMerge(ProjectEnrichmentService.layer),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(ProjectFaviconResolver.layer),
Layer.provideMerge(T3ProjectFileLoader.layer),
Layer.provideMerge(WorkspacePaths.layer),
Layer.provideMerge(SqlitePersistenceLayerLive),
Layer.provideMerge(NodeServices.layer),
Layer.provide(ServerConfig.layer(config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
);
return yield* ProjectService.ProjectService.pipe(
Effect.flatMap((projects) => projects.snapshot),
Effect.provide(layer),
);
});
it("maps declared server failures into structural project command errors", () => {
const cause = new EnvironmentInternalError({
code: "internal_error",
reason: "orchestration_snapshot_failed",
reason: "access_token_issuance_failed",
traceId: "trace-123",
});
@@ -35,3 +112,23 @@ it("preserves unexpected server failures without deriving the message from them"
assert.strictEqual(error.message, "Failed to call the running server.");
assert.strictEqual(error.cause, cause);
});
it.effect("adds, renames, and removes projects through the V2 project CLI domain", () =>
Effect.gen(function* () {
const baseDir = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-v2-project-cli-"));
const workspaceRoot = NodeFS.mkdtempSync(
NodePath.join(NodeOS.tmpdir(), "t3-v2-project-workspace-"),
);
yield* runCli(["project", "add", workspaceRoot, "--title", "Alpha", "--base-dir", baseDir]);
const added = (yield* readProjects(baseDir)).projects[0];
assert.equal(added?.title, "Alpha");
assert.equal(added?.workspaceRoot, workspaceRoot);
yield* runCli(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
assert.equal((yield* readProjects(baseDir)).projects[0]?.title, "Beta");
yield* runCli(["project", "remove", added?.id ?? "", "--base-dir", baseDir]);
assert.deepEqual((yield* readProjects(baseDir)).projects, []);
}).pipe(Effect.provide(NodeServices.layer)),
);
+63 -30
View File
@@ -1,15 +1,14 @@
import {
CommandId,
AuthAdministrativeScopes,
CommandId,
EnvironmentHttpApi,
EnvironmentHttpCommonError,
type OrchestrationReadModel,
type ProjectMutation,
type ProjectSnapshot,
ProjectId,
type ClientOrchestrationCommand,
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -25,11 +24,13 @@ import * as HttpApiClient from "effect/unstable/httpapi/HttpApiClient";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerConfig from "../config.ts";
import * as OrchestrationEngine from "../orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "../orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
import { ProjectServiceLayerLive } from "../orchestration-v2/runtimeLayer.ts";
import * as ProjectEnrichmentService from "../project/ProjectEnrichmentService.ts";
import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts";
import * as RepositoryIdentityResolver from "../project/RepositoryIdentityResolver.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as T3ProjectFileLoader from "../project/T3ProjectFileLoader.ts";
import * as ServerRuntimeStartup from "../serverRuntimeStartup.ts";
import {
clearPersistedServerRuntimeState,
@@ -45,10 +46,7 @@ type ProjectMutationTarget = {
};
type ProjectCommandExecutionMode = "live" | "offline";
type ProjectCliDispatchCommand = Extract<
ClientOrchestrationCommand,
{ type: "project.create" | "project.meta.update" | "project.delete" }
>;
type ProjectCliDispatchCommand = ProjectMutation;
const isEnvironmentHttpCommonError = Schema.is(EnvironmentHttpCommonError);
@@ -198,12 +196,17 @@ const projectCommandUuid = Crypto.Crypto.pipe(
),
);
const ProjectCliRuntimeLive = Layer.mergeAll(
WorkspacePaths.layer,
OrchestrationLayerLive.pipe(
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(SqlitePersistenceLayerLive),
const ProjectCliRuntimeLive = ProjectServiceLayerLive.pipe(
Layer.provideMerge(ProjectEnrichmentService.layer),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(
ProjectFaviconResolver.layer.pipe(
Layer.provide(WorkspacePaths.layer),
Layer.provide(T3ProjectFileLoader.layer),
),
),
Layer.provideMerge(WorkspacePaths.layer),
Layer.provideMerge(SqlitePersistenceLayerLive),
);
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
@@ -256,7 +259,7 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
});
const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
readonly snapshot: OrchestrationReadModel;
readonly snapshot: ProjectSnapshot;
readonly identifier: string;
}) {
const trimmedIdentifier = input.identifier.trim();
@@ -311,7 +314,7 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
Effect.gen(function* () {
const client = yield* makeLiveServerClient(origin);
return yield* client.orchestration.snapshot({
return yield* client.projects.snapshot({
headers: { authorization: `Bearer ${bearerToken}` },
});
}).pipe(
@@ -326,18 +329,18 @@ const dispatchLiveOrchestrationCommand = (
) =>
Effect.gen(function* () {
const client = yield* makeLiveServerClient(origin);
yield* client.orchestration.dispatch({
yield* client.projects.mutate({
headers: { authorization: `Bearer ${bearerToken}` },
payload: command,
} as Parameters<typeof client.orchestration.dispatch>[0]);
} as Parameters<typeof client.projects.mutate>[0]);
}).pipe(
withProjectCliLiveServerTimeout,
Effect.mapError(projectCommandErrorFromLiveServerRequest),
);
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
return yield* projectionSnapshotQuery.getSnapshot();
const projects = yield* ProjectService.ProjectService;
return yield* projects.snapshot;
});
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
@@ -375,7 +378,7 @@ const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecu
const runProjectMutation = Effect.fn("runProjectMutation")(function* (
flags: CliAuthLocationFlags,
run: (input: {
readonly snapshot: OrchestrationReadModel;
readonly snapshot: ProjectSnapshot;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
@@ -420,10 +423,41 @@ const runProjectMutation = Effect.fn("runProjectMutation")(function* (
return yield* Effect.gen(function* () {
const snapshot = yield* getOfflineSnapshot();
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
const projects = yield* ProjectService.ProjectService;
const output = yield* run({
snapshot,
dispatch: (command) => orchestrationEngine.dispatch(command),
dispatch: (command) =>
command.type === "project.create"
? projects
.create({
commandId: command.commandId,
projectId: command.projectId,
title: command.title,
workspaceRoot: command.workspaceRoot,
...(command.defaultModelSelection === undefined
? {}
: { defaultModelSelection: command.defaultModelSelection }),
...(command.scripts === undefined ? {} : { scripts: command.scripts }),
})
.pipe(Effect.asVoid)
: command.type === "project.update"
? projects
.update({
commandId: command.commandId,
projectId: command.projectId,
...(command.title === undefined ? {} : { title: command.title }),
...(command.workspaceRoot === undefined
? {}
: { workspaceRoot: command.workspaceRoot }),
...(command.defaultModelSelection === undefined
? {}
: { defaultModelSelection: command.defaultModelSelection }),
...(command.scripts === undefined ? {} : { scripts: command.scripts }),
})
.pipe(Effect.asVoid)
: projects
.delete({ commandId: command.commandId, projectId: command.projectId })
.pipe(Effect.asVoid),
mode: "offline",
});
yield* Console.log(output);
@@ -454,7 +488,7 @@ const projectAddCommand = Command.make("add", {
snapshot,
dispatch,
}: {
readonly snapshot: OrchestrationReadModel;
readonly snapshot: ProjectSnapshot;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
@@ -480,7 +514,6 @@ const projectAddCommand = Command.make("add", {
title,
workspaceRoot,
defaultModelSelection: ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(),
createdAt: DateTime.formatIso(yield* DateTime.now),
});
return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
}),
@@ -506,7 +539,7 @@ const projectRemoveCommand = Command.make("remove", {
snapshot,
dispatch,
}: {
readonly snapshot: OrchestrationReadModel;
readonly snapshot: ProjectSnapshot;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
@@ -542,7 +575,7 @@ const projectRenameCommand = Command.make("rename", {
snapshot,
dispatch,
}: {
readonly snapshot: OrchestrationReadModel;
readonly snapshot: ProjectSnapshot;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
@@ -557,7 +590,7 @@ const projectRenameCommand = Command.make("rename", {
}
yield* dispatch({
type: "project.meta.update",
type: "project.update",
commandId: CommandId.make(yield* projectCommandUuid),
projectId: project.id,
title: nextTitle,
@@ -65,6 +65,7 @@ export class GitWorkflowService extends Context.Service<
readonly createWorktree: (
input: VcsCreateWorktreeInput,
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
readonly fetchRemote: (input: {
readonly cwd: string;
readonly remoteName: string;
@@ -299,6 +300,10 @@ export const make = Effect.gen(function* () {
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
Effect.andThen(git.createWorktree(input)),
),
listLocalBranchNames: (cwd) =>
ensureGitCommand("GitWorkflowService.listLocalBranchNames", cwd).pipe(
Effect.andThen(git.listLocalBranchNames(cwd)),
),
fetchRemote: (input) =>
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
Effect.andThen(git.fetchRemote(input)),
@@ -23,7 +23,6 @@ const invocation = {
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["preview"] as const),
issuedAt: 1,
expiresAt: Number.MAX_SAFE_INTEGER,
};
const client = McpSchema.McpServerClient.of({
clientId: 1,
+21 -1
View File
@@ -11,8 +11,11 @@ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstab
import packageJson from "../../package.json" with { type: "json" };
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as OrchestratorMcpService from "./OrchestratorMcpService.ts";
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
import { OrchestratorToolkitHandlersLive } from "./toolkits/orchestrator/handlers.ts";
import { OrchestratorToolkit } from "./toolkits/orchestrator/tools.ts";
import {
PreviewSnapshotToolkitHandlersLive,
PreviewStandardToolkitHandlersLive,
@@ -22,6 +25,9 @@ import {
PreviewSnapshotToolkit,
PreviewStandardToolkit,
} from "./toolkits/preview/tools.ts";
import { WorktreeToolkitHandlersLive } from "./toolkits/worktree/handlers.ts";
import { WorktreeToolkit } from "./toolkits/worktree/tools.ts";
import * as WorktreeMcpService from "./WorktreeMcpService.ts";
const unauthorized = HttpServerResponse.jsonUnsafe(
{
@@ -208,10 +214,24 @@ export const PreviewToolkitRegistrationLive = Layer.mergeAll(
PreviewSnapshotRegistrationLive,
);
export const OrchestratorToolkitRegistrationLive = McpServer.toolkit(OrchestratorToolkit).pipe(
Layer.provide(OrchestratorToolkitHandlersLive),
Layer.provide(OrchestratorMcpService.layer),
);
export const WorktreeToolkitRegistrationLive = McpServer.toolkit(WorktreeToolkit).pipe(
Layer.provide(WorktreeToolkitHandlersLive),
Layer.provide(WorktreeMcpService.layer),
);
const McpTransportLive = McpServer.layerHttp({
name: "T3 Code",
version: packageJson.version,
path: "/mcp",
}).pipe(Layer.provide(McpAuthMiddlewareLive));
export const layer = PreviewToolkitRegistrationLive.pipe(Layer.provideMerge(McpTransportLive));
export const layer = Layer.mergeAll(
PreviewToolkitRegistrationLive,
OrchestratorToolkitRegistrationLive,
WorktreeToolkitRegistrationLive,
).pipe(Layer.provideMerge(McpTransportLive));
@@ -17,7 +17,6 @@ it.effect("reports the scoped credential context when preview capability is unav
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(),
issuedAt: 1,
expiresAt: 2,
};
return Effect.gen(function* () {
+3 -3
View File
@@ -7,7 +7,8 @@ import {
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
export type McpCapability = "preview";
export const ALL_MCP_CAPABILITIES = ["preview", "orchestration", "worktree"] as const;
export type McpCapability = (typeof ALL_MCP_CAPABILITIES)[number];
export interface McpInvocationScope {
readonly environmentId: EnvironmentId;
@@ -16,7 +17,6 @@ export interface McpInvocationScope {
readonly providerInstanceId: ProviderInstanceId;
readonly capabilities: ReadonlySet<McpCapability>;
readonly issuedAt: number;
readonly expiresAt: number;
}
export class McpInvocationContext extends Context.Service<
@@ -25,7 +25,7 @@ export class McpInvocationContext extends Context.Service<
>()("t3/mcp/McpInvocationContext") {}
export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* (
capability: McpCapability,
capability: "preview",
) {
const invocation = yield* McpInvocationContext;
if (!invocation.capabilities.has(capability)) {
@@ -21,11 +21,7 @@ const fakeEnvironment = ServerEnvironment.ServerEnvironment.of({
const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
McpSessionRegistry.__testing
.make({
now,
idleTimeoutMs: 100,
maximumLifetimeMs: 1_000,
})
.make({ now })
.pipe(
Effect.provideService(HttpServer.HttpServer, httpServer),
Effect.provideService(ServerEnvironment.ServerEnvironment, fakeEnvironment),
@@ -47,6 +43,7 @@ it.effect("stores only a token hash, resolves the bearer token, and revokes by t
const resolved = yield* registry.resolve(token);
expect(resolved?.threadId).toBe(threadId);
expect(resolved?.capabilities).toEqual(new Set(["preview", "orchestration", "worktree"]));
yield* registry.revokeThread(threadId);
expect(yield* registry.resolve(token)).toBeUndefined();
@@ -75,7 +72,7 @@ it.effect("builds MCP endpoints from the bound server host", () =>
}),
);
it.effect("expires credentials after inactivity", () =>
it.effect("keeps credentials valid until they are explicitly revoked", () =>
Effect.gen(function* () {
let timestamp = 1_000;
const registry = yield* makeRegistry(() => timestamp);
@@ -84,7 +81,12 @@ it.effect("expires credentials after inactivity", () =>
providerInstanceId: ProviderInstanceId.make("claude"),
});
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
timestamp += 101;
const resolved = yield* registry.resolve(token);
expect(resolved?.providerSessionId).toBe(issued.config.providerSessionId);
timestamp += 365 * 24 * 60 * 60 * 1_000;
expect(yield* registry.resolve(token)).toEqual(resolved);
yield* registry.revokeProviderSession(issued.config.providerSessionId);
expect(yield* registry.resolve(token)).toBeUndefined();
}),
);
@@ -0,0 +1,26 @@
import { EnvironmentId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { McpSessionRegistry } from "./McpSessionRegistry.ts";
export const layer = Layer.succeed(
McpSessionRegistry,
McpSessionRegistry.of({
issue: ({ threadId, providerInstanceId }) =>
Effect.succeed({
config: {
environmentId: EnvironmentId.make("environment:mcp-test"),
threadId,
providerSessionId: `mcp-test:${threadId}`,
providerInstanceId,
endpoint: "http://127.0.0.1/mcp",
authorizationHeader: `Bearer mcp-test:${threadId}`,
},
}),
resolve: () => Effect.succeed(undefined),
revokeProviderSession: () => Effect.void,
revokeThread: () => Effect.void,
revokeAll: Effect.void,
}),
);
+6 -35
View File
@@ -18,10 +18,10 @@ export interface McpCredentialRequest {
export interface McpIssuedCredential {
readonly config: McpProviderSession.McpProviderSessionConfig;
readonly expiresAt: number;
}
export interface McpSessionRegistryShape {
/** Credentials have no time-based expiry and must be explicitly revoked by their owner. */
readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
readonly resolve: (
rawToken: string,
@@ -37,9 +37,7 @@ export class McpSessionRegistry extends Context.Service<
>()("t3/mcp/McpSessionRegistry") {}
interface CredentialRecord {
readonly tokenHash: string;
readonly scope: McpInvocationContext.McpInvocationScope;
readonly lastUsedAt: number;
}
interface RegistryState {
@@ -47,14 +45,9 @@ interface RegistryState {
}
export interface McpSessionRegistryOptions {
readonly idleTimeoutMs?: number;
readonly maximumLifetimeMs?: number;
readonly now?: () => number;
}
const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;
const DEFAULT_MAXIMUM_LIFETIME_MS = 8 * 60 * 60 * 1_000;
const bytesToHex = (bytes: Uint8Array): string =>
Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
@@ -80,8 +73,6 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
const httpServer = yield* HttpServer.HttpServer;
const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
const maximumLifetimeMs = options.maximumLifetimeMs ?? DEFAULT_MAXIMUM_LIFETIME_MS;
const endpoint =
httpServer.address._tag === "TcpAddress"
? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`
@@ -92,35 +83,23 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
.digest("SHA-256", new TextEncoder().encode(token))
.pipe(Effect.map(bytesToHex), Effect.orDie);
const pruneExpired = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {
const next = new Map(
Array.from(records).filter(
([, record]) =>
timestamp <= record.scope.expiresAt && timestamp - record.lastUsedAt <= idleTimeoutMs,
),
);
return next.size === records.size ? records : next;
};
const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
function* (request) {
const issuedAt = yield* currentTimeMillis;
const providerSessionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
const rawToken = yield* crypto.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
const tokenHash = yield* hashToken(rawToken);
const expiresAt = issuedAt + maximumLifetimeMs;
const scope: McpInvocationContext.McpInvocationScope = {
environmentId,
threadId: ThreadId.make(request.threadId),
providerSessionId,
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
capabilities: new Set(["preview"]),
capabilities: new Set(McpInvocationContext.ALL_MCP_CAPABILITIES),
issuedAt,
expiresAt,
};
yield* SynchronizedRef.update(state, ({ records }) => {
const next = new Map(pruneExpired(records, issuedAt));
next.set(tokenHash, { tokenHash, scope, lastUsedAt: issuedAt });
const next = new Map(records);
next.set(tokenHash, { scope });
return { records: next };
});
return {
@@ -132,7 +111,6 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
endpoint,
authorizationHeader: `Bearer ${rawToken}`,
},
expiresAt,
};
},
);
@@ -141,15 +119,8 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
function* (rawToken) {
if (rawToken.length === 0) return undefined;
const tokenHash = yield* hashToken(rawToken);
const timestamp = yield* currentTimeMillis;
return yield* SynchronizedRef.modify(state, ({ records }) => {
const current = pruneExpired(records, timestamp);
const record = current.get(tokenHash);
if (!record) return [undefined, { records: current }] as const;
const next = new Map(current);
next.set(tokenHash, { ...record, lastUsedAt: timestamp });
return [record.scope, { records: next }] as const;
});
const record = (yield* SynchronizedRef.get(state)).records.get(tokenHash);
return record?.scope;
},
);
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -31,7 +31,6 @@ const scope = {
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["preview"] as const),
issuedAt: 1,
expiresAt: Number.MAX_SAFE_INTEGER,
};
const makeHost = (overrides: Partial<PreviewAutomationHost> = {}): PreviewAutomationHost => ({
@@ -22,7 +22,6 @@ import {
type PreviewAutomationStreamEvent,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
@@ -79,7 +78,6 @@ interface HostAssignment {
readonly clientId: ClientConnection["clientId"];
readonly connectionId: ClientConnection["connectionId"];
readonly queue: ClientConnection["queue"];
readonly expiresAt: number;
readonly tabId?: PreviewTabId;
readonly tabSequence?: number;
}
@@ -422,13 +420,11 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
): Effect.fn.Return<A, PreviewAutomationError> {
const timeoutMs = input.timeoutMs ?? 15_000;
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
const now = yield* Clock.currentTimeMillis;
const route = yield* SynchronizedRef.modify(state, (current) => {
const assignments = new Map(
Array.from(current.assignments).filter(([, assignment]) => {
const connection = current.clients.get(assignment.clientId);
return (
assignment.expiresAt > now &&
connection?.connectionId === assignment.connectionId &&
connection.queue === assignment.queue
);
@@ -473,7 +469,6 @@ export const make = Effect.gen(function* PreviewAutomationBrokerMake() {
clientId: connection.clientId,
connectionId: connection.connectionId,
queue: connection.queue,
expiresAt: input.scope.expiresAt,
...(canReuseAssignedTab && assigned.tabId !== undefined ? { tabId: assigned.tabId } : {}),
...(canReuseAssignedTab && assigned.tabSequence !== undefined
? { tabSequence: assigned.tabSequence }
File diff suppressed because it is too large. Load diff
+481
View File
@@ -0,0 +1,481 @@
import {
CommandId,
MessageId,
type ProjectId,
WorktreeMcpFailure,
type WorktreeMcpContinuationStatus,
type WorktreeMcpHandoffInput,
type WorktreeMcpHandoffResult,
type WorktreeMcpSetupScriptStatus,
type WorktreeMcpStatusResult,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as GitWorkflowService from "../git/GitWorkflowService.ts";
import { ThreadManagementService } from "../orchestration-v2/ThreadManagementService.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as VcsStatusBroadcaster from "../vcs/VcsStatusBroadcaster.ts";
import type { McpInvocationScope } from "./McpInvocationContext.ts";
export class WorktreeMcpService extends Context.Service<
WorktreeMcpService,
{
readonly handoff: (
scope: McpInvocationScope,
input: WorktreeMcpHandoffInput,
) => Effect.Effect<WorktreeMcpHandoffResult, WorktreeMcpFailure>;
readonly status: (
scope: McpInvocationScope,
) => Effect.Effect<WorktreeMcpStatusResult, WorktreeMcpFailure>;
}
>()("t3/mcp/WorktreeMcpService") {}
function failure(code: WorktreeMcpFailure["code"], message: string): WorktreeMcpFailure {
return new WorktreeMcpFailure({ code, message });
}
function errorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
if (typeof error === "object" && error !== null && "message" in error) {
return String((error as { message: unknown }).message);
}
return String(error);
}
const asOperationFailed = (prefix: string) =>
Effect.mapError((error: unknown) =>
failure("operation_failed", `${prefix}: ${errorMessage(error)}`),
);
const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const path = yield* Path.Path;
const threadManagement = yield* ThreadManagementService;
const projects = yield* ProjectService.ProjectService;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const gitWorkflow = yield* GitWorkflowService.GitWorkflowService;
const setupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
// Serializes handoffs per thread: two concurrent calls could otherwise both
// pass the worktreePath === null check and each create a worktree, leaving
// one untracked on disk.
const handoffThreadsInFlight = new Set<string>();
const requireCapability = (scope: McpInvocationScope) =>
scope.capabilities.has("worktree")
? Effect.void
: Effect.fail(
failure("capability_denied", "This MCP credential does not grant worktree capabilities."),
);
const loadThread = (scope: McpInvocationScope) =>
threadManagement.getThreadProjection(scope.threadId).pipe(
Effect.mapError((error) =>
error._tag === "OrchestratorProjectionError"
? failure("thread_not_found", `Thread '${scope.threadId}' was not found.`)
: failure(
"operation_failed",
`Unable to read thread ${scope.threadId}: ${errorMessage(error)}`,
),
),
Effect.filterOrFail(
(projection) => projection.thread.deletedAt === null,
() => failure("thread_not_found", `Thread '${scope.threadId}' was not found.`),
),
);
const loadProject = (scope: McpInvocationScope, projectId: ProjectId) =>
projects.getById(projectId).pipe(
asOperationFailed(`Unable to read project ${projectId}`),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
failure(
"project_not_found",
`Project '${projectId}' was not found for thread '${scope.threadId}'.`,
),
),
onSome: Effect.succeed,
}),
),
);
const readDefaultStartFromOrigin = serverSettings.getSettings.pipe(
Effect.map((settings) => settings.newWorktreesStartFromOrigin),
asOperationFailed("Unable to read server settings"),
);
const handoffIds = (scope: McpInvocationScope) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => {
const part = (kind: string, operation: string) =>
[kind, "mcp", encodeURIComponent(scope.providerSessionId), operation, uuid].join(":");
return {
commandId: CommandId.make(part("command", "worktree-handoff")),
continuationCommandId: CommandId.make(part("command", "worktree-continuation")),
continuationMessageId: MessageId.make(part("message", "worktree-continuation")),
};
}),
Effect.orDie,
);
const performHandoff = Effect.fn("WorktreeMcpService.performHandoff")(function* (
scope: McpInvocationScope,
input: WorktreeMcpHandoffInput,
) {
const alreadyInWorktree = (worktreePath: string) =>
failure(
"already_in_worktree",
`Thread '${scope.threadId}' is already attached to worktree '${worktreePath}'.`,
);
const projection = yield* loadThread(scope);
if (projection.thread.worktreePath !== null) {
return yield* alreadyInWorktree(projection.thread.worktreePath);
}
// An archived thread would accept the binding but refuse the continuation
// message (and any other follow-up), so reject the handoff outright.
if (projection.thread.archivedAt !== null) {
return yield* failure(
"invalid_request",
`Thread '${scope.threadId}' is archived and cannot be handed off to a worktree.`,
);
}
const project = yield* loadProject(scope, projection.thread.projectId);
const projectCwd = project.workspaceRoot;
if (input.path !== undefined && !path.isAbsolute(input.path)) {
return yield* failure(
"invalid_request",
`path must be an absolute filesystem path, got '${input.path}'. A relative path would be created relative to the project workspace but stored verbatim as the thread's worktree binding.`,
);
}
// The repo check runs regardless of whether baseRef was supplied, so a
// non-repository workspace fails with an actionable error instead of an
// opaque git failure further down.
const localStatus = yield* gitWorkflow
.localStatus({ cwd: projectCwd })
.pipe(asOperationFailed("Unable to read git status"));
if (!localStatus.isRepo) {
return yield* failure(
"invalid_request",
`Project workspace '${projectCwd}' is not a git repository.`,
);
}
// Fail fast with an actionable message when the branch already exists:
// the git driver deliberately keeps stderr out of its errors, so letting
// `git worktree add` fail would surface only an opaque failure. The
// existence check uses the complete local branch list (exact match); the
// paginated substring search only enriches the message with the checkout
// location when available.
const localBranchNames = yield* gitWorkflow
.listLocalBranchNames(projectCwd)
.pipe(asOperationFailed("Unable to list branches"));
if (localBranchNames.includes(input.branch)) {
const existingRef = yield* gitWorkflow
.listRefs({ cwd: projectCwd, query: input.branch, refKind: "local" })
.pipe(
Effect.map((result) =>
result.refs.find((ref) => ref.name === input.branch && ref.isRemote !== true),
),
Effect.orElseSucceed(() => undefined),
);
const checkoutPath = existingRef?.worktreePath ?? null;
return yield* failure(
"invalid_request",
`Branch '${input.branch}' already exists${
checkoutPath === null ? "" : ` and is checked out at '${checkoutPath}'`
}. Choose a different branch name, or delete the existing branch${
checkoutPath === null ? "" : " and its worktree"
} first.`,
);
}
let baseRef = input.baseRef;
if (baseRef === undefined) {
if (localStatus.refName === null) {
return yield* failure(
"invalid_request",
"Could not determine the current branch of the project workspace (detached HEAD?). Pass baseRef explicitly.",
);
}
baseRef = localStatus.refName;
}
const startFromOrigin = input.startFromOrigin ?? (yield* readDefaultStartFromOrigin);
let worktreeBaseRef = baseRef;
if (startFromOrigin) {
yield* gitWorkflow
.fetchRemote({ cwd: projectCwd, remoteName: "origin" })
.pipe(asOperationFailed("Unable to fetch origin"));
const resolvedRemoteBase = yield* gitWorkflow
.resolveRemoteTrackingCommit({
cwd: projectCwd,
refName: baseRef,
fallbackRemoteName: "origin",
})
.pipe(asOperationFailed(`Unable to resolve the remote-tracking commit of '${baseRef}'`));
worktreeBaseRef = resolvedRemoteBase.commitSha;
}
const ids = yield* handoffIds(scope);
// uninterruptibleMask: only the potentially slow worktree creation itself
// stays interruptible (restore). From the moment it succeeds, through the
// binding, continuation queue, setup script launch, and result
// construction, there is no interruptible gap: a client cancel can
// therefore neither orphan the created worktree before the rollback is
// armed, nor skip setting up a worktree the thread was just bound to
// (once the binding commits, the scheduled session detach can sever this
// request's connection and interrupt the fiber).
return yield* Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
const worktree = yield* restore(
gitWorkflow
.createWorktree({
cwd: projectCwd,
refName: worktreeBaseRef,
newRefName: input.branch,
baseRefName: baseRef,
path: input.path ?? null,
})
.pipe(asOperationFailed("Unable to create the worktree")),
);
const worktreePath = worktree.worktree.path;
// Shared shape for "the handoff already succeeded, so report the failure
// in the result instead of failing the call" (continuation, setup script).
const reportFailed = (logMessage: string) =>
Effect.catchCause((cause: Cause.Cause<unknown>) => {
const detail = errorMessage(Cause.squash(cause));
return Effect.logWarning(logMessage, {
threadId: scope.threadId,
worktreePath,
detail,
}).pipe(Effect.as({ status: "failed", detail } as const));
});
// suspend: build the removal call only if cleanup actually runs.
const removeCreatedWorktree = Effect.suspend(() =>
gitWorkflow.removeWorktree({ cwd: projectCwd, path: worktreePath, force: true }),
).pipe(Effect.ignoreCause({ log: true }));
const recheckAndBind = Effect.gen(function* () {
// The projection was read before the potentially slow git work
// above; a concurrent binding (for example from the UI) could have
// attached the thread in the meantime. Re-check before committing so
// the race cannot leave a second, untracked worktree.
const recheck = yield* loadThread(scope);
if (recheck.thread.worktreePath !== null) {
return yield* alreadyInWorktree(recheck.thread.worktreePath);
}
// Mirror the up-front archived check: the thread may have been
// archived during the slow git work, and an archived thread must
// not be bound to a fresh worktree it can never use.
if (recheck.thread.archivedAt !== null) {
return yield* failure(
"invalid_request",
`Thread '${scope.threadId}' was archived while the worktree was being created; the handoff was rolled back.`,
);
}
yield* threadManagement
.dispatch({
type: "thread.metadata.update",
commandId: ids.commandId,
threadId: scope.threadId,
branch: worktree.worktree.refName,
worktreePath,
})
.pipe(
Effect.catchCause((cause) =>
// Interrupt-only causes propagate unchanged: whether the
// dispatch committed is unknown, so neither a typed failure
// nor a rollback would be correct. Failures and defects
// (including mixed causes) map to a typed operation_failed.
Cause.hasInterruptsOnly(cause)
? Effect.failCause(cause as Cause.Cause<never>)
: Effect.fail(
failure(
"operation_failed",
`Unable to re-point the thread at the worktree: ${errorMessage(Cause.squash(cause))}`,
),
),
),
);
}).pipe(
// onError: the worktree was already created, so any failure between
// here and the committed binding (recheck read, recheck race,
// dispatch typed failure or defect) must remove it again so a failed
// handoff leaves nothing behind on disk. Interrupt-only causes skip
// the removal: the binding may have committed, and force-deleting a
// worktree the thread now points at would be worse than leaking one.
Effect.onError((cause) =>
Cause.hasInterruptsOnly(cause) ? Effect.void : removeCreatedWorktree,
),
);
// Queue the continuation right after the binding commits: the detach
// that the metadata update schedules will terminate the calling
// session, and a durably queued message is what guarantees the thread
// re-launches inside the worktree. When the dying run reaches a
// terminal state the orchestrator promotes the queued run, which
// derives its cwd from the updated projection.
// suspend: build the send effect only when the binding has succeeded,
// so a failed dispatch never even constructs the continuation call.
const queueContinuation: Effect.Effect<WorktreeMcpContinuationStatus, WorktreeMcpFailure> =
Effect.suspend(() =>
input.continuationPrompt === undefined
? Effect.succeed<WorktreeMcpContinuationStatus>({ status: "skipped" })
: threadManagement
.sendToThread({
projectId: projection.thread.projectId,
commandId: ids.continuationCommandId,
threadId: scope.threadId,
messageId: ids.continuationMessageId,
text: input.continuationPrompt,
attachments: [],
mode: "queue",
createdBy: "agent",
creationSource: "mcp",
})
.pipe(
Effect.map(
(sendResult): WorktreeMcpContinuationStatus => ({
status: "scheduled",
delivery: sendResult.delivery,
}),
),
// catchCause via reportFailed: the binding is already recorded,
// so a failed continuation must be reported, not fail the handoff.
reportFailed("worktree handoff continuation failed to queue"),
),
);
const continuation = yield* recheckAndBind.pipe(Effect.andThen(queueContinuation));
yield* vcsStatusBroadcaster
.refreshStatus(worktreePath)
.pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach);
let setupScript: WorktreeMcpSetupScriptStatus = { status: "skipped" };
if (input.runSetupScript ?? true) {
setupScript = yield* setupScriptRunner
.runForThread({
threadId: scope.threadId,
projectId: projection.thread.projectId,
projectCwd,
worktreePath,
project: {
workspaceRoot: project.workspaceRoot,
scripts: project.scripts,
},
})
.pipe(
Effect.map(
(result): WorktreeMcpSetupScriptStatus =>
result.status === "started"
? {
status: "started",
scriptName: result.scriptName,
terminalId: result.terminalId,
}
: { status: "no-script" },
),
// catchCause via reportFailed: the thread is already re-pointed at the
// worktree, so even a defect in the setup runner must not fail the handoff.
reportFailed("worktree handoff setup script failed"),
);
}
const result: WorktreeMcpHandoffResult = {
worktreePath,
branch: worktree.worktree.refName,
baseRef,
startedFromOrigin: startFromOrigin,
setupScript,
continuation,
note:
continuation.status === "scheduled"
? "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the queued continuation prompt then starts the next turn inside the worktree with the conversation preserved. The worktree is not removed automatically when the thread is deleted."
: "Handoff recorded. Changing the workspace detaches this provider session, so the current turn ends shortly after this call; the conversation continues inside the worktree when the thread receives its next message. Pass continuationPrompt to resume automatically. The worktree is not removed automatically when the thread is deleted.",
};
return result;
}),
);
});
const handoff: WorktreeMcpService["Service"]["handoff"] = Effect.fn("WorktreeMcpService.handoff")(
function* (scope, input) {
yield* requireCapability(scope);
// uninterruptibleMask: the guard acquisition and the registration of the
// releasing finalizer happen with no interruptible gap in between. An
// interrupt landing between a bare add() and the start of an ensured
// effect would otherwise leak the guard entry and block every future
// handoff for this thread until restart.
return yield* Effect.uninterruptibleMask((restore) =>
Effect.suspend(() => {
if (handoffThreadsInFlight.has(scope.threadId)) {
return Effect.fail(
failure(
"handoff_in_progress",
`A worktree handoff is already in progress for thread '${scope.threadId}'.`,
),
);
}
handoffThreadsInFlight.add(scope.threadId);
return restore(performHandoff(scope, input)).pipe(
Effect.ensuring(Effect.sync(() => handoffThreadsInFlight.delete(scope.threadId))),
);
}),
);
},
);
const status: WorktreeMcpService["Service"]["status"] = Effect.fn("WorktreeMcpService.status")(
function* (scope) {
yield* requireCapability(scope);
const projection = yield* loadThread(scope);
const project = yield* loadProject(scope, projection.thread.projectId);
const defaultStartFromOrigin = yield* readDefaultStartFromOrigin;
const result: WorktreeMcpStatusResult = {
attached: projection.thread.worktreePath !== null,
worktreePath: projection.thread.worktreePath,
branch: projection.thread.branch,
projectWorkspaceRoot: project.workspaceRoot,
defaultStartFromOrigin,
};
return result;
},
);
return WorktreeMcpService.of({ handoff, status });
});
export const layer: Layer.Layer<
WorktreeMcpService,
never,
| Crypto.Crypto
| Path.Path
| ThreadManagementService
| ProjectService.ProjectService
| ServerSettings.ServerSettingsService
| GitWorkflowService.GitWorkflowService
| ProjectSetupScriptRunner.ProjectSetupScriptRunner
| VcsStatusBroadcaster.VcsStatusBroadcaster
> = Layer.effect(WorktreeMcpService, make);
@@ -0,0 +1,114 @@
import { OrchestratorToolkit } from "./tools.ts";
import * as Effect from "effect/Effect";
import { McpInvocationContext } from "../../McpInvocationContext.ts";
import { OrchestratorMcpService } from "../../OrchestratorMcpService.ts";
const handlers = {
orchestrator_capabilities: () =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.capabilities(scope);
}),
delegate_task: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.delegateTask(scope, input);
}),
task_status: ({ taskId }) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.taskStatus(scope, taskId);
}),
task_cancel: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.cancelTask(scope, input);
}),
schedule_task: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.scheduleTask(scope, input);
}),
list_scheduled_tasks: () =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.listScheduledTasks(scope);
}),
update_scheduled_task: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.updateScheduledTask(scope, input);
}),
delete_scheduled_task: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.deleteScheduledTask(scope, input);
}),
create_threads: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.createThreads(scope, input);
}),
t3_thread_start: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
const result = yield* service.createThreads(scope, {
...(input.clientRequestId === undefined ? {} : { clientRequestId: input.clientRequestId }),
threads: [
{
prompt: input.prompt,
...(input.title === undefined ? {} : { title: input.title }),
...(input.target === undefined ? {} : { target: input.target }),
...(input.runtimeMode === undefined ? {} : { runtimeMode: input.runtimeMode }),
...(input.interactionMode === undefined
? {}
: { interactionMode: input.interactionMode }),
},
],
});
return result.threads[0]!;
}),
t3_thread_list: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.listThreads(scope, input);
}),
t3_thread_read: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.readThread(scope, input);
}),
t3_thread_send: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.sendToThread(scope, input);
}),
t3_thread_wait: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.waitForThread(scope, input);
}),
t3_thread_interrupt: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* OrchestratorMcpService;
return yield* service.interruptThread(scope, input);
}),
} satisfies Parameters<typeof OrchestratorToolkit.toLayer>[0];
export const OrchestratorToolkitHandlersLive = OrchestratorToolkit.toLayer(handlers);
@@ -0,0 +1,28 @@
import { assert, describe, it } from "@effect/vitest";
import { Tool } from "effect/unstable/ai";
import { CreateThreadsTool, DelegateTaskTool, ScheduleTaskTool } from "./tools.ts";
describe("orchestrator MCP tool guidance", () => {
it("directs subagent requests to delegation instead of ordinary threads", () => {
assert.include(DelegateTaskTool.description ?? "", "child agent/subagent");
assert.include(DelegateTaskTool.description ?? "", "cross-provider");
assert.include(CreateThreadsTool.description ?? "", "not delegation");
assert.include(CreateThreadsTool.description ?? "", "call delegate_task");
});
it("publishes an actionable schedule schema and compatibility string branch", () => {
const schema = Tool.getJsonSchema(ScheduleTaskTool) as {
readonly type?: unknown;
readonly properties?: Readonly<
Record<string, { readonly description?: unknown; readonly anyOf?: ReadonlyArray<unknown> }>
>;
};
assert.equal(schema.type, "object");
assert.isString(schema.properties?.schedule?.description);
assert.isAtLeast(schema.properties?.schedule?.anyOf?.length ?? 0, 2);
assert.include(ScheduleTaskTool.description ?? "", "STRUCTURED OBJECT");
assert.include(ScheduleTaskTool.description ?? "", "nextRunAt");
});
});
@@ -0,0 +1,248 @@
import {
OrchestratorMcpCapabilitiesResult,
OrchestratorMcpCreatedThread,
OrchestratorMcpCreateThreadsInput,
OrchestratorMcpCreateThreadsResult,
OrchestratorMcpDelegateTaskInput,
OrchestratorMcpDelegateTaskResult,
OrchestratorMcpDeleteScheduledTaskInput,
OrchestratorMcpDeleteScheduledTaskResult,
OrchestratorMcpFailure,
OrchestratorMcpListScheduledTasksResult,
OrchestratorMcpScheduleTaskInput,
OrchestratorMcpScheduleTaskResult,
OrchestratorMcpTaskCancelInput,
OrchestratorMcpTaskCancelResult,
OrchestratorMcpUpdateScheduledTaskInput,
OrchestratorMcpTaskStatusInput,
OrchestratorMcpThreadInterruptInput,
OrchestratorMcpThreadInterruptResult,
OrchestratorMcpThreadListInput,
OrchestratorMcpThreadListResult,
OrchestratorMcpThreadReadInput,
OrchestratorMcpThreadReadResult,
OrchestratorMcpThreadSendInput,
OrchestratorMcpThreadSendResult,
OrchestratorMcpThreadStartInput,
OrchestratorMcpThreadWaitInput,
OrchestratorMcpThreadWaitResult,
} from "@t3tools/contracts";
import { Tool, Toolkit } from "effect/unstable/ai";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import { OrchestratorMcpService } from "../../OrchestratorMcpService.ts";
const dependencies = [McpInvocationContext.McpInvocationContext, OrchestratorMcpService];
export const OrchestratorCapabilitiesTool = Tool.make("orchestrator_capabilities", {
description:
"List the V2 provider instances, models, inherited runtime settings, and app-owned orchestration features available to this T3 thread.",
success: OrchestratorMcpCapabilitiesResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Get orchestration capabilities")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const DelegateTaskTool = Tool.make("delegate_task", {
description:
"Delegate one task to a T3-owned child agent/subagent of THIS thread and run it with only the supplied task prompt, without copying parent conversation history. Use this whenever the user asks for an agent, subagent, worker, delegated task, or parallel help—including cross-provider work. The childThreadId is backing storage, not an ordinary top-level thread. Provider, model, model options (see orchestrator_capabilities), runtime mode, and interaction mode inherit unless target overrides them. Prefer mode='async' for long work; mode='wait' blocks until completion or timeout. An async child's completion wakes this thread with a continuation message naming the task (queued behind any turn in progress), so end the turn instead of polling or spawning watchers; use task_status only when the result is needed mid-turn.",
parameters: OrchestratorMcpDelegateTaskInput,
success: OrchestratorMcpDelegateTaskResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Delegate a child task")
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);
export const TaskStatusTool = Tool.make("task_status", {
description:
"Read the latest durable state and final summary for a T3-owned delegated task created by this parent thread.",
parameters: OrchestratorMcpTaskStatusInput,
success: OrchestratorMcpDelegateTaskResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Get delegated task status")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const TaskCancelTool = Tool.make("task_cancel", {
description:
"Request interruption of an active T3-owned delegated task. Completed tasks are returned unchanged.",
parameters: OrchestratorMcpTaskCancelInput,
success: OrchestratorMcpTaskCancelResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Cancel delegated task")
.annotate(Tool.Destructive, true);
export const ScheduleTaskTool = Tool.make("schedule_task", {
description:
"Create persistent recurring work in the app scheduler, which runs even when no turn is active. Pass schedule as a STRUCTURED OBJECT, never JSON text: {type:'interval', everyMs:3600000} means hourly; {type:'fixed_time', timeOfDay:'09:00', weekdays:[1,2,3,4,5]} means weekday mornings. By default (bindToCurrentThread=true) each run posts into THIS thread; use false only when the user wants a fresh top-level thread per run. Provider, model, and runtime settings inherit from this thread. Report the returned schedule and nextRunAt after success.",
parameters: OrchestratorMcpScheduleTaskInput,
success: OrchestratorMcpScheduleTaskResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Schedule a recurring task")
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);
export const ListScheduledTasksTool = Tool.make("list_scheduled_tasks", {
description:
"List the recurring scheduled tasks in the calling thread's project, including their id, schedule, prompt, enabled state, bound thread, next run time, and last run status. Use the returned scheduledTaskId with update_scheduled_task or delete_scheduled_task.",
success: OrchestratorMcpListScheduledTasksResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "List scheduled tasks")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const UpdateScheduledTaskTool = Tool.make("update_scheduled_task", {
description:
"Update an existing scheduled task by scheduledTaskId (from list_scheduled_tasks). Only the provided fields change; omit a field to leave it as-is. Use enabled=false to pause a task without deleting it. Set bindToCurrentThread to move the task between posting into this thread and launching a fresh thread per run.",
parameters: OrchestratorMcpUpdateScheduledTaskInput,
success: OrchestratorMcpScheduleTaskResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Update a scheduled task")
.annotate(Tool.Destructive, true);
export const DeleteScheduledTaskTool = Tool.make("delete_scheduled_task", {
description:
"Permanently delete a scheduled task by scheduledTaskId (from list_scheduled_tasks). The task stops running immediately. To keep it but stop runs, use update_scheduled_task with enabled=false instead.",
parameters: OrchestratorMcpDeleteScheduledTaskInput,
success: OrchestratorMcpDeleteScheduledTaskResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Delete a scheduled task")
.annotate(Tool.Destructive, true);
export const CreateThreadsTool = Tool.make("create_threads", {
description:
"Create one or more ORDINARY TOP-LEVEL T3 conversations. This is not delegation and does not create child agents/subagents. If the user asks for agents, subagents, workers, delegation, or parallel help, call delegate_task once per child instead—even when selecting different providers. Use create_threads only when the user explicitly asks for separate/new/top-level threads or conversations. Each entry may override provider, model, options, runtime mode, and interaction mode; omitted settings inherit.",
parameters: OrchestratorMcpCreateThreadsInput,
success: OrchestratorMcpCreateThreadsResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Create T3 threads")
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);
export const ThreadStartTool = Tool.make("t3_thread_start", {
description:
"Create an ordinary TOP-LEVEL T3 conversation and immediately start its first turn. This is not a child agent/subagent; use delegate_task for delegated work. The new thread inherits this thread's project, checkout, provider, model, and runtime settings unless overridden. Use t3_thread_wait and t3_thread_read to collect its result.",
parameters: OrchestratorMcpThreadStartInput,
success: OrchestratorMcpCreatedThread,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Start a T3 thread")
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);
export const ThreadListTool = Tool.make("t3_thread_list", {
description:
"List T3 threads in the calling thread's project, newest first. Filter by durable run status or title and paginate with the returned cursor. Threads from other projects are never exposed.",
parameters: OrchestratorMcpThreadListInput,
success: OrchestratorMcpThreadListResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "List T3 threads")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const ThreadReadTool = Tool.make("t3_thread_read", {
description:
"Read durable state and a paginated timeline from a T3 thread in the calling project. The default messages view returns user messages, assistant messages, and proposed plans; activity returns all summarized timeline items. Continue with afterPosition=nextPosition.",
parameters: OrchestratorMcpThreadReadInput,
success: OrchestratorMcpThreadReadResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Read a T3 thread")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const ThreadSendTool = Tool.make("t3_thread_send", {
description:
"Send a message to a T3 thread in the calling project. mode='auto' starts an idle thread, steers a fully active turn, or queues behind a turn that is not yet steerable. Use queue for a separate follow-up turn, steer for an in-flight update, or restart to interrupt-and-restart the active turn. clientRequestId makes retries idempotent.",
parameters: OrchestratorMcpThreadSendInput,
success: OrchestratorMcpThreadSendResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Send to a T3 thread")
.annotate(Tool.Destructive, true)
.annotate(Tool.OpenWorld, true);
export const ThreadWaitTool = Tool.make("t3_thread_wait", {
description:
"Wait for a T3 thread run to reach a terminal durable state. Without runId, the latest run at call time is selected; an idle thread returns immediately. Timeout does not interrupt work, so call again or use t3_thread_read/list after timedOut=true.",
parameters: OrchestratorMcpThreadWaitInput,
success: OrchestratorMcpThreadWaitResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Wait for a T3 thread")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const ThreadInterruptTool = Tool.make("t3_thread_interrupt", {
description:
"Request interruption of a running turn in a T3 thread in the calling project. Without runId, the newest interruptible run is selected. Terminal runs and threads without an active turn return without another side effect. clientRequestId makes retries idempotent.",
parameters: OrchestratorMcpThreadInterruptInput,
success: OrchestratorMcpThreadInterruptResult,
failure: OrchestratorMcpFailure,
failureMode: "return",
dependencies,
})
.annotate(Tool.Title, "Interrupt a T3 thread")
.annotate(Tool.Destructive, true);
export const OrchestratorToolkit = Toolkit.make(
OrchestratorCapabilitiesTool,
DelegateTaskTool,
TaskStatusTool,
TaskCancelTool,
ScheduleTaskTool,
ListScheduledTasksTool,
UpdateScheduledTaskTool,
DeleteScheduledTaskTool,
CreateThreadsTool,
ThreadStartTool,
ThreadListTool,
ThreadReadTool,
ThreadSendTool,
ThreadWaitTool,
ThreadInterruptTool,
);
@@ -0,0 +1,22 @@
import * as Effect from "effect/Effect";
import { McpInvocationContext } from "../../McpInvocationContext.ts";
import { WorktreeMcpService } from "../../WorktreeMcpService.ts";
import { WorktreeToolkit } from "./tools.ts";
const handlers = {
t3_worktree_handoff: (input) =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* WorktreeMcpService;
return yield* service.handoff(scope, input);
}),
t3_worktree_status: () =>
Effect.gen(function* () {
const scope = yield* McpInvocationContext;
const service = yield* WorktreeMcpService;
return yield* service.status(scope);
}),
} satisfies Parameters<typeof WorktreeToolkit.toLayer>[0];
export const WorktreeToolkitHandlersLive = WorktreeToolkit.toLayer(handlers);
@@ -0,0 +1,136 @@
import { expect, it } from "@effect/vitest";
import { NodeHttpServer } from "@effect/platform-node";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { HttpBody, HttpClient, HttpRouter } from "effect/unstable/http";
import * as ServerEnvironment from "../../../environment/ServerEnvironment.ts";
import * as GitWorkflowService from "../../../git/GitWorkflowService.ts";
import { ThreadManagementService } from "../../../orchestration-v2/ThreadManagementService.ts";
import * as ProjectService from "../../../project/ProjectService.ts";
import * as ProjectSetupScriptRunner from "../../../project/ProjectSetupScriptRunner.ts";
import { ProviderRegistry } from "../../../provider/Services/ProviderRegistry.ts";
import { ScheduledTaskService } from "../../../scheduledTasks/ScheduledTaskService.ts";
import * as ServerSettings from "../../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../../vcs/VcsStatusBroadcaster.ts";
import * as McpHttpServer from "../../McpHttpServer.ts";
import * as McpSessionRegistry from "../../McpSessionRegistry.ts";
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
const StubServicesLive = Layer.mergeAll(
Layer.mock(ThreadManagementService)({}),
Layer.mock(ProviderRegistry)({}),
Layer.mock(ScheduledTaskService)({}),
Layer.mock(ProjectService.ProjectService)({}),
ServerSettings.layerTest({}),
Layer.mock(GitWorkflowService.GitWorkflowService)({}),
Layer.mock(ProjectSetupScriptRunner.ProjectSetupScriptRunner)({}),
Layer.mock(VcsStatusBroadcaster)({}),
);
it.effect("production mcp layer lists worktree tools over http", () =>
Effect.scoped(
Effect.gen(function* () {
const routes = McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer));
yield* HttpRouter.serve(routes, {
disableListenLog: true,
disableLogger: true,
}).pipe(
Layer.provide(
Layer.mock(ServerEnvironment.ServerEnvironment)({
getEnvironmentId: Effect.succeed("environment-scratch" as never),
}),
),
Layer.provide(PreviewAutomationBroker.layer),
Layer.provide(StubServicesLive),
Layer.build,
);
const registry = McpSessionRegistry.issueActiveMcpCredential({
threadId: ThreadId.make("thread-scratch"),
providerInstanceId: ProviderInstanceId.make("claudeAgent"),
});
const credential = yield* registry;
expect(credential).toBeDefined();
const httpClient = yield* HttpClient.HttpClient;
const auth = credential!.config.authorizationHeader;
const initResponse = yield* httpClient.post("/mcp", {
headers: {
accept: "application/json, text/event-stream",
authorization: auth,
},
body: HttpBody.text(
`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"scratch","version":"1.0.0"}}}`,
"application/json",
),
});
expect(initResponse.status).toBe(200);
const sessionId = initResponse.headers["mcp-session-id"];
const listResponse = yield* httpClient.post("/mcp", {
headers: {
accept: "application/json, text/event-stream",
authorization: auth,
...(sessionId ? { "mcp-session-id": sessionId } : {}),
},
body: HttpBody.text(
`{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}`,
"application/json",
),
});
const bodyText = yield* listResponse.text;
const ToolsListPayload = Schema.fromJsonString(
Schema.Struct({
result: Schema.Struct({
tools: Schema.Array(
Schema.Struct({
name: Schema.String,
inputSchema: Schema.Struct({ type: Schema.optional(Schema.String) }),
annotations: Schema.optional(
Schema.Struct({
readOnlyHint: Schema.optional(Schema.Boolean),
destructiveHint: Schema.optional(Schema.Boolean),
openWorldHint: Schema.optional(Schema.Boolean),
}),
),
}),
),
}),
}),
);
const payload = yield* Schema.decodeUnknownEffect(ToolsListPayload)(
bodyText.match(/\{.*\}/s)![0],
);
const tools = payload.result.tools;
const toolNames = tools.map((tool) => tool.name);
expect(toolNames).toContain("t3_worktree_handoff");
expect(toolNames).toContain("t3_worktree_status");
// The worktree registration merges alongside the other toolkits rather
// than replacing them.
expect(toolNames).toContain("preview_status");
expect(toolNames).toContain("delegate_task");
// The handoff tool mutates thread state, reaches the network (origin
// fetch), and runs project setup scripts, so its MCP hints must not
// promise a read-only, closed-world, non-destructive tool.
const handoff = tools.find((tool) => tool.name === "t3_worktree_handoff");
expect(handoff?.annotations?.readOnlyHint).toBe(false);
expect(handoff?.annotations?.destructiveHint).toBe(true);
expect(handoff?.annotations?.openWorldHint).toBe(true);
const status = tools.find((tool) => tool.name === "t3_worktree_status");
expect(status?.annotations?.readOnlyHint).toBe(true);
expect(status?.annotations?.destructiveHint).toBe(false);
// MCP requires every tool input schema to be a top-level object schema.
// A non-object schema (e.g. the anyOf produced by an empty
// Schema.Struct({})) makes clients reject the entire server.
for (const tool of tools) {
expect(tool.inputSchema.type, `inputSchema.type of ${tool.name}`).toBe("object");
}
}),
).pipe(Effect.provide(Layer.mergeAll(NodeHttpServer.layerTest, NodeServices.layer))),
);
Loaded 100 of 757 files, more files were not shown because too many files have changed in this diff. Show more