Compare commits

...
Author SHA1 Message Date
Julius MarmingeandClaude Fable 5 269e5a8f89 Tick audit plan item 6: collab subagents covered upstream
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:53:23 +02:00
Julius MarmingeandClaude Fable 5 b11bb00094 Update audit plan for the combined PR-stack restructure
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:52:08 +02:00
Julius MarmingeandClaude Fable 5 ac3dc22a5e Flush throttled subagent text in ACP finalizeTurn
After the turn ends the run fiber that routes child-thread events may be
gone, so text left to the coalescer's timer flush could drop the tail of
a subagent stream (cursor bugbot review finding on the coalescer).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:52:08 +02:00
Julius MarmingeandClaude Fable 5 63b64f489c Coalesce streamed ACP subagent assistant deltas before persistence
ACP streams a subagent's result per token, and emitSubagentAssistant
persisted a full-row message.updated + turn-item.updated event pair per
chunk — one 6KB grok subagent result amplified into ~2700 stored events,
14% of a whole session's event table (audit plan #10). Streamed chunks
now accumulate and emit at most once per 100ms window; the final text is
always flushed immediately on task completion, so the projection stays
exact. The grok_subagent_lineage fixture now asserts each child result
persists a single coalesced message.updated event (was one per chunk).

App-checked: a real streaming ACP result (4190 chars) persisted 4
message.updated events instead of thousands.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:52:08 +02:00
Julius MarmingeandClaude Fable 5 d17635201c Route shared codex app-server logs to the owning app thread
One codex app-server process multiplexes many app threads (the opener
plus every native subagent child), but the protocol logger froze the
opener's threadId at open time, so all traffic landed in the opener's
log file — and rotation of that busy file destroyed other threads'
native ground truth (audit plan #9, threads c878541b/de5f191a/68f7595b/
af66fc2c had no log file at all). The logger now resolves the target per
frame: it extracts the native thread id from each frame and looks it up
in a per-session route map seeded when a root turn or subagent thread
registers, falling back to the opener for unrouted frames.

App-verified with a real codex subagent spawn: the two subagent native
threads each got their own dedicated log file containing only their own
traffic (94 and 54 frames), where previously everything multiplexed into
the parent's file. Unit tests cover native-thread-id extraction across
decoded/raw frame shapes and the two-thread routing decision.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:52:08 +02:00
Julius MarmingeandClaude Fable 5 08bebb2472 Write runner.error frames to native provider logs on SDK failures
The native provider logs are the debugging ground truth, but SDK
rejections (query open, message stream, prompt offer, agent open,
run start/wait) raised errors without any log write — a failed turn
left the log ending mid-conversation with no explanation (audit plan
#4: neither of thread 721fc23c's failed turns was explainable from its
log). The Claude and Cursor runners now tap every fallible SDK boundary
and write a runner.error frame carrying the redacted cause chain.

App-verified: with a broken Claude binary the native log now records
`runner.error messages.stream | Claude Agent SDK query failed. ← Claude
Code native binary not found at ...` where it previously went silent.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:51:39 +02:00
Julius MarmingeandClaude Fable 5 0ac8024a02 Surface runtime-reconcile cancellations as visible turn items
A run cancelled by the startup/shutdown reconcile was indistinguishable
from a user cancel: the user's message simply never got an answer and no
explanation appeared anywhere (audit plan #5, threads 721fc23c and
48663fb7 — cursor crash and server restart both ate the turn silently).
The reconcile now appends a "Run interrupted" error item per terminalized
run carrying the reason ("Cancelled because the server restarted/shut
down before the provider work completed."), ordinal-appended after all
projected items to respect the thread-wide position uniqueness.

App-verified: killed the backend mid-turn; after restart the thread
shows "Run interrupted — Cancelled because the server restarted before
the provider work completed."

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:51:39 +02:00
Julius MarmingeandClaude Fable 5 c86ed345a4 Add claude_text_segments regression fixture
Locks in per-uuid assistant text segmentation (audit plan #11): the
6d618dc4 MCP session on build fc23be8184 merged 5 interleaved assistant
text segments into one separator-less end-of-turn item ordered after all
tool calls. The current emitAssistantTextArtifacts path already projects
one item per SDK message uuid; this fixture asserts text → command → text
ordering survives replay.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:51:39 +02:00
Julius MarmingeandClaude Fable 5 cf23cc1dd1 Keep output/error on opencode file_search items
Failed read/grep/glob tools projected only {status: failed, pattern} —
the provider's error message was unrecoverable from projections, and
successful outputs were dropped too (audit plan #12, thread 3029dc85
item prt_f15692f3). The file_search contract gains optional output and
error fields; the OpenCode adapter maps part.state.output/error by
terminal status.

App-verified with a real OpenCode agent: a successful package.json read
projects the content in output, and a read of a nonexistent file
projects status failed with error "File not found: ...".

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:51:17 +02:00
Julius MarmingeandClaude Fable 5 7177ae1264 Persist cursor run correlation data on turn failures
A failed cursor turn projected only the generic "Provider turn failed."
because the adapter read a nonexistent `error` field off RunResult
(@cursor/sdk 1.0.22 carries no error text on results; errorCode lives
only in the SDK's internal run store). Persist what the result does
carry — run id, requestId, and duration — so failures can be matched to
Cursor-side logs (audit plan #3, thread c9e72a05 run 2 lost requestId
beca30c7 + 440s duration). The speculative `error` read stays as a
makeProviderFailure cause for future SDK versions.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:51:17 +02:00
Julius MarmingeandClaude Fable 5 20a1f53ae2 Preserve nested failure causes in projected provider errors
Adapter errors are tagged wrappers whose message getter is a fixed string
("Claude Agent SDK query failed.", "Failed to start run ...") while the
real defect lives in .cause — makeProviderFailure only read the wrapper,
so every failed run persisted a generic message with the root cause
recorded nowhere (audit plan #2: 8 undebuggable failures across 5
threads). makeProviderFailure now walks the cause chain (bounded depth,
deduped) and joins the messages, and picks up the deepest error code.
The run-execution failure log also prints the Cause pretty-formatted
instead of a depth-elided object.

App-verified: breaking the Claude binary path now projects
"Claude Agent SDK query failed. ← Claude Code native binary not found at
/tmp/nonexistent-claude-binary. ..." as the user-visible error item.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:51:17 +02:00
Julius MarmingeandClaude Fable 5 a0cdebce7e Add orchestration v2 audit remediation plan and findings
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-12 11:51:17 +02:00
Mike Olson c14c9088e3 [orchestrator-v2] fix(orchestrator): Codex background command completion and subagent resume (#3908) 2026-07-12 11:43:17 +02:00
798c458954 [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-12 11:42:49 +02:00
Mike Olson ea57e97d58 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-11 22:31:36 -04:00
Julius MarmingeandClaude Fable 5 92d2b60789 Merge origin/main into t3code/codex-turn-mapping
Ports main's features onto the V2 orchestrator and wire protocol:

- HTTP snapshot loading (#3719): new OrchestrationV2ThreadDetailSnapshot
  contract, /api/orchestration/{shell,threads/:threadId} endpoints served
  from the V2 engine (orchestration-v2/http.ts), afterSequence resume on
  the V2 subscribeShell/subscribeThread WS methods, and V2-typed client
  snapshot loaders wired into shell/thread sync with warm-cache resume.
- Thread cache now persists the snapshot sequence (cache schema v3) so
  warm caches resume via afterSequence instead of refetching.
- Mobile: main's react-navigation architecture retained; branch's V2
  surfaces (relationships banner, queue control, activity inspector,
  work-log thread links, fork-from-run) ported off expo-router; thread
  status presentation and awareness diagnostics mapped to V2 runtime
  fields; pending-task start-turn helper gains creationSource "mobile".
- Retired v1-only additions from main (v1 RPC schemas, session/latestTurn
  awareness heuristics, v1 engine test updates) where the branch already
  replaced those systems with V2 equivalents.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-07 16:50:21 -07: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
715 changed files with 113108 additions and 68486 deletions

No files matched your search

@@ -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
@@ -0,0 +1,958 @@
{
"sessionSummaries": [
{
"sessionKey": "GLOBAL",
"summary": "Global cross-thread audit of the v2 orchestrator DB (43,378 events across 63 streams, 6,286 turn items, 60 threads, 206 runs). Core invariants are healthy: event streams have zero version gaps/duplicates and no occurred_at regressions >5s; turn-item ordinals have zero collisions and are 100% consistent with orchestration_v2_turn_item_positions; no nativeItemRef duplicates; outbox (463 rows) and command receipts (580) are fully succeeded/accepted; all 12 failed runs surfaced exactly one user-visible error item; no items/runs stuck beyond the one currently-live run (started 17:03Z, audit ran 17:07Z). Findings are edge-case lineage danglers, generic error strings that discard the underlying cause, sessions left 'ready' after detach, and 13 old local_bash tasks projected as empty-prompt subagents.",
"stats": "43,378 events / 63 streams (0 version gaps, 0 dupes, 0 time regressions >5s); 6,286 turn items (6,042 completed, 243 failed, 2 interrupted, 1 running=live); 206 runs (188 completed, 12 failed, 4 cancelled, 1 interrupted, 1 running=live); 212 provider_turns; 19 provider_sessions (3 ready, 16 stopped); 40 subagents (38 completed, 2 failed); outbox 463 rows all 'succeeded'; receipts 580 all 'accepted'; 12 error items total. Loss sample: 258 native tool_use ids in latest 71e29ba5 log \u2192 all accounted for (254 direct items, 3 Agent spawns as subagent items, 1 in-flight run)."
},
{
"sessionKey": "a5a643b2-codex-heya",
"summary": "Small 4-run codex smoke session (\"heya\") on 2026-06-28 04:52-05:22 UTC, plus one delegated Claude task child thread. Core pipeline is healthy: all 19 main-thread items + 3 child items are projected with verbatim text, ordinals match turn_item_positions exactly, lineage (run/node/provider_turn refs, subagent -> child thread -> context-transfer -> handoff) fully resolves, and all runs/turns/nodes/items are terminal. Two real problems: the codex-native collab subagent spawned in run 3 left zero trace in ingested events (its wait tool call, web search, and final \"Hello.\" message are lost), and the run-4 delegated Claude task that failed with a 401 auth error is recorded as status \"completed\" everywhere because the adapter ignores is_error on subtype \"success\" results.",
"stats": "Main thread: 138 events, 19 projected items (19 distinct item ids in turn-item.updated events), 4 runs / 4 attempts / 4 provider turns, all completed. Child delegated-task thread: 27 events, 3 items, 1 run completed. Native log: 798 lines, 4 turn/start requests but 5 native turns (extra = codex-native subagent thread 019f0c93-d260), 22 item/completed across 2 native threads, 5 reasoning items (all empty summaries), 1 native error (401 auth, is_error:true result)."
},
{
"sessionKey": "a61e9269-codex",
"summary": "Short two-turn Codex session (\"hey\" then \"spawn a subagent and say hello\") that spawned one provider-native subagent thread. Pipeline health is very good: every user-visible native item (2 user messages, 2 assistant messages, webSearch, subAgentActivity, child assistant message) is ingested and projected with exact untruncated text; lineage is fully consistent (subagent item childThreadId -> child thread, forkedFrom points back to parent provider-thread/turn, provider_turns map to run_attempts); all runs/turns/nodes/items terminal completed matching the native turn/completed events; ordinals match orchestration_v2_turn_item_positions with no collisions or duplicates and projection order matches native emission order. Only gaps: an (empty) reasoning item and token-usage/rate-limit notifications are dropped by the adapter, which has no handlers for them.",
"stats": "Native (decoded, deduped): main thread 2 userMessage, 2 agentMessage, 1 subAgentActivity, 1 webSearch, 1 empty reasoning; child thread 1 agentMessage; 3 native turns all turn/completed; 0 native errors, 2 dev-feature warnings. Ingested: 74 events on main stream (versions 0-73, monotonic), 12 on child stream. Projected: 9 turn_items main (incl 2 synthetic checkpoints + workspace-preparation) + 1 child; 2 runs completed, 2 attempts completed, 3 provider_turns completed, 8 nodes completed; positions table matches item ordinals exactly, no duplicates."
},
{
"sessionKey": "20296b49-grok-tasks",
"summary": "Short grok session (2026-06-29 21:46-21:48): user said \"yoo\", then \"spawn some subagents\"; grok ran 3 parallel Task subagents (git state, architecture docs, mobile connection changes) as child threads and summarized. Pipeline health is good: all runs/attempts/provider-turns completed, provider session stopped, lineage intact, no ordinal collisions, no duplicates, no truncation (subagent item result lengths 3721/6274/2647 exactly match child assistant_message lengths). The children's 1319-2711 events vs 2 projected items is EXPECTED: each child has exactly 2 distinct item ids (prompt + result) and the event volume is per-token streaming re-upserts of the result item, not lost items.",
"stats": "Main thread: 300 events, 14 turn_items, 2 runs (both completed), 2 run_attempts, 2 provider_turns (completed), 9 subagent.updated events -> 3 subagent rows (completed). Children: 3 threads, 5717 events (1319/2711/1687), 2 items each (6 total, all completed), 6 position rows. Native log: 3702 lines (3694 protocol \u2014 payloads redacted to byteLength/itemCount, 8 request), 2 session/prompt \"failed\" (errorTag Interrupt), no other errors. Integrity: 0 bad run/node/turn/parent refs, 0 ordinal collisions, 0 nativeItemRef dupes, 0 timestamp regressions."
},
{
"sessionKey": "721fc23c-cursor",
"summary": "Short cursor (glm-5.2) session \"Hello therw!\" with 2 user turns and zero assistant output. The 7-line native log is genuine: the backend child process fatally crashed (Node error originating in @cursor/sdk/dist/esm/index.js) ~0.3s after run 1's run.started, killing the provider mid-turn; a startup reconcile then cancelled run 1. Run 2 (\"what did you just say\") resumed the agent but agent.send rejected 4ms after run.start and was projected as a failed run with only a generic error string; the process crashed again with the same @cursor/sdk fatal error 29s later. Projection internals (ordinals, positions, statuses, lineage forward-links) are consistent and all state is terminal \u2014 the problems are crash handling and error fidelity, not ingestion mechanics.",
"stats": "47 events on stream 721fc23c-... (seq 6271-6340, versions 0-46); 7 native log lines (all protocol/decoded, 0 assistant/tool output); 4 turn items (2 user_message, 1 command_execution \"Workspace ready\", 1 error); 2 runs (ordinal 1 cancelled, ordinal 2 failed); 2 messages (both user); 1 provider_turn (cancelled); 0 subagents/handoffs/transfers; 2 backend-child process crashes; 2 startup reconciles."
},
{
"sessionKey": "48663fb7-cursor",
"summary": "Thread 48663fb7 is a single \"hello\" message sent to the cursor provider (glm-5.2) at 2026-06-29T21:49:07Z. The provider session opened and acked run.started at 21:49:09.097Z, then the server restarted; a startup runtime-reconcile at 21:49:10.775Z cancelled the run/attempt/provider-turn, idled the provider thread, and stopped the session. Pipeline health is good: no native output was lost (the provider emitted nothing after run.started), lineage and ordinals are consistent, and nothing is stuck in a non-terminal state. The only gap is that the user got no assistant response and no explanation of why the run was cancelled.",
"stats": "Native log: 4 decoded protocol lines (agent.open/agent.opened/run.start/run.started), 0 provider output items, 0 errors. Events: 28 (stream_version 0-27, seq 6318-6346 excl. 6340). Projections: 1 run (cancelled), 1 attempt (cancelled), 1 provider_turn (cancelled), 1 node (cancelled), 2 turn_items (both completed), 1 message, 0 subagents, 0 child threads. Provider session: stopped; provider thread: idle."
},
{
"sessionKey": "3029dc85-opencode",
"summary": "Opencode chat session \"Hey!\" (2026-06-29 22:02-22:16, idle-reaped 22:46): 7 user turns spawning 5 native opencode subagent sessions, 2 cross-provider delegated claudeAgent tasks (results handed back via context-transfer/handoff), and 3 top-level threads (codex/grok/claude). Pipeline health is very good: all 9 runs/7 attempts/12 provider turns completed, every distinct item id in events has exactly one projection, ordinals match event arrival order with zero collisions or duplicates, lineage (run/node/provider-turn/subagent->child-thread) fully resolves, and the provider session was cleanly stopped after the 30-min idle window. Main issues found are debuggability gaps rather than data loss: the one failed tool call projected no error message (file_search items structurally cannot carry one), file_search outputs are never projected, a placeholder \"pending\" provider_thread row lingers, and the native log itself is payload-redacted so content-level verification is impossible.",
"stats": "Native log: 17,198 lines (15,542 part deltas, 723 part updates, 204 message updates, 7 promptAsync, 5 session.created, 12 session.idle; 0 error lines). Events: main 3,335 (1,047 turn-item.updated over 50 distinct items), opencode children 1051/1107/559/241/209, delegated-task children 94/34. Projected items: main 50, opencode children 185, delegated children 23 \u2014 every distinct event item id has exactly one projection (50/90/41/39/8/7 match 1:1). Runs: 7 main + 2 delegated, all completed; 7 attempts completed; 12 provider_turns completed; sessions stopped. 1 failed item (file_search), 0 stuck items, 0 ordinal collisions, 0 dangling run/node/turn/thread refs, 0 nativeItemRef dupes, positions table fully consistent."
},
{
"sessionKey": "9f8d616d-opencode",
"summary": "Single-turn opencode session ('hey' -> greeting reply) on 2026-06-29: 1 run, 1 provider turn, ~5s of activity, then 30min of heartbeats until the idle reaper stopped the session. The 100-events/5-items ratio is benign: 25 of the 33 turn-item.updated events are streaming updates of one reasoning part. No data loss, no duplicates, no ordering violations, no errors in the native log, and all runs/turns/items are terminal. Only minor findings: the pending-vs-resolved provider-thread dual-row pattern leaves run/attempt/turn pointing at a different provider_thread_id than the items, and the resolved provider-thread row lingered 'active' for ~20h after session stop before being marked idle.",
"stats": "Native log: 273 lines (180 heartbeats, 32 file.watcher, 31 part deltas, 7 part updates, 6 message updates, 1 session.idle, 0 errors). Ingested: 100 events (stream_version 0-99 contiguous, 100 distinct event_ids), incl. 33 turn-item.updated over exactly 5 distinct items. Projected: 5 turn_items (ordinals 1000001-1000005, positions table matches 1:1), 2 messages, 1 run + 1 attempt + 1 provider_turn (all completed), 3 nodes completed, 2 checkpoints, 0 subagents/children, provider_session stopped."
},
{
"sessionKey": "1156181e-delegated-task",
"summary": "MCP delegated task \"hello-opus-48\" sent one user prompt (\"Say hello briefly and stop.\") to claudeAgent (claude-opus-4-8). The API call never succeeded: the SDK logged two api_retry events with error_status 401 (authentication_failed) and then emitted a synthetic assistant message \"Failed to authenticate. API Error: 401 Invalid authentication credentials\" plus a result with subtype \"success\" but is_error:true / api_error_status:401. Ingestion and projection are structurally clean (all 3 items projected, ordinals consistent, lineage valid, nothing stuck), but the run/attempt/provider-turn were all recorded as \"completed\" with no failure info, so the delegated task looks successful despite executing zero tokens.",
"stats": "Native log: 10 decoded lines (1 query.open, 1 prompt.offer, 5 system incl. 2x api_retry 401, 1 synthetic assistant msg, 1 result is_error:true). Events: 30 (stream_version 0-29, sequences 116-168). Projections: 1 run, 1 attempt, 1 provider_turn, 2 messages, 3 turn_items (user_message, assistant_message, checkpoint), 0 child threads/subagents. Errors seen: 401 authentication_failed x3."
},
{
"sessionKey": "6d618dc4-mcp-group",
"summary": "MCP-driven fan-out session: 2 claudeAgent delegated-task threads plus 3 parallel MCP threads (codex :0, grok :1, claudeAgent :2), all single-run. Pipeline health is good overall: all 122 items verified against native logs with exact tool-call counts (19/19 on :2, 1/1 and 16/16 on the delegated tasks), ordinals fully consistent with turn_item_positions, zero lineage orphans, no duplicates, and the codex 400 model error was ingested verbatim and surfaced as a user-visible failed error item. Main defects found: the claudeAgent adapter (as of the code that ran, fc23be8184) concatenates intra-turn assistant text segments without separators into one end-of-turn item, destroying segment boundaries and native interleaving; and the three claudeAgent provider sessions were never idle-reaped, staying 'ready' for ~21 hours until a simultaneous shutdown sweep.",
"stats": "5 threads, 1842 ingested events (34/94/22/1587/105), 122 projected items (4/19/2/75/22), 5 runs (4 completed, 1 failed), 5 provider turns, 5 provider sessions (all stopped). Native: mcp log 3763 lines (grok 3158 / claude 499 / codex 106), delegated log 495 lines. 1 provider error (codex 400), 0 orphan run/node/provider_turn/parent references, 0 ordinal collisions, 0 nativeItemRef dupes, positions match 122/122."
},
{
"sessionKey": "5dcea72d-grok-subagent",
"summary": "Two-run grok session (\"spawn a subagent\"): run 1 asked the user clarifying questions (xai-question), spawned a background explore subagent; run 2 fetched its output via a blocking TaskOutput tool call and summarized it. Main-thread projections are complete and consistent (16 items, all completed, positions/ordinals match, no dupes, all terminal states correct, no backwards timestamps). The main problem is the subagent child thread: it froze at spawn time with a placeholder result, and the subagent's entire live transcript (116 tool calls over 74.9s) was never ingested \u2014 the real output survives only inside a parent-thread tool item.",
"stats": "Native log: 7028 lines, 3501 decoded incoming + 8 decoded outgoing protocol msgs, 10 request events (2 session/prompt terminations logged failed/Interrupt); payload contents are redacted (shape-only). Ingested: 257 events on main thread + 8 on child thread. Projected: 16 turn_items main + 2 child; 2 runs / 2 attempts / 2 provider_turns all completed; provider session stopped; provider thread idle; 1 subagent row (completed). 0 tool failures / rate limits observed."
},
{
"sessionKey": "7f1dfff1-claude-scheduled-tasks",
"summary": "Dev session on scheduled tasks: run 1 on codex, then a provider handoff to claudeAgent for runs 2-10 (8 completed, run 9 user-cancelled, run 10 failed 2s after query.open with no SDK response). Pipeline health is very good: zero lost native content in the claudeAgent portion, lineage fully intact, ordering matches native emission exactly, no duplicates, and nothing stuck non-terminal (session stopped, provider threads idle, 0 running items). The only real defect found is that run 10's failure was persisted with a hardcoded generic message, making it undebuggable from the DB.",
"stats": "Main thread: 1707 events, 363 items (169 codex run-1 + 194 claude), 69 messages, 10 runs, 10 provider turns (8 completed/1 cancelled/1 failed). 15 child threads: 2 Explore subagents (95+245 events, 20+50 items) + 13 bash-task threads (7-9 events, 2 items each); all child items completed. Native log 5336 lines (2 files, runs 2-10 only). Cross-checks: 156/156 main tool_use ids accounted for (154 toolu items + 2 Agent calls projected as task subagent items), 64/64 subagent tool_use ids, assistant text preserved exactly (27311 chars log = 27311 chars items), 94 thinking blocks all natively empty (SDK sends thinking_delta with empty text), 5/5 is_error tool_results projected as failed, 1 api_retry (recovered), 14 task_notifications + 1 task_updated-only completion (bqu8waxt3) all reconciled; 0 ordinal collisions, 0 position mismatches, 0 orphan lineage refs. All backgrounded-bash tasks completed within their runs, so cross-run/wakeup paths were not exercised in this session."
},
{
"sessionKey": "47763f5e-claude-fable",
"summary": "Long claudeAgent coding session (PR #3638 scheduled-tasks work, 20:56-23:43 UTC on 2026-07-01) with 16 runs, 2 Task subagents, and heavy post-turn wakeup activity via task notifications. The persisted portion of the pipeline is healthy \u2014 lineage, ordinals/positions, ordering vs native emission, terminal states, and text fidelity all check out \u2014 but roughly 40% of the provider's actual output (10 full post-turn wakeup turns: 16 assistant messages and ~84 tool calls, including real git pushes) was never ingested at all, this being one of the threads on which that gap was originally diagnosed. Two error-handling gaps stand out: a 401 auth failure projected as a completed run, and run 10's failure persisted only as 'Claude Agent SDK query failed.' with no root cause recorded anywhere.",
"stats": "Native log: 8088 lines (all protocol/decoded): 25 results, 594 assistant msgs (68 distinct main-thread text msgs, 122 with thinking), 371 unique tool_use (307 main / 64 child), 49 task_notification, 4 rate_limit (all 'allowed'), 3 query.open, 1 query.close. Ingested: 1546 events on main stream. Projected: 16 runs (15 completed, 1 failed), 16 provider_turns, 308 main items + 70 child items = 378 (positions table matches 378, no collisions/dupes), 68 messages, 2 subagents (both completed, child threads linked). Coverage gap: 84 tool calls + 16 assistant texts in log with no projection (all in wakeup windows); 0 items stuck running/streaming."
},
{
"sessionKey": "ea84f015-cursor-handoff",
"summary": "Long mixed-provider session (13 claudeAgent runs, then a clean claudeAgent\u2192cursor provider handoff at run 14, then 3 failed cursor runs) with two claudeAgent subagent child threads. Core pipeline health is good: ordering/positions are perfectly consistent, no duplicates, no stuck non-terminal items/nodes/messages, sampled long assistant text survives un-truncated, and handoff lineage (context-transfer consumed \u2192 handoff ready \u2192 run 14, thread.provider-switched) is fully intact. The big defect is the known 'invisible post-turn turns' problem: three post-run wakeup turns (10 and 17 native turns' worth of tool calls, including a GitHub comment being posted) produced zero events and zero projections. Secondary issues: 529-Overloaded turns (runs 11-13) projected as completed despite native is_error:true, and cursor run failures persisted with only a generic 'Provider turn failed.' string.",
"stats": "Events: 6482 (main) + 165 + 255 (two subagent child threads). Items: 695 main + 34 + 52 child; positions table matches 695/695 with zero ordinal collisions, zero duplicate nativeItemRefs. Runs: 17 total \u2014 13 claudeAgent completed, 1 cursor completed (14), 3 cursor failed (15/16/17; 15 had a superseded steering_restart attempt). 2 subagents, both completed and linked to child threads. Tool-call coverage: cursor run 15 window 51/51 projected; claudeAgent era 529 native tool_use ids, all projected except 42 post-turn-wakeup calls (lost) and 2 Agent spawns (correctly represented as subagent items). Nodes: 751, all terminal. Errors seen natively: 3 is_error results (529 Overloaded), 1 error_during_execution, 1 model_refusal_fallback, 29 api_retry, 3 cursor run status:error."
},
{
"sessionKey": "c9e72a05-cursor-failing-turns",
"summary": "Two-run cursor session (composer-2.5, fastMode) where the user asked why cursor turns fail; run 1 completed a full debugging pass, run 2 hung silently for 440s and failed \u2014 reproducing the very bug being investigated. The ingestion/projection pipeline itself is in excellent health: all 123 native tool calls plus reasoning/assistant text project 1:1 with exact character counts (3664/3664 assistant, 3382/3382 thinking), ordering matches native emission exactly, positions table is consistent (150/150, 0 ordinal mismatches or dupes), lineage refs all resolve, no stuck states (run/attempt/turn/node all 'failed' for run 2, session 'stopped' after agent.close), and timestamps are monotonic. The one substantive problem is error-handling fidelity: the run 2 failure is projected only as failure {message:\"Provider turn failed.\", code:null}, because CursorAdapterV2 reads a non-existent result.error and never surfaces the Cursor SDK's real error_code (an authentication error), dropping even the requestId/durationMs present in the decoded payload.",
"stats": "Native log: 1920 decoded protocol lines, 2 native runs (run-1cbebefe finished; run-f4d64e64 status error), 123 distinct tool calls (87 shell / 18 read / 14 grep / 4 glob; 118 natively completed), 17 thinking blocks, 3664 assistant chars, 3382 thinking chars. Ingested: 906 orchestration_events for the stream. Projected: 150 turn items (2 user_message, 5 assistant_message, 17 reasoning, 88 command_execution, 36 file_search, 1 checkpoint, 1 error), 2 runs (1 completed / 1 failed), 2 run attempts, 2 provider turns, 7 messages, 0 subagents/child threads. 1 provider failure seen (generic)."
},
{
"sessionKey": "8ee00dcc-cursor-spacing",
"summary": "Single-run Cursor (composer-2.5, fastMode) session: user asked to remove extra spacing on the mobile Threads/Home screen; the agent searched, read files, made 3 edits to HomeScreen.tsx, and summarized. The pipeline is essentially clean: every native item (33 tool calls, 10 thinking segments, 3 assistant messages, 1 user message) maps 1:1 to projected turn_items with exact content fidelity, ordinals are contiguous and match native emission order, all statuses reached terminal states, and no errors occurred in the native log. Only minor gaps found: token usage from the native turn-ended/run.completed is not ingested anywhere, and run_attempt.provider_turn_id is never backfilled.",
"stats": "Native log: 665 lines (all stage=decoded), 659 interaction.update (33 tool-call-started + 33 tool-call-completed, 10 thinking-completed, 94 text-delta, 107 thinking-delta, 377 token-delta, 3 partial-tool-call, 1 turn-ended, 1 step-completed) + run.start/started/completed + agent.open/opened/close. Events: 415 (stream versions 0-414 contiguous; 194 turn-item.updated, 194 node.updated). Projections: 49 turn_items (1 user_message, 1 workspace-prep command_execution, 3 assistant_message, 10 reasoning, 29 file_search, 3 file_change, 1 tool command_execution, 1 checkpoint), 49 positions, 1 run (completed), 1 attempt (completed), 1 provider_turn (completed), 4 messages. Zero errors in native log."
},
{
"sessionKey": "codex-no-native-logs",
"summary": "Four sibling codex threads multiplexed onto the shared codex app-server session ('provider-session:provider-instance:codex:shared'). The missing native logs are explained: the codex protocol logger is bound to the threadId that opened the shared session (71e29ba5, whose own codex native thread is 019f1b50), so all four threads' traffic went to 71e29ba5's log file and was mostly rotated away by that thread's heavy claude traffic. Events-to-projections consistency is excellent: all 11 runs and provider turns terminal (10 completed, 1 user-interrupted with proper interrupt request/result items), zero lineage violations, zero ordinal collisions or duplicates, projection order matches native start order (verified against the surviving log window for c878541b runs 4-6), and message text verified byte-exact (1733/1733 chars). Only gaps: codex reasoning items (empty-content in this session) and one contextCompaction item are not projected at all.",
"stats": "4 sibling codex threads (not parent/child; 0 subagent rows), 1797 events total (1077/468/222/30), 11 runs (10 completed, 1 interrupted), 440 turn_items (117 assistant_message, 264 command_execution incl. 20 failed, 18 file_change, 8 dynamic_tool, 12 user_message, 11 checkpoint, 2 interrupt items), 129 messages sampled on c878541b (61 assistant/7 user = item counts). 0 lineage violations, 0 ordinal collisions, 0 native-ref dupes, 0 non-terminal items/runs/turns/nodes. Native log survives only for c878541b runs 4-6 (16:00-16:44Z window)."
},
{
"sessionKey": "71e29ba5-claude-mega",
"summary": "Largest session in the store: the wakeup/blur dev thread, started on codex (runs 1-55), provider-switched to claudeAgent via a ready context handoff (runs 56-122), spawning 7 claude subagent child threads; still live during the audit (run 122 completed mid-audit at 17:13:36Z). In-run ingestion is very healthy: ordinals/positions are perfectly consistent across main + child threads with zero collisions or dangling lineage refs, projection order exactly matches native emission (run 121 verified item-by-item), no duplicates, no stuck items/turns/streaming messages, and all failed runs and user-interrupted subagents are surfaced with error/failed items. The two significant problems are both loss-of-data outside run windows: 76 completed claudeAgent tool calls plus assistant text from post-turn task_notification wakeup turns were never ingested (the known invisible-post-turn-turns bug this thread was used to develop the fix for \u2014 no provider_wakeup runs exist here), and a 30-minute codex-era ingestion gap (16:10-16:40 Jul 1) lost 119 command/fileChange items with only assistant text later backfilled at a single flattened timestamp.",
"stats": "Main thread: 14259 events (seq 13799-43607, still live during audit), 3390 projected turn_items (922 assistant_message, 1658 command_execution, 345 file_change, 144 dynamic_tool, 26 web_search, 7 subagent, 4 error, 169 user_message, 117 checkpoint, 1 handoff), 1091 messages, 122 runs = 122 provider_turns (117 completed / 4 failed / 1 cancelled, statuses exactly aligned). 7 subagent child threads (not 9): 79-260 events and 17-53 items each, 214 child items total. Native logs cover only 2026-07-01T16:00:59Z onward (~50k lines, 11 files; earlier rotations deleted). Claude era: 1130 native toolu ids vs 1045 projected (76 lost in wakeup gaps, 7 Agent-remapped, 2 in-flight). Codex era (in-log): 450 native call ids, 119 unprojected. 4 native error_during_execution, 2 orchestrator transport failures, 1 user cancel, 2 user-interrupted subagents."
}
],
"confirmed": [
{
"title": "Codex-native collab subagent (run 3) entirely missing from events and projections",
"category": "lost-data",
"severity": "high",
"confidence": "high",
"knownIssue": false,
"evidence": "User prompt run 3 was 'spawn a subagent'. Native log a5a643b2-...log shows: item/completed subAgentActivity call_9wPxyaS7ueh1MXl7XJt6zysq (kind 'started', agentThreadId 019f0c93-d260-7740-a477-0c0d19e8b299, agentPath /root/hello_agent) at 2026-06-28T04:54:02.530Z; collabAgentToolCall call_DO2fwaX8dQlHoNipTbnPWxIX (tool 'wait', inProgress 04:54:04.013Z -> completed 04:54:14.015Z); and on child native thread 019f0c93-d260: webSearch ws_08e14d73aa33777f016a40a8f75cd0819ba433374351c23d4f (query 'Codex OpenAI latest docs'), reasoning rs_08e14..., agentMessage msg_08e14d73aa33777f016a40a8fd816c819bbd856f295f6ce730 (text 'Hello.', completed 04:54:23, child turn 019f0c93-d421 completed 04:54:23.777Z -- AFTER parent run 3 finalized 04:54:15.874Z). SQL: 0 rows in orchestration_events for LIKE '%call_DO2fwaX8dQlHoNipTbnPWxIX%', '%call_9wPxyaS7ueh1MXl7XJt6zysq%', '%ws_08e14d73%', '%msg_08e14d73%', '%019f0c93-d260%'; orchestration_v2_projection_subagents has only the run-4 delegate-task row. Run 3 projected only user_message + 2 assistant messages + checkpoint; the parent assistant text ('Subagent spawned as /root/hello_agent. It hasn't returned within the short wait window yet.') is the only user-visible trace. Note: current CodexAdapterV2.ts (registerSubagentActivity/registerSubagentThreads, lines ~2815/2986; commits 3b864044c6 2026-06-28 'Adopt userdata-v2 and subagent activity mapping' and 57aa76ac14 2026-06-29) now maps these item types, so the session likely ran a pre-fix build -- but the historical data is unrecoverable and the child agent's post-run-completion output (arrived 8s after parent turn completed) remains a late-arrival hazard.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE payload_json LIKE '%call_DO2fwaX8dQlHoNipTbnPWxIX%' OR payload_json LIKE '%019f0c93-d260%'\" # returns 0; vs grep -c 'subAgentActivity\\|collabAgentToolCall' ~/.t3/userdata-v2/logs/provider/a5a643b2-6ca8-4250-9c54-ddefe7d55565.log",
"sessionKey": "a5a643b2-codex-heya",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Every evidence point reproduces: the native log contains subAgentActivity call_9wPxyaS7ueh1MXl7XJt6zysq, collabAgentToolCall call_DO2fwaX8dQlHoNipTbnPWxIX, and 29 child-thread (019f0c93-d260) lines including agentMessage msg_08e14d73 (\"Hello.\") at 04:54:23.755Z, while orchestration_events and all projections return 0 rows for every identifier; run 3 projected only user_message + 2 assistant messages + checkpoint, and the subagents table has only the run-4 delegate-task row. The child output also arrived 8s after run 3's projected completed_at (04:54:15.874Z), matching the late-arrival claim. So the data loss is real and unrecoverable. Severity adjusted to medium because the session predates fix commit 3b864044c6 (2026-06-28 17:58 PDT, ~20h after the session) and current CodexAdapterV2.ts (lines 2815/2986-2998) now maps both item types, so recurrence for these types is addressed; only the historical loss and an unverified late-arrival hazard remain."
}
},
{
"title": "Backend child process fatally crashed twice on @cursor/sdk, killing run 1 mid-turn with no user-visible error",
"category": "error-handling",
"severity": "high",
"confidence": "high",
"knownIssue": false,
"evidence": "server-child.log (~/.t3/userdata-v2/logs/server-child.log): stderr fatal-error dump referencing 'file:///Applications/T3 Code (Alpha).app/.../node_modules/@cursor/sdk/dist/esm/index.js:1' at 2026-06-29T21:48:20.166Z (0.33s after native run.started run-9d9ff525-e89c-41e3-90e6-1f7e841cc188 at 21:48:19.834Z) and again at 21:49:09.455Z (followed by 'Node.js v24.15.0' crash footer). Server restart at 21:48:21.35 logged 'V2 orchestration recovery completed { terminalizedRuns: 1, stoppedSessions: 2 }'. Reconcile events seq 6294-6299 (command:runtime-reconcile:startup...21:48:21.501Z) set run:thread:721fc23c...:ordinal:1, its attempt, and provider-turn run-9d9ff525 to 'cancelled'. Run 1 has no error/cancelled turn item \u2014 user asked 'Hello therw!' and got only the 'Workspace ready' item; the cancellation is silent (run status is the only signal). No assistant content was lost in the log sense (crash preceded any deltas), but the turn was killed by a server bug, not a user cancel, and is projected indistinguishably from a user cancellation.",
"repro": "grep -n 'cursor/sdk\\|terminalizedRuns' ~/.t3/userdata-v2/logs/server-child.log ; sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT event_type,occurred_at FROM orchestration_events WHERE stream_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND event_id LIKE '%runtime-reconcile%'\"",
"sessionKey": "721fc23c-cursor",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Every cited artifact reproduces: the @cursor/sdk fatal stderr dump at 21:48:20.166Z (0.33s after native run.started run-9d9ff525), a second fatal crash at 21:49:09.455Z with Node.js footer and child exit code=1, the recovery log 'terminalizedRuns: 1, stoppedSessions: 2', reconcile events seq 6294-6299 setting run 1/attempt/node/provider-turn to 'cancelled', and no error or cancelled turn item on run 1 (only user_message + workspace item). ProviderRuntimeRecoveryService.ts intentionally marks interrupted runs 'cancelled' and never persists its 'server restarted' detail string user-visibly, so the crash-induced kill is projected identically to a user cancel with zero debuggable trace \u2014 a real gap, though the terminalization itself is designed behavior. Downgraded to medium because recovery worked cleanly (nothing stuck, no assistant content lost since the crash preceded any deltas), and the finding slightly overstates impact: run 2's failure WAS surfaced with a visible provider_error item; only run 1 died silently."
}
},
{
"title": "401 authentication failure recorded as fully successful run \u2014 is_error on SDK result ignored",
"category": "error-handling",
"severity": "high",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log 2026-06-28T05:22:33.360Z: result payload has subtype:\"success\" but is_error:true, api_error_status:401, result:\"Failed to authenticate. API Error: 401 Invalid authentication credentials\", usage all zeros; preceded by two api_retry events (05:22:31.612Z, 05:22:32.312Z, error_status 401 authentication_failed). Projections: run run:...ordinal:1 status=completed (event seq 146, run.updated stream_version 27), run_attempt ...attempt:1 status=completed (seq 139), provider_turn ...attempt%3A1 status=completed (seq 138), assistant turn-item turn-item:provider:claudeAgent:native-item:03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc status=completed. No failure/error field anywhere in any payload_json; the only trace of the error is the synthetic assistant message text (which did survive verbatim, so it is user-visible as ordinary assistant text, not as an error state). Root cause: terminalStatusFromResult in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts:1652 returns \"completed\" whenever message.subtype === \"success\" and the failure branch at ~line 3254 only fires for non-success subtypes; is_error/api_error_status are never checked (only tool-result is_error at lines 1498-1500). An MCP delegate_task caller polling run status sees success for a task that never executed.",
"repro": "grep 'api_error_status' ~/.t3/userdata-v2/logs/provider/thread-delegated-task-command-3amcp-3a1156181e-e188-4fe4-8cc5-a294003ebfed-3adel.log ; sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status FROM orchestration_v2_projection_runs WHERE thread_id LIKE '%1156181e%';\"",
"sessionKey": "1156181e-delegated-task",
"verdict": {
"isReal": true,
"adjustedSeverity": "high",
"reasoning": "Every evidence point reproduces: the native log at 2026-06-28T05:22:33.360Z shows a result with subtype \"success\" but is_error:true, api_error_status:401, zero usage, preceded by two api_retry 401 authentication_failed events (05:22:31.612Z, 05:22:32.312Z); projections show run (seq 146), run_attempt (seq 139), provider_turn (seq 138) and assistant turn-item 03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc all status=completed with no failure field in any payload_json. The code claim is accurate: terminalStatusFromResult (ClaudeAdapterV2.ts:1658) returns \"completed\" for any subtype===\"success\" and the failure branch at ~3254 only fires for non-success subtypes, while the SDK's SDKResultSuccess type explicitly exposes is_error and api_error_status (sdk.d.ts:2739-2740) \u2014 so this is an ignored error signal, not an SDK ambiguity or intentional design. Severity high stands because this thread is a delegated MCP task whose caller consumes run status programmatically; an auth failure that executed zero turns is reported as a fully successful run, with the only trace being ordinary assistant text."
}
},
{
"title": "Subagent live transcript and final output never projected to its child thread",
"category": "lost-data",
"severity": "high",
"confidence": "high",
"knownIssue": false,
"evidence": "Child thread 'thread:provider:grok:native-thread:019f1b5f-efdb-7da0-acd7-1a31b3fe00bc%3Atask%3Acall-cdbbacb3-0c58-4992-86ce-7b549ffb16ce-1' has only 8 events (sequences 14437-14451, last stream_version 7 at 2026-07-01T01:52:10.705Z) and 2 turn_items, both timestamped at spawn (01:52:10). Its assistant_message item 'turn-item:provider:grok:native-item:call-cdbbacb3-...-1%3Aresult' contains only the bootstrap text 'Subagent started in background... Use get_command_or_subagent_output ... to wait for results.' Yet the task actually ran 01:52:10Z-01:53:25Z with tool_calls=116 (per TaskOutput result in parent item turn-item:provider:grok:native-item:019f1b5f...%3Atool%3Acall-5ca8a4be-6fc8-4924-909c-b198de7dcbc8-2). Native log shows 811 decoded incoming ACP messages between 01:52:14 and 01:52:59 (gap between run 1 Interrupt at 01:52:13.249 and run 2 start at 01:52:59.9) with ZERO orchestration_events ingested for any session stream in that window \u2014 the subagent's streamed activity was dropped, likely because AcpAdapterV2's subagent context (context.subagents / subagentsBySessionId / pendingSubagentNotifications in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts ~line 559) is per-active-turn and turn 1 had already finalized. The 15,053-char final output is preserved un-truncated ONLY inside the parent's turn-2 dynamic_tool item; a user opening the child thread 'Explore codebase structure and architecture' sees none of the subagent's work.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE occurred_at>'2026-07-01T01:52:13.4' AND occurred_at<'2026-07-01T01:52:59' AND (stream_id LIKE '%5dcea72d%' OR stream_id LIKE 'thread:provider:grok:native-thread:019f1b5f%');\" -- returns 0, vs grep of the log showing 811 decoded incoming messages in the same window",
"sessionKey": "5dcea72d-grok-subagent",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "All evidence reproduces: child thread has only 8 spawn-time events (seq 14437-14451, all 01:52:10Z) and its result item contains only bootstrap text; 0 orchestration_events exist in the 01:52:13.4-01:52:59 gap despite continuous decoded incoming traffic in the log; run 1 prompt failed with errorTag Interrupt at 01:52:13.249Z and the subagent ran to 01:53:25Z (116 tool_calls per parent TaskOutput item). Code intent confirms this is a bug, not design: AcpAdapterV2's emitSubagentAssistant/projectSubagentNotification/pendingSubagentNotifications (lines 845-882, 1447-1461) are built to stream subagent text into the child thread, but the per-turn context's finalized guard plus run 2's empty subagentsBySessionId map dropped everything; the subagent projection row is also frozen at spawn (completed_at 01:52:10.702Z, result=bootstrap text). Downgraded to medium because the full 15,053-char final output is preserved un-truncated and user-visible in the parent's turn-2 dynamic_tool item, and even happy-path design only projects assistant text chunks (not tool calls) to the child thread \u2014 the loss is the child-thread transcript and an accurate subagent row, not the final answer."
}
},
{
"title": "10 post-turn wakeup turns entirely unpersisted (16 assistant messages + 84 tool calls lost)",
"category": "lost-data",
"severity": "high",
"confidence": "high",
"knownIssue": true,
"evidence": "Native log has 25 result messages but only 16 runs exist. 10 results have no corresponding run/message/item: 21:19:42 ('CodeRabbit's final pass came back clean'), 22:14:37, 22:19:27, 22:25:18, 22:32:25, 22:38:55 (review-fix 'Rounds 3-7' incl. real git pushes 'a3c87931a2', 'cb28a0842f', 'c435bec111', '57ca73e655', 'd851eb7b9c'), 23:12:04, 23:17:19, 23:32:05 ('Round 11 pushed c19ceca8a5'), 23:41:55 ('Converged. PR #3638 is fully green'). Diff of tool_use ids in log vs nativeItemRef in projections: 86 missing (84 after excluding 2 Agent ids that are represented as task-id subagent items) \u2014 all timestamped inside wakeup windows (21:19, 22:13-22:38, 22:59:24-32, 23:11:24-34, 23:16-23:23, 23:29-23:31, 23:41). 16 native assistant text messages missing (uuids incl. 6299b5cf-7941-4355-8063-eb9d60d7216f @21:19:41, d226f500-43a0-489e-a1bd-888747c56495 @22:38:54, 093e91b9-0d5b-4ad9-a7a9-2ef06c4c2021 @23:41:52). Zero orchestration_events on the stream between 22:10:30 and 22:48:00 except one provider-session.updated (stopped) at 22:41:50.039Z. No run/message has inputIntent provider_wakeup; all 16 user messages have creationSource=web. This is the documented 'invisible post-turn turns' issue diagnosed on this exact thread (fix implemented later on branch t3code/codex-turn-mapping); this session's data predates the fix.",
"repro": "SELECT COUNT(*) FROM orchestration_events WHERE stream_id='47763f5e-76c1-4d67-8037-442a280f1514' AND occurred_at>'2026-07-01T22:10:30' AND occurred_at<'2026-07-01T22:48:00'; -- =1 (session stop only), while the native log shows 5 full result turns in that window: grep '\"type\":\"result\"' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1 | grep 'T22:[123]'",
"sessionKey": "47763f5e-claude-fable",
"verdict": {
"isReal": true,
"adjustedSeverity": "high",
"reasoning": "Every evidence point reproduces: 25 decoded result messages in the native log vs 16 projected runs, with the exact 10 cited orphan results unmatched by any run completed_at; the repro SQL returns 1 (only a provider-session stop at 22:41:50.039Z) for a window where the log shows 5 full turns; 86 top-level tool_use ids (371 in log vs 285 projected across all threads) are missing, all timestamped in the orphan-turn windows; cited assistant texts/uuids exist in the log but in zero projection rows; and no run/message carries provider_wakeup intent. This is real, substantial user-facing data loss (whole review-fix rounds with real git pushes invisible), matching the documented pre-fix \"invisible post-turn turns\" issue on this exact thread \u2014 known issue, but the lost session data is not backfilled by the fix, so high severity stands."
}
},
{
"title": "Invisible post-turn wakeup turns: 42 native tool calls + final assistant messages never ingested or projected",
"category": "lost-data",
"severity": "high",
"confidence": "high",
"knownIssue": true,
"evidence": "Three windows where the claudeAgent SDK kept working after the orchestrator closed the run: 23:31:27-23:36:48 (16 calls: Bash/Read/Edit/TaskCreate/TaskUpdate, after run 5 completed 23:30:07), 00:16:13-00:17:13 (9 calls, after run 6 completed 00:16:09), 00:33:32-00:37:24 (16 calls incl. mcp__t3-code__preview_* tools, after run 7 completed 00:33:22). Native results confirm full turns: [2026-07-02T00:17:51.602Z] subtype success num_turns:10 and [00:37:39.534Z] num_turns:17. Zero rows in orchestration_events for e.g. toolu_012dzkuS4eoKeRiAaQ3icFpD (Bash 00:17:05.797Z); zero main-stream events between 00:16:10 and 00:21:50. The wakeup turn's final assistant text 'Done \u2014 comment posted: https://github.com/pingdotgg/t3code/pull/2829#issuecomment-4861082710' (log.2, 00:17:4x) has 0 events and 0 turn_items \u2014 the agent posted a GitHub comment with no user-visible record. This is the diagnosed 'invisible post-turn turns' issue; the fix (turn.wakeup / ProviderWakeupService / attach_wakeup) is on this branch but this session ran on the pre-fix build (this thread is itself the diagnosis session, title 'check in on this thread: 47763f5e...').",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE payload_json LIKE '%toolu_012dzkuS4eoKeRiAaQ3icFpD%'\" -- returns 0; grep toolu_012dzkuS4eoKeRiAaQ3icFpD ~/.t3/userdata-v2/logs/provider/ea84f015-*.log.2 shows the Bash tool_use",
"sessionKey": "ea84f015-cursor-handoff",
"verdict": {
"isReal": true,
"adjustedSeverity": "high",
"reasoning": "Re-ran the full evidence trail: run 5/6/7 completion timestamps match, all 9 window-2 tool ids (e.g. toolu_012dzkuS4eoKeRiAaQ3icFpD) and 33 window-1/3 ids have zero rows in orchestration_events, zero main-stream events exist in all three gap windows, and the final assistant text with the posted GitHub comment URL (issuecomment-4861082710) has 0 events and 0 turn_items despite 4 native log occurrences with a success result (num_turns:10 at 00:17:51.602Z). Minor correction: 5 ids the finding attributed to window 1 belong to run 6 and were ingested, but the total lost count is still exactly 42. The session ran on the pre-fix build (the fix lives uncommitted on this branch), so whole turns including a real-world side effect were permanently lost with no user-visible record \u2014 real lost-data, correctly flagged as a known issue, severity stays high."
}
},
{
"title": "Cursor turn failure projected with only generic 'Provider turn failed.' \u2014 real error detail (auth error) never captured",
"category": "error-handling",
"severity": "high",
"confidence": "high",
"knownIssue": false,
"evidence": "Run 2 (native run-f4d64e64-0af6-42bc-8813-5b6ce53a328d) failed: native log line [2026-07-02T02:35:28.424Z] run.completed result {status:\"error\", requestId:\"beca30c7-7e90-481b-abf7-fdab84b3c48d\", durationMs:440732} \u2014 no error field in the decoded payload, and zero interaction.updates for the entire 440s turn (only run.started at 02:28:07.973Z then silence). Projected error item turn-item:provider:cursor:native-item:terminal-failure%3Aprovider-turn%3A...run-f4d64e64... (event seq 38493, occurred_at 2026-07-02T02:35:28.524Z) carries failure {class:\"provider_error\", message:\"Provider turn failed.\", code:null, retryable:null} \u2014 requestId and durationMs from the native payload are dropped too. Cause: CursorAdapterV2.ts:2165-2168 maps `cause: (result as { readonly error?: unknown }).error` which is undefined on the SDK RunResult, falling back to DEFAULT_PROVIDER_FAILURE_MESSAGE. The session's own in-turn diagnosis (final assistant item ...assistant%3Arun-1cbebefe...%3A5) confirmed the real cause lives only in the Cursor SDK store runs.error_code (\"Authentication error If you are logged in, try logging out and back in.\") which T3 never reads. The failure IS surfaced user-visibly (error item status failed, run/attempt/provider-turn all 'failed'), but with zero debuggable detail \u2014 this exact gap forced the user to spawn this debugging thread, and then recurred on the thread itself (run ordinal 2).",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND type='error';\" ; grep 'run.completed' ~/.t3/userdata-v2/logs/provider/c9e72a05-4c87-4dd5-b1b6-83834cc73afe.log | tail -1",
"sessionKey": "c9e72a05-cursor-failing-turns",
"verdict": {
"isReal": true,
"adjustedSeverity": "high",
"reasoning": "Fully reproduced: the projected error item for run-f4d64e64 carries only {\"message\":\"Provider turn failed.\",\"code\":null}, while the native log's run.completed (02:35:28.424Z, status \"error\", requestId beca30c7, durationMs 440732) confirms no detail was captured and requestId/durationMs were dropped. The cited code (CursorAdapterV2.ts:2165-2168) reads (result as {error?: unknown}).error, but @cursor/[email protected]'s RunResult type has no error field whatsoever \u2014 the fallback is guaranteed dead-code behavior for EVERY failed Cursor turn, and the SDK's public store API does expose RunRecord.errorCode (\"Authentication error...\") which T3 never reads. The failure is surfaced user-visibly with correct terminal states (so nothing is swallowed), but the projection retains zero debuggable detail for a systematic, provider-wide failure path, which matches the audit's explicit error-handling criterion; severity high stands."
}
},
{
"title": "Shared codex session native logs written to opener thread's file, not the active thread's \u2014 no log file ever created for these threads",
"category": "other",
"severity": "high",
"confidence": "high",
"knownIssue": false,
"evidence": "All four threads bind provider_session_id 'provider-session:provider-instance:codex:shared'. Their codex app-server protocol traffic appears in 71e29ba5-654b-4f67-b363-ad400e5bd016.log.6/.9/.10 (e.g. 019f1b62-f532 = c878541b's nativeThreadRef: 4768 hits in .log.10, 2828 in .log.9), interleaved with that thread's own claudeAgent and codex (019f1b50-4248) traffic. Cause: in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts, codexAppServerClientFactoryFromSettingsLayer.open builds makeCodexAppServerProtocolLogger({ nativeEventLogger, threadId: input.threadId, ... }) once per app-server process; EventNdjsonLogger.write routes to `${threadSegment}.log` from that frozen threadId, so every thread multiplexed onto the shared session logs under the opener's file. No file named c878541b-*/de5f191a-*/68f7595b-*/af66fc2c-* was ever created.",
"repro": "grep -l '019f1b62-f532' ~/.t3/userdata-v2/logs/provider/*.log* # hits only 71e29ba5-654b-...log.{6,9,10}, never a file named after the audited threads",
"sessionKey": "codex-no-native-logs",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Fully reproduced: all four threads bind provider-session:provider-instance:codex:shared; c878541b's nativeThreadRef 019f1b62-f532 appears exactly 4768x in 71e29ba5.log.10 and 2828x in .log.9 (interleaved with 71e29ba5's own codex ref 019f1b50-4248), and no log file named after any of the four threads exists. Code confirms the cause: CodexAdapterV2.ts line 1136 freezes input.threadId into makeCodexAppServerProtocolLogger at app-server open, so every multiplexed thread's protocol traffic routes to the opener's `${threadSegment}.log` \u2014 defeating EventNdjsonLogger's per-write threadId routing, so this is a misrouting bug, not intent. Downgraded to medium because ingestion/projections for these threads are intact (observability-only defect), though rotation under the busy opener file has permanently deleted 3 of 4 threads' protocol history."
}
},
{
"title": "Invisible post-turn wakeup turns (claudeAgent): 76 completed tool calls + assistant text never ingested or projected",
"category": "lost-data",
"severity": "high",
"confidence": "high",
"knownIssue": true,
"evidence": "1130 unique toolu_ ids in decoded native logs vs 1045 projected nativeItemRef ids. Of the 85 unmatched, 7 are Agent spawns (projected under task:<hash>:subagent ids, fine) and 2 are stream-only in-flight blocks; the remaining 76 (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup) ALL fall in gaps between run windows \u2014 0 fall inside any run. Example: run 56 completed 2026-07-01T22:18:57.958Z (result subtype=success 22:18:57.333Z); at 22:20:52.374Z 'system task_notification bk7bmoyti' re-woke the session, assistant emitted text 'The build failed \u2014 let me see the actual error.' (22:20:58.275Z) then Bash toolu_011YH7oQm6yGVjWTfxwQ1QsH (22:20:59, tool_result 22:21:00) etc. \u2014 none exist in orchestration_events or turn_items (LIKE search for that text returns 0). This thread has ZERO wakeup runs/messages (0 messages with inputIntent provider_wakeup / creationSource other than agent|provider,user|web), while 367 provider_wakeup events exist elsewhere in the DB (first at 2026-07-01T22:47:41) \u2014 this is the thread on which the fix was being developed (memory: diagnosed 2026-07-01 on threads 47763f5e & 71e29ba5).",
"repro": "comm -23 /tmp/native_toolu.txt /tmp/proj_toolu.txt (native ids from grep -h '\"stage\":\"decoded\"' ~/.t3/userdata-v2/logs/provider/71e29ba5-654b-4f67-b363-ad400e5bd016.log* | grep -o 'toolu_[A-Za-z0-9]*' vs SELECT json_extract(payload_json,'$.nativeItemRef.nativeId') FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%71e29ba5%')",
"sessionKey": "71e29ba5-claude-mega",
"verdict": {
"isReal": true,
"adjustedSeverity": "high",
"reasoning": "Re-ran the full evidence trail: 85 genuine claudeAgent tool_use ids in decoded native logs have no projection; after excluding 7 Agent spawns (verified projected as task:<hash> items) and 2 stream-only in-flight blocks, exactly 76 completed tool calls (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup) all fall in gaps between run windows (0 inside any of the 127 runs). The cited example reproduces: assistant text 'The build failed...' at 2026-07-01T22:20:58.275Z between run 56 (ended 22:18:57.958Z) and run 57 (started 22:22:38.734Z), with 0 matching rows in orchestration_events; the thread has 0 provider_wakeup events/messages while 367 exist elsewhere. This is the documented known issue the branch fixes, but for this session the provider-emitted tool calls, results, and assistant text are unrecoverably absent from ingestion and projections, with losses continuing into 2026-07-02 \u2014 real high-severity lost data, correctly flagged knownIssue=true."
}
},
{
"title": "Provider failures persist only generic error strings; underlying cause is unrecoverable from the DB",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "4 claudeAgent error items say only 'Claude Agent SDK query failed.' (class transport_error, code null) \u2014 e.g. run:thread:47763f5e-76c1-4d67-8037-442a280f1514:ordinal:10 failed 2026-07-01T22:48:38 with zero native-log traffic in that minute, so the real exception exists nowhere. Root cause: ClaudeAgentSdkQueryRunnerError.message getter in apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts:280 hardcodes the string and discards `cause`. Similarly 4 cursor items say 'Provider turn failed.' (code null) while the native run.completed carried status:'error' plus requestId d1cd7f44-91fb-45ce-bdd3-86e9b5cc8e3e and durationMs 2434335 that were dropped. Counter-example showing it can be done right: codex errors keep full detail ('stream disconnected before completion: error sending request for url (https://chatgpt.com/backend-api/codex/responses)' and the full 400 invalid_request_error body for gpt-5.3-codex).",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT thread_id, json_extract(payload_json,'$.failure.message') FROM orchestration_v2_projection_turn_items WHERE type='error';\"",
"sessionKey": "GLOBAL",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Reproduced the SQL: all 4 claudeAgent error items persist only 'Claude Agent SDK query failed.' (code/retryable null) and no richer detail exists in any orchestration_events row for those failures; the root cause is confirmed at ClaudeAdapterV2.ts:279-281 where the message getter hardcodes the string while the Schema.Defect cause field is discarded by makeProviderFailure (real exception goes only to Effect.logWarning). This is not intentional: ProviderFailure.ts has redaction/4096-char bounding built to persist real error text, and codex failures do persist full detail. Minor correction: the '47763f5e had zero native-log traffic at 22:48' claim is false (8 lines exist in .log.1, outgoing query.open/prompt.offer at 22:48:38.086), and the cursor generic message is partly upstream (native run.completed carried no error message, only requestId d1cd7f44/durationMs which were dropped) \u2014 but the core finding stands, so severity stays medium."
}
},
{
"title": "Delegated Claude task failed with 401 auth error but all statuses say 'completed' (is_error ignored on success-subtype result)",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Child native log thread-delegated-task-command-3amcp-3a1156181e-...log (2026-06-28T05:22:33Z) shows SDK result {\"type\":\"result\",\"subtype\":\"success\",\"is_error\":true,\"result\":\"Failed to authenticate. API Error: 401 Invalid authentication credentials\"}. Projections: child run run:thread:thread%3Adelegated-task%3Acommand%253Amcp%253A1156181e-...:ordinal:1 status=completed; provider_turn status=completed; subagent row node:delegated-task:command%3Amcp%3A1156181e-...%3Ahello-opus-48 status='completed' with result='Failed to authenticate...'; delegate_task tool item call_qV0wnlB5N6Osa6CPxTGN1Ajh output.status='completed'. Root cause in current code: ClaudeAdapterV2.ts terminalStatusFromResult (~line 1658) returns 'completed' whenever message.subtype==='success' without checking is_error, and the result handler (~line 3254) only attaches a ProviderFailure when subtype!=='success'. Mitigating: the error text IS preserved and user-visible (child assistant item 03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc text = the 401 message; parent's final assistant message msg_...9bb460 explains the failure), so nothing was swallowed -- but status semantics are wrong for anything filtering on failed tasks.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT status, json_extract(payload_json,'$.result') FROM orchestration_v2_projection_subagents WHERE subagent_id LIKE '%hello-opus-48%'\" # completed | Failed to authenticate. API Error: 401 ...",
"sessionKey": "a5a643b2-codex-heya",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Re-ran every evidence step: the child native log shows SDK result subtype=\"success\" with is_error=true and api_error_status=401 (zero tokens, \"Failed to authenticate. API Error: 401...\"), yet the child run, provider_turn, subagent row, and the parent's delegate_task item (call_qV0wnlB5N6Osa6CPxTGN1Ajh, output.status=\"completed\") all report completed. Source confirms the cause: ClaudeAdapterV2.ts terminalStatusFromResult (line 1658) returns \"completed\" on subtype===\"success\" without checking is_error, and the result handler (lines 3250-3263) only attaches a ProviderFailure when subtype!==\"success\" \u2014 is_error is checked only for tool results, so this is an oversight, not intent. Medium stands: the error text is preserved and user-visible, but status semantics are wrong end-to-end for anything filtering on failed delegated tasks."
}
},
{
"title": "Streaming deltas persisted as full-row event pairs cause ~2800x event amplification on child result items",
"category": "other",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Child thread ...composer_call_kFjs8 accumulated 2711 events (1352 turn-item.updated + 1352 message.updated + overhead) to stream a single 6274-char result; the 3 children total 5702 turn-item/message events for ~12.6KB of final text. This one 2-minute session wrote 6017 rows to orchestration_events (43k total table), i.e. each streaming delta is persisted as a full-row upsert event for both the turn item and its message. Not a correctness bug (final projections are correct) but a storage/replay-cost anomaly.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT event_type, COUNT(*) FROM orchestration_events WHERE stream_id LIKE 'thread:provider:grok:native-thread:019f1558%' GROUP BY 1;\"",
"sessionKey": "20296b49-grok-tasks",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Evidence reproduces exactly: 1352 turn-item.updated + 1352 message.updated events on the single kFjs8 result item with monotonically growing text (4 -> 6274 chars, sequences 2160-4862), and the session totals exactly 6017 event rows. Code confirms the mechanism: AcpAdapterV2.emitSubagentAssistant emits a full-row message+turn-item event pair per agent_message_chunk and ProviderEventIngestor persists each pair durably with no coalescing, throttling, or event-log pruning (ProjectionMaintenance only rebuilds projections by replaying the full log). Quantified: 18.0 MB of payload_json for ~12.6 KB of final subagent text (~1400x, quadratic in output length), 15.5% of the entire event table from one 2-minute session. Final projections are correct so severity stays medium, but the unbounded quadratic storage/replay cost is a real, unmitigated pipeline anomaly, not intended behavior or a misreading."
}
},
{
"title": "Run 2 failure projected with generic wrapper message; actual cause dropped from projection and depth-elided in server log",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Error turn item turn-item:provider:cursor:native-item:terminal-failure%3Aprovider-turn%3A...ordinal%25253A2... (ordinal 2000002, status failed, 21:48:40.703Z) persists failure = {class:'provider_error', message:'Failed to start run run:thread:721fc23c-2cf3-42bf-9d84-edd94359dca9:ordinal:2 on cursor provider thread provider-thread:provider:cursor:native-thread:pending%3A...', code:null, retryable:null}. That string is ProviderAdapterTurnStartError's message getter (apps/server/src/orchestration-v2/ProviderAdapter.ts:291); RunExecutionService.ts:830 builds the failure via makeProviderFailure({cause: Cause.squash(cause)}) so the tagged error's wrapped `cause` (the real agent.send rejection from CursorAgentSdk runnerError 'run.start') never reaches the projection. The only other record, server-child.log line 89 at 21:48:40.703Z, printed the cause as \"{ _id: 'Cause', failures: [ [Object] ] }\" \u2014 depth-elided. The underlying reason run 2 failed 4ms after run.start is now unrecoverable. Positive: the failure WAS surfaced user-visibly as an error item and run/attempt/node all show 'failed'.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND type='error'\" ; grep -n '721fc23c' ~/.t3/userdata-v2/logs/server-child.log",
"sessionKey": "721fc23c-cursor",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "All cited evidence reproduces: the projected error item and its source event (orchestration_events sequence 6314) both persist only ProviderAdapterTurnStartError's generic message getter (ProviderAdapter.ts:280-293); RunExecutionService.ts:~831 feeds Cause.squash(cause) into makeProviderFailure, which (ProviderFailure.ts:90-113) reads only .message/.code and never unwraps the nested cause defect that CursorAdapterV2.ts:2203 attaches. server-child.log line 89 depth-elides the cause as \"[ [Object] ]\" and the native provider log ends at the outgoing run.start (21:48:40.699Z) with no error event, so the real reason run 2 failed is unrecoverable from any persisted artifact. The failure was surfaced user-visibly with correct terminal statuses, so medium (not high) is the honest severity \u2014 this is a debuggability gap, not silent loss."
}
},
{
"title": "Native provider log never records failure frames \u2014 cursor SDK send errors and process death are invisible in the ground-truth log",
"category": "other",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log 721fc23c-2cf3-42bf-9d84-edd94359dca9.log ends at [2026-06-29T21:48:40.699Z] with outgoing run.start 'what did you just say' and no incoming frame, though the turn failed at 21:48:40.703Z. In Adapters/CursorAgentSdk.ts send(), the log writes cover outgoing run.start and incoming run.started/interaction.update/run.completed only; when agent.send rejects, Effect.tryPromise raises runnerError(cause,'run.start') with no protocol log write. Similarly run 1 shows run.started at 21:48:19.834Z and then nothing \u2014 no error, no lifecycle/exit record \u2014 because the process crash killed the logger too. Result: the 'ground truth' log cannot explain either failed turn, which is exactly why this session looked suspicious (7 lines vs 47 events).",
"repro": "cat ~/.t3/userdata-v2/logs/provider/721fc23c-2cf3-42bf-9d84-edd94359dca9.log | tail -2 ; grep -n 'runnerError(cause, \"run.start\")' apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts",
"sessionKey": "721fc23c-cursor",
"verdict": {
"isReal": true,
"adjustedSeverity": "low",
"reasoning": "Evidence reproduces fully: the native log ends at 21:48:40.699Z with the outgoing run.start and no failure frame while events 6313-6315 record the run failing at 21:48:40.703Z, and CursorAgentSdk.ts's error paths (runnerError catches at lines 408/440; run.completed logged via success-only Effect.tap) confirm no error-frame logging exists \u2014 indeed no adapter has an error/lifecycle log kind at all. However, the pipeline did not swallow anything: the failure was ingested and user-surfaced as turn-item 6314 (type error, status failed) with correct terminal statuses, and the raw cause is logged to the server application log (CursorAdapterV2.ts:2188 logWarning with cause), so this is an observability gap in the debug/protocol log (compounded by the generic projected message with code:null) rather than a data-loss or projection bug. Run 1's \"process crash\" explanation is unproven (DB shows cancelled, lastError null), so I downgrade to low: real, design-wide log-scope limitation worth fixing, but errors remain debuggable and user-visible through other channels."
}
},
{
"title": "Failed tool item drops the provider error message (file_search projection has no error/output field)",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Child thread ses_0ea978228: turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc (ordinal 87) went running->failed at 2026-06-29T22:04:02.915Z (events seq 8284 -> 8286 on stream thread:provider:opencode:native-thread:ses_0ea978228ffeVM6qpFUgGn62Vl). Final payload contains only {status:'failed', type:'file_search', pattern:'/Users/julius/Development/Work/codething-mvp/CLAUDE.md'} \u2014 no error text at all. Root cause in OpenCodeAdapterV2.ts: toolOutput() (line 659) returns part.state.error for status 'error', but the file_search branch (~line 1376) only maps 'pattern'; output/error is only attached for dynamic_tool. The contract (packages/contracts/src/orchestrationV2.ts line 841) also has no output/error field on file_search items, so the failure reason is unrecoverable from projections. Failure IS user-visible via status=failed, but not debuggable.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE turn_item_id='turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc';\"",
"sessionKey": "3029dc85-opencode",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Reproduced the exact projection payload (failed file_search item prt_f15692f30001qL66As1xsUCQXc, ordinal 87, no error text) and the running->failed transition at events seq 8284->8286. Source confirms the mechanism: OpenCodeAdapterV2.ts toolOutput() (line 659) extracts part.state.error, but the file_search branch (lines 1376-1383) only maps pattern \u2014 output/error is attached only for command_execution/dynamic_tool \u2014 and the contract's file_search schema (orchestrationV2.ts line 841) has no field to hold it. The native log is additionally redacted (protocol payloads logged as fieldCount summaries only), so the error message is unrecoverable anywhere; failure is visible via status=failed but not debuggable, so medium stands."
}
},
{
"title": "Claude assistant text segments merged without separator into a single end-of-turn item, losing interleaving",
"category": "lost-data",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Thread :2 native log has 5 assistant text blocks with distinct SDK uuids (341420a1 len 95 @22:09:54, 78f308a1 len 37 @22:09:58, 26b0aa8d len 90 @22:10:11, 31c4bfa0 len 73 @22:11:40, bfa7a134 len 10347 @22:13:07), interleaved with 19 tool calls. Projection has ONE assistant_message item turn-item:provider:claudeAgent:native-item:bfa7a134-04d5-4434-bb14-66927497fb91, ordinal 1000021 (after all tools), text length 10642 = exact sum, joined with no whitespace: '...read all the files thoroughly.I'll read all files in the directory.Let me gather context...'. The 4 intermediate uuids have ZERO orchestration_events (only seq 11544-11546 reference bfa7a134, all at 22:13:07). Root cause in code that ran (git fc23be8184 ClaudeAdapterV2.ts:2815): `context.assistant.text += assistantText.text` with single emission at result time; current worktree code (emitAssistantTextArtifacts per message.uuid) already emits per-segment items, so this appears fixed for future runs.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT substr(json_extract(payload_json,'$.text'),80,150) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%126456a2%:2' AND type='assistant_message';\"",
"sessionKey": "6d618dc4-mcp-group",
"verdict": {
"isReal": true,
"adjustedSeverity": "low",
"reasoning": "Reproduced every claim: native log has 5 assistant text blocks (lens 95/37/90/73/10347 at 22:09:54\u201322:13:07) but the projection has one assistant_message item (native ref bfa7a134, ordinal 1000021 after all 19 tools) of length 10642 = exact sum, joined with no separator (\"thoroughly.I'll read all files in the directory.Let me gather context\"); the 4 intermediate uuids have zero orchestration_events while bfa7a134 has seq 11544\u201311547. Historical code (fc23be8184 ClaudeAdapterV2.ts:2815 `context.assistant.text +=`) caused it; current worktree emitAssistantTextArtifacts emits per-nativeItemId, so it is fixed going forward. Real for this session's data, but downgraded to low because no text content was lost (only interleaving/segmentation) and the fix already landed."
}
},
{
"title": "Subagent projection marked completed at spawn with placeholder result (lifecycle wrong by ~75s)",
"category": "other",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "orchestration_v2_projection_subagents row 'node:provider:grok:native-item:call-cdbbacb3-0c58-4992-86ce-7b549ffb16ce-1' has status=completed, started_at=2026-07-01T01:52:10.677Z, completed_at=2026-07-01T01:52:10.702Z and result='Subagent started in background...\\nUse get_command_or_subagent_output...' \u2014 but the task's real lifetime was 01:52:10Z to 01:53:25Z (duration_secs 74.874 per the TaskOutput payload). The parent 'subagent' turn_item (ordinal 1000007) mirrors the same premature completedAt and placeholder result. Cause visible in AcpAdapterV2.emitSubagent (~lines 1047-1060): when the spawn tool returns 'started in background', taskStatus is non-running and update.result (the bootstrap text) is adopted as assistantText/result; nothing later updates it when the background task actually finishes.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, completed_at, substr(json_extract(payload_json,'$.result'),1,60) FROM orchestration_v2_projection_subagents WHERE thread_id='5dcea72d-15e1-4ded-922b-0b00c587de6c';\"",
"sessionKey": "5dcea72d-grok-subagent",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Reproduced end-to-end: projection row 'node:provider:grok:native-item:call-cdbbacb3-...-1' has status=completed, completed_at=2026-07-01T01:52:10.702Z with result='Subagent started in background...' while the TaskOutput payload (event seq 14622, 01:53:28.477Z, item call-5ca8a4be-...) shows the task actually ran 01:52:10Z-01:53:25Z (duration_secs 74.874); only 3 subagent.updated events exist, all at spawn time, so nothing ever corrects it. Code confirms the cause: extractXAiAcpSubagentUpdate (XAiAcpExtension.ts:86-91) maps the spawn tool's completed status straight to subagent status with no background-spawn detection, and AcpAdapterV2.ts:1047-1053 adopts the bootstrap text as assistantText/result; the later TaskOutput tool call is projected as an unrelated dynamic_tool item and never routed back to the subagent, and the child thread's only assistant message is also the placeholder. Severity stays medium: the real 15.5KB output survives user-visibly in the separate dynamic_tool item, but the subagent card's lifecycle, result, and child-thread transcript are wrong, and this Grok/ACP path is not covered by the claudeAgent backgrounded-task known issue."
}
},
{
"title": "Run 10 terminal failure persisted with only a generic error message",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Run run:thread:7f1dfff1-...:ordinal:10 failed at 2026-07-01T20:47:58.607Z. The projected error item (turn-item:provider:claudeAgent:native-item:terminal-failure%3A...ordinal%25253A10..., event seq 25810) has failure {class:\"transport_error\", message:\"Claude Agent SDK query failed.\", code:null, retryable:null}. run-attempt payload (seq 25811) carries no error detail either. Native log ends at 20:47:58.429Z with outgoing query.open + prompt.offer (user text \".\") and zero incoming SDK messages, so the DB retains no clue what actually failed. Root cause in code: ClaudeAdapterV2.ts:279-280 \u2014 ClaudeAgentSdkQueryRunnerError.message hardcodes \"Claude Agent SDK query failed.\" and the underlying `cause` defect is never propagated into the projected failure. The failure IS user-visible (error item + run failed), but is undebuggable after the fact.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='7f1dfff1-4cbb-450b-8514-764d11c903e1' AND type='error';\"",
"sessionKey": "7f1dfff1-claude-scheduled-tasks",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Re-ran the repro: the error turn-item (event seq 25810) and run-attempt (seq 25811) for run ordinal 10 persist only {class:\"transport_error\", message:\"Claude Agent SDK query failed.\", code:null}, and the native log truly ends at 20:47:58.429Z with outgoing query.open/prompt.offer and no incoming SDK data, so no error detail exists anywhere in DB or provider log. Code confirms the mechanism: ClaudeAgentSdkQueryRunnerError.message is hardcoded at ClaudeAdapterV2.ts:279-280 and makeProviderFailure (ProviderFailure.ts:97-100) reads exactly that getter, dropping the Schema.Defect cause; the real cause only reaches an ephemeral Effect.logWarning. Other adapters (e.g. OpenCodeAdapterV2.ts:2202) propagate real detail, so this is an unintended gap, not design \u2014 finding stands at medium since the failure is user-visible but undebuggable after the fact."
}
},
{
"title": "401 authentication error result projected as successful run + plain assistant message",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Native result at 2026-07-01T20:56:54.878Z has is_error=true with result 'Failed to authenticate. API Error: 401 Invalid authentication credentials'. Run run:thread:47763f5e-...:ordinal:1 is projected status='completed' (completed_at 20:56:54.916Z) and its provider_turn completed. The error text is user-visible only as a normal assistant_message (turn-item:provider:claudeAgent:native-item:94ed662f-814a-43d7-aad3-92e479b9dfe8, status=completed, type=assistant_message) \u2014 no error item, no failed status, so the run reads as a success.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status FROM orchestration_v2_projection_runs WHERE run_id='run:thread:47763f5e-76c1-4d67-8037-442a280f1514:ordinal:1';\" vs grep -m1 '\"type\":\"result\"' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1 (is_error:true)",
"sessionKey": "47763f5e-claude-fable",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Reproduced fully: native result at 20:56:54.878Z has subtype \"success\" with is_error:true and api_error_status:401, yet run ordinal:1 and its provider_turn are projected status=completed, and the error text survives only as a plain completed assistant_message item (94ed662f, itself the SDK's synthetic \"<synthetic>\"-model assistant message). Code confirms this is a gap, not intent: terminalStatusFromResult in ClaudeAdapterV2.ts only inspects message.subtype and the failure payload is attached only for non-\"success\" subtypes; is_error/api_error_status on result messages are never checked. The error text is user-visible via the SDK's synthetic message, but the run's structured status misreports failure as success and the 401 detail is not persisted, so medium severity stands."
}
},
{
"title": "Run 10 failure persisted with generic message only \u2014 no root cause anywhere",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Run ordinal:10 failed in 0.5s (requested 22:48:37.674Z, completed 22:48:38.293Z). The only error record is the error turn-item terminal-failure...ordinal%25253A10 with failure {class:'transport_error', message:'Claude Agent SDK query failed.', code:null, retryable:null}. The native log contains no error detail either \u2014 line 6324 (.log.1) shows the outgoing query.open at 22:48:38.086Z using create-style param sessionId:'b896a082-a480-416f-8ffd-c42845e71993' (after the session was closed at 22:41:50), then nothing incoming; the retry run 11 at 22:48:55.300Z used resume:'b896a082...' and succeeded. The actual SDK failure reason was never captured, and the failed open plausibly stems from reopening with sessionId instead of resume. Related: the query.close at 22:41:50 came ~31.8 min after run 9 completed (22:10:01) despite native wakeup activity through 22:38:55 \u2014 consistent with the known idle-session-reaper-vs-wakeup issue.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514' AND type='error';\" and sed -n '6323,6327p' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1",
"sessionKey": "47763f5e-claude-fable",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Fully reproduced: run ordinal:10 failed in ~0.6s and the only persisted failure anywhere (turn-item event seq 29464) is the generic {class:transport_error, message:'Claude Agent SDK query failed.'}; the native log (.log.1 lines 6324-6325) shows query.open at 22:48:38.086Z with create-style sessionId after the 22:41:50 query.close, no incoming lines, then a successful resume-based retry at 22:48:55. The genericness is by construction: ClaudeAgentSdkQueryRunnerError (ClaudeAdapterV2.ts:279-281) hardcodes its .message getter, defeating makeProviderFailure's cause.message extraction (ProviderFailure.ts), whose redaction/4096-char bounding shows real messages were intended to flow through. Even the fallback Effect.logWarning (server-child.log:457) collapsed the cause to '[Object]', so the root cause is unrecoverable from every persisted artifact \u2014 a real error-handling gap, though user-visibly surfaced and recovered by retry, so medium stands."
}
},
{
"title": "Runs 11-13 projected as 'completed' although native result had is_error:true (API 529 Overloaded)",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Native results in log.2: [2026-07-02T00:51:30.884Z], [00:55:19.085Z], [01:00:28.143Z] all 'subtype':'success','is_error':true,'num_turns':1 (preceded by 29 api_retry 'overloaded' events and one model_refusal_fallback at 00:51:30.857Z). Projections: runs ordinal 11/12/13 status 'completed', provider_turns 'completed'. The only user-visible signal is that the SDK emitted the error text as an assistant message (turn-item:provider:claudeAgent:native-item:9c0cead6-f253-44c8-8cc7-3c95b58a326e, run 13, text 'API Error: 529 Overloaded...'; run 11 item text 'API Error: Overloaded'). Run/attempt/turn statuses do not reflect the failure, so downstream logic treating these runs as successful is wrong.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT run_id,status FROM orchestration_v2_projection_runs WHERE run_id LIKE '%ea84f015%ordinal:1_' \" vs grep '\"is_error\":true' ~/.t3/userdata-v2/logs/provider/ea84f015-*.log.2",
"sessionKey": "ea84f015-cursor-handoff",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Evidence fully reproduces: log.2 has three decoded results with subtype 'success' but is_error:true (00:51:30.884Z 'API Error: Overloaded', 00:55:19.085Z api_error_status:529, 01:00:28.143Z), while runs ordinal 11/12/13 and their provider_turns project as 'completed' with matching completed_at timestamps, and the only trace is the error text projected as a completed assistant_message (item 9c0cead6-... on run 13). Code confirms the gap: terminalStatusFromResult in ClaudeAdapterV2.ts returns 'completed' for any subtype==='success' and attaches a failure payload only for non-success subtypes, even though the SDK's SDKResultSuccess type explicitly carries is_error and api_error_status \u2014 the signal is typed and available but ignored, so this is a real mapping bug, not intended behavior. Severity stays medium: the error is user-visible as assistant text, but structured run/attempt/turn statuses misreport success and the 529 detail is not queryable, which misleads any downstream logic."
}
},
{
"title": "Native ground truth for most of the session destroyed by rotation of the opener thread's log",
"category": "lost-data",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Because codex traffic shares 71e29ba5's high-churn log (10 files x 10MB), the oldest surviving rotation (71e29ba5-...log.10) starts 2026-07-01T16:00:59.024Z. Everything earlier is deleted: c878541b runs 1-3 (01:54-15:58Z), all of de5f191a runs 1-3 (07:42-15:49Z), all of 68f7595b (05:53-05:56Z) and af66fc2c incl. its interrupted run (05:52-05:53Z). Only c878541b runs 4-6 (16:00-16:44Z) retain native logs. Consequence of the finding above; debuggability loss only \u2014 projections for the lost window exist and are internally consistent.",
"repro": "for f in ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log*; do head -1 \"$f\" | cut -c2-25; done # earliest = 2026-07-01T16:00:59.024Z",
"sessionKey": "codex-no-native-logs",
"verdict": {
"isReal": true,
"adjustedSeverity": "low",
"reasoning": "Evidence fully reproduces: oldest surviving rotation (71e29ba5-...log.10) starts 2026-07-01T16:00:59.024Z; DB run windows confirm c878541b runs 1-3, all of de5f191a/68f7595b/af66fc2c predate it; native item ids from c878541b run 1 (msg_024da2f2..., call_z8cGFhrA...) appear in zero log files while run 4's msg_0e493c0caf68... appears 82x in .log.10, and no dedicated logs exist for the codex threads because CodexAdapterV2's protocol logger is keyed to the shared session's opener thread. Downgraded to low: the loss is a by-design consequence of intentional bounded rotation (10x10MB in EventNdjsonLogger.ts), the durable pipeline record (events + projections) for the lost window is intact and consistent, and the actual defect (codex traffic sharing a high-churn foreign thread's rotation budget) is the parent finding this one merely derives from."
}
},
{
"title": "Terminal-failure error items carry only generic message ('Claude Agent SDK query failed.'), underlying cause not preserved",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "All 4 failed runs (37, 54 codex; 89, 119 claudeAgent) DO get a user-visible type='error' item (good surfacing), but payload is generic: run 119 item failure = {class:'transport_error', message:'Claude Agent SDK query failed.', code:null, retryable:null}, title 'Provider error'. The native log at both claude failure sites (2026-07-02T04:47:07.200Z and 16:45:25.921Z) shows only outgoing query.open/prompt.offer with no captured error line, so neither projection nor provider log retains the actual failure reason \u2014 undebuggable after the fact.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure'), json_extract(payload_json,'$.title') FROM orchestration_v2_projection_turn_items WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND type='error'\"",
"sessionKey": "71e29ba5-claude-mega",
"verdict": {
"isReal": true,
"adjustedSeverity": "medium",
"reasoning": "Reproduced fully: claudeAgent failed runs 89/119 project only {class:'transport_error', message:'Claude Agent SDK query failed.', code:null} (event seq 43072), and the provider log at both failure sites (04:47:07.200Z log.2:790, 16:45:25.921Z log:3026) shows only outgoing query.open/prompt.offer with no error line. Source confirms the mechanism: ClaudeAgentSdkQueryRunnerError (ClaudeAdapterV2.ts:280) hardcodes its message getter while the real error lives in its cause Defect, which makeProviderFailure (ProviderFailure.ts:90) never unwraps \u2014 defeating the redaction/bounding machinery built to carry real messages (codex failures on this same thread DO carry specific messages, proving intent). The adapter's Effect.logWarning with the full cause was not found in any retained server trace log, so the failure reason is genuinely lost; medium severity stands since errors are surfaced but undebuggable."
}
}
],
"refuted": [
{
"title": "Orchestrator ingestion gap 16:10-16:40 Jul 1 (codex era): 119 native command/fileChange items lost; assistant messages backfilled with flattened timestamps",
"category": "lost-data",
"severity": "high",
"confidence": "high",
"knownIssue": true,
"evidence": "Zero orchestration_events for the stream between 2026-07-01T16:10:19 (run 50 completed) and 16:40:12 (run 51 requested), yet the native codex log shows substantive work in that window and around it: item/started fileChange items and commandExecutions incl. 'vp test .../OrchestratorReplayFixtures', 'vp check', 'git add apps/server/src/orchestration-v2/Adapters/Claude...' (call_0j3Wjk1K3an2l1CpCRgYBp8b 16:43:43) and 'git push origin t3code/codex-turn-mapping' (call_Hc9NQMOiQ9wo3by6RnzGbShQ 16:43:50), all with source 'unifiedExecStartup' on native thread 019f1b62-f532-79e2-9553-af817911965c. 119 of 450 native call_ ids have no projected turn_item (comm diff), all first seen 16:01-16:43 Jul 1. When run 51 started, 13 assistant messages (message:provider:codex:native-item:msg_*) were backfilled with IDENTICAL created_at 2026-07-01T16:40:14.821Z describing that missing work, but 0 turn_items have startedAt in 16:11-16:40. Text recovered, tool/file items and real timestamps lost. Mechanism (server down/restart vs codex turn-mapping bug) not fully determinable because logs older than 16:00:59Z were rotated away; loss itself is certain.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE stream_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND occurred_at BETWEEN '2026-07-01T16:11' AND '2026-07-01T16:39'\" -> 0; SELECT count(*) FROM orchestration_v2_projection_messages WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND created_at='2026-07-01T16:40:14.821Z' -> 13",
"sessionKey": "71e29ba5-claude-mega",
"verdict": {
"isReal": false,
"reasoning": "The \"lost\" work belongs to a different session: the codex provider session is shared, so this thread's log contains other threads' traffic. All gap-window log lines (1322 decoded events, 16:11-16:39) carry threadId 019f1b62-f532-..., which per orchestration_v2_projection_provider_threads is owned by thread c878541b-a832-..., not 71e29ba5 (whose codex nativeThreadRef is 019f1b50-4248-...). Exactly 119 call_ ids in the log belong to 019f1b62 and ALL 119 (including the cited call_0j3Wjk1K3an2l1CpCRgYBp8b and call_Hc9NQMOiQ9wo3by6RnzGbShQ) are projected on thread c878541b; all 62 call_ ids on this thread's own native id are projected on 71e29ba5 (comm diff = 0 both ways). The zero-event window is genuine idle time between run 50 (completed 16:10:19) and run 51 (requested 16:40:12), and the 13 messages at created_at 16:40:14.821Z are run 51's live-streamed assistant messages (e.g. msg_00c4d1e6... streamed at 16:48:38 on threadId 019f1b50) \u2014 every one of the 55 codex runs shows the same pattern of assistant messages sharing created_at = run start, so this is systematic projection behavior, not backfill of lost work."
}
},
{
"title": "All thinking/reasoning blocks dropped for main thread (122 native thinking messages, 0 reasoning items)",
"category": "lost-data",
"severity": "medium",
"confidence": "medium",
"knownIssue": false,
"evidence": "Native log contains 122 distinct main-thread assistant messages with thinking content blocks plus 646 'thinking_tokens' system events, but the main thread has zero projected reasoning turn-items (the only 2 'reasoning' items in the session are subagent-progress placeholders on the child threads, e.g. turn-item:...task%3Aac08aa451ed54d3f6%3Aprogress). ClaudeAdapterV2.ts only extracts part.type==='text' blocks (line 730: content.flatMap((part) => (part.type === \"text\" ? [part.text] : []))). May be an intentional product choice for claudeAgent, but it means no reasoning is ever visible/persisted for this provider.",
"repro": "cat log.1 log | jq 'select(.event.payload.type==\"assistant\" and .event.payload.parent_tool_use_id==null) | select([.event.payload.message.content[]?|select(.type==\"thinking\")]|length>0) | .event.payload.uuid' | sort -u | wc -l # 122, vs SELECT COUNT(*) FROM orchestration_v2_projection_turn_items WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514' AND type='reasoning'; -- 0",
"sessionKey": "47763f5e-claude-fable",
"verdict": {
"isReal": false,
"reasoning": "The counts reproduce (155 native thinking blocks, 0 projected reasoning items), but inspection of the actual block contents refutes the lost-data claim: every final thinking block in the native log is {\"thinking\":\"\",\"signature\":\"...\"} and all 593 thinking_delta stream events are {\"thinking\":\"\",\"estimated_tokens\":N} \u2014 the Claude Agent SDK redacted all thinking text at the source for claude-fable-5, so there was never any reasoning content to project. ClaudeAdapterV2.ts:730 extracting only text parts drops nothing user-visible here; projecting these blocks would produce 155 empty reasoning items. The 646 'thinking_tokens' system events are token telemetry, not content."
}
},
{
"title": "Failed cursor runs 15/16/17 keep only a generic 'Provider turn failed.' with code:null \u2014 no diagnostic detail persisted",
"category": "error-handling",
"severity": "medium",
"confidence": "high",
"knownIssue": false,
"evidence": "Error items exist and are user-visible (turn-item:provider:cursor:native-item:terminal-failure%3A...run-abf255cf / run-ceb09abc / run-f5fe7fcf, status failed, ordinals 15000098/16000002/17000002) but failure = {class:'provider_error', message:'Provider turn failed.', code:null, retryable:null}; run and run_attempt payloads contain no error field at all. Native run.completed results (log: 02:05:24.474Z, 02:16:37.138Z, 02:19:07.097Z) carry status:'error' with no message either \u2014 so cursor itself gave nothing \u2014 but available context (result.status, requestId d1cd7f44/55687657/6de8f367, durationMs 2434335/1223/657) was dropped. Run 15 did 40 min of work then errored; runs 16/17 ('continue') died in ~1s each with only 'Provider error' shown.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id='ea84f015-e597-4f79-9557-d39b5a895fba' AND type='error'\"",
"sessionKey": "ea84f015-cursor-handoff",
"verdict": {
"isReal": false,
"reasoning": "The evidence reproduces (three failed cursor runs projected with the generic 'Provider turn failed.' failure), but the native log shows cursor's run.completed results carried status:'error' with NO error/message/code field at all, so there was no provider diagnostic to persist. The code path is intentional: CursorAdapterV2 forwards result.error as cause, and makeProviderFailure (ProviderFailure.ts) extracts message/code when supplied, falling back to the tested DEFAULT_PROVIDER_FAILURE_MESSAGE \u2014 including an explicit test asserting arbitrary cause objects are deliberately not serialized. The 'dropped context' claim largely fails: result.status is persisted as failed on item/run/provider_turn, and durationMs is recoverable from the persisted provider_turn startedAt/completedAt (01:24:50.203Z\u219202:05:24.475Z \u2248 2434335ms); only cursor's requestId is unpersisted, which the ProviderFailure contract intentionally omits and which remains in the provider log. This is an upstream cursor SDK limitation plus a possible enhancement (persist requestId), not a pipeline discrepancy.",
"adjustedSeverity": "low"
}
}
],
"lowUnverified": [
{
"title": "Interrupt-result turn item references an interrupt-request parent that was never emitted",
"category": "lineage",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "turn_item 'turn-item:run:run%3Athread%3Aea84f015-e597-4f79-9557-d39b5a895fba%3Aordinal%3A15:signal:interrupt-result' (event seq 34176, 2026-07-02T01:24:49.393Z) has parent_item_id '...:signal:interrupt-request' with no matching row/event. Contrast thread af66fc2c-73cd-4c30-bea5-66932ecdba29 where both request (seq 20000) and result (seq 20003) were emitted. Code: makeInterruptResultTurnItem in apps/server/src/orchestration-v2/RunExecutionService.ts (line ~874) unconditionally derives parentItemId from the request id without ensuring that item was emitted; the request emission lives on a separate path in Orchestrator.ts:4422.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id, parent_item_id FROM orchestration_v2_projection_turn_items ti WHERE parent_item_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM orchestration_v2_projection_turn_items p WHERE p.turn_item_id=ti.parent_item_id);\"",
"sessionKey": "GLOBAL"
},
{
"title": "Synthesized terminal-failure error item references a provider_turn_id that was never projected",
"category": "lineage",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "turn_item 'turn-item:provider:cursor:native-item:terminal-failure%3A...' on thread 721fc23c-2cf3-42bf-9d84-edd94359dca9 (updated 2026-06-29T21:48:40.703Z) carries providerTurnId 'provider-turn:provider:cursor:native-turn:failed%3Arun-attempt%3A...ordinal%253A2%3Aattempt%3A1' which has no row in orchestration_v2_projection_provider_turns. The run failed 4ms after the outgoing run.start ('what did you just say', log 2026-06-29T21:48:40.699Z) with no incoming response; the synthetic 'failed' turn id was minted for the failure item but the turn itself never projected.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items ti WHERE ti.provider_turn_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM orchestration_v2_projection_provider_turns p WHERE p.provider_turn_id=ti.provider_turn_id);\"",
"sessionKey": "GLOBAL"
},
{
"title": "provider_sessions stay status='ready' after provider-session.detached (projection ignores detach)",
"category": "stuck-state",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Session provider-session:...claudeAgent:thread:47763f5e...:1c70abe8-4ecb-... got provider-session.detached event seq 31344 (2026-07-01T23:44:29.976Z, reason 'Thread archived.') and session ...ea84f015...:21ed85a2-... got detached seq 32566 (2026-07-02T01:03:00.273Z), yet both projection rows still show status='ready' with stale updated_at (22:48:37 / 22:12:31 \u2014 predating even later provider-session.updated events like seq 31274 at 23:42:43). The 16 'stopped' sessions were transitioned via updated events; detach alone leaves rows 'ready' indefinitely on archived threads.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT s.provider_session_id, s.status, s.updated_at FROM orchestration_v2_projection_provider_sessions s WHERE s.status='ready' AND EXISTS (SELECT 1 FROM orchestration_events e WHERE e.event_type='provider-session.detached' AND e.payload_json LIKE '%'||s.provider_session_id||'%');\"",
"sessionKey": "GLOBAL"
},
{
"title": "13 backgrounded local_bash tasks projected as subagents with empty prompts and synthetic child threads",
"category": "other",
"severity": "low",
"confidence": "high",
"knownIssue": true,
"evidence": "Thread 7f1dfff1-4cbb-450b-8514-764d11c903e1 run 2 (2026-07-01T15:51): tasks bw28jiyac, bzmkw8629, bnkw62tp7, etc. are task_type 'local_bash' in the native log (task_started has only a 'description' like 'vp run --filter @t3tools/web typecheck...', no prompt), yet each got a subagent row (prompt length 0), a child thread, and a user_message prompt item with text ''. Newer local_agent tasks (a-prefixed 16-hex ids) capture full prompts (1.9k-4.3k chars). Predates the backgrounded-Bash redesign on t3code/codex-turn-mapping where local_bash stays a running Bash item completed cross-run; these are stale artifacts of the old mapping, not current behavior.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE type='user_message' AND coalesce(json_extract(payload_json,'$.text'),'')='';\"",
"sessionKey": "GLOBAL"
},
{
"title": "Cursor stream stall: abandoned partial-tool-call finalized as 'completed'; provider retry duplicated assistant text",
"category": "duplicate",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Thread ea84f015 run 15: partial-tool-call toolu_01HgLigck78NC9MSVyjitDXe (edit) at log 2026-07-02T01:54:20.622Z never received tool-call-started/completed (stream stalled 6.5 min, cursor retried at 02:00:47 with new callId toolu_01NkWmCzHTn5ofjtYi4NkhsJ); the abandoned call's item 'turn-item:provider:cursor:native-item:toolu_01HgLigck78NC9MSVyjitDXe' (type file_change) was finalized status='completed' at run end (02:05:24.475Z) though the edit never executed. The retry also re-emitted identical assistant text ('Now the `WorkGroupSection` filter and the `SimpleWorkEntryRow` indicator.') producing items ...abf255cf...%3A6 (ordinal 15000077) and %3A7 (15000079) with duplicate visible text \u2014 faithful to two native text-delta emissions (log 01:54:19.813Z and 02:00:47.715Z), so provider-side, but rendered twice to the user.",
"repro": "grep -a 'SimpleWorkEntryRow\\` indicator' ~/.t3/userdata-v2/logs/provider/ea84f015-e597-4f79-9557-d39b5a895fba.log | cut -c1-30",
"sessionKey": "GLOBAL"
},
{
"title": "provider_turn status has no 'waiting' literal during ScheduleWakeup sleep loops",
"category": "stuck-state",
"severity": "low",
"confidence": "high",
"knownIssue": true,
"evidence": "Known issue per assignment; currently only 1 provider_turn 'running' (thread 71e29ba5, started 2026-07-02T17:03:04.470Z \u2014 genuinely live at audit time 17:07Z), so no stale instance observed in this pass, but the schema/status distribution confirms no 'waiting' state exists (statuses seen: cancelled/completed/failed/interrupted/running).",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, count(*) FROM orchestration_v2_projection_provider_turns GROUP BY status;\"",
"sessionKey": "GLOBAL"
},
{
"title": "Codex reasoning items never ingested (no content lost in this session: all summaries empty)",
"category": "lost-data",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Native log contains 5 reasoning item/completed events (e.g. rs_0cfa4cea83165175016a40a8e17de08199a84ec646c88a40cd run 2, rs_0cfa4cea...8c48/9052/9329 run 4), all with summary: []. SQL: 0 orchestration_events on stream a5a643b2-... with payload LIKE '%native-item:rs_%', and 0 turn_items of reasoning type with a codex provider_thread anywhere in the DB (172 reasoning items exist for other providers). CodexAdapterV2.ts has no reasoning item mapping (grep hits only 'reasoningEffort' config). With empty summaries nothing user-visible was lost here, and dropping empty reasoning may be intentional, but non-empty reasoning summaries would be silently dropped.",
"repro": "sed 's/^\\[[^]]*\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/a5a643b2-6ca8-4250-9c54-ddefe7d55565.log | jq -c 'select(.event.stage==\"decoded\") | .event.payload | select(.method==\"item/completed\" and .params.item.type==\"reasoning\")' | wc -l # 5, vs sqlite count 0",
"sessionKey": "a5a643b2-codex-heya"
},
{
"title": "Codex reasoning items are silently dropped by CodexAdapterV2 (no handler for item type \"reasoning\")",
"category": "lost-data",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log emits item/started + item/completed for reasoning item rs_056ea93bc8adc0f3016a42c0594d788194ad4afb537a0a0b16 at 2026-06-29T18:58:33.314Z/33.340Z (turn 019f14bf-4440-7bb0-9655-7194b384e690), but zero rows in orchestration_events reference it and no turn_item exists. Code confirms: CodexAdapterV2.ts item/started (line 2802) and item/completed (line 2875) handlers cover userMessage, subAgentActivity, commandExecution, mcpToolCall/dynamicToolCall, fileChange, webSearch, plan, collabAgentToolCall, agentMessage \u2014 no \"reasoning\" branch and no item/reasoning delta handler, despite capabilities declaring streamsReasoning: true (line 139). In THIS session the item had empty summary/content so no user-visible text was lost, hence severity low \u2014 but any non-empty reasoning summary would vanish.",
"repro": "grep 'rs_056ea93bc8adc0f3' ~/.t3/userdata-v2/logs/provider/a61e9269-0180-4f4c-988a-aca00b240469.log ; sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE payload_json LIKE '%rs_056ea93bc8adc0f3%'\" -- returns 0",
"sessionKey": "a61e9269-codex"
},
{
"title": "thread/tokenUsage/updated and account/rateLimits/updated notifications never ingested; runs have no usage data",
"category": "lost-data",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Native log contains 5 thread/tokenUsage/updated and 5 account/rateLimits/updated decoded notifications; CodexAdapterV2.ts registers no handler for either (only item/agentMessage/delta, item/plan/delta, turn/plan/updated, turn/started, item/started, item/completed, turn/completed at lines 2693-3395). Runs projection payload has usage:null for both run:thread:a61e9269-0180-4f4c-988a-aca00b240469:ordinal:1 and :2, and no orchestration_events row carries token usage. May be intentional scope, but per-turn token accounting from the provider is discarded.",
"repro": "sed 's/^\\[[^]]*\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/a61e9269-0180-4f4c-988a-aca00b240469.log | jq -r 'select(.event.stage==\"decoded\") | .event.payload.method' | grep -c tokenUsage",
"sessionKey": "a61e9269-codex"
},
{
"title": "Child task threads projecting only 2 items is intended, not data loss",
"category": "lost-data",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Each child stream (e.g. ...composer_call_kFjs8) has exactly 2 distinct turn-item ids across its 2711 events: ...%3Aprompt (user_message, 1 event) and ...%3Aresult (assistant_message, 1352 events growing text 4->6274 chars). Grok's ACP Task envelope only exposes rawInput.prompt plus streamed output text (apps/server/src/provider/acp/XAiAcpExtension.ts extractXAiAcpSubagentUpdate / xAiTaskOutputText), and the child's intermediate narration is contained in the streamed result text ('I'll read the connection files...'). Parent subagent items' result lengths (3721/6274/2647) exactly equal child assistant_message text lengths \u2014 nothing truncated.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.id'), COUNT(*), MAX(length(json_extract(payload_json,'$.text'))) FROM orchestration_events WHERE stream_id LIKE '%composer_call_kFjs8' AND event_type='turn-item.updated' GROUP BY 1;\"",
"sessionKey": "20296b49-grok-tasks"
},
{
"title": "Every successful grok turn logs session/prompt as failed with errorTag Interrupt",
"category": "error-handling",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log events ec0b4762-8c1d-41c9-b4b3-2687da09d40b (2026-06-29T21:46:13.448Z) and 5a4a5b58-40ad-4f71-b2de-6e703e0c9173 (21:47:37.827Z): payload {method:'session/prompt',status:'failed',errorTag:'Interrupt'} \u2014 yet both runs completed successfully (run ordinal 1 completedAt 21:46:13.476Z, ordinal 2 completedAt 21:47:38.686Z). Cause: XAiAcpExtension races the direct prompt request against the private _x.ai/session/prompt_complete fallback; the losing fiber is interrupted and logged as a failed request. Correctly NOT surfaced as a user-visible error (nothing to surface), but the 'failed' log entries are misleading noise for future debugging.",
"repro": "grep '\"status\":\"failed\"' ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log",
"sessionKey": "20296b49-grok-tasks"
},
{
"title": "Grok native log redacts all payload content, limiting ground-truth audits",
"category": "other",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "All 3694 protocol lines in ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log carry only shape summaries, e.g. payload {valueType:'string',byteLength:165} or {valueType:'array',itemCount:1} \u2014 no message text, tool names, or ids. Content-level loss/truncation verification against the provider is impossible from this log; verification here relied on internal consistency (event max text length == projection text length). If other providers' logs contain full JSON, grok's redaction is an inconsistency worth knowing about.",
"repro": "grep -c 'byteLength' ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log",
"sessionKey": "20296b49-grok-tasks"
},
{
"title": "Child task thread items carry null run_id/provider_thread_id/provider_turn_id",
"category": "lineage",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "All 6 child items have runId=null, providerThreadId=null, providerTurnId=null (e.g. turn-item ...composer_call_Olv1X%3Aprompt payload: runId:null, nodeId:'node:...%3Achild-root', creationSource:'provider'); child threads have zero run.created / provider-turn events. node_id resolves (child-root nodes exist) and the subagents projection links parent node -> child_thread_id, so navigation works via subagents rather than runs. Appears intentional for provider-native task children (no orchestrator run exists), but any consumer that groups items by run_id will see these as orphans.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id, run_id, provider_turn_id FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:grok:native-thread:019f1558%';\"",
"sessionKey": "20296b49-grok-tasks"
},
{
"title": "run_attempts.provider_turn_id is never populated (null for all 207 attempts DB-wide) \u2014 back-link from attempt to provider turn missing",
"category": "lineage",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "This session: run-attempt:run:run%3Athread%3A721fc23c...%3Aordinal%3A1:attempt:1 has providerTurnId:null although provider-turn:provider:cursor:native-turn:run-9d9ff525-e89c-41e3-90e6-1f7e841cc188 references that exact runAttemptId (forward link intact, nativeTurnRef strong). Global check: SELECT provider_turn_id IS NULL, count(*) FROM orchestration_v2_projection_run_attempts GROUP BY 1 shows every row (completed 188, failed 12, cancelled 4, interrupted 1, running 1, superseded 1) has NULL \u2014 the column/payload field exists but nothing ever writes it. Forward resolution via provider_turns.run_attempt_id works, so impact is limited to reverse-lookup ergonomics; may be intentional but the schema advertises the field.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, provider_turn_id IS NULL, count(*) FROM orchestration_v2_projection_run_attempts GROUP BY 1,2\"",
"sessionKey": "721fc23c-cursor"
},
{
"title": "Run orphaned by server restart is cancelled with no user-visible or persisted reason; user's message got no response",
"category": "error-handling",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log ends at run.started 2026-06-29T21:49:09.097Z (runId run-f062e5d9-534a-48a8-8214-48fea97bc268) with zero assistant output. Events seq 6341-6346 (command:runtime-reconcile:startup:48663fb7-...:2026-06-29T21:49:10.775Z) set run:thread:48663fb7-...:ordinal:1, its attempt, and provider-turn:provider:cursor:native-turn:run-f062e5d9-... to status 'cancelled' with no reason field in any payload, indistinguishable from a user cancel. No error/system turn_item was emitted, so the timeline shows only the user 'hello' and 'Workspace ready' with nothing explaining the missing reply. Source: ProviderRuntimeRecoveryService.ts:107 builds detail 'Cancelled because the server restarted before the provider work completed.' but attaches it only to runtime-request payloads and outbox effect cancellations (lines 291/316), never to run/attempt/turn/item rows \u2014 intentional code path, but a debuggability/UX gap.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, event_type, payload_json FROM orchestration_events WHERE stream_id='48663fb7-fbd6-4be2-ad14-d8163282c069' AND command_id LIKE 'command:runtime-reconcile:%'\" \u2014 note status 'cancelled' payloads contain no reason; and grep -c NTIVE ~/.t3/userdata-v2/logs/provider/48663fb7-fbd6-4be2-ad14-d8163282c069.log shows only 4 lines with no assistant output.",
"sessionKey": "48663fb7-cursor"
},
{
"title": "file_search items never carry results (read/grep/glob outputs dropped) despite contract supporting them",
"category": "lost-data",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "All 117 file_search items across the 5 opencode child threads have results=NULL (contract OrchestrationV2FileSearchResult array at orchestrationV2.ts:843 is never populated by OpenCodeAdapterV2 \u2014 its file_search branch emits only 'pattern'). Example: prt_f15688536002X4CTVKyjMIxGfL (ses_0ea978228, ordinal 3) has only pattern '/Users/julius/Development/Work/codething-mvp'. Tool outputs (file contents read, matches found) exist in opencode's part.state.output but are discarded for this item type. Likely intentional UI minimalism, but it is provider-emitted content with no projection.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*), SUM(json_extract(payload_json,'$.results') IS NOT NULL) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:opencode:native-thread:ses_%' AND type='file_search';\" -- returns 117|0",
"sessionKey": "3029dc85-opencode"
},
{
"title": "Placeholder 'pending' provider_thread row persists alongside the real one; orchestrator-synthesized items split across the two",
"category": "lineage",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Main thread has TWO provider_thread rows: provider-thread:provider:opencode:native-thread:pending%3Arun%3Athread%3A3029dc85...%3Aordinal%3A1 (status idle, first/last run ordinals 1-7) and the real provider-thread:provider:opencode:native-thread:ses_0ea983868ffens4ayJQLKgPE6J (idle, 1-7). 20 items (7 user_message, 7 checkpoint, 3 thread_created, 2 delegated subagent, 1 command_execution) still reference the pending placeholder while all native items reference ses_0ea983868 \u2014 e.g. thread_created item turn-item:created-thread:...126456a2...%3A0 has providerThreadId '...pending%3Arun%3A...ordinal%3A1' but providerTurnId pointing at the real session ses_0ea983868. Lineage is queryable but split; the placeholder was never collapsed after the native session id was learned.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT provider_thread_id, status, first_run_ordinal, last_run_ordinal FROM orchestration_v2_projection_provider_threads WHERE thread_id='3029dc85-93b7-43c5-8993-1beff41b1c98';\"",
"sessionKey": "3029dc85-opencode"
},
{
"title": "Single occurred_at inversion on main stream (checkpoint capture vs concurrent subagent-result handoff)",
"category": "ordering",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Stream 3029dc85...: stream_version 1868 (sequence 10004, checkpoint.captured, occurred_at 2026-06-29T22:09:54.344Z, checkpoint root:name:5 for run 5) was appended AFTER stream_versions 1863-1867 (sequences 9881-9885, delegated subagent d43de13f completion + context-handoff/transfer, occurred_at 22:09:54.779Z) \u2014 occurred_at goes backwards by 435ms. Benign concurrency between run-5 completion checkpointing and the delegated claudeAgent subagent result handoff landing; projection ordinals unaffected (0 ordinal inversions vs first-seen event order across all 6 threads).",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT stream_version, sequence, event_type, occurred_at FROM (SELECT stream_version, sequence, event_type, occurred_at, LAG(occurred_at) OVER (ORDER BY stream_version) prev FROM orchestration_events WHERE stream_id='3029dc85-93b7-43c5-8993-1beff41b1c98') WHERE occurred_at < prev;\"",
"sessionKey": "3029dc85-opencode"
},
{
"title": "Native provider log payloads are fully redacted (valueType/fieldCount only), preventing content-level loss auditing",
"category": "other",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Every one of the 17,198 log lines in 3029dc85-93b7-43c5-8993-1beff41b1c98.log(.1) has kind='protocol' with inner payload reduced to {valueType:'object', fieldCount:N} \u2014 e.g. message.part.updated lines carry no part id, text, or error. Only method-level counts are auditable (15,542 message.part.delta, 723 message.part.updated, 204 message.updated, 7 session.promptAsync, 5 session.created, 12 session.idle). Method counts DO reconcile with projections (7 promptAsync = 7 runs; 5 session.created = 5 child threads; 12 session.idle = 7 main turns + 5 child turns), but text truncation and the actual error string of the failed file_search cannot be verified against the wire. If these logs are meant to be 'ground truth', the opencode SSE logger is not recording decoded payloads.",
"repro": "grep -h '\"message.part.updated\"' ~/.t3/userdata-v2/logs/provider/3029dc85-93b7-43c5-8993-1beff41b1c98.log.1 | head -1",
"sessionKey": "3029dc85-opencode"
},
{
"title": "Split provider-thread identity: run/attempt/provider_turn reference the pending-keyed provider-thread row while turn items and threads.active_provider_thread_id reference the ses_-keyed row",
"category": "lineage",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Two rows in orchestration_v2_projection_provider_threads for the same native session: 'provider-thread:provider:opencode:native-thread:pending%3Arun%3Athread%3A9f8d616d-...%3Aordinal%3A1' and 'provider-thread:provider:opencode:native-thread:ses_0ea7ea5deffe0eNd8RbfyTfgAw' (both idle, same provider_session_id, and the pending row's payload has nativeThreadRef.nativeId=ses_0ea7ea5deffe0eNd8RbfyTfgAw strength strong). projection_runs.provider_thread_id, run_attempts.provider_thread_id and provider_turns.provider_thread_id all point at the pending-keyed row, while the two provider-part turn_items (prt_f158168eb001r0Ubqqry5Z31Q1, prt_f158169d0002CgOsT8eNRkPGI3) and threads.active_provider_thread_id point at the ses_-keyed row. Notably provider_turns row provider-turn:...ses_0ea7ea5deffe0eNd8RbfyTfgAw%3Aattempt... encodes ses_ in its own id but its provider_thread_id column is the pending row. Pending id minted in Orchestrator.ts (`nativeThreadId: \\`pending:${runId}\\``, lines 2384/2772); the pending row is resolved via nativeThreadRef rather than rebinding downstream rows, so joins on provider_thread_id split the turn across two ids.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT provider_thread_id FROM orchestration_v2_projection_provider_turns WHERE thread_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3'; SELECT DISTINCT provider_thread_id FROM orchestration_v2_projection_turn_items WHERE thread_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3';\"",
"sessionKey": "9f8d616d-opencode"
},
{
"title": "Real provider-thread row stayed status 'active' for ~20h after the provider session stopped",
"category": "stuck-state",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "provider-session.updated seq 13792 marks session stopped at 2026-06-29T23:00:38.028Z (idle reaper ~30min after last activity 22:30:30; last native log line heartbeat 2026-06-29T23:00:27.024Z). The pending-keyed provider-thread went idle at turn completion (seq 13783, 22:30:30.877Z), but the ses_0ea7ea5deffe0eNd8RbfyTfgAw provider-thread's last status update before shutdown was 'active' (seq 13779, 22:30:30.876Z) and it was only flipped to idle by seq 13797 at 2026-06-30T18:59:15.308Z, ~20h later (presumably on next app start). During that window the projection showed an active provider-thread bound to a stopped session. Eventually reconciled; final state is consistent.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, occurred_at, json_extract(payload_json,'$.id'), json_extract(payload_json,'$.status') FROM orchestration_events WHERE stream_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3' AND event_type IN ('provider-thread.updated','provider-session.updated') ORDER BY sequence\"",
"sessionKey": "9f8d616d-opencode"
},
{
"title": "OpenCode native log payloads are redacted to shape summaries, preventing content-level ground-truth verification",
"category": "other",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Every one of the 273 lines in 9f8d616d-86ee-4560-bd52-2387d6adb1c3.log is kind 'protocol' (opencode-sdk.sse) with payload reduced to e.g. {\"payload\":{\"valueType\":\"object\",\"fieldCount\":3}} \u2014 no message text, part ids, or tool args (contrast with claude logs which carry full decoded JSON). Only method names/counts are auditable: 31 message.part.delta, 7 message.part.updated, 6 message.updated, 1 session.idle, 0 session.error. Projected content was spot-checked instead and looks sensible and un-truncated (user 'hey'; reasoning 'The user is just saying \"hey\" - a casual greeting...'; assistant 'Hey! What can I help you with?').",
"repro": "sed -E 's/^\\[[^]]+\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/9f8d616d-86ee-4560-bd52-2387d6adb1c3.log | jq -r '[.event.payload.direction,.event.payload.method]|@tsv' | sort | uniq -c",
"sessionKey": "9f8d616d-opencode"
},
{
"title": "run_attempt.provider_turn_id never populated (null on all 207 attempts DB-wide)",
"category": "lineage",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "run-attempt row run-attempt:...ordinal%3A1:attempt:1 has providerTurnId:null in payload_json and empty provider_turn_id column, while the provider_turn row correctly back-references runAttemptId. DB-wide: SELECT count(*), sum(provider_turn_id IS NOT NULL AND provider_turn_id != '') FROM orchestration_v2_projection_run_attempts \u2192 207|0. Forward lineage attempt\u2192turn is only recoverable by scanning provider_turns; may be intentional (reverse-only linkage) but the column exists and is never filled.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*), sum(provider_turn_id IS NOT NULL AND provider_turn_id != '') FROM orchestration_v2_projection_run_attempts;\"",
"sessionKey": "1156181e-delegated-task"
},
{
"title": "Provider session stayed 'running' ~25h after turn ended; only reconciled to 'stopped' at server shutdown",
"category": "stuck-state",
"severity": "low",
"confidence": "medium",
"knownIssue": true,
"evidence": "Turn completed 2026-06-28T05:22:33.360Z (last native log line); no further session events until sequence 168 provider-session.updated at 2026-06-29T06:33:36.481Z via command:runtime-reconcile:shutdown, which set status=stopped. No provider-session.detached was ever emitted for this thread. Related to the known idle-session-reaper/session-lifecycle area; state is correct now, so no data impact, but the projection reported a live session for a day for a one-shot delegated task.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, event_type, occurred_at FROM orchestration_events WHERE stream_id LIKE '%1156181e%' AND event_type LIKE 'provider-session%' ORDER BY sequence;\"",
"sessionKey": "1156181e-delegated-task"
},
{
"title": "claudeAgent provider sessions never idle-reaped; stayed 'ready' ~21 hours until simultaneous shutdown sweep",
"category": "stuck-state",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "codex session stopped 2026-06-29T22:39:55 (seq 13789, 30 min after its 22:09:55 failure) and grok stopped 22:41:44 (seq 13790, 30 min after 22:11:44 completion) \u2014 idle reaper working. But all 3 claudeAgent sessions (last activity 22:08:48 / 22:09:50 / 22:13:07 on 6/29) only transitioned ready->stopped at 2026-06-30T18:59:15.286/.289/.291 (seq 13793-13795), simultaneously, ~21h later \u2014 a shutdown sweep, not the 30-min reaper. Native logs show no claude activity after 22:13, so either processes lingered or projections misreported 'ready' for a day. Inverse of the known 'reaper kills long sleeps' issue: reaper never fired for claudeAgent.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, occurred_at, json_extract(payload_json,'$.status') FROM orchestration_events WHERE event_type LIKE 'provider-session%' AND stream_id LIKE '%6d618dc4%' ORDER BY sequence;\"",
"sessionKey": "6d618dc4-mcp-group"
},
{
"title": "Codex model-rejection error fully preserved and user-visible (works as intended)",
"category": "error-handling",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log 22:09:55.424 method 'error' / turn/completed status failed with message 'The gpt-5.3-codex model is not supported when using Codex with a ChatGPT account' (400 invalid_request_error). Projection: turn_item turn-item:provider:codex:native-item:terminal-failure%3A...019f156e-851a... type=error status=failed carries the verbatim JSON error in failure.message; run/run_attempt/provider_turn all 'failed'. No swallowing \u2014 this is a positive verification, listed for completeness.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure.message') FROM orchestration_v2_projection_turn_items WHERE turn_item_id LIKE '%terminal-failure%019f156e-851a%';\"",
"sessionKey": "6d618dc4-mcp-group"
},
{
"title": "Grok session/prompt request ends with errorTag 'Interrupt' at the instant the turn completes",
"category": "other",
"severity": "low",
"confidence": "low",
"knownIssue": false,
"evidence": "Log 2026-06-29T22:11:44.909Z: {method:'session/prompt',status:'failed',errorTag:'Interrupt'} while provider_turn 019f156e-797f...:turn:1 completedAt 22:11:44.910 status=completed and the 6663-char assistant report is fully projected (item ordinal 1000074). Likely adapter-initiated interrupt cleanup after observing turn completion (grok capabilities: supportsSteeringByInterruptRestart=true); no data lost, but a native 'failed' prompt request maps to a 'completed' turn, which could confuse future debugging.",
"repro": "grep '\"method\":\"session/prompt\",\"status\":\"failed\"' ~/.t3/userdata-v2/logs/provider/thread-mcp-6d618dc4-25fd-453b-9193-fd22a6739d1f-126456a2-f1ff-4098-a0a0-fde04bb1.log",
"sessionKey": "6d618dc4-mcp-group"
},
{
"title": "Grok file_search/read items persist only pattern + fileName echo, no tool output; grok native log fully redacted",
"category": "lost-data",
"severity": "low",
"confidence": "low",
"knownIssue": false,
"evidence": "49 file_search items on thread :1 store e.g. pattern='pnpm-workspace.yaml', results=[{'fileName':'pnpm-workspace.yaml'}] (item turn-item:provider:grok:native-item:...call-e4489e09-...-1, ordinal 1000004) \u2014 the file content the tool returned is not kept, unlike claudeAgent command items which keep full stdout envelopes. Additionally the grok log redacts all decoded payloads to shape summaries ({'valueType':'array','itemCount':1}), so native-vs-projection content verification is impossible for grok; command_execution and reasoning items do carry real content, so this may be an intentional thin mapping for read-style tools.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.pattern'), json_extract(payload_json,'$.results') FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%126456a2%:1' AND type='file_search' LIMIT 5;\"",
"sessionKey": "6d618dc4-mcp-group"
},
{
"title": "Both session/prompt requests logged as failed with errorTag=Interrupt despite runs completing",
"category": "error-handling",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Native log request events: session/prompt started 01:51:45.517 -> failed errorTag=Interrupt at 01:52:13.249; session/prompt started 01:53:00.071 -> failed errorTag=Interrupt at 01:53:37.665. These timestamps exactly equal provider_turn completed_at values (turn 1: 01:52:13.249, turn 2: 01:53:37.665), and both runs/turns/items project as completed with full assistant content, so this appears to be intentional adapter teardown (interrupting the pending ACP prompt fiber once the turn result is reached; grok sets interruptPromptOnCancel:false in GrokAdapterV2.ts line 90/641). No content was lost and no spurious failure surfaced, but the log-level 'failed' status for successful turns will mislead debugging.",
"repro": "sed 's/^\\[[^]]*\\] NTIVE: //' ~/.t3/userdata-v2/logs/provider/5dcea72d-15e1-4ded-922b-0b00c587de6c.log | jq -c 'select(.event.kind==\"request\" and .event.payload.method==\"session/prompt\")'",
"sessionKey": "5dcea72d-grok-subagent"
},
{
"title": "run_attempts.provider_turn_id never populated (reverse link only)",
"category": "lineage",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Both attempts for this session (run-attempt:run:run%3Athread%3A5dcea72d...ordinal%3A1:attempt:1 and ...ordinal%3A2:attempt:1) have provider_turn_id NULL in both the column and payload_json; DB-wide, 0 of all rows in orchestration_v2_projection_run_attempts have a non-NULL provider_turn_id. Lineage is still resolvable via orchestration_v2_projection_provider_turns.run_attempt_id (both turns correctly reference their attempts), so this may be an intentionally unused column, but the forward link is dead.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_v2_projection_run_attempts WHERE provider_turn_id IS NOT NULL;\"",
"sessionKey": "5dcea72d-grok-subagent"
},
{
"title": "Backgrounded-bash child threads have empty-text prompt user_message items",
"category": "other",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "All 13 backgrounded-bash child threads project a user_message item task%3A<id>%3Aprompt with text:\"\" (e.g. turn-item:provider:claudeAgent:native-item:task%3Abw28jiyac%3Aprompt, startedAt 2026-07-01T15:51:26.160Z), even though the native task_started event carried description \"vp run --filter @t3tools/web typecheck 2>&1 | tail...\". The command is still user-visible via the main-thread subagent item title, so impact is cosmetic (empty bubble if the child thread is opened).",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%7f1dfff1%' AND type='user_message' AND json_extract(payload_json,'$.text')='';\"",
"sessionKey": "7f1dfff1-claude-scheduled-tasks"
},
{
"title": "Codex run 1 (169 items) has no surviving native log to verify against",
"category": "other",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Run ordinal 1 (codex, 2026-07-01T01:45:03Z\u201302:01:10Z, 169 items incl. 10 failed command_executions) predates the oldest surviving log rotation: 7f1dfff1-...log.1 first line is 2026-07-01T15:48:00.224Z (run 2). The codex portion of the log was rotated away, so item-level loss/ordering for run 1 could not be ground-truthed; its events/projections are internally consistent (contiguous ordinals 1000001-1000169, all terminal).",
"repro": "head -1 ~/.t3/userdata-v2/logs/provider/7f1dfff1-4cbb-450b-8514-764d11c903e1.log.1",
"sessionKey": "7f1dfff1-claude-scheduled-tasks"
},
{
"title": "Provider session projection stuck at status 'ready' after detach/archive",
"category": "stuck-state",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "provider-session.detached event at 2026-07-01T23:44:29.976Z (reason 'Thread archived.') for provider-session:...:1c70abe8-4ecb-43f8-8ee6-9ce19beddcfe, but the orchestration_v2_projection_provider_sessions row still shows status='ready' with updated_at=2026-07-01T22:48:37.724Z and thread_id still bound. The event stream also shows the session flip stopped\u2192ready correctly at 22:41:50/22:48:37, so the projection simply never reflects the final detached/terminated state.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, updated_at FROM orchestration_v2_projection_provider_sessions WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514';\"",
"sessionKey": "47763f5e-claude-fable"
},
{
"title": "Detached claudeAgent provider session left in status 'ready' forever after handoff",
"category": "stuck-state",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Event seq 32566 provider-session.detached at 2026-07-02T01:03:00.273Z (reason 'Provider or model selection changed.') for provider-session:provider-instance:claudeAgent:thread:ea84f015-...:21ed85a2-2ed1-4bd8-94be-1e5affe1aa72, but the orchestration_v2_projection_provider_sessions row still shows status='ready' \u2014 no stopped update was ever emitted. The replacement cursor session was correctly moved to 'stopped' at 02:49:07 (seq 38639).",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT provider_session_id,status FROM orchestration_v2_projection_provider_sessions WHERE provider_session_id LIKE '%ea84f015%'\"",
"sessionKey": "ea84f015-cursor-handoff"
},
{
"title": "Subagent child-thread items have null run_id / provider_thread_id / provider_turn_id",
"category": "lineage",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "All 34 items of child thread ...a4bd1db1834cb086a and 52 items of ...ab96794f302d5fd03 have runId:null, providerThreadId:null, providerTurnId:null (e.g. turn-item:provider:claudeAgent:native-item:toolu_01L5SAT2nkGMce3gWf3qFFqJ). Lineage back to the parent exists only via orchestration_v2_projection_subagents (child_thread_id set, run_id = parent runs ordinal 2 and 5, both completed) and the two parent subagent turn items (task%3Aa4bd1db1834cb086a%3Asubagent / task%3Aab96794f302d5fd03%3Asubagent). Likely by design (child threads have no runs of their own), but items cannot be joined to any run/turn directly.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:claudeAgent%ea84f015%' AND run_id IS NULL\"",
"sessionKey": "ea84f015-cursor-handoff"
},
{
"title": "error_during_execution result during run 5 coincides with steering message \u2014 absorbed without any projected trace",
"category": "error-handling",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "log.3 line 677 [2026-07-01T23:13:24.083Z] result subtype error_during_execution, is_error:true, duration_api_ms 2473149, session 44cbb4c7. A user steering message was ingested 50ms earlier (seq 30447 message.updated 23:13:24.031Z, message 513621d3-5a03-46e1-8fd7-cc4de4b417f1, run 5), so this looks like the intentional interrupt-for-steering path; run 5 continued and completed at 23:30:07 with items after 23:13. No event records the aborted query, which is acceptable if intentional but leaves no audit trail of the abort.",
"repro": "grep -n error_during_execution ~/.t3/userdata-v2/logs/provider/ea84f015-e597-4f79-9557-d39b5a895fba.log.3",
"sessionKey": "ea84f015-cursor-handoff"
},
{
"title": "5 tool calls that never returned natively were auto-marked 'completed' (with no results) at turn end",
"category": "lost-data",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log has 123 distinct tool-call-started but only 118 tool-call-completed; the 5 without completion (tool_e1f3ce39... glob, tool_fd1ba594..., tool_e2f6262c..., tool_840aeaa9... grep, tool_671d1b53... read) are all projected as status 'completed' with completedAt forced to the turn-end timestamp 2026-07-02T02:25:57.991Z and no results payload (e.g. turn-item:provider:cursor:native-item:tool_e1f3ce39-4604-4ced-8039-bbd5e75946b ends with pattern:'**/*' and no results field). This is the intentional finalizeTurn flush (CursorAdapterV2.ts:1886-1889 emitToolArtifacts({completed:true})), but 'completed' misrepresents tools whose results never arrived; something like 'interrupted' or an explicit no-result marker would be more truthful. Minor: cursor itself abandoned these calls, so no user-visible content was lost.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT status, json_extract(payload_json,'$.completedAt') FROM orchestration_v2_projection_turn_items WHERE json_extract(payload_json,'$.nativeItemRef.nativeId')='tool_e1f3ce39-4604-4ced-8039-bbd5e75946b';\"",
"sessionKey": "c9e72a05-cursor-failing-turns"
},
{
"title": "Run 2 was a 7.3-minute silent hang before failing \u2014 nothing projected during the window (faithful to provider, but no progress/heartbeat signal exists)",
"category": "other",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log: run.started for run-f4d64e64 at 02:28:07.973Z, next event is run.completed status 'error' at 02:35:28.424Z \u2014 zero interaction.updates in between. Ingested events for the stream in that window: 0 (SELECT COUNT(*) ... occurred_at BETWEEN '02:28:09' AND '02:35:28' returns 0). The pipeline mirrors the provider exactly (nothing lost), but the projection offers no signal distinguishing 'model working' from 'SDK dead due to auth error' during those 440s; the user just saw a running turn that eventually failed generically.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE stream_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND occurred_at > '2026-07-02T02:28:09' AND occurred_at < '2026-07-02T02:35:28';\"",
"sessionKey": "c9e72a05-cursor-failing-turns"
},
{
"title": "Native 'read' tool calls are projected as type 'file_search'",
"category": "other",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "18 native 'read' tool calls (e.g. tool_671d1b53-bb49-46ef-94de-8f682391c93 reading a file path) are projected as type 'file_search' with the file path as 'pattern'. Intentional per CursorAdapterV2.ts:1203-1219 (glob/grep/read/ls/readLints/semSearch all map to file_search), so the content is preserved, but the item type flattens semantically distinct operations (file reads rendered as searches). Cosmetic fidelity note only.",
"repro": "sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT type FROM orchestration_v2_projection_turn_items WHERE json_extract(payload_json,'$.nativeItemRef.nativeId')='tool_671d1b53-bb49-46ef-94de-8f682391c93';\"",
"sessionKey": "c9e72a05-cursor-failing-turns"
},
{
"title": "Token usage from turn-ended/run.completed is dropped by the ingestion pipeline",
"category": "lost-data",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log line 663 (2026-07-02T07:08:07.565Z) turn-ended carries usage {inputTokens:596379, outputTokens:6430, cacheReadTokens:522080}; line 664 run.completed repeats it with totalTokens:1124889. No event for stream_id=8ee00dcc-fa04-4fe7-9920-cd3432d45415 contains 'usage' or 'Tokens' (query returned 0 rows), and neither the run nor provider_turn projection payloads have a usage field. grep for 'usage' in apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts, ProviderEventIngestor.ts and ProviderAdapter.ts returns nothing \u2014 the v2 contract simply doesn't model usage, so this looks like a pipeline-wide design gap rather than a session bug, but users lose per-turn token/cost data.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE stream_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415' AND payload_json LIKE '%Tokens%';\" (returns 0) vs grep -c 'inputTokens' ~/.t3/userdata-v2/logs/provider/8ee00dcc-fa04-4fe7-9920-cd3432d45415.log (returns 2)",
"sessionKey": "8ee00dcc-cursor-spacing"
},
{
"title": "run_attempt.provider_turn_id never backfilled (forward link missing; reverse link intact)",
"category": "lineage",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "orchestration_v2_projection_run_attempts row run-attempt:run:run%3Athread%3A8ee00dcc-fa04-4fe7-9920-cd3432d45415%3Aordinal%3A1:attempt:1 has provider_turn_id='' and payload providerTurnId:null even after completion, while orchestration_v2_projection_provider_turns row provider-turn:provider:cursor:native-turn:run-ee800ef2-cd0e-45bd-9481-65fd5cfdae67 correctly points back via run_attempt_id to that attempt. Lineage is resolvable only in one direction (turn->attempt).",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT a.attempt_id, a.provider_turn_id, t.provider_turn_id FROM orchestration_v2_projection_run_attempts a JOIN orchestration_v2_projection_provider_turns t ON t.run_attempt_id=a.attempt_id WHERE a.thread_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415';\"",
"sessionKey": "8ee00dcc-cursor-spacing"
},
{
"title": "file_change diffStr has malformed diff headers (a//abs/path, b//abs/path)",
"category": "other",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "turn-item:provider:cursor:native-item:tool_fee434e5-6388-483d-82f1-9e6c6ab418c (ordinal 1000042) payload diffStr begins '--- a//Users/julius/.t3/worktrees/codething-mvp/t3code-3cba2658/apps/mobile/src/features/home/HomeScreen.tsx' \u2014 absolute path concatenated after 'a/' yields double slash and a non-standard diff header; same for the other two file_change items (tool_361abe3b, tool_b586252d). Diff hunk content itself is intact (additions:2 deletions:1 recorded). Cosmetic, but breaks strict unified-diff parsers.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT substr(json_extract(payload_json,'$.diffStr'),1,80) FROM orchestration_v2_projection_turn_items WHERE thread_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415' AND type='file_change';\"",
"sessionKey": "8ee00dcc-cursor-spacing"
},
{
"title": "Codex 'reasoning' items are silently dropped (no adapter handler, no projection)",
"category": "lost-data",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Surviving log window shows 45 item/started + 45 item/completed reasoning items for native thread 019f1b62-f532 (c878541b runs 4-6), but the projection has 0 reasoning-type turn_items for any of the four threads (types present: assistant_message, command_execution, file_change, user_message, checkpoint, dynamic_tool, run_interrupt_*). CodexAdapterV2.ts item/started / item/completed handlers dispatch on userMessage/commandExecution/mcpToolCall/dynamicToolCall/fileChange/webSearch/plan/collabAgentToolCall/subAgentActivity and fall through for 'reasoning' despite capabilities streamsReasoning:true (line 139). Mitigating: every observed reasoning item had empty summary/content (e.g. rs_0e493c0caf681939016a4539c1c0988193b7174c9c067dfdb2, summary:[], content:[]), so no user-visible text was actually lost in this session.",
"repro": "cat ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log.10 | grep '\"decoded\"' | grep '\"item/completed\"' | grep '019f1b62' | grep -c '\"reasoning\"' vs SELECT count(*) FROM orchestration_v2_projection_turn_items WHERE thread_id='c878541b-a832-4757-a254-5550e3f6c2d1' AND type LIKE '%reason%';",
"sessionKey": "codex-no-native-logs"
},
{
"title": "contextCompaction native item has no projection representation",
"category": "lost-data",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Native log shows item/completed contextCompaction id ad331e6d-f971-46a9-a04a-c70a1b86894f on turn 019f1e69-826e-7de2-9200-b6852ff53138 (c878541b run 4, ~16:00-16:05Z); no turn_item, node, or event for it exists (payload_json LIKE '%ompaction%' matches only incidental message text). Users cannot see that context was compacted mid-run. Native item carries only an id (no content), so the informational loss is small.",
"repro": "grep 'contextCompaction' ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log.10 | grep 019f1b62",
"sessionKey": "codex-no-native-logs"
},
{
"title": "Run 119 marked failed while its native query kept running; retry run 120 adopted the result, leaving a duplicated user message",
"category": "duplicate",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Run 119 failed at 2026-07-02T16:45:26.143Z (transport_error, ~1.5s after requested_at 16:45:24.618Z), but the native log shows query.open + prompt.offer at 16:45:25.921Z proceeding to SessionStart:resume (16:45:41) and a successful result at 16:47:00.764Z. Retry run 120 (requested 16:45:36.222Z) completed at 16:47:01.354Z with that assistant message (message:provider:claudeAgent:native-item:693d3576-4e56-4c10-9b0f-90ff9825f663, 3190 chars, intact). Two user messages with identical text exist: 9b135da3-dd1b-4a9a-90bc-ee4166bce48d (run 119) and 0f1b1078-74cb-4488-9626-e1ddbe933a9a (run 120) \u2014 timeline shows the prompt twice (plus the error item). Content preserved; cosmetic/duplication issue only.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT message_id, run_id, created_at FROM orchestration_v2_projection_messages WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND created_at BETWEEN '2026-07-02T16:45' AND '2026-07-02T16:46'\"",
"sessionKey": "71e29ba5-claude-mega"
},
{
"title": "4 native error_during_execution results silently recovered in-adapter with no projection trace",
"category": "error-handling",
"severity": "low",
"confidence": "medium",
"knownIssue": false,
"evidence": "Native results with subtype=error_during_execution/is_error=true at 2026-07-02T01:34:23.046Z, 02:29:30.034Z, 05:08:27.090Z, 17:03:10.206Z fall inside runs 73/80/95/122 \u2014 all completed with a single run attempt and no error item/event. At 01:34:23 the error coincides with an outgoing prompt.offer (mid-stream steering) followed immediately by system init and continued streaming, so the adapter's transparent re-query is likely intentional; but the transient error is invisible to projections (debug info only in provider log).",
"repro": "grep -h '\"subtype\":\"error_during_execution\"' ~/.t3/userdata-v2/logs/provider/71e29ba5*.log* | grep '\"stage\":\"decoded\"'",
"sessionKey": "71e29ba5-claude-mega"
},
{
"title": "Session has 7 subagent child threads, not 9 as briefed; all 7 fully linked and consistent",
"category": "lineage",
"severity": "low",
"confidence": "high",
"knownIssue": false,
"evidence": "Native log contains exactly 7 top-level Agent tool_use spawns (toolu_01CtiEb3..., 01CrTuja..., 01TiUmm..., 01W2SNA..., 01RjCn6..., 017H3QK..., 018VQWh...); projections have 7 type='subagent' items, 7 orchestration_v2_projection_subagents rows all with non-null child_thread_id resolving to existing thread rows, and 7 child-thread event streams (79-260 events each) with items on the correct thread ids (0 items with mismatched threadId). The 2 failed subagents (task%3Aafbafdde..., task%3Aa0e0b5f3..., completed_at 2026-07-02T08:34:33.868Z) match native '[Request interrupted by user for tool use]' is_error tool_results for toolu_017H3QKcEb9FrecsT4tyzg1M / toolu_018VQWhHKSAP1cFkZwZGRGe5 at 08:34:33.867Z \u2014 correct failure surfacing, not a bug.",
"repro": "sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_v2_projection_subagents WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016'\"",
"sessionKey": "71e29ba5-claude-mega"
}
]
}
@@ -0,0 +1,534 @@
# Plan: Orchestration V2 Session Audit Remediation
## Summary
A full audit of every v2 orchestrator session in `~/.t3/userdata-v2` (2026-07-02, 18 session
groups, ~43k events, ~6.3k projected turn items, all 5 providers) compared native provider logs
against ingested events and item projections. Core mechanics are healthy — zero stream_version
gaps, zero ordinal collisions, positions table 100% consistent, no duplicate `nativeItemRef`s,
no stuck non-terminal state — but 23 verified discrepancies cluster into the workstreams below.
Every finding was adversarially re-verified against the raw DB/logs and the adapter source.
Repro commands are inline. File/line references are as of branch `t3code/codex-turn-mapping`
on the audit date; expect drift.
Status legend: `[ ]` todo · `[~]` in progress · `[x]` done
## Tracking checklist
> **Restructure note (2026-07-04):** the PR stack was reorganized to combine with
> mwolson's parallel work. Shared continuation plumbing (C0, ea57e97d58) now lives
> directly on `t3code/codex-turn-mapping`; Claude session-continuity fixes including
> our #1/#15 (+ fixtures `claude_result_is_error`, `claude_idle_resume`,
> `advance_clock` step) live in PR #3860; grok/ACP lifecycle (superset of plan #7)
> lives in PR #3578; this branch (PR #3677) keeps the remaining audit fixes:
> #2 #3 #4 #5 #9 #10 #11 #12. Our turn.wakeup implementation was dropped in favor
> of the C0 continuation design.
- [x] 1. Honor `is_error` on Claude SDK results — MOVED to PR #3860 (with fixture claude_result_is_error)
- [x] 2. Preserve real failure causes in projected errors (Claude adapter + ProviderFailure)
- [x] 3. Preserve cursor failure detail (requestId, durationMs; SDK exposes no error text yet)
- [x] 4. Log failure/lifecycle frames in native provider logs (claude + cursor runners)
- [x] 5. Surface provider-process crashes / reconcile cancellations to the user
- [x] 6. Ingest codex-native collab subagents — already implemented upstream (verified 2026-07-04 on #3908's branch: registerSubagentActivity/registerSubagentThreads handle subAgentActivity + collabAgentToolCall, and the subagent_v2 fixtures replay the exact a5a643b2 loss scenario incl. post-settle child completion, asserting the child's "Hello." result)
- [ ] 7. Fix grok/ACP background subagent lifecycle + transcript projection
- [x] 8. Invisible post-turn wakeup turns — SUPERSEDED by C0/#3860's provider-continuation design (our turn.wakeup implementation dropped in the restructure)
- [x] 9. Route shared-codex-session native logs to the correct thread's file
- [x] 10. Coalesce streaming-delta event persistence (~2800x amplification)
- [x] 11. Assistant text segments merged without separator (fixed in worktree — add regression fixture)
- [x] 12. OpenCode `file_search` items drop error/output
- [ ] 13. Low-severity backlog (see section)
- [ ] 14. Cursor SDK unhandled `write EPIPE` crashes the backend child (recurring, post-SDK-bump)
---
## 1. `is_error: true` on Claude SDK results ignored — failed runs recorded as completed
**Severity: high.** The Claude Agent SDK emits terminal `result` messages with
`subtype: "success"` but `is_error: true` for API-level failures. The adapter only branches on
subtype, so the run, run_attempt, provider_turn, and (for delegated tasks) the subagent row and
the parent's `delegate_task` item all read `completed`.
Observed in four independent places:
- Delegated task `hello-opus-48` (thread `1156181e`): 401 auth failure, zero token usage,
everything projected `completed`.
- Same 401 in a5a643b2's run-4 delegated child — parent `delegate_task` item output.status
`completed`.
- Thread `47763f5e` run 1: 401 result projected as a completed run; error text survives only as
a plain completed `assistant_message` (the SDK's synthetic `<synthetic>`-model message) — no
error item, so the run reads as a success.
- Thread `ea84f015` runs 11–13: `API Error: 529 Overloaded` (29 `api_retry` events preceding),
all three runs `completed`.
**Root cause:** `ClaudeAdapterV2.ts` — `terminalStatusFromResult` (~line 1652) returns
`"completed"` whenever `message.subtype === "success"`; the failure branch (~line 3254) only
fires for non-success subtypes. `is_error` / `api_error_status` are never consulted.
**Proposed fix:**
1. In `terminalStatusFromResult` (and the result handler), treat `subtype === "success" &&
is_error === true` as a failure.
2. Build a `ProviderFailure` from the result: `message` = the `result` text (e.g. `Failed to
authenticate. API Error: 401 ...`), `code` = `api_error_status` when present, plausibly
`retryable: true` for 429/529.
3. Ensure a terminal-failure error item is emitted (not just the synthetic assistant message)
and delegated-task subagent rows go to `failed`.
4. Testkit: extend `ClaudeAdapterV2.testkit.ts` + replay fixtures with an
`is_error`-on-success-subtype result.
**Repro:**
```sh
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
"SELECT status FROM orchestration_v2_projection_runs WHERE thread_id LIKE '%1156181e%';" # completed
grep 'api_error_status' ~/.t3/userdata-v2/logs/provider/thread-delegated-task-command-3amcp-3a1156181e-*.log
```
- [ ] Status: not started
## 2. Terminal failures persist only generic strings — root cause unrecoverable from DB
**Severity: high (systemic).** Every claudeAgent failed run in the DB persists exactly
`{class: "transport_error", message: "Claude Agent SDK query failed.", code: null,
retryable: null}` (threads 47763f5e run 10, 7f1dfff1 run 10, 71e29ba5 runs 89/119). The native
log at those failure sites shows only the outgoing `query.open`/`prompt.offer` with nothing
incoming — so after the fact, **no record of the actual failure exists anywhere**. The same
pattern hit cursor (issue 3) — while codex proves it can be done right: codex failures keep the
full upstream error body.
**Root causes:**
- `ClaudeAdapterV2.ts:279-281` — `ClaudeAgentSdkQueryRunnerError.message` getter hardcodes the
string; the wrapped `cause` defect is discarded.
- `ProviderFailure.ts:90-113` — `makeProviderFailure` reads only `.message`/`.code` off the
squashed cause and never unwraps nested causes of tagged wrapper errors.
- `RunExecutionService.ts:~830` — feeds `Cause.squash(cause)` into `makeProviderFailure`, so a
tagged error's inner cause never reaches the projection. The server log printed the cause
depth-elided (`failures: [ [Object] ]`), destroying the last copy.
**Proposed fix:**
1. Give wrapper errors (`ClaudeAgentSdkQueryRunnerError`, `ProviderAdapterTurnStartError` at
`ProviderAdapter.ts:~291`) a message that includes `String(cause)` (or a `detail` field).
2. In `makeProviderFailure`, walk the cause chain (`Cause.prettyErrors` / unwrap `.cause`) and
persist a structured `detail` (message chain + code) on the failure payload; contracts change
in `packages/contracts/src/orchestrationV2.ts` if the failure schema needs a `detail` field.
3. Fix the server-log print to use full-depth inspection for causes.
4. Side note from 47763f5e run 10: the failed `query.open` reused a **create-style `sessionId`
param after the session had been closed** (retry with `resume:` succeeded) — check
`ProviderSessionManager`/adapter open-vs-resume selection for closed sessions while fixing.
**Repro:**
```sh
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
"SELECT thread_id, json_extract(payload_json,'$.failure.message') \
FROM orchestration_v2_projection_turn_items WHERE type='error';"
```
- [ ] Status: not started
## 3. Cursor failure detail dropped (requestId, durationMs, SDK error_code)
**Severity: high.** Thread `c9e72a05` (the "why are cursor turns failing" session): run 2 failed
after a 440s silent turn; native `run.completed` carried `status:"error"`,
`requestId:"beca30c7-..."`, `durationMs:440732`. Projection kept only
`{message: "Provider turn failed.", code: null}` — requestId and duration dropped. The real
cause ("Authentication error. If you are logged in, try logging out and back in.") lives only in
the Cursor SDK's local store (`runs.error_code`), which T3 never reads.
**Root cause:** `CursorAdapterV2.ts:2165-2168` maps `cause: (result as {error?: unknown}).error`
— that field does not exist on the SDK `RunResult`, so it always falls back to
`DEFAULT_PROVIDER_FAILURE_MESSAGE`.
**Proposed fix:**
1. Map what the result actually carries: persist `requestId` and `durationMs` on the failure
payload (code field is a natural home for requestId).
2. On `status === "error"`, query the Cursor SDK store for `runs.error_code` /
error message for that run id and attach it.
3. Note: verify against current SDK shape — the audit also found (refuted-as-intentional) cases
where cursor's `run.completed` genuinely carries no detail; the fix is "persist everything
present", not "invent detail".
**Repro:**
```sh
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items \
WHERE thread_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND type='error';"
grep 'run.completed' ~/.t3/userdata-v2/logs/provider/c9e72a05-*.log | tail -1
```
- [ ] Status: not started
## 4. Native provider logs never record failure/lifecycle frames
**Severity: medium.** The "ground truth" logs cannot explain failed turns. In `721fc23c` the
log ends with an outgoing `run.start` and no trace of the `agent.send` rejection 4ms later, nor
of the provider child process fatally crashing (twice, `@cursor/sdk` Node error — visible only
in `server-child.log`). No adapter has an error/lifecycle log kind at all.
**Root cause:** e.g. `CursorAgentSdk.ts` `send()` — log writes cover outgoing `run.start` and
incoming frames only; `runnerError(cause, "run.start")` paths (lines ~408/440) write nothing.
Process exit is not logged to the per-thread native log either.
**Proposed fix:**
1. Add an `error`/`lifecycle` kind to the native event logger contract and write a frame on:
adapter send/open rejections, runner errors, provider process spawn/exit (with exit code),
and turn-abort paths — across all adapters (cursor, claude, codex, ACP, opencode).
2. Keep payloads small (message + code + native run/turn id), no secrets.
- [ ] Status: not started
## 5. Provider crashes / reconcile cancellations are silent to the user
**Severity: high.** In `721fc23c` the cursor backend crashed mid-turn; startup reconcile
cancelled run 1. In `48663fb7` a server restart orphaned the run; reconcile cancelled it. In
both cases the user asked something, got **no response, no error item, and no explanation** —
a reconcile-cancelled run is projected indistinguishably from a user cancellation.
**Root cause:** the startup runtime-reconcile (`command:runtime-reconcile:startup...`)
terminalizes runs/attempts/turns to `cancelled` but emits no user-visible item and no reason.
**Proposed fix:**
1. When reconcile terminalizes a run it did not start, emit an error (or `interrupted`) turn
item with a reason: e.g. "Provider process exited unexpectedly" / "Run was interrupted by an
app restart".
2. Record the cancellation reason on the run payload (`cancelReason: "runtime_reconcile" |
"user" | ...`) so UI and debugging can distinguish.
3. Optional: auto-offer retry in UI for reconcile-cancelled runs.
**Repro:**
```sh
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
"SELECT event_type, occurred_at FROM orchestration_events \
WHERE stream_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND event_id LIKE '%runtime-reconcile%';"
grep -n 'cursor/sdk\|terminalizedRuns' ~/.t3/userdata-v2/logs/server-child.log
```
- [ ] Status: not started
## 6. Codex-native collab subagents entirely missing from events and projections
**Severity: high (lost data).** In `a5a643b2` run 3 ("spawn a subagent"), codex spawned a
native collab subagent: `subAgentActivity` item, `collabAgentToolCall` (`wait`), and a child
native thread (`019f0c93-d260`) with webSearch, reasoning, and a final `agentMessage`
("Hello."). **Zero** of it was ingested — no events, no items, no subagent row, no child
thread. The child also completed *after* the parent turn finalized, so late-arriving child
items need routing even post-turn.
**Root cause:** `CodexAdapterV2.ts` has no handlers for `subAgentActivity` /
`collabAgentToolCall` item types, and events on non-primary native threads of the shared
app-server session are not attributed to any T3 thread.
**Proposed fix:**
1. Handle `subAgentActivity`: create a subagent projection row + child provider thread (mirror
of what `a61e9269`'s newer session shape already does — that session projected
`subAgentActivity` fine, so check what differs: likely experimental collab API vs newer
subagent API).
2. Handle `collabAgentToolCall` as a tool item on the parent.
3. Route child-native-thread items to the child T3 thread, including after the parent turn
completed (same routing-loosening pattern used for owned-provider-thread updates in the
wakeup work).
**Repro:**
```sh
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
"SELECT COUNT(*) FROM orchestration_events WHERE payload_json LIKE '%019f0c93-d260%';" # 0
grep -c 'subAgentActivity\|collabAgentToolCall' ~/.t3/userdata-v2/logs/provider/a5a643b2-*.log # >0
```
- [ ] Status: not started
## 7. Grok/ACP background subagent: wrong lifecycle + transcript never projected
**Severity: high (lost data) + medium (lifecycle).** Thread `5dcea72d` ("spawn a subagent"):
- The subagent row and parent `subagent` item were marked `completed` at spawn time
(01:52:10) with the placeholder result "Subagent started in background..." — the task
actually ran 75s (116 tool calls, per the later `TaskOutput` payload).
- The child thread got only its 2 spawn-time items; the live transcript (811 decoded incoming
ACP messages between runs) produced **zero** ingested events. The subagent's real final
output never reached the child thread.
**Root cause:** `AcpAdapterV2.ts` `emitSubagent` (~lines 1047-1060) adopts the spawn tool's
bootstrap text as the result and a non-running taskStatus as terminal; session notifications
arriving **between runs** (no active turn) are dropped rather than buffered/routed to the
subagent's child thread.
**Proposed fix:**
1. Keep the subagent `running` until a terminal task status; update result/completedAt from
`TaskOutput` (or task-completion notification) when it arrives.
2. Route/buffer ACP session notifications for background tasks outside active turns to the
child thread (reuse the wakeup-buffer pattern from ClaudeAdapterV2 if applicable to ACP).
3. Related low finding: child-thread items carry null `run_id`/`provider_thread_id`/
`provider_turn_id` — populate lineage when projecting child items.
**Repro:**
```sh
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
"SELECT status, completed_at, substr(json_extract(payload_json,'$.result'),1,60) \
FROM orchestration_v2_projection_subagents WHERE thread_id='5dcea72d-15e1-4ded-922b-0b00c587de6c';"
```
- [ ] Status: not started
## 8. Invisible post-turn wakeup turns (known — fix on this branch)
**Severity: high (lost data), known issue.** The audit quantified the pre-fix damage:
- `47763f5e`: 10 whole wakeup turns unpersisted — 16 assistant messages + 84 tool calls,
including 5 real git pushes and the final "Converged. PR #3638 is fully green".
- `ea84f015`: 42 tool calls + final assistant messages across 3 windows — including a GitHub
comment posted with no user-visible record (`pull/2829#issuecomment-4861082710`).
- `71e29ba5`: 76 completed tool calls (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup), all falling
in gaps between run windows, zero inside any run.
The fix (`turn.wakeup` / `ProviderWakeupService` / `attach_wakeup` / backgrounded-bash
adoption) is implemented on `t3code/codex-turn-mapping`; these sessions ran on pre-fix builds.
First `provider_wakeup` events in the DB appear 2026-07-01T22:47:41 — post-fix threads persist
wakeups.
**Remaining work:**
- [x] Core fix implemented (this branch, replay fixture `claude_provider_wakeup`)
- [ ] Sanity-check the three audit scenarios against the fixture set (task-notification wakeup,
ScheduleWakeup sleep-loop, backgrounded Bash completion) — the audit evidence makes good
additional fixture material
- [ ] Known follow-ups (from memory): idle session reaper vs long sleeps; superseded-wakeup
buffer only replays task bookkeeping; provider_turn has no `waiting` status literal
## 9. Shared codex session logs written to opener thread's file
**Severity: medium.** Four codex threads (`c878541b`, `de5f191a`, `68f7595b`, `af66fc2c`) have
**no native log file at all** — their app-server traffic was written into
`71e29ba5-...log.*` because that thread opened the shared codex app-server session.
Consequence: rotation of the busy opener's log (10 files × 10MB) **destroyed the native ground
truth** for most of those threads' runs; it also produced a false "ingestion gap" signal during
the audit (another thread's traffic interleaved in 71e29ba5's log).
**Root cause:** `CodexAdapterV2.ts:~1136` — `codexAppServerClientFactoryFromSettingsLayer.open`
builds `makeCodexAppServerProtocolLogger({ threadId: input.threadId })` once per app-server
process; `EventNdjsonLogger.write` routes to `${threadSegment}.log` from that frozen threadId.
**Proposed fix:**
1. Resolve the log target per message, not per process: maintain a native-thread-id → T3
thread-id map (the adapter already tracks owned native threads) and route each protocol
frame to the owning thread's log; fall back to a shared
`codex-shared-session.log` for unattributable frames (initialize, thread/start, etc.).
2. Consider retention bump for provider logs, since they are the only ground truth
(`.plans/06-provider-logstream-lifecycle.md` is the related prior art).
**Repro:**
```sh
grep -l '019f1b62-f532' ~/.t3/userdata-v2/logs/provider/*.log* # only 71e29ba5-*.log.{6,9,10}
ls ~/.t3/userdata-v2/logs/provider/ | grep -c 'c878541b\|de5f191a\|68f7595b\|af66fc2c' # 0
```
- [ ] Status: not started
## 10. Streaming deltas persisted as full-row event pairs (~2800x amplification)
**Severity: medium (cost/scale, not correctness).** Grok/ACP streams a child task's result
per-token; each chunk is persisted as a **full-row** `turn-item.updated` + `message.updated`
event pair. One 6,274-char result accumulated 2,704 events; a 2-minute session wrote 6,017
rows (14% of the whole 43k-row table). Replay and projection costs scale with this.
**Root cause:** `AcpAdapterV2.emitSubagentAssistant` emits a full event pair per
`agent_message_chunk`, and `ProviderEventIngestor` persists every emission.
**Proposed fix:**
1. Split live streaming from persistence: broadcast deltas to subscribers in-memory, persist
coalesced snapshots (e.g. on item completion + every N seconds/K bytes while running).
2. Alternatively debounce persistence per item id in the ingestor so any adapter gets the
benefit.
3. Check other adapters for the same pattern (claude/codex emit per-block, which is fine;
ACP per-token is the outlier).
**Repro:**
```sh
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
"SELECT event_type, COUNT(*) FROM orchestration_events \
WHERE stream_id LIKE 'thread:provider:grok:native-thread:019f1558%' GROUP BY 1;"
```
- [ ] Status: not started
## 11. Claude assistant text segments merged without separator (fixed — needs regression fixture)
**Severity: medium, already fixed in worktree.** In the `6d618dc4` MCP group (build
`fc23be8184`), 5 interleaved assistant text blocks were accumulated
(`context.assistant.text += ...`) and emitted as ONE item at end of turn — 10,642 chars joined
with no separator, ordered after all 19 tool calls, losing interleaving. Current worktree code
(`emitAssistantTextArtifacts` per `message.uuid`) already emits per-segment items.
**Remaining work:**
- [x] Fix (already in worktree)
- [ ] Add a replay fixture asserting multi-segment assistant text produces one item per SDK
uuid, interleaved with tool items at correct ordinals
## 12. OpenCode `file_search` items drop error/output
**Severity: medium.** Child session `ses_0ea978228`: a failed `file_search` item projects only
`{status: 'failed', type: 'file_search', pattern: '...'}` — the provider's error message is
unrecoverable. Same shape drops successful read/grep/glob outputs (low finding).
**Root cause:** `OpenCodeAdapterV2.ts` — `toolOutput()` (line ~659) extracts
`part.state.error`, but the `file_search` mapping branch (~line 1376) only maps `pattern`;
output/error only attach for `dynamic_tool`. The contract type
(`packages/contracts/src/orchestrationV2.ts` ~line 841) has no output/error field on
`file_search` either.
**Proposed fix:**
1. Add optional `output`/`error` to the `file_search` item contract.
2. Map `part.state.error` (and output where present) in the opencode/ACP `file_search` branch.
3. Grok has the same gap (`file_search`/`read` persist only pattern/fileName echo — low
finding); fix at the shared mapping level if possible.
**Repro:**
```sh
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
"SELECT payload_json FROM orchestration_v2_projection_turn_items \
WHERE turn_item_id='turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc';"
```
- [ ] Status: not started
## 13. Low-severity backlog
Unverified (single-auditor) findings, grouped. Tick when triaged/fixed:
**Lineage**
- [ ] `run_attempts.provider_turn_id` is null on ALL 207 attempts DB-wide (reverse link only) —
populate the forward link or drop the column
- [ ] Opencode/claude "pending"-keyed provider-thread placeholder row persists alongside the
real `ses_`-keyed row; runs/attempts reference one, items/active_provider_thread_id the
other (3029dc85, 9f8d616d)
- [ ] Subagent child-thread items carry null run/provider_thread/provider_turn ids (grok,
ea84f015)
- [ ] Interrupt-result turn item references an interrupt-request parent item that was never
emitted (GLOBAL)
- [ ] Synthesized terminal-failure error item references a provider_turn_id that was never
projected (GLOBAL)
**Stuck state / lifecycle**
- [ ] Projection ignores `provider-session.detached` — sessions stay `ready`/`running` for
~20-25h until shutdown sweep (GLOBAL, 1156181e, 6d618dc4, 47763f5e, ea84f015); also
claudeAgent sessions are never idle-reaped
- [ ] Provider-thread row stayed `active` ~20h after its session stopped (9f8d616d)
- [ ] Run 119 (71e29ba5) marked failed while its native query kept running; retry run 120
adopted the result leaving a duplicated user message — dedupe/adopt semantics on retry
**Dropped provider data (no user-visible loss observed yet)**
- [ ] Codex `reasoning` items silently dropped (no adapter handler; all observed summaries were
empty — would lose data once codex emits populated summaries)
- [ ] Codex `thread/tokenUsage/updated` + `account/rateLimits/updated` never ingested — runs
have no usage data; cursor `run.completed` usage also dropped (8ee00dcc)
- [ ] Codex `contextCompaction` item has no projection representation
- [ ] Cursor tool calls that never returned natively are auto-marked `completed` with no
results at turn end (c9e72a05) — should be `failed`/`interrupted`
- [ ] 4 native `error_during_execution` results silently recovered in-adapter with no
projection trace (71e29ba5); one absorbed during a steering message (ea84f015)
**Cosmetic / observability**
- [ ] Grok + opencode native logs redact payloads to shape summaries — no content-level ground
truth for audits; consider a debug setting to log content
- [ ] Grok logs every successful `session/prompt` as `failed` with `errorTag: Interrupt`
- [ ] Cursor native `read` tool calls projected as type `file_search` (semantic mismatch)
- [ ] Cursor `file_change` diffStr has malformed headers (`a//abs/path`, `b//abs/path`)
- [ ] 13 old backgrounded `local_bash` tasks projected as subagents with empty prompts and
synthetic child threads (GLOBAL); backgrounded-bash child threads have empty-text prompt
user_message items (7f1dfff1)
- [ ] Cursor 7.3-minute silent hang before failing (c9e72a05) — no progress/heartbeat signal
exists to distinguish a hung turn from a thinking one
## 14. Cursor SDK unhandled `write EPIPE` crashes the backend child (recurring)
**Severity: high.** Added 2026-07-02 after new cursor sessions reproduced backend crashes.
Distinct from the June-29 crash that the `@cursor/sdk` version bump addressed.
Three occurrences in `server-child.log`, identical signature — `Unhandled 'error' event /
Error: write EPIPE` on a `net.Socket`, followed by the `Node.js v24.15.0` footer (process
death):
- **2026-07-02T19:04:57.558Z** — stack definitively inside `@cursor/sdk/dist/esm/357.js`
(`et.execute` → `We.execute` → `Is.execute`): a connect-RPC execute writing to a
cursor-agent socket whose far end had closed. Context: TWO cursor sessions streaming
concurrently (d1bfdd3d run-0294b303, 4f3381e5 run-c7e93ba0, each with its own provider
session, plus a native subagent task thread); both streamed token-deltas until 19:04:55.5.
- **2026-07-01T20:47:34.573Z** and **2026-07-02T04:46:20.557Z** — same signature, but stack is
only the async write-completion frame (`WriteWrap.onWriteComplete`), so origin unproven. No
cursor turns were active; consistent with a lingering cursor-agent connection dying idle and
a later write hitting EPIPE.
**Collateral (ties into issues 2/4/5):**
- d1bfdd3d run 1 + 4f3381e5 run 1 silently `cancelled` by startup reconcile at 19:05:01;
4f3381e5 has NO error item at all (issue 5).
- d1bfdd3d run 2 (retry) failed with the generic `Failed to start run ... on cursor provider
thread ...pending...` wrapper, cause depth-elided in the log (issue 2), and targeted the
stale `pending`-keyed provider thread (issue 13 lineage note).
- The two earlier EPIPE crashes explain two previously "undebuggable" audit failures: the
restarted child killed the live claude CLI processes, so 7f1dfff1 run 10 (requested
20:47:56, `claude-query-stream-failed` 20:47:58) and 71e29ba5 run 89 (requested 04:47:03)
failed ~20-40s after each crash with the generic "Claude Agent SDK query failed."
- The June-29 crash's actual error text is unknowable: the stderr dump was truncated at
51,674 chars (log line cap) BEFORE the error message — only minified bundle source survived.
**Proposed fix:**
1. Containment: attach `error` handlers to (or wrap) the cursor SDK's sockets, and add a
`process.on('uncaughtException'/'unhandledRejection')` policy in the backend child that
fails the owning provider session instead of dying. Longer-term: isolate provider SDKs in
their own child process so an SDK crash cannot kill the orchestrator.
2. Report upstream to Cursor: SDK leaves its agent socket without an `error` listener;
`write EPIPE` after agent-process exit is fatal to the host.
3. Fix stderr log truncation: when capping captured child output, keep the TAIL (where Node
prints the error + stack), not just the head.
4. Issues 2/4/5 remain the reason this was hard to diagnose — they get us error items with
real causes, native-log failure frames, and user-visible reconcile cancellations.
**Repro:**
```sh
grep -n "Unhandled 'error' event" ~/.t3/userdata-v2/logs/server-child.log # 3 hits
sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \
"SELECT run_id,status,completed_at FROM orchestration_v2_projection_runs \
WHERE thread_id IN ('d1bfdd3d-38cc-4ff3-ab75-8be6dc592b00','4f3381e5-89e2-45a8-bca1-bbe5d520bbba');"
```
- [ ] Status: not started
## Refuted during verification (do NOT act on)
- 71e29ba5 "ingestion gap, 119 items lost" — traffic belonged to c878541b via the shared codex
session (see issue 9).
- 47763f5e "122 thinking blocks dropped" — all native thinking blocks were empty
(`{"thinking":""}`); nothing to lose. (Reasoning ingestion is still absent, tracked as low.)
- ea84f015 failed cursor runs 15-17 "generic error" — native results genuinely carried no
detail; nothing to persist (but see issues 3/4 for making cursor carry detail).
## Validation
- Re-run the audit repro queries above after each fix; each issue's repro should flip.
- Extend replay fixtures (`testkit/fixtures/`) per issue where marked; the audit evidence
(thread ids + native log excerpts) is fixture source material.
- Full audit data with per-finding evidence, verifier verdicts, and repro commands:
`.plans/22-orchestration-v2-audit-findings.json`.
+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`
@@ -126,7 +126,7 @@ const withIdentity = <A, E, R>(
input.legacyPathProbeError
? Effect.fail(input.legacyPathProbeError)
: Effect.succeed(
input.legacyPathExists === true && path.includes("T3 Code (Alpha)"),
input.legacyPathExists === true && path.includes("T3 Code (Alpha v2)"),
),
readFileString: () =>
Effect.succeed(input.packageJson ?? '{"t3codeCommitHash":"abcdef1234567890"}'),
@@ -147,14 +147,14 @@ describe("DesktopAppIdentity", () => {
const identity = yield* DesktopAppIdentity.DesktopAppIdentity;
const userDataPath = yield* identity.resolveUserDataPath;
assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha)");
assert.equal(userDataPath, "/Users/alice/Library/Application Support/T3 Code (Alpha v2)");
}),
{ legacyPathExists: true },
),
);
it.effect("preserves failures while inspecting the legacy userData path", () => {
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha)";
const legacyPath = "/Users/alice/Library/Application Support/T3 Code (Alpha v2)";
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
@@ -254,7 +254,7 @@ describe("DesktopConnectionCatalogStore", () => {
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/connection-catalog.json`,
pathOrDescriptor: `${baseDir}/userdata-v2/connection-catalog.json`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
@@ -271,11 +271,11 @@ describe("DesktopConnectionCatalogStore", () => {
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreReadError,
);
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Failed to read the desktop connection catalog at ${baseDir}/userdata/connection-catalog.json.`,
`Failed to read the desktop connection catalog at ${baseDir}/userdata-v2/connection-catalog.json.`,
);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
@@ -291,7 +291,7 @@ describe("DesktopConnectionCatalogStore", () => {
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: `${baseDir}/userdata`,
pathOrDescriptor: `${baseDir}/userdata-v2`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
@@ -309,11 +309,11 @@ describe("DesktopConnectionCatalogStore", () => {
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreWriteError,
);
assert.equal(error.operation, "create-directory");
assert.equal(error.path, `${baseDir}/userdata`);
assert.equal(error.path, `${baseDir}/userdata-v2`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata.`,
`Desktop connection catalog write failed during create-directory at ${baseDir}/userdata-v2.`,
);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
@@ -398,14 +398,14 @@ describe("DesktopConnectionCatalogStore", () => {
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
);
assert.equal(error.operation, "decrypt-catalog");
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.equal(error.catalogPath, `${baseDir}/userdata-v2/connection-catalog.json`);
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
assert.instanceOf(decryptError.cause, Error);
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
assert.equal(
error.message,
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata-v2/connection-catalog.json.`,
);
assert.notEqual(error.message, decryptError.message);
yield* Ref.set(failDecrypt, false);
@@ -78,7 +78,7 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("derives production state paths under userdata", () =>
it.effect("derives production state paths under userdata-v2", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
{},
@@ -88,10 +88,12 @@ describe("DesktopEnvironment", () => {
);
assert.equal(environment.isDevelopment, false);
assert.equal(environment.stateDir, "/tmp/t3/userdata");
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.stateDir, "/tmp/t3/userdata-v2");
assert.equal(environment.logDir, "/tmp/t3/userdata-v2/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata-v2/browser-artifacts");
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata-v2/settings.json");
assert.equal(environment.userDataDirName, "t3code-v2");
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha v2)");
}),
);
+3 -3
View File
@@ -155,9 +155,9 @@ const make = Effect.fn("desktop.environment.make")(function* (
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata-v2");
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code-v2";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha v2)";
const resourcesPath = input.resourcesPath;
return DesktopEnvironment.of({
@@ -358,7 +358,7 @@ describe("DesktopBackendConfiguration", () => {
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const settingsPath = path.join(baseDir, "userdata", "settings.json");
const settingsPath = path.join(baseDir, "userdata-v2", "settings.json");
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
@@ -503,7 +503,7 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
};
// Forward the dev-server URL as an explicit CLI flag so the WSL backend's
// config resolution lands in dev/ instead of userdata/. Inheriting through
// config resolution lands in dev/ instead of userdata-v2/. Inheriting through
// WSLENV is unreliable in practice (URL-shaped values with colons /
// slashes get translated unpredictably depending on flags), and the
// packaged build leaves devServerUrl as None anyway.
@@ -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
@@ -83,7 +83,7 @@ describe("DesktopClientSettings diagnostics", () => {
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
pathOrDescriptor: `${baseDir}/userdata-v2/client-settings.json`,
});
return Effect.gen(function* () {
@@ -403,7 +403,7 @@ describe("DesktopSavedEnvironments", () => {
const baseDir = yield* baseFileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-saved-environments-test-",
});
const registryPath = `${baseDir}/userdata/saved-environments.json`;
const registryPath = `${baseDir}/userdata-v2/saved-environments.json`;
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
@@ -439,7 +439,7 @@ describe("DesktopSavedEnvironments", () => {
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: `${baseDir}/userdata`,
pathOrDescriptor: `${baseDir}/userdata-v2`,
});
const fileSystemLayer = Layer.succeed(
FileSystem.FileSystem,
@@ -455,11 +455,11 @@ describe("DesktopSavedEnvironments", () => {
const error = yield* savedEnvironments.setRegistry([savedRegistryRecord]).pipe(Effect.flip);
assert.instanceOf(error, DesktopSavedEnvironments.DesktopSavedEnvironmentsWriteError);
assert.equal(error.operation, "create-directory");
assert.equal(error.path, `${baseDir}/userdata`);
assert.equal(error.path, `${baseDir}/userdata-v2`);
assert.strictEqual(error.cause, permissionError);
assert.equal(
error.message,
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata.`,
`Desktop saved-environment write failed during create-directory at ${baseDir}/userdata-v2.`,
);
assert.notEqual(error.message, permissionError.message);
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+1 -1
View File
@@ -204,7 +204,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>
+68 -62
View File
@@ -3,6 +3,10 @@ import {
ConnectionRegistrationStore,
ConnectionTargetStore,
EnvironmentCacheStore,
ORCHESTRATION_CACHE_SCHEMA_VERSION,
StoredOrchestrationShellSnapshot,
StoredOrchestrationThreadSnapshot,
decodeOrDiscardOrchestrationCache,
registerConnectionInCatalog,
removeConnectionFromCatalog,
removeCatalogValue,
@@ -14,12 +18,7 @@ import {
CredentialStore,
ProfileStore,
} from "@t3tools/client-runtime/connection";
import {
EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
ThreadId,
} from "@t3tools/contracts";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -29,34 +28,16 @@ import * as SecureStore from "expo-secure-store";
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
// v2 stores the snapshot sequence alongside the thread so a warm cache can
// resume via `afterSequence` instead of re-downloading the full thread body.
// Older v1 entries (no sequence) fail to decode and are treated as a cold cache.
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
snapshot: OrchestrationShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
threadId: ThreadId,
snapshot: OrchestrationThreadDetailSnapshot,
});
const LegacyStoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(1),
environmentId: EnvironmentId,
snapshotReceivedAt: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot);
const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot);
const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot);
const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot);
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
@@ -292,44 +273,50 @@ export const connectionStorageLayer = Layer.effectContext(
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-shell", cause)),
);
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
}
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
if (!legacyFile.exists) {
return Option.none();
if (legacyFile.exists) {
yield* Effect.try({
try: () => legacyFile.delete(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
}
const legacyRaw = yield* Effect.tryPromise({
try: () => legacyFile.text(),
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyParsed = yield* Effect.try({
try: () => JSON.parse(legacyRaw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
: Option.none();
}),
return Option.none();
}).pipe((decode) =>
decodeOrDiscardOrchestrationCache(
decode,
shellSnapshotFile(environmentId, "load-shell").pipe(
Effect.flatMap((file) =>
Effect.try({
try: () => {
if (file.exists) file.delete();
},
catch: (cause) => shellPersistenceError("load-shell", cause),
}),
),
Effect.catch(() => Effect.void),
),
),
),
saveShell: (environmentId, snapshot) =>
Effect.gen(function* () {
const file = yield* shellSnapshotFile(environmentId, "save-shell");
const stored = {
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe(
Effect.mapError((cause) => shellPersistenceError("save-shell", cause)),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -354,21 +341,40 @@ export const connectionStorageLayer = Layer.effectContext(
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-thread", cause)),
);
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.snapshot)
: Option.none();
}),
}).pipe((decode) =>
decodeOrDiscardOrchestrationCache(
decode,
threadSnapshotFile(environmentId, threadId, "load-thread").pipe(
Effect.flatMap((file) =>
Effect.try({
try: () => {
if (file.exists) file.delete();
},
catch: (cause) => shellPersistenceError("load-thread", cause),
}),
),
Effect.catch(() => Effect.void),
),
),
),
saveThread: (environmentId, snapshot) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, snapshot.thread.id, "save-thread");
const file = yield* threadSnapshotFile(
environmentId,
snapshot.projection.thread.id,
"save-thread",
);
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
encodeStoredThreadSnapshot({
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
environmentId,
threadId: snapshot.thread.id,
threadId: snapshot.projection.thread.id,
snapshot,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
@@ -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,40 +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,
};
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",
},
};
}
+2 -2
View File
@@ -139,7 +139,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,
};
}
@@ -402,7 +402,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;
@@ -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,27 +34,39 @@ 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,
session: 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,
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 {
@@ -6,6 +6,7 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools
import { describe, expect, it } from "vite-plus/test";
import { buildHomeThreadGroups } from "./homeThreadList";
import { makeThreadShellFixture } from "../../test-fixtures";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
@@ -25,23 +26,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,
};
});
}
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
@@ -473,7 +473,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(
@@ -37,7 +37,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";
@@ -165,7 +165,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
@@ -276,13 +278,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,216 @@
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 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.activity, 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,
@@ -90,7 +93,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;
@@ -287,9 +290,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";
@@ -42,10 +42,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;
@@ -53,11 +55,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;
@@ -84,16 +86,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;
@@ -404,7 +406,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}
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
@@ -412,6 +415,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}
@@ -440,6 +449,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
) : null}
<ThreadQueueControl
environmentId={props.environmentId}
threadId={props.selectedThread.id}
/>
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="gap-3 px-4 pb-3"
+156 -66
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 { SymbolView } from "expo-symbols";
import { HeaderHeightContext } from "@react-navigation/elements";
@@ -75,6 +83,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,
@@ -86,11 +95,15 @@ 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 { ThreadWorkLog } from "./thread-work-log";
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";
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
@@ -121,17 +134,19 @@ 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 listRef: RefObject<LegendListRef | null>;
readonly freeze: SharedValue<boolean>;
readonly anchorMessageId: MessageId | null;
readonly contentInsetEndAdjustment: SharedValue<number>;
readonly contentTopInset?: number;
readonly contentBottomInset?: number;
readonly topAccessory?: ReactNode;
readonly contentMaxWidth?: number;
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
@@ -139,6 +154,80 @@ export interface ThreadFeedProps {
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
}
async function waitForThreadShell(environmentId: EnvironmentId, threadId: ThreadId): Promise<void> {
const atom = environmentThreadShells.threadShellAtom(scopeThreadRef(environmentId, threadId));
const deadline = Date.now() + 2_000;
while (appAtomRegistry.get(atom) === null && Date.now() < deadline) {
await new Promise<void>((resolve) => setTimeout(resolve, 40));
}
}
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;
await waitForThreadShell(props.environmentId, targetThreadId);
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;
@@ -697,15 +786,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" | "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;
@@ -714,17 +804,18 @@ function renderFeedEntry(
readonly reviewCommentColors: ReviewCommentColors;
readonly reviewCommentBubbleWidth: number;
readonly userBubbleMaxWidth: number;
readonly threadTitle: string;
},
) {
const entry = info.item;
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
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]"
>
@@ -741,18 +832,6 @@ function renderFeedEntry(
);
}
if (entry.type === "work-toggle") {
return (
<ThreadWorkGroupToggle
expanded={entry.expanded}
hiddenCount={entry.hiddenCount}
iconSubtleColor={iconSubtleColor}
onlyToolActivities={entry.onlyToolActivities}
onToggle={() => props.onToggleWorkGroup(entry.groupId)}
/>
);
}
if (entry.type === "message") {
const { message } = entry;
const isUser = message.role === "user";
@@ -763,7 +842,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) &&
@@ -777,6 +856,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={{
@@ -868,6 +952,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}
@@ -888,10 +978,14 @@ function renderFeedEntry(
<ThreadWorkLog
activities={entry.activities}
copiedRowId={props.copiedRowId}
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}
/>
);
}
@@ -1169,9 +1263,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,
@@ -1182,7 +1276,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: {},
@@ -1255,6 +1349,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const listAppearanceData = useMemo(
() => ({
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1264,6 +1359,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}),
[
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
iconSubtleColor,
markdownStyles,
@@ -1303,24 +1399,9 @@ 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,
expandedTurnIds,
expandedWorkGroupIds,
),
[expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn],
() => deriveThreadFeedPresentation(props.feed, props.latestRun, expandedTurnIds),
[expandedTurnIds, props.feed, props.latestRun],
);
// The empty↔filled key below remounts the list, which resets its imperative
@@ -1349,29 +1430,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),
@@ -1380,14 +1461,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 () => {
@@ -1455,7 +1536,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const onToggleWorkGroup = useCallback(
(groupId: string) => {
suspendEndScrollMaintenanceForDisclosure(`work-toggle:${groupId}`);
suspendEndScrollMaintenanceForDisclosure(groupId);
setInteractionState((current) => ({
...current,
expandedWorkGroups: {
@@ -1468,8 +1549,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: {
@@ -1482,14 +1563,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 };
});
@@ -1506,6 +1587,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
renderFeedEntry(info, {
environmentId: props.environmentId,
copiedRowId,
expandedWorkGroups,
expandedWorkRows,
terminalAssistantMessageIds,
unsettledTurnId,
@@ -1521,10 +1603,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,
@@ -1541,7 +1626,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onToggleWorkGroup,
onToggleWorkRow,
props.environmentId,
props.threadTitle,
props.skills,
props.workspaceRoot,
],
);
@@ -1657,7 +1744,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,
@@ -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,297 @@
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 { 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(
() =>
immediateThreadRelationships(graph, props.threadId).toSorted(
(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";
@@ -306,7 +307,7 @@ function ThreadRouteContent(
}),
[knownTerminalSessions, selectedThreadProject?.workspaceRoot],
);
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
const handleReconnectEnvironment = useCallback(() => {
if (!environmentId) {
return;
@@ -442,20 +443,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]);
@@ -1,12 +1,17 @@
import * as Haptics from "expo-haptics";
import { SymbolView, type SFSymbol } from "expo-symbols";
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 { 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 +74,57 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): SFSymbol {
}
}
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 +136,31 @@ function isFreshRow(createdAt: string): boolean {
export function ThreadWorkLog(props: {
readonly activities: ReadonlyArray<ThreadFeedActivity>;
readonly copiedRowId: string | null;
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,16 +168,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.fullDetail !== null;
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
const detail = compactActivityDetail(row.detail);
const displayText = detail ? `${row.summary} ${detail}` : row.summary;
const iconIsDestructive = 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}
@@ -137,13 +204,13 @@ 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">
<View className="min-h-9 flex-row items-center gap-1.5">
<View className="h-5 w-5 shrink-0 items-center justify-center">
<SymbolView
name={workRowSymbolName(row.icon)}
size={13}
size={14}
weight="medium"
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
type="monochrome"
@@ -159,8 +226,8 @@ export function ThreadWorkLog(props: {
>
{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>
@@ -201,81 +268,61 @@ export function ThreadWorkLog(props: {
</Pressable>
{expanded && row.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
style={{ maxHeight: 240 }}
contentContainerStyle={{ paddingRight: 8 }}
>
<Text
selectable
className="text-2xs leading-normal text-foreground-muted"
style={{ fontFamily: "ui-monospace" }}
>
{row.fullDetail}
</Text>
</ScrollView>
<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}
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>
</View>
);
}
export function ThreadWorkGroupToggle(props: {
readonly expanded: boolean;
readonly hiddenCount: number;
readonly iconSubtleColor: import("react-native").ColorValue;
readonly onlyToolActivities: boolean;
readonly onToggle: () => void;
}) {
const colorScheme = useColorScheme();
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
const noun = props.onlyToolActivities
? props.hiddenCount === 1
? "tool call"
: "tool calls"
: props.hiddenCount === 1
? "log entry"
: "log entries";
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
const expandedLabel = props.onlyToolActivities
? "Show fewer tool calls"
: "Show fewer log entries";
return (
<View className="-mx-1 mb-1 px-1 py-0">
<Pressable
accessibilityRole="button"
accessibilityState={{ expanded: props.expanded }}
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
hitSlop={4}
onPress={() => {
void Haptics.selectionAsync();
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"
>
<View className="h-[18px] w-5 items-center justify-center">
<SymbolView
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}`}
</Text>
</Pressable>
{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>
);
}
@@ -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 -4
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,22 +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,
};
});
}
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}`;
}
+218 -401
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,401 +16,227 @@ 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,
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?.fullDetail).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).toEqual([
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,
{
id: "tool-completed",
createdAt: "2026-04-01T00:00:02.000Z",
turnId: "turn-1",
summary: "Run tests",
detail: "bun run test",
fullDetail: "/bin/zsh -lc 'bun run test'",
copyText: "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
icon: "command",
toolLike: true,
status: "success",
},
]);
});
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]?.fullDetail).toContain('"query": "work log"');
expect(group.activities[0]?.fullDetail).toContain("repository.search");
});
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",
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",
});
expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
expect(presented.find((entry) => entry.type === "activity-group")?.activities[0]?.status).toBe(
"failure",
);
});
it("keeps an active turn expanded and classifies error-shaped tool output", () => {
const turnId = TurnId.make("turn-running");
const thread = makeThread({
id: ThreadId.make("thread-4"),
projectId: ProjectId.make("project-1"),
title: "Running work",
latestTurn: {
turnId,
state: "running",
requestedAt: "2026-04-01T00:00:00.000Z",
startedAt: "2026-04-01T00:00:01.000Z",
completedAt: null,
assistantMessageId: null,
},
activities: [
makeActivity({
id: EventId.make("tool-failed"),
kind: "tool.completed",
tone: "tool",
summary: "Run command",
createdAt: "2026-04-01T00:00:05.000Z",
turnId,
payload: {
title: "Run command",
itemType: "command_execution",
detail: "zsh: command not found: nope",
status: "completed",
},
}),
],
});
const feed = buildThreadFeed(thread);
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
expect(feed[0]).toMatchObject({
type: "activity-group",
activities: [{ status: "failure" }],
});
});
it("models work-log overflow as list rows", () => {
it("keeps work-log overflow inside grouped activity rows", () => {
const activity = (
id: string,
createdAt: string,
@@ -420,21 +244,23 @@ describe("buildThreadFeed", () => {
): ThreadFeedActivity => ({
id,
createdAt,
turnId: null,
runId: null,
summary: `Tool ${id}`,
detail: null,
fullDetail: null,
copyText: id,
icon: "command",
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"),
@@ -444,25 +270,16 @@ describe("buildThreadFeed", () => {
},
];
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
expect(collapsed[1]).toMatchObject({
type: "work-toggle",
groupId: "work-group-1",
hiddenCount: 2,
expanded: false,
});
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
expect(expanded.map((entry) => entry.id)).toEqual([
"activity-1",
"activity-2",
"activity-3",
"work-toggle:work-group-1",
]);
expect(expanded.at(-1)).toMatchObject({
type: "work-toggle",
expanded: true,
const presented = deriveThreadFeedPresentation(feed, null, new Set());
expect(presented).toHaveLength(1);
expect(presented[0]).toMatchObject({
type: "activity-group",
id: "work-group-1",
});
expect(
presented[0]?.type === "activity-group"
? presented[0].activities.map((entry) => entry.id)
: [],
).toEqual(["activity-1", "activity-neutral", "activity-2", "activity-3"]);
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,228 @@
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);
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);
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);
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,
);
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,
});
expect(model.canRollback).toBe(true);
expect(model.rollbackTarget).toEqual({
threadId: sourceThreadId,
checkpointId,
scopeId,
});
});
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,
});
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,304 @@
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,
): 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" ? 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 {
@@ -216,6 +217,7 @@ export function useThreadOutboxDrain(): void {
environmentId: queuedMessage.environmentId,
input: {
commandId: queuedMessage.commandId,
creationSource: "mobile",
threadId: queuedMessage.threadId,
message: {
messageId: queuedMessage.messageId,
@@ -309,7 +311,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;
+52 -15
View File
@@ -2,12 +2,16 @@ 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 { useProject, useThreadShell } from "../state/entities";
@@ -29,9 +33,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,30 +46,61 @@ 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 = projection.runs.toSorted((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,
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,
}),
),
);
}
+70
View File
@@ -0,0 +1,70 @@
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,
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:",
+80 -42
View File
@@ -40,6 +40,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 +56,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>();
@@ -224,35 +228,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 +277,56 @@ 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 {};
}),
);
yield* agent.handleCreateSession(() =>
Effect.succeed({
sessionId,
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
Effect.gen(function* () {
if (!authenticated) {
return yield* AcpError.AcpRequestError.authRequired();
}
return {
sessionId,
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
};
}),
);
@@ -380,6 +392,38 @@ const program = Effect.gen(function* () {
}),
);
yield* agent.handleListSessions((request) =>
Effect.succeed({
sessions: [
{
sessionId,
cwd: request.cwd ?? process.cwd(),
title: "Mock session",
updatedAt: "1970-01-01T00:00:00.000Z",
},
],
}),
);
yield* agent.handleForkSession((request) =>
Effect.succeed({
sessionId: `${request.sessionId}-fork`,
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
);
yield* agent.handleResumeSession(() =>
Effect.succeed({
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
);
yield* agent.handleCloseSession(() => Effect.succeed({}));
yield* agent.handleSetSessionModel((request) =>
Effect.gen(function* () {
if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
@@ -878,12 +922,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");
}
});
@@ -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 ?? "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(".")) {
-522
View File
@@ -1,522 +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 { EnvironmentOrchestrationHttpApi } from "@t3tools/contracts";
import * as NetService from "@t3tools/shared/Net";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
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 { 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,
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("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("logs in to headless connect 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]),
);
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 to T3 Connect.");
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.");
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("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 }),
};
}
+1 -1
View File
@@ -328,7 +328,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
assert.equal(join(baseDir, "userdata"), resolved.stateDir);
assert.equal(join(baseDir, "userdata-v2"), resolved.stateDir);
}),
);
+96 -2
View File
@@ -1,17 +1,91 @@
// @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 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,
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(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 +109,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)),
);
+58 -31
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,12 @@ 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 ServerRuntimeStartup from "../serverRuntimeStartup.ts";
import {
clearPersistedServerRuntimeState,
@@ -45,10 +45,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 +195,12 @@ 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.provideMerge(WorkspacePaths.layer),
Layer.provideMerge(SqlitePersistenceLayerLive),
);
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
@@ -256,7 +253,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 +308,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 +323,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 +372,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 +417,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 +482,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 +508,6 @@ const projectAddCommand = Command.make("add", {
title,
workspaceRoot,
defaultModelSelection: ServerRuntimeStartup.getAutoBootstrapDefaultModelSelection(),
createdAt: DateTime.formatIso(yield* DateTime.now),
});
return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
}),
@@ -502,7 +529,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>;
@@ -537,7 +564,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>;
@@ -552,7 +579,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,
+1 -1
View File
@@ -93,7 +93,7 @@ export const deriveServerPaths = Effect.fn(function* (
devUrl: ServerConfig["Service"]["devUrl"],
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
const { join } = yield* Path.Path;
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata-v2");
const dbPath = join(stateDir, "state.sqlite");
const attachmentsDir = join(stateDir, "attachments");
const logsDir = join(stateDir, "logs");
@@ -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,
+12 -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,
@@ -208,10 +211,18 @@ export const PreviewToolkitRegistrationLive = Layer.mergeAll(
PreviewSnapshotRegistrationLive,
);
export const OrchestratorToolkitRegistrationLive = McpServer.toolkit(OrchestratorToolkit).pipe(
Layer.provide(OrchestratorToolkitHandlersLive),
Layer.provide(OrchestratorMcpService.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,
).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* () {
+2 -3
View File
@@ -7,7 +7,7 @@ import {
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
export type McpCapability = "preview";
export type McpCapability = "preview" | "orchestration";
export interface McpInvocationScope {
readonly environmentId: EnvironmentId;
@@ -16,7 +16,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 +24,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"]));
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(["preview", "orchestration"]),
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 }
@@ -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,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:
"Create a T3-owned child agent thread and run it with only the supplied task prompt, without copying parent conversation history. Provider, model, runtime mode, and interaction mode inherit from the parent unless overridden. Prefer mode='async' and poll task_status for long work; mode='wait' blocks until completion or timeout.",
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 a recurring scheduled task that automatically runs a prompt on a schedule. Use this to set up autonomous recurring work — the app's scheduler fires it even when no turn is active. By default (bindToCurrentThread=true) each run posts into THIS thread, which is how you 'wake up' and continue here on an interval or at a fixed time; set bindToCurrentThread=false to launch a fresh thread each run instead. Provider, model, and runtime settings inherit from the calling thread. Schedule is either {type:'interval', everyMs} (e.g. everyMs=60000 for every minute) or {type:'fixed_time', timeOfDay:'HH:MM', weekdays?:[0-6] where 0=Sunday}.",
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 V2 threads. Each entry may have its own prompt, title, provider instance or driver, model, runtime mode, and interaction mode. Omitted provider/model/settings inherit from the calling thread; entries without prompts create empty threads.",
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 thread and immediately start its first turn. 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,198 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import {
CommandId,
type ModelSelection,
MessageId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { FetchHttpClient } from "effect/unstable/http";
import { describe } from "vite-plus/test";
import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
import { ServerConfig } from "../config.ts";
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import { ProviderInstanceRegistryHydrationLive } from "../provider/Layers/ProviderInstanceRegistryHydration.ts";
import {
NoOpProviderEventLoggers,
ProviderEventLoggers,
} from "../provider/Layers/ProviderEventLoggers.ts";
import { OpenCodeRuntimeLive } from "../provider/opencodeRuntime.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
import { OrchestratorV2 } from "./Orchestrator.ts";
import { OrchestrationV2LayerLive } from "./runtimeLayer.ts";
import { layer as mcpSessionRegistryTestLayer } from "../mcp/McpSessionRegistry.testkit.ts";
const liveAgentId = process.env.T3_ACP_REGISTRY_LIVE_AGENT_ID?.trim() || "devin";
const liveCommandPath = process.env.T3_ACP_REGISTRY_LIVE_COMMAND?.trim();
const liveInstanceId = ProviderInstanceId.make("acpRegistry_live");
const liveModelSelection = {
instanceId: liveInstanceId,
model: "default",
} satisfies ModelSelection;
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-acp-registry-v2-live-",
});
const vcsDriverRegistryLayer = VcsDriverRegistry.layer.pipe(
Layer.provide(VcsProcess.layer),
Layer.provide(serverConfigLayer),
Layer.provide(NodeServices.layer),
);
const checkpointStoreLayer = CheckpointStore.layer.pipe(Layer.provide(vcsDriverRegistryLayer));
const serverSettingsLayer = ServerSettingsService.layerTest({
providerInstances: {
[liveInstanceId]: {
driver: ProviderDriverKind.make("acpRegistry"),
displayName: `ACP Registry: ${liveAgentId}`,
enabled: true,
config: {
agentId: liveAgentId,
...(liveCommandPath ? { commandPath: liveCommandPath } : {}),
},
},
},
});
const providerInstanceRegistryLayer = ProviderInstanceRegistryHydrationLive.pipe(
Layer.provide(
Layer.mergeAll(
serverConfigLayer.pipe(Layer.provide(NodeServices.layer)),
serverSettingsLayer,
NodeServices.layer,
FetchHttpClient.layer,
OpenCodeRuntimeLive.pipe(Layer.provide(NodeServices.layer)),
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
),
),
);
const liveLayer = OrchestrationV2LayerLive.pipe(
Layer.provide(mcpSessionRegistryTestLayer),
Layer.provide(SqlitePersistenceMemory),
Layer.provide(checkpointStoreLayer),
Layer.provide(serverConfigLayer),
Layer.provide(serverSettingsLayer),
Layer.provide(providerInstanceRegistryLayer),
Layer.provide(NodeServices.layer),
);
const waitForIdle = Effect.fn("AcpRegistryOrchestratorV2Live.waitForIdle")(function* (
threadId: ThreadId,
expectedRunCount: number,
) {
const orchestrator = yield* OrchestratorV2;
for (let attempt = 0; attempt < 900; attempt += 1) {
const projection = yield* orchestrator.getThreadProjection(threadId);
if (
projection.runs.length >= expectedRunCount &&
projection.runs.every(
(run) => !["queued", "starting", "running", "waiting"].includes(run.status),
)
) {
return projection;
}
yield* Effect.sleep("500 millis");
}
return yield* Effect.die(new Error(`Timed out waiting for ACP Registry thread ${threadId}.`));
});
describe.runIf(process.env.T3_ACP_REGISTRY_LIVE_ORCHESTRATOR === "1")(
"ACP Registry V2 live orchestrator",
() => {
it.live(
"runs and resumes a real registry agent through the production V2 harness",
() =>
Effect.gen(function* () {
const orchestrator = yield* OrchestratorV2;
const projectId = ProjectId.make("project:acp-registry-live");
const threadId = ThreadId.make("thread:acp-registry-live");
const marker = "ACP_REGISTRY_LIVE_7H3Q";
yield* orchestrator.dispatch({
type: "thread.create",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make("command:acp-registry-live:create"),
threadId,
projectId,
title: `ACP Registry live: ${liveAgentId}`,
modelSelection: liveModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
});
yield* Console.log(
`ACP Registry thread created for '${liveAgentId}'; dispatching first prompt.`,
);
yield* orchestrator.dispatch({
type: "message.dispatch",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make("command:acp-registry-live:first"),
threadId,
messageId: MessageId.make("message:acp-registry-live:first"),
text: `Remember this opaque marker. Respond with exactly: ${marker}`,
attachments: [],
modelSelection: liveModelSelection,
dispatchMode: { type: "start_immediately" },
});
const firstProjection = yield* waitForIdle(threadId, 1);
const firstAssistant = firstProjection.messages.findLast(
(message) => message.role === "assistant",
)?.text;
assert.deepEqual(
firstProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[[liveInstanceId, "completed"]],
);
assert.include(firstAssistant ?? "", marker);
yield* Console.log("First ACP turn completed; dispatching continuation prompt.");
yield* orchestrator.dispatch({
type: "message.dispatch",
createdBy: "user",
creationSource: "web",
commandId: CommandId.make("command:acp-registry-live:second"),
threadId,
messageId: MessageId.make("message:acp-registry-live:second"),
text: "Return the opaque marker from the previous turn. Respond with only the marker.",
attachments: [],
modelSelection: liveModelSelection,
dispatchMode: { type: "start_immediately" },
});
const finalProjection = yield* waitForIdle(threadId, 2);
const finalAssistant = finalProjection.messages.findLast(
(message) => message.role === "assistant",
)?.text;
assert.deepEqual(
finalProjection.runs.map((run) => [run.providerInstanceId, run.status]),
[
[liveInstanceId, "completed"],
[liveInstanceId, "completed"],
],
);
assert.include(finalAssistant ?? "", marker);
assert.deepEqual(finalProjection.providerSessions.length, 2);
assert.isAtLeast(finalProjection.providerThreads.length, 1);
assert.deepEqual(
finalProjection.providerTurns.map((turn) => turn.status),
["completed", "completed"],
);
}).pipe(Effect.provide(liveLayer), Effect.scoped),
480_000,
);
},
);
@@ -0,0 +1,556 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import {
MessageId,
type ModelSelection,
NodeId,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ProviderSessionId,
ProviderThreadId,
RunAttemptId,
RunId,
ThreadId,
type OrchestrationV2ProviderThread,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/unstable/process";
import type * as EffectAcpProtocol from "effect-acp/protocol";
import { ServerConfig } from "../../config.ts";
import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
import {
ProviderAdapterV2RuntimePolicy,
type ProviderAdapterV2TurnInput,
} from "../ProviderAdapter.ts";
import {
AcpProviderCapabilitiesV2,
makeAcpAdapterV2,
type AcpAdapterV2Flavor,
} from "./AcpAdapterV2.ts";
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-acp-v2-adapter-",
}).pipe(Layer.provide(NodeServices.layer));
const testLayer = Layer.mergeAll(NodeServices.layer, idAllocatorLayer, serverConfigLayer);
const ACP_TEST_DRIVER = ProviderDriverKind.make("acp-test");
const decodeUnknownJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString);
function makeMockRuntime(input: {
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly mockAgentPath: string;
readonly environment?: Readonly<Record<string, string>>;
readonly protocolEvents?: Queue.Queue<EffectAcpProtocol.AcpProtocolLogEvent>;
}): AcpAdapterV2Flavor["makeRuntime"] {
return (runtimeInput) =>
Effect.gen(function* () {
const protocolEvents = input.protocolEvents;
const protocolLogging =
protocolEvents === undefined
? runtimeInput.protocolLogging
: {
...runtimeInput.protocolLogging,
logger: (event: EffectAcpProtocol.AcpProtocolLogEvent) =>
Queue.offer(protocolEvents, event).pipe(
Effect.andThen(runtimeInput.protocolLogging.logger?.(event) ?? Effect.void),
Effect.asVoid,
),
};
const context = yield* Layer.build(
AcpSessionRuntime.layer({
...runtimeInput,
protocolLogging,
spawn: {
command: process.execPath,
args: [input.mockAgentPath],
cwd: runtimeInput.cwd,
env: { T3_ACP_SESSION_LIFECYCLE: "1", ...input.environment },
},
authMethodId: "test",
}).pipe(
Layer.provide(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
),
),
);
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
Effect.provide(context),
);
});
}
function rawProtocolMethod(event: EffectAcpProtocol.AcpProtocolLogEvent): string | undefined {
if (event.stage !== "raw" || typeof event.payload !== "string") return undefined;
for (const line of event.payload.split("\n")) {
const trimmed = line.trim();
if (trimmed.length === 0) continue;
const decoded = Option.getOrUndefined(decodeUnknownJson(trimmed));
if (typeof decoded === "object" && decoded !== null && "method" in decoded) {
const method = (decoded as { readonly method?: unknown }).method;
if (typeof method === "string") return method;
}
}
return undefined;
}
function makeTurnInput(input: {
readonly threadId: ThreadId;
readonly providerThread: OrchestrationV2ProviderThread;
readonly instanceId: ProviderInstanceId;
readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
readonly now: DateTime.Utc;
readonly ordinal?: number;
readonly modelSelection?: ModelSelection;
}): ProviderAdapterV2TurnInput {
const ordinal = input.ordinal ?? 1;
const suffix = `${input.threadId}:${ordinal}`;
const modelSelection =
input.modelSelection ?? ({ instanceId: input.instanceId, model: "default" } as const);
return {
appThread: {
createdBy: "user",
creationSource: "web",
id: input.threadId,
projectId: ProjectId.make(`project:${input.threadId}`),
title: "ACP adapter test",
providerInstanceId: input.instanceId,
modelSelection,
runtimeMode: "approval-required",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: input.providerThread.id,
lineage: {
parentThreadId: null,
relationshipToParent: null,
rootThreadId: input.threadId,
},
forkedFrom: null,
createdAt: input.now,
updatedAt: input.now,
archivedAt: null,
deletedAt: null,
},
threadId: input.threadId,
runId: RunId.make(`run:${suffix}`),
runOrdinal: ordinal,
providerTurnOrdinal: ordinal,
attemptId: RunAttemptId.make(`attempt:${suffix}`),
rootNodeId: NodeId.make(`node:${suffix}`),
providerThread: input.providerThread,
message: {
createdBy: "user",
creationSource: "web",
messageId: MessageId.make(`message:${suffix}`),
text: "test prompt",
attachments: [],
},
modelSelection,
runtimePolicy: input.runtimePolicy,
};
}
describe("AcpAdapterV2", () => {
it.effect("negotiates and executes optional native session forks through the ACP runtime", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const mockAgentPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
const makeRuntime = makeMockRuntime({ childProcessSpawner, mockAgentPath });
const instanceId = ProviderInstanceId.make("acp-test");
const adapter = makeAcpAdapterV2({
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime,
},
fileSystem,
idAllocator,
serverConfig,
});
const sourceThreadId = ThreadId.make("thread-acp-native-fork-source");
const targetThreadId = ThreadId.make("thread-acp-native-fork-target");
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: process.cwd(),
});
const modelSelection = { instanceId, model: "default" } as const;
const runtime = yield* adapter.openSession({
threadId: sourceThreadId,
providerSessionId: ProviderSessionId.make("provider-session-acp-native-fork"),
modelSelection,
runtimePolicy,
});
assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread);
assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot);
const sourceProviderThread = yield* runtime.ensureThread({
threadId: sourceThreadId,
modelSelection,
runtimePolicy,
});
const forkedProviderThread = yield* runtime.forkThread({
sourceProviderThread,
targetThreadId,
});
assert.equal(sourceProviderThread.nativeThreadRef?.nativeId, "mock-session-1");
assert.equal(forkedProviderThread.nativeThreadRef?.nativeId, "mock-session-1-fork");
assert.equal(forkedProviderThread.appThreadId, targetThreadId);
assert.equal(forkedProviderThread.forkedFrom?.providerThreadId, sourceProviderThread.id);
}).pipe(Effect.provide(testLayer), Effect.scoped),
);
it.effect("rejects requested options that the active ACP session does not expose", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const mockAgentPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
const instanceId = ProviderInstanceId.make("acp-test");
const adapter = makeAcpAdapterV2({
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath }),
},
fileSystem,
idAllocator,
serverConfig,
});
const threadId = ThreadId.make("thread-acp-unsupported-option");
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: process.cwd(),
});
const error = yield* adapter
.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-acp-unsupported-option"),
modelSelection: {
instanceId,
model: "default",
options: [{ id: "missing-option", value: "high" }],
},
runtimePolicy,
})
.pipe(Effect.flip);
assert.equal(error._tag, "ProviderAdapterOpenSessionError");
assert.include(String(error.cause), "does not expose requested configuration option(s)");
assert.include(String(error.cause), "missing-option");
}).pipe(Effect.provide(testLayer), Effect.scoped),
);
it.effect("reconfigures a loaded ACP session from its own active setup metadata", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const mockAgentPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
const instanceId = ProviderInstanceId.make("acp-test");
const adapter = makeAcpAdapterV2({
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath, protocolEvents }),
},
fileSystem,
idAllocator,
serverConfig,
});
const firstThreadId = ThreadId.make("thread-acp-active-setup:first");
const secondThreadId = ThreadId.make("thread-acp-active-setup:second");
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: process.cwd(),
});
const initialSelection = { instanceId, model: "default" } satisfies ModelSelection;
const alternateSelection = {
instanceId,
model: "grok-mock-alt",
} satisfies ModelSelection;
const originalSelection = { instanceId, model: "grok-build" } satisfies ModelSelection;
const runtime = yield* adapter.openSession({
threadId: firstThreadId,
providerSessionId: ProviderSessionId.make("provider-session-acp-active-setup"),
modelSelection: initialSelection,
runtimePolicy,
});
const firstProviderThread = yield* runtime.ensureThread({
threadId: firstThreadId,
modelSelection: initialSelection,
runtimePolicy,
});
const now = yield* DateTime.now;
yield* runtime.startTurn(
makeTurnInput({
threadId: firstThreadId,
providerThread: firstProviderThread,
instanceId,
runtimePolicy,
modelSelection: alternateSelection,
now,
}),
);
yield* runtime.events.pipe(
Stream.filter((event) => event.type === "turn.terminal"),
Stream.runHead,
);
const secondProviderThread: OrchestrationV2ProviderThread = {
...firstProviderThread,
id: ProviderThreadId.make("provider-thread-acp-active-setup:second"),
appThreadId: secondThreadId,
nativeThreadRef: {
driver: ACP_TEST_DRIVER,
nativeId: "mock-session-2",
strength: "strong",
},
status: "idle",
};
yield* runtime.resumeThread({
providerThread: secondProviderThread,
modelSelection: alternateSelection,
runtimePolicy,
});
yield* runtime.startTurn(
makeTurnInput({
threadId: secondThreadId,
providerThread: secondProviderThread,
instanceId,
runtimePolicy,
modelSelection: originalSelection,
now,
ordinal: 2,
}),
);
yield* runtime.events.pipe(
Stream.filter((event) => event.type === "turn.terminal"),
Stream.runHead,
);
const setModelRequests = Array.from(yield* Queue.takeAll(protocolEvents)).filter(
(event) =>
event.direction === "outgoing" && rawProtocolMethod(event) === "session/set_model",
);
assert.lengthOf(setModelRequests, 2);
}).pipe(Effect.provide(testLayer), Effect.scoped),
);
it.effect("cancels pending permission requests while interrupting an ACP turn", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const mockAgentPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
const instanceId = ProviderInstanceId.make("acp-test");
const adapter = makeAcpAdapterV2({
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime: makeMockRuntime({
childProcessSpawner,
mockAgentPath,
environment: { T3_ACP_EMIT_TOOL_CALLS: "1" },
}),
},
fileSystem,
idAllocator,
serverConfig,
});
const threadId = ThreadId.make("thread-acp-cancel-permission");
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "approval-required",
interactionMode: "default",
cwd: process.cwd(),
});
const modelSelection = { instanceId, model: "default" } as const;
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-acp-cancel-permission"),
modelSelection,
runtimePolicy,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection,
runtimePolicy,
});
const now = yield* DateTime.now;
yield* runtime.startTurn(
makeTurnInput({ threadId, providerThread, instanceId, runtimePolicy, now }),
);
const pendingRequest = Option.getOrThrow(
yield* runtime.events.pipe(
Stream.filter(
(event) =>
event.type === "runtime_request.updated" && event.runtimeRequest.status === "pending",
),
Stream.runHead,
),
);
if (
pendingRequest.type !== "runtime_request.updated" ||
pendingRequest.runtimeRequest.providerTurnId === null
) {
return yield* Effect.die("Expected a pending ACP permission request with a provider turn");
}
yield* runtime.interruptTurn({
providerThread,
providerTurnId: pendingRequest.runtimeRequest.providerTurnId,
});
const cancelledRequest = Option.getOrThrow(
yield* runtime.events.pipe(
Stream.filter(
(event) =>
event.type === "runtime_request.updated" &&
event.runtimeRequest.id === pendingRequest.runtimeRequest.id &&
event.runtimeRequest.status === "cancelled",
),
Stream.runHead,
),
);
assert.equal(cancelledRequest.type, "runtime_request.updated");
}).pipe(Effect.provide(testLayer), Effect.scoped),
);
it.effect("does not release an ACP turn when cancellation is not acknowledged", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const mockAgentPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
const instanceId = ProviderInstanceId.make("acp-test");
const protocolEvents = yield* Queue.bounded<EffectAcpProtocol.AcpProtocolLogEvent>(256);
const adapter = makeAcpAdapterV2({
instanceId,
flavor: {
driver: ACP_TEST_DRIVER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime: makeMockRuntime({
childProcessSpawner,
mockAgentPath,
environment: { T3_ACP_PROMPT_DELAY_MS: "5000" },
protocolEvents,
}),
},
fileSystem,
idAllocator,
serverConfig,
});
const threadId = ThreadId.make("thread-acp-cancel-timeout");
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: process.cwd(),
});
const modelSelection = { instanceId, model: "default" } as const;
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-acp-cancel-timeout"),
modelSelection,
runtimePolicy,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection,
runtimePolicy,
});
const now = yield* DateTime.now;
const firstTurn = makeTurnInput({
threadId,
providerThread,
instanceId,
runtimePolicy,
now,
});
yield* runtime.startTurn(firstTurn);
yield* Stream.fromQueue(protocolEvents).pipe(
Stream.filter(
(event) =>
event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt",
),
Stream.runHead,
);
const providerTurnId = idAllocator.derive.providerTurn({
driver: ACP_TEST_DRIVER,
nativeTurnId: "mock-session-1:turn:1",
});
const interruptFiber = yield* runtime
.interruptTurn({ providerThread, providerTurnId })
.pipe(Effect.flip, Effect.forkScoped);
yield* Stream.fromQueue(protocolEvents).pipe(
Stream.filter(
(event) =>
event.direction === "outgoing" && rawProtocolMethod(event) === "session/cancel",
),
Stream.runHead,
);
yield* TestClock.adjust("10 seconds");
const interruptError = yield* Fiber.join(interruptFiber);
assert.equal(interruptError._tag, "ProviderAdapterInterruptError");
const secondTurnError = yield* runtime
.startTurn(
makeTurnInput({
threadId,
providerThread,
instanceId,
runtimePolicy,
now,
ordinal: 2,
}),
)
.pipe(Effect.flip);
assert.equal(secondTurnError._tag, "ProviderAdapterTurnStartError");
}).pipe(Effect.provide(testLayer), Effect.scoped),
);
});
@@ -0,0 +1,190 @@
import {
ProviderDriverKind,
ProviderReplayEntry,
type ProviderReplayTranscript,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as EffectAcpErrors from "effect-acp/errors";
import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
import { ACP_PROTOCOL, type AcpAdapterV2RuntimeInput } from "./AcpAdapterV2.ts";
export const AcpReplayTranscript = Schema.Struct({
provider: ProviderDriverKind,
protocol: Schema.Literal(ACP_PROTOCOL),
version: Schema.String,
scenario: Schema.String,
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
entries: Schema.Array(ProviderReplayEntry),
});
export type AcpReplayTranscript = typeof AcpReplayTranscript.Type;
const decodeAcpReplayTranscriptSchema = Schema.decodeUnknownEffect(AcpReplayTranscript);
export class AcpReplayTranscriptDecodeError extends Schema.TaggedErrorClass<AcpReplayTranscriptDecodeError>()(
"AcpReplayTranscriptDecodeError",
{
expectedProvider: ProviderDriverKind,
driver: Schema.optional(Schema.String),
protocol: Schema.optional(Schema.String),
scenario: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to decode ${this.expectedProvider} ACP replay transcript for scenario ${this.scenario ?? "<unknown>"}.`;
}
}
const isAcpReplayTranscriptDecodeError = Schema.is(AcpReplayTranscriptDecodeError);
function metadataFromTranscript(transcript: ProviderReplayTranscript): {
readonly provider?: string;
readonly protocol?: string;
readonly scenario?: string;
} {
return {
provider: transcript.provider,
protocol: transcript.protocol,
scenario: transcript.scenario,
};
}
export function decodeAcpReplayTranscript(
transcript: ProviderReplayTranscript,
expectedProvider: ProviderDriverKind,
options: { readonly retargetProvider?: boolean } = {},
): Effect.Effect<AcpReplayTranscript, AcpReplayTranscriptDecodeError> {
const candidate = options.retargetProvider
? { ...transcript, provider: expectedProvider }
: transcript;
return decodeAcpReplayTranscriptSchema(candidate).pipe(
Effect.filterOrFail(
(decoded) => decoded.provider === expectedProvider,
() =>
new AcpReplayTranscriptDecodeError({
expectedProvider,
...metadataFromTranscript(transcript),
cause: `Expected provider ${expectedProvider}, received ${transcript.provider}`,
}),
),
Effect.mapError((cause) =>
isAcpReplayTranscriptDecodeError(cause)
? cause
: new AcpReplayTranscriptDecodeError({
expectedProvider,
...metadataFromTranscript(transcript),
cause,
}),
),
);
}
interface ReplayStatus {
readonly cursor: number;
readonly total: number;
readonly failure?: unknown;
}
function decodeReplayStatus(raw: string): ReplayStatus {
const value: unknown = JSON.parse(raw);
if (
typeof value !== "object" ||
value === null ||
typeof Reflect.get(value, "cursor") !== "number" ||
typeof Reflect.get(value, "total") !== "number"
) {
throw new Error("ACP replay status is malformed.");
}
return value as ReplayStatus;
}
export function makeAcpReplayCompletenessAssertion(
fileSystem: FileSystem.FileSystem,
statusPath: string,
transcript: AcpReplayTranscript,
): Effect.Effect<void, EffectAcpErrors.AcpError> {
return fileSystem.readFileString(statusPath).pipe(
Effect.mapError(
(cause) =>
new EffectAcpErrors.AcpTransportError({
detail: `Failed to read ACP replay status for ${transcript.scenario}`,
cause,
}),
),
Effect.flatMap((raw) =>
Effect.try({
try: () => decodeReplayStatus(raw),
catch: (cause) =>
new EffectAcpErrors.AcpTransportError({
detail: `Failed to decode ACP replay status for ${transcript.scenario}`,
cause,
}),
}),
),
Effect.flatMap((status) => {
if (
status.failure === undefined &&
status.cursor === transcript.entries.length &&
status.total === transcript.entries.length
) {
return Effect.void;
}
return Effect.fail(
new EffectAcpErrors.AcpTransportError({
detail: `ACP replay did not consume all frames for ${transcript.scenario}`,
cause: status,
}),
);
}),
);
}
export function makeAcpReplayRuntime(input: {
readonly transcript: AcpReplayTranscript;
readonly statusPath: string;
readonly scriptPath: string;
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
}): (
runtimeInput: AcpAdapterV2RuntimeInput,
) => Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
> {
const encodedTranscript = Buffer.from(JSON.stringify(input.transcript), "utf8").toString(
"base64",
);
return (runtimeInput) =>
Effect.gen(function* () {
const context = yield* Layer.build(
AcpSessionRuntime.layer({
...runtimeInput,
spawn: {
command: process.execPath,
args: [input.scriptPath],
cwd: runtimeInput.cwd,
env: {
...process.env,
T3_ACP_REPLAY_TRANSCRIPT: encodedTranscript,
T3_ACP_REPLAY_STATUS_PATH: input.statusPath,
T3_ACP_REPLAY_WORKSPACE: runtimeInput.cwd,
},
},
authMethodId: "replay",
}).pipe(
Layer.provide(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, input.childProcessSpawner),
),
),
);
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
Effect.provide(context),
);
});
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,157 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import { ProviderInstanceId, ProviderSessionId, ThreadId } from "@t3tools/contracts";
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 Schema from "effect/Schema";
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { makeAcpRegistryResolver } from "../../provider/acp/AcpRegistrySupport.ts";
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
import { ProviderAdapterV2RuntimePolicy } from "../ProviderAdapter.ts";
import { BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2 } from "../builtInProviderAdapterDrivers.ts";
import {
ACP_REGISTRY_DRIVER_KIND,
AcpRegistryAdapterV2Driver,
makeAcpRegistryAdapterV2,
} from "./AcpRegistryAdapterV2.ts";
const registryUrl = "https://registry.test/registry.json";
const decodeAcpRegistryAdapterSettings = Schema.decodeUnknownEffect(
AcpRegistryAdapterV2Driver.configSchema,
);
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-acp-registry-v2-adapter-",
}).pipe(Layer.provide(NodeServices.layer));
const registryLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request) =>
Effect.succeed(
HttpClientResponse.fromWeb(
request,
Response.json({
version: "1.0.0",
agents: [
{
id: "fixture-agent",
name: "Fixture Agent",
version: "1.0.0",
description: "ACP V2 adapter fixture",
distribution: {
binary: {
"darwin-aarch64": {
archive: "https://registry.test/unused",
cmd: "fixture-agent",
args: [],
},
"linux-x86_64": {
archive: "https://registry.test/unused",
cmd: "fixture-agent",
args: [],
},
},
},
},
],
}),
),
),
),
);
const testLayer = Layer.mergeAll(
NodeServices.layer,
idAllocatorLayer,
serverConfigLayer,
registryLayer,
);
describe("AcpRegistryAdapterV2", () => {
it("is registered as a generic provider driver with schema defaults", () => {
assert.isTrue(BUILT_IN_PROVIDER_ADAPTER_DRIVER_KINDS_V2.has(ACP_REGISTRY_DRIVER_KIND));
assert.equal(AcpRegistryAdapterV2Driver.driverKind, ACP_REGISTRY_DRIVER_KIND);
assert.deepEqual(AcpRegistryAdapterV2Driver.defaultConfig(), {
enabled: true,
agentId: "",
commandPath: "",
authMethodId: "",
distribution: "auto",
customModels: [],
});
});
it.effect("opens a real ACP child process resolved from registry configuration", () =>
Effect.gen(function* () {
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const mockAgentPath = yield* path.fromFileUrl(
new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
);
const resolver = yield* makeAcpRegistryResolver({
cacheDir: serverConfig.providerStatusCacheDir,
registryUrl,
});
const settings = yield* decodeAcpRegistryAdapterSettings({
agentId: "fixture-agent",
commandPath: process.execPath,
authMethodId: "test",
});
const instanceId = ProviderInstanceId.make("acp-registry-fixture");
const adapter = makeAcpRegistryAdapterV2({
instanceId,
settings,
environment: {
T3_ACP_SESSION_LIFECYCLE: "1",
},
childProcessSpawner,
fileSystem,
idAllocator,
resolver: {
resolve: (configuredSettings, cwd, environment) =>
resolver.resolve(configuredSettings, cwd, environment).pipe(
Effect.map((resolved) => ({
...resolved,
spawn: {
...resolved.spawn,
args: [mockAgentPath],
},
})),
),
},
serverConfig,
});
const threadId = ThreadId.make("thread-acp-registry-fixture");
const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({
runtimeMode: "full-access",
interactionMode: "default",
cwd: process.cwd(),
});
const modelSelection = { instanceId, model: "default" } as const;
const runtime = yield* adapter.openSession({
threadId,
providerSessionId: ProviderSessionId.make("provider-session-acp-registry-fixture"),
modelSelection,
runtimePolicy,
});
const providerThread = yield* runtime.ensureThread({
threadId,
modelSelection,
runtimePolicy,
});
assert.equal(runtime.providerSession.driver, "acpRegistry");
assert.equal(providerThread.nativeThreadRef?.nativeId, "mock-session-1");
assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot);
assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread);
}).pipe(Effect.provide(testLayer), Effect.scoped),
);
});
@@ -0,0 +1,89 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { AcpRegistrySettings } from "@t3tools/contracts";
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 Schema from "effect/Schema";
import { ChildProcessSpawner } from "effect/unstable/process";
import { ServerConfig } from "../../config.ts";
import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts";
import { makeLayerEffect as makeProviderAdapterRegistryLayerEffect } from "../ProviderAdapterRegistry.ts";
import type { OrchestratorV2ProviderReplayHarness } from "../testkit/ProviderReplayHarness.ts";
import { makeReplayServerConfig } from "../testkit/ProviderReplayHarness.ts";
import {
type AcpReplayTranscript,
AcpReplayTranscriptDecodeError,
decodeAcpReplayTranscript,
makeAcpReplayCompletenessAssertion,
makeAcpReplayRuntime,
} from "./AcpAdapterV2.testkit.ts";
import {
ACP_REGISTRY_DEFAULT_INSTANCE_ID,
ACP_REGISTRY_PROVIDER,
makeAcpRegistryAdapterV2,
} from "./AcpRegistryAdapterV2.ts";
const REPLAY_SETTINGS = Schema.decodeUnknownSync(AcpRegistrySettings)({
agentId: "replay-agent",
authMethodId: "replay",
});
export function makeAcpRegistryProviderAdapterRegistryReplayLayer(transcript: AcpReplayTranscript) {
const serverConfigLayer = Layer.effect(
ServerConfig,
makeReplayServerConfig(`acp-registry-${transcript.scenario}`).pipe(Effect.orDie),
).pipe(Layer.provide(NodeServices.layer));
return makeProviderAdapterRegistryLayerEffect(
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const idAllocator = yield* IdAllocatorV2;
const serverConfig = yield* ServerConfig;
const replayDir = yield* fileSystem
.makeTempDirectory({
prefix: `t3-orchestration-v2-acp-registry-replay-${transcript.scenario}-`,
})
.pipe(Effect.orDie);
const statusPath = path.join(replayDir, "status.json");
const scriptPath = yield* path
.fromFileUrl(new URL("../../../scripts/acp-replay-agent.ts", import.meta.url))
.pipe(Effect.orDie);
const adapter = makeAcpRegistryAdapterV2({
instanceId: ACP_REGISTRY_DEFAULT_INSTANCE_ID,
settings: REPLAY_SETTINGS,
environment: {},
childProcessSpawner,
fileSystem,
idAllocator,
resolver: {
resolve: () => Effect.die("ACP registry resolver must not run during replay"),
},
serverConfig,
makeRuntime: makeAcpReplayRuntime({
transcript,
statusPath,
scriptPath,
childProcessSpawner,
}),
assertComplete: makeAcpReplayCompletenessAssertion(fileSystem, statusPath, transcript),
});
return [adapter];
}),
).pipe(Layer.provide(Layer.mergeAll(serverConfigLayer, NodeServices.layer, idAllocatorLayer)));
}
export const AcpRegistryOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness<
AcpReplayTranscript,
AcpReplayTranscriptDecodeError
> = {
driver: ACP_REGISTRY_PROVIDER,
decodeTranscript: (transcript) =>
decodeAcpReplayTranscript(transcript, ACP_REGISTRY_PROVIDER, {
retargetProvider: true,
}),
makeProviderAdapterRegistryLayer: makeAcpRegistryProviderAdapterRegistryReplayLayer,
};
@@ -0,0 +1,180 @@
import {
AcpRegistrySettings,
defaultInstanceIdForDriver,
ProviderDriverKind,
} from "@t3tools/contracts";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as Crypto from "effect/Crypto";
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 Schema from "effect/Schema";
import type * as Scope from "effect/Scope";
import { HttpClient } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as EffectAcpErrors from "effect-acp/errors";
import { ServerConfig } from "../../config.ts";
import {
makeAcpRegistryResolver,
type AcpRegistryResolverShape,
} from "../../provider/acp/AcpRegistrySupport.ts";
import * as AcpSessionRuntime from "../../provider/acp/AcpSessionRuntime.ts";
import { makeAcpNativeLoggerFactory } from "../../provider/acp/AcpNativeLogging.ts";
import { ProviderEventLoggers } from "../../provider/Layers/ProviderEventLoggers.ts";
import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanceEnvironment.ts";
import { IdAllocatorV2 } from "../IdAllocator.ts";
import {
ProviderAdapterDriverCreateError,
type ProviderAdapterDriver,
type ProviderAdapterDriverCreateInput,
} from "../ProviderAdapterDriver.ts";
import {
AcpProviderCapabilitiesV2,
makeAcpAdapterV2,
type AcpAdapterV2Flavor,
type AcpAdapterV2RuntimeInput,
} from "./AcpAdapterV2.ts";
export const ACP_REGISTRY_PROVIDER = ProviderDriverKind.make("acpRegistry");
export const ACP_REGISTRY_DRIVER_KIND = ACP_REGISTRY_PROVIDER;
export const ACP_REGISTRY_DEFAULT_INSTANCE_ID =
defaultInstanceIdForDriver(ACP_REGISTRY_DRIVER_KIND);
const DEFAULT_ACP_REGISTRY_SETTINGS = Schema.decodeSync(AcpRegistrySettings)({});
export interface AcpRegistryAdapterV2Options {
readonly instanceId: Parameters<typeof makeAcpAdapterV2>[0]["instanceId"];
readonly settings: AcpRegistrySettings;
readonly environment: NodeJS.ProcessEnv;
readonly childProcessSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"];
readonly fileSystem: FileSystem.FileSystem;
readonly idAllocator: IdAllocatorV2["Service"];
readonly resolver: AcpRegistryResolverShape;
readonly serverConfig: ServerConfig["Service"];
readonly nativeLogging?: Parameters<typeof makeAcpAdapterV2>[0]["nativeLogging"];
readonly makeRuntime?: (
input: AcpAdapterV2RuntimeInput,
) => Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
>;
readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
}
function makeAcpRegistryRuntime(options: AcpRegistryAdapterV2Options) {
return (
input: AcpAdapterV2RuntimeInput,
): Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
> =>
Effect.gen(function* () {
const resolved = yield* options.resolver
.resolve(options.settings, input.cwd, options.environment)
.pipe(
Effect.mapError(
(cause) =>
new EffectAcpErrors.AcpSpawnError({
command: options.settings.agentId || ACP_REGISTRY_PROVIDER,
cause,
}),
),
);
const context = yield* Layer.build(
AcpSessionRuntime.layer({
...input,
spawn: resolved.spawn,
...(options.settings.authMethodId ? { authMethodId: options.settings.authMethodId } : {}),
}).pipe(
Layer.provide(
Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, options.childProcessSpawner),
),
),
);
return yield* Effect.service(AcpSessionRuntime.AcpSessionRuntime).pipe(
Effect.provide(context),
);
});
}
export function makeAcpRegistryAdapterV2(options: AcpRegistryAdapterV2Options) {
const flavor: AcpAdapterV2Flavor = {
driver: ACP_REGISTRY_PROVIDER,
capabilities: AcpProviderCapabilitiesV2,
makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(options),
...(options.assertComplete === undefined ? {} : { assertComplete: options.assertComplete }),
};
return makeAcpAdapterV2({
instanceId: options.instanceId,
flavor,
fileSystem: options.fileSystem,
idAllocator: options.idAllocator,
serverConfig: options.serverConfig,
...(options.nativeLogging === undefined ? {} : { nativeLogging: options.nativeLogging }),
});
}
export type AcpRegistryAdapterV2DriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
| Crypto.Crypto
| FileSystem.FileSystem
| HttpClient.HttpClient
| IdAllocatorV2
| Path.Path
| ProviderEventLoggers
| ServerConfig;
export const AcpRegistryAdapterV2Driver: ProviderAdapterDriver<
AcpRegistrySettings,
AcpRegistryAdapterV2DriverEnv
> = {
driverKind: ACP_REGISTRY_DRIVER_KIND,
configSchema: AcpRegistrySettings,
defaultConfig: (): AcpRegistrySettings => DEFAULT_ACP_REGISTRY_SETTINGS,
create: Effect.fn("AcpRegistryAdapterV2Driver.create")(
function* (input: ProviderAdapterDriverCreateInput<AcpRegistrySettings>) {
const hostEnvironment = yield* HostProcessEnvironment;
const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const idAllocator = yield* IdAllocatorV2;
const providerEventLoggers = yield* ProviderEventLoggers;
const serverConfig = yield* ServerConfig;
const makeNativeLogger = yield* makeAcpNativeLoggerFactory();
const resolver = yield* makeAcpRegistryResolver({
cacheDir: serverConfig.providerStatusCacheDir,
});
return makeAcpRegistryAdapterV2({
instanceId: input.instanceId,
settings: { ...input.config, enabled: input.enabled },
environment: mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
childProcessSpawner,
fileSystem,
idAllocator,
resolver,
serverConfig,
nativeLogging: (threadId) =>
makeNativeLogger({
nativeEventLogger: providerEventLoggers.native,
provider: ACP_REGISTRY_PROVIDER,
threadId,
}),
});
},
(effect, input) =>
effect.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterDriverCreateError({
driver: ACP_REGISTRY_DRIVER_KIND,
instanceId: input.instanceId,
detail: "Failed to create ACP Registry adapter.",
cause,
}),
),
),
),
};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Loaded 100 of 715 files, more files were not shown because too many files have changed in this diff. Show more