diff --git a/.plans/21-orchestration-v2-application-integration.md b/.plans/21-orchestration-v2-application-integration.md index 7d9107e310..b5005f69bc 100644 --- a/.plans/21-orchestration-v2-application-integration.md +++ b/.plans/21-orchestration-v2-application-integration.md @@ -20,14 +20,15 @@ Execution rules: - Shape 3 performs the backend hard cut and intentionally breaks the old client protocol. - Shape 4.0 updates web and mobile to the final protocol while preserving the current product experience and component structure. - Shape 4.5 enriches that working application with V2-native graph, execution, tool, and context information. -- Do not create a server-side V2-to-V1 compatibility projection. Client presentation adapters may generalize existing component props, but the source of truth remains the complete V2 projection. +- Do not create a server-side V2-to-V1 compatibility projection. Shape 4.0 may use temporary parity adapters around existing component props, but Shape 4.5 must not grow those adapters into a second complete thread/projection model. +- Keep React bindings platform-owned. Web and mobile may have intentionally similar binding and presentation modules; shared client-runtime ownership applies to projection state and domain semantics, not to React hooks or native UI policy. - Only the completed Shape 4.5 system is eligible for a fresh-state user-facing release. Shipping an upgrade to an installation with V1 threads additionally requires the separate Stage 5 migration decision. - Do not drop V1 tables, migrations, provider runtime rows, or attachment files during this plan. - V1 removal happens inside the shape that replaces it; there is no deferred general cleanup phase. ## Alignment With The Current Production Path -At the start of this plan, the application path was V1 at the orchestration boundary. After the completed Shape 3, the server is V2-only while the ordinary web and mobile clients still call the removed V1 protocol. Several provider and selection concepts beneath that boundary were already provider-neutral and have been retained. Shapes 4.0 and 4.5 must continue reusing them rather than recreating the existing model, mode, and provider-instance UX. +At the start of this plan, the application path was V1 at the orchestration boundary. Between completed Shapes 3 and 4.0, the server was V2-only while the ordinary web and mobile clients still called the removed V1 protocol. Shape 4.0 has now closed that temporary gap. Several provider and selection concepts beneath that boundary were already provider-neutral and have been retained. Shape 4.5 must continue reusing them rather than recreating the existing model, mode, and provider-instance UX. The historical pre-cut flow was: @@ -40,21 +41,22 @@ Web/mobile model and mode selection -> driver-specific legacy adapter ``` -The current branch boundary is: +The current post-Shape-4.0 boundary is: ```text ordinary web/mobile state and commands - -> orchestrationV1.* RPCs - -> no server handler after the Shape 3 hard cut - -V2 debug client, CLI, MCP, and backend consumers + -> shared client-runtime V2 shell and thread projections -> final orchestration.* RPCs / V2 application services -> shared application event transaction -> Agent Orchestrator V2 -> provider execution + +V2 debug client + -> direct V2 projection and item inspection + -> reference presentation for Shape 4.5 production enrichment ``` -Shape 4.0 closes this intentional client/server gap. Shape 4.5 enriches the resulting working frontend. +Shape 4.0 closed the intentional client/server gap. Shape 4.5 replaces temporary parity-oriented chat shaping with direct, scoped consumption of the complete V2 projection and its server-authoritative visible item sequence. Current ownership and intended treatment: @@ -315,7 +317,7 @@ Add coverage for: ## Shape 2: Application Services Around V2 -Implementation status: complete. Shape 3 completed the backend protocol cut; the production web/mobile cutover remains intentionally deferred to Shape 4.0. +Implementation status: complete. Shape 3 completed the backend protocol cut; the production web/mobile cutover was subsequently completed in Shape 4.0. ### Goal @@ -702,7 +704,16 @@ Add backend integration coverage for: ## Shape 4.0: V2 Frontend Cutover And Product Parity -Implementation status: pending. +Implementation status: complete. + +Implementation outcome: + +- Web and mobile now consume the unified V2 shell and full V2 thread projections through the shared client runtime, including reconnect/cursor handling and versioned V2-only caches. +- Ordinary project, thread, message, run-control, runtime-request, settings, archive, delete, checkpoint, attachment, and plan-implementation commands now use the final event-sourced project and V2 orchestration transports. +- Existing root-workspace, newly provisioned worktree, origin-based worktree, and already-prepared worktree launch flows are preserved, including promotion of an empty server thread into a worktree before its first message. +- Existing web and mobile product components consume V2-native parity models. The complete projection and structured turn-item payload remain available, while unsupported rich V2 visualization stays deferred to Shape 4.5. +- The parity models are an explicit temporary bridge for existing product components. They are not the intended Shape 4.5 thread API and may be removed incrementally as direct item consumers replace them. +- Production V1 client reducers, subscriptions, command paths, and persistence writers have been removed. Legacy server state remains untouched for the separate Stage 5 migration decision. ### Goal @@ -716,6 +727,8 @@ At the end of Shape 4.0, the ordinary application—not only the V2 debug route - Reuse existing sidebar, chat, composer, approval, archive, diff, settings, and model-picker components where their behavior remains correct. - Generalize component props around V2-native view models instead of manufacturing V1 commands, events, activities, or thread projections. - Retain the complete V2 projection in client state even when the parity UI initially presents only a subset of it. +- Preserve shell and thread-detail state as separately subscribable streams. Shape 4.0 components may compose them locally where required, but the client runtime must not make detail traffic a dependency of shell/sidebar state. +- Keep web and mobile React bindings separate. Similar binding code is intentional and is not a Shape 4.0 deduplication target. - Provide a safe generic renderer for V2 turn-item types that do not yet have a rich presentation. Do not drop structured tool or execution data merely because Shape 4.5 owns the final renderer. - Defer graph visualization, rich execution inspection, and provider-native tool presentation to Shape 4.5. - Do not import V1 server rows or migrate existing V1 threads in this shape. @@ -735,7 +748,7 @@ The server's committed application sequence is the shell reconnect boundary. A t Bump web and mobile orchestration-cache versions. Discard cached V1 shell/thread projections while preserving drafts, credentials, environment configuration, preferences, and unrelated local state. Cache invalidation is not the Stage 5 server-state migration. -### 2. Add a parity-focused V2 presentation adapter +### 2. Add a temporary parity-focused V2 presentation adapter Create shared, V2-native client view models for the existing application surfaces, including: @@ -750,7 +763,7 @@ Create shared, V2-native client view models for the existing application surface Derive these models from the V2 thread projection, `visibleTurnItems`, runs, attempts, runtime requests, and checkpoints. Existing components may be adapted to consume these models, but the adapter must not recreate an `OrchestrationThread`, `OrchestrationThreadActivity`, V1 `latestTurn`, or a V1 event stream. -Web and mobile share the projection reducer and parity derivation rules. Platform-specific components may render the resulting view models differently. +Web and mobile share the projection reducer and retain the complete structured V2 data. Platform-specific components may render temporary parity views differently. Shape 4.5 owns replacing full-thread parity shaping with direct, scoped item consumption; Shape 4.0 does not need to pre-design that final API. ### 3. Replace production client commands @@ -847,6 +860,9 @@ Add web and mobile integration coverage for: - A user can create a project and thread, converse with an agent, reconnect, respond to requests, inspect diffs, archive, and delete. - Existing V1-era product behavior that remains supported by V2 is present without routing through V1 data shapes. - Full V2 projections and structured turn-item payloads are retained even when rendered generically. +- Server-projected `visibleTurnItems`, including inherited and synthetic rows, remain intact in client state even when Shape 4.0 surfaces do not render them richly. +- Shell/sidebar state remains independently subscribable from full thread detail. +- Temporary full-thread parity models and separate web/mobile React binding modules are allowed at this boundary; their final cleanup belongs to Shape 4.5. - No production code calls an `orchestrationV1.*` endpoint. - No V2-to-V1 server or persistence compatibility projection exists. - The V2 debug route is no longer the only functional V2 client. @@ -855,139 +871,189 @@ Add web and mobile integration coverage for: ## Shape 4.5: V2-Native Frontend Enrichment -Implementation status: pending. +Implementation status: in progress. Sections 1 and 2 are implemented for web; mobile cutover and the deeper supporting-state, graph, workflow, and parity-removal sections remain. ### Goal -Enrich the now-working application with information and workflows that V2 models explicitly but the V1 UI could not represent well. This shape builds on the Shape 4.0 state and command path; it must not introduce a second projection model or replace working frontend components without a concrete UX need. +Enrich the now-working application with information and workflows that V2 models explicitly but the V1 UI could not represent well. The production chat must move from the temporary Shape 4.0 parity reconstruction to the server-authoritative ordered V2 item sequence without introducing a second complete projection or a shared React presentation layer. -### 1. Build the complete shared V2 presentation model +The V2 projection remains the client semantic source of truth. Client enrichment adds environment scope and narrowly derived relationships; it does not copy every projection table into another thread-shaped model. -Extend the shared derivation layer to use: +### Shape 4.5 implementation order -- `visibleTurnItems` -- runs and attempts -- execution nodes -- provider sessions, threads, and turns -- runtime requests -- plans and todo steps -- checkpoint scopes and captures -- context handoffs and transfers -- fork, merge-back, and subagent relationships +Complete the following sections in order. The client-runtime substrate is intentionally small; web proves the first production presentation, mobile follows from the same projection semantics, and only then are demonstrated shared domain selectors extracted. -Expose stable UI entries for: +### 1. Establish the scoped projection and item atom boundary -- user and assistant messages -- reasoning -- typed tool and command execution -- file changes -- file, code, and web search -- approvals and user-input requests -- plans and todo lists -- checkpoints and rollback activity -- interrupts, retries, and recovered attempts -- handoffs, forks, merges, and subagents -- errors and diagnostic status +Keep shell and detail as independent sources: -Preserve provider-native and dynamic tool payloads behind a structured fallback so adding a new tool type never makes information disappear. +- `EnvironmentThreadShell` remains the environment-scoped, list-oriented view of the server shell stream. +- Introduce a detail value containing `environmentId` and the pristine `OrchestrationV2ThreadProjection`. Use a temporary migration name such as `ScopedThreadProjection` while the Shape 4.0 parity facade still owns `EnvironmentThread`; after that facade is removed, the contextual wrapper may take the unversioned `EnvironmentThread` name. +- Preserve `wrapper.projection === projectionState.data` and the identities of every nested projection collection. Do not spread or translate the complete projection into a second object graph. +- Do not attach `environmentId` to every nested message, run, node, or item. Values that leave their scoped thread context or participate in cross-thread relationships must carry an explicit `ScopedThreadRef` or equivalent environment-qualified reference. +- Shell consumers read shell atoms. Detail consumers read `projection.thread` and detail atoms. Do not synthesize a shell from detail, globally merge the streams, or make sidebar state depend on detail traffic. A component that truly needs both subscribes to both explicitly. -### 2. Expose thread and execution relationships +The stable client-runtime access surface begins with: -Create a shared graph/lineage model from thread lineage, execution nodes, subagents, forks, and context transfers. It must support: +- the full thread state atom, including cached, synchronizing, live, deleted, and error state +- a scoped whole-thread atom for debugger, graph, and other whole-projection consumers +- a `visibleTurnItems` atom exposing the server-projected ordered item rows +- status/error or an equivalently stable synchronization atom that does not invalidate merely because projection content changed + +`visibleTurnItems` is the production conversation source. It already carries the discriminated union for messages, reasoning, plans, tools, approvals, input requests, checkpoints, interruption request/result items, compaction, handoff, fork, subagent, and dynamic tools. It also carries local, inherited, and synthetic visibility metadata. Production chat must not reconstruct this sequence by merging separate messages, plans, and work-entry arrays. + +Do not publish one atom merely because each projection table exists. Add a derived atom or an entity-by-ID lookup only when a concrete row, control, graph, or inspector needs state absent from its turn item, for example: + +- runtime-request response capability for an approval or user-input row +- current checkpoint/ref state for rollback +- run, attempt, or node state for execution inspection +- context-transfer lifecycle for merge-back or provider handoff + +These lookups must retain the original V2 entity types and identities. A whole-thread atom is a firehose and must not be the default subscription for granular timeline components. + +Keep web and mobile React bindings separate. Do not introduce a shared React package, a shared binding factory, or a `createClientStateGraph` abstraction merely because the two bindings are currently similar. + +#### `visibleTurnItems` structural-sharing prerequisite + +Fix the incremental client reducer before the production rich timeline depends on it: + +- inherited and synthetic rows remain server-authoritative and are never locally reconstructed +- a run or attempt update that does not change visible membership returns the previous `visibleTurnItems` array reference +- a turn-item update with unchanged membership replaces only the affected row and preserves every unaffected row object and position +- positions are recomputed only when visible membership changes +- membership equality alone must not suppress a streaming item-content update + +This is a reducer allocation and correctness requirement, not an atom-level equality workaround. + +### 2. Move the web conversation to authoritative V2 items + +Implement the first Shape 4.5 production vertical slice in web: + +- render the conversation directly from `visibleTurnItems` +- preserve item order across interruption request, intervening provider activity, and interruption result +- preserve inherited items and synthetic fork markers +- render user and assistant messages, reasoning, plans, tool activity, requests, checkpoints, compaction, handoffs, forks, subagents, and dynamic tools from the discriminated union +- retain complete structured/provider-native input and output behind a safe fallback for every item type +- join a row to targeted supporting state by ID only when the item itself is insufficient for interaction or inspection + +Reuse the proven presentation work in the V2 debugger where it fits, especially its direct `visibleTurnItems` path and item renderers. Do not reuse the debugger's local subscriptions, local projection reducer, log reconstruction fallback, or debug-only state management. Production consumes the client-runtime thread state established in section 1. + +Web owns visual row types, icons, labels, folding, adjacent visual grouping, expansion, and copy behavior. Those policies are not client-runtime domain models. + +### 3. Move the mobile conversation to the same projection semantics + +After the web item path is working, move mobile from its Shape 4.0 parity feed to the same authoritative `visibleTurnItems` sequence and targeted entity lookups. + +Mobile keeps its own React bindings and form-factor-specific presentation, including native list behavior, expansion, composer layout, offline/outbox policy, and navigation. It does not need to share web row interfaces, fold policy, labels, or visual grouping. + +Promote logic into client-runtime only when both platforms need the same nontrivial domain interpretation and the relationship is not already explicit in V2. Examples may include environment-scoped cross-thread references or capability-safe entity linkage. Do not extract presentation logic merely because two current implementations happen to look alike. + +### 4. Enrich tools, execution, and supporting state + +Add item renderers and targeted inspectors for: + +- command execution with input, working directory where available, lifecycle, output, duration, and exit state +- file changes with affected paths and patch/diff navigation +- file, code, and web search with query and result provenance +- MCP, dynamic, and provider-native tool calls with complete structured fallback +- nested tool work associated with execution nodes or subagents +- queued, steering, restarting, active, interrupted, failed, retried, superseded, and recovered execution +- attempt history, execution-node progress, and retry reasons +- provider session/thread/turn identity where diagnostically useful +- native resume versus portable context handoff +- context-window and token indicators +- plans, todos, approvals, user input, checkpoints, and rollback state + +The ordered chat remains item-based. Runs, attempts, nodes, provider state, runtime requests, checkpoints, and transfers are supporting relational state; they enrich specific rows, controls, and inspectors rather than becoming additional reconstructed chat feeds. + +Keep primary chat status simple. Detailed execution state belongs in targeted or expandable surfaces. Rendering must preserve live updates without duplicating rows as attempts or provider items change, and large output must remain inspectable without overwhelming the timeline. + +### 5. Expose relationships and V2-native workflows + +Build environment-scoped, cycle-safe graph/lineage derivation from shell threads, thread lineage, execution nodes, subagents, forks, and context transfers. It must support: - root, parent, child, fork, and subagent relationships -- navigation between related threads +- navigation between related threads using environment-qualified references - per-node run and terminal status - merge-back and context-transfer state - archived or deleted related threads -- missing-parent, partial-replay, and cycle-safe fallback behavior +- missing-parent and partial-replay fallback -Web should provide an efficient tree or graph surface without replacing the ordinary project/thread sidebar. Mobile should provide the same relationships through a form-factor-appropriate drill-down rather than attempting to copy the desktop visualization exactly. +Web should provide an efficient tree or graph surface without replacing the ordinary project/thread sidebar. Mobile should expose the same domain relationships through a form-factor-appropriate drill-down rather than copying the desktop visualization. -### 3. Enrich tool and work-log presentation - -Reuse the existing chat activity and work-log components, then add V2-aware renderers for: - -- command execution with command, working directory, lifecycle, output, duration, and exit state -- file changes with affected paths and patch/diff navigation -- file, code, and web search with query and result provenance -- MCP and provider-native tool calls -- dynamic tools with complete structured input/output fallback -- nested tool work associated with execution nodes or subagents -- failed, interrupted, retried, and superseded calls - -Rendering must preserve live updates without duplicating rows as attempts or provider items change. Large output should remain inspectable without overwhelming the conversation timeline. - -### 4. Expose runs, attempts, and recovery - -Add UI affordances for: - -- queued, steering, restarting, and active runs -- attempt history and retry reasons -- execution-node progress -- provider session/thread identity where diagnostically useful -- native resume versus portable context handoff -- context-window and token indicators -- recoverable versus terminal failure state - -Keep the primary chat status simple. Detailed runtime state belongs in expandable inspection surfaces rather than permanently crowding the composer or message list. - -### 5. Add V2-native workflows - -Integrate: +Integrate capability-gated workflows for: - thread fork and merge-back - provider switching and provider-session detach - advanced queue reorder and promotion - subagent navigation and delegated-task state - plan/todo progress -- checkpoint scopes, diff, and rollback +- checkpoint scope, diff, and rollback - context handoff and transfer visibility -Each action must be capability-gated from V2 projection/runtime policy rather than provider-name checks in the UI. +Actions derive from V2 capability and runtime policy. They must not use provider-name conditionals. -### 6. Finish web/mobile reuse and cleanup +### 6. Retire parity state and finish cleanup -- Use one shared presentation derivation for web and mobile. -- Keep platform-specific visual components where appropriate, but do not duplicate event interpretation. -- Remove obsolete V1 `session-logic.ts`, mobile `threadActivity.ts`, and equivalent transformations after their consumers are gone. -- Remove unused V1 client RPC contracts and compatibility exports. -- Split still-required project application contracts and frozen legacy thread decoders into clear ownership boundaries instead of deleting reusable application infrastructure. -- Delete the V2 debug route after its inspection tools and useful renderers have production homes. -- Rename V2 production-facing client types to unversioned names only if the rename reduces long-term ambiguity without obscuring the retained application event-source contracts. +After web and mobile no longer depend on the Shape 4.0 full-thread parity facade: + +- remove `presentThread`-style whole-projection remapping and the shell/detail reconciliation it required +- give the environment-scoped projection wrapper the final unversioned client name if doing so improves clarity +- remove message/work/plan feed reconstruction and other obsolete transformations from `session-logic.ts`, mobile `threadActivity.ts`, and equivalent modules while retaining genuinely platform-specific presentation helpers +- remove unused V1 client RPC contracts and compatibility exports +- split still-required project application contracts and frozen legacy thread decoders into clear ownership boundaries instead of deleting reusable application infrastructure +- delete the V2 debug route after its useful inspection and rendering surfaces have production homes + +No production client should end with both a complete `OrchestrationV2ThreadProjection` and a second complete thread presentation object containing copied messages, work entries, runs, plans, requests, and checkpoints. ### Shape 4.5 tests -Add shared presentation tests for: +Add client-runtime state and reducer coverage for: -- every known V2 turn-item type and the dynamic fallback -- graph construction for roots, forks, subagents, merges, archives, and missing nodes -- incremental updates without duplicate graph nodes or timeline rows -- run attempts, retry, recovery, and interruption presentation -- provider-session transition and context-handoff presentation -- plans, todos, checkpoints, and rollback +- environment-scoped detail identity without copying or mutating the server projection +- cached, synchronizing, live, deleted, and error state independent of projection content +- preservation of local, inherited, and synthetic `visibleTurnItems` +- unchanged `visibleTurnItems` identity for run/attempt updates that do not change visibility +- single-row replacement and unaffected-row identity for streaming item updates +- membership changes, removal, and position renumbering without losing inherited or synthetic rows +- any targeted entity lookup or shared domain selector introduced by a concrete consumer +- environment-scoped graph construction for roots, forks, subagents, merges, archives, missing nodes, and cycles - capability-gated action availability Add web and mobile integration coverage for: +- every known V2 turn-item type and the structured dynamic fallback +- interruption request, intervening activity, and interruption result in committed order +- inherited conversation items and synthetic fork markers +- rich tool expansion and live updates without duplicate rows +- request response capability, checkpoint rollback, and other targeted item/entity joins - related-thread navigation -- rich tool-call expansion and live updates - fork and merge-back - subagent and delegated-task inspection - queue reorder and promotion - provider switch and detach - context handoff -- reconnect while graph, tool, or attempt state is changing +- reconnect while item, graph, tool, request, or attempt state is changing +- all existing Shape 4.0 product flows ### Shape 4.5 exit gate - Web and mobile remain fully usable for every Shape 4.0 flow. -- Thread lineage, forks, subagents, and merge relationships are navigable. -- Typed tool calls and their structured results are visible without losing provider-native fallback data. -- Runs, attempts, retries, recovery, plans, checkpoints, and handoffs have coherent presentation. +- Production web and mobile conversations render from server-authoritative `visibleTurnItems`; neither reconstructs the chat by merging separate message, plan, and work-entry collections. +- Thread detail values carry explicit environment scope while retaining the pristine V2 projection and nested entity identities. +- Shell/sidebar and thread-detail state remain independently subscribable; ordinary detail traffic does not invalidate the project/thread shell. +- Granular timeline components consume the item atom and targeted entity lookups rather than subscribing to the whole projection. +- Run/attempt updates with unchanged visibility preserve `visibleTurnItems` identity, while streaming item updates replace only the affected row and remain visible. +- Local, inherited, and synthetic items survive snapshot, incremental update, cache restore, and reconnect. +- Typed tool calls and structured results are visible without losing provider-native fallback data. +- Interruption request, intervening activity, and interruption result remain independently visible and correctly ordered. +- Runs, attempts, retries, recovery, plans, checkpoints, requests, handoffs, and context transfers have coherent targeted presentation without becoming a second reconstructed chat model. +- Thread lineage, forks, subagents, merge relationships, and environment-qualified navigation are available on web and mobile in platform-appropriate forms. - New V2 capabilities are capability-gated and do not rely on provider-name conditionals. -- Web and mobile share event interpretation and presentation derivation. +- Web and mobile retain separate React bindings and presentation policy while consuming the same V2 projection/reducer semantics. +- No production client maintains a complete parallel thread presentation model beside `OrchestrationV2ThreadProjection`; the Shape 4.0 parity facade is removed from production consumers. - No production TypeScript import references a V1 client orchestration type or endpoint. +- The V2 debug route is removed after its useful production surfaces are integrated. - `vp check`, `vp run typecheck`, and `vp test` pass. - `vp run lint:mobile` passes for mobile changes. @@ -1011,7 +1077,8 @@ Nothing in Shape 4.0 or 4.5 may destroy, rewrite, or make assumptions that close At the end of Shape 4.5: - V2 is the only live agent orchestration system from provider process through web and mobile UI. -- The existing product experience works on V2, and V2-native graph, execution, tool, and context information is available in the application. +- The existing product experience works on V2, and production conversations render the authoritative environment-scoped V2 item sequence without a parallel full-thread presentation model. +- V2-native graph, execution, tool, request, interruption, and context information is available through targeted platform-appropriate surfaces. - V1 runtime, server endpoints, production client state, and production client operations are removed. - Reusable application event-sourcing and platform infrastructure remain. - Legacy database rows, provider continuation data, attachments, and other migration inputs remain untouched and read-only. diff --git a/apps/mobile/src/connection/storage.ts b/apps/mobile/src/connection/storage.ts index 276ea3c5c0..1c3bead420 100644 --- a/apps/mobile/src/connection/storage.ts +++ b/apps/mobile/src/connection/storage.ts @@ -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, - OrchestrationThread, - OrchestrationShellSnapshot, - 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,31 +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"; -const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1; 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, - thread: OrchestrationThread, -}); - -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({ @@ -289,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) { @@ -351,21 +341,36 @@ 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.thread) : 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, thread) => Effect.gen(function* () { - const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread"); + const file = yield* threadSnapshotFile(environmentId, thread.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: thread.id, + threadId: thread.thread.id, thread, }), ).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause))); diff --git a/apps/mobile/src/features/archive/archivedThreadList.test.ts b/apps/mobile/src/features/archive/archivedThreadList.test.ts index 6cd530ab37..77e45963b8 100644 --- a/apps/mobile/src/features/archive/archivedThreadList.test.ts +++ b/apps/mobile/src/features/archive/archivedThreadList.test.ts @@ -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 & - Pick, -): 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 & { + 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, - threads: ReadonlyArray, + threads: ReadonlyArray, targetEnvironmentId = environmentId, ): ArchivedSnapshotEntry { return { environmentId: targetEnvironmentId, snapshot: { + schemaVersion: 1, snapshotSequence: 1, projects, threads, - updatedAt: "2026-06-04T00:00:00.000Z", }, }; } diff --git a/apps/mobile/src/features/home/HomeScreen.tsx b/apps/mobile/src/features/home/HomeScreen.tsx index 7ee5660edf..f1e120a38c 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -60,14 +60,16 @@ interface HomeScreenProps { /* ─── Status indicator colors ────────────────────────────────────────── */ function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } { - switch (thread.session?.status) { + switch (thread.runtime?.status) { case "running": + case "waiting": return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" }; - case "ready": + case "completed": return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" }; + case "queued": case "starting": return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" }; - case "error": + case "failed": return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" }; default: return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" }; @@ -161,7 +163,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, }; } @@ -544,7 +546,7 @@ export function HomeScreen(props: HomeScreenProps) { ) : !hasResults ? ( ) : ( projectGroups.map((group) => { diff --git a/apps/mobile/src/features/home/homeThreadList.test.ts b/apps/mobile/src/features/home/homeThreadList.test.ts index cf9b0824aa..50be9a68a7 100644 --- a/apps/mobile/src/features/home/homeThreadList.test.ts +++ b/apps/mobile/src/features/home/homeThreadList.test.ts @@ -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 & Pick, @@ -25,23 +26,21 @@ function makeThread( input: Partial & Pick, ): 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, - }; + }); } function buildGroups( diff --git a/apps/mobile/src/features/review/reviewModel.test.ts b/apps/mobile/src/features/review/reviewModel.test.ts index 3390afd9ff..3543b4de89 100644 --- a/apps/mobile/src/features/review/reviewModel.test.ts +++ b/apps/mobile/src/features/review/reviewModel.test.ts @@ -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/shell"; import { buildReviewListItems, @@ -18,9 +14,9 @@ import { } from "./reviewModel"; function makeCheckpoint( - input: Partial & - Pick, -): OrchestrationCheckpointSummary { + input: Partial & + Pick, +): 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", }), diff --git a/apps/mobile/src/features/review/reviewModel.ts b/apps/mobile/src/features/review/reviewModel.ts index 9459d41872..1704f9c52a 100644 --- a/apps/mobile/src/features/review/reviewModel.ts +++ b/apps/mobile/src/features/review/reviewModel.ts @@ -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/shell"; +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( +const readyCheckpointOrder = Order.make( compareCheckpointTurnCountDescending, ); @@ -510,14 +511,14 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile { } export function getReviewSectionIdForCheckpoint( - checkpoint: Pick, + checkpoint: Pick, ): string { return `turn:${checkpoint.checkpointTurnCount}`; } export function getReadyReviewCheckpoints( - checkpoints: ReadonlyArray, -): ReadonlyArray { + checkpoints: ReadonlyArray, +): ReadonlyArray { return pipe( checkpoints, Arr.filter((checkpoint) => checkpoint.status === "ready"), @@ -526,7 +527,7 @@ export function getReadyReviewCheckpoints( } export function buildReviewSectionItems(input: { - readonly checkpoints: ReadonlyArray; + readonly checkpoints: ReadonlyArray; readonly gitSections: ReadonlyArray; readonly turnDiffById: Readonly>; readonly loadingTurnIds: Readonly>; diff --git a/apps/mobile/src/features/review/useReviewSections.ts b/apps/mobile/src/features/review/useReviewSections.ts index 8732549099..7c725e2583 100644 --- a/apps/mobile/src/features/review/useReviewSections.ts +++ b/apps/mobile/src/features/review/useReviewSections.ts @@ -1,6 +1,7 @@ import { useCallback, useEffect, useMemo } from "react"; -import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts"; +import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { useCheckpointDiff } from "../../state/queries"; import { useEnvironmentQuery } from "../../state/query"; @@ -59,7 +60,7 @@ export function useReviewSections(input: { getReviewSectionIdForCheckpoint(checkpoint), checkpoint, ]), - ) as Record, + ) as Record, [readyCheckpoints], ); const reviewSections = useMemo( diff --git a/apps/mobile/src/features/threads/PendingApprovalCard.tsx b/apps/mobile/src/features/threads/PendingApprovalCard.tsx index 0617ef1cbc..2906bcd7d1 100644 --- a/apps/mobile/src/features/threads/PendingApprovalCard.tsx +++ b/apps/mobile/src/features/threads/PendingApprovalCard.tsx @@ -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; } export function PendingApprovalCard(props: PendingApprovalCardProps) { + const canRespond = props.approval.responseCapability === "live"; + const disabled = !canRespond || props.respondingApprovalId === props.approval.requestId; return ( @@ -27,17 +29,23 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) { {props.approval.detail} ) : null} + {!canRespond ? ( + + The provider process for this request is no longer available. Interrupt or restart the run + to continue. + + ) : null} void props.onRespond(props.approval.requestId, "accept")} > Allow once void props.onRespond(props.approval.requestId, "acceptForSession")} > @@ -46,7 +54,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) { void props.onRespond(props.approval.requestId, "decline")} > Decline diff --git a/apps/mobile/src/features/threads/PendingUserInputCard.tsx b/apps/mobile/src/features/threads/PendingUserInputCard.tsx index c9e0177721..cdff7a3b96 100644 --- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx +++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx @@ -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; readonly answers: Record | 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 ( @@ -32,6 +29,12 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) { Fill in the pending answers + {!canRespond ? ( + + The provider process for this request is no longer available. Interrupt or restart the run + to continue. + + ) : null} {props.pendingUserInput.questions.map((question) => { const draft = props.drafts[question.id]; return ( @@ -49,6 +52,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) { return ( 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()} > diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 75991cae88..3381e609ae 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -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, @@ -80,7 +83,7 @@ export interface ThreadComposerProps { readonly connectionState: RemoteClientConnectionState; readonly connectionError: string | null; readonly environmentLabel: string | null; - readonly selectedThread: OrchestrationThreadShell; + readonly selectedThread: EnvironmentThreadShell; readonly serverConfig: T3ServerConfig | null; readonly queueCount: number; readonly activeThreadBusy: boolean; @@ -239,9 +242,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 diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 62d1bce115..c53da68905 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -1,15 +1,15 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; 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"; @@ -46,7 +46,7 @@ import { ThreadFeed } from "./ThreadFeed"; import type { ThreadContentPresentation } from "./threadContentPresentation"; export interface ThreadDetailScreenProps { - readonly selectedThread: OrchestrationThreadShell; + readonly selectedThread: EnvironmentThreadShell; readonly contentPresentation: ThreadContentPresentation; readonly screenTone: StatusTone; readonly connectionError: string | null; @@ -54,11 +54,11 @@ export interface ThreadDetailScreenProps { readonly selectedThreadFeed: ReadonlyArray; readonly activeWorkStartedAt: string | null; readonly activePendingApproval: PendingApproval | null; - readonly respondingApprovalId: ApprovalRequestId | null; + readonly respondingApprovalId: RuntimeRequestId | null; readonly activePendingUserInput: PendingUserInput | null; readonly activePendingUserInputDrafts: Record; readonly activePendingUserInputAnswers: Record | null; - readonly respondingUserInputId: ApprovalRequestId | null; + readonly respondingUserInputId: RuntimeRequestId | null; readonly draftMessage: string; readonly draftAttachments: ReadonlyArray; readonly connectionStateLabel: EnvironmentConnectionPhase; @@ -82,16 +82,16 @@ export interface ThreadDetailScreenProps { readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void; readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void; readonly onRespondToApproval: ( - requestId: ApprovalRequestId, + requestId: RuntimeRequestId, decision: ProviderApprovalDecision, ) => Promise; readonly onSelectUserInputOption: ( - requestId: ApprovalRequestId, + requestId: RuntimeRequestId, questionId: string, label: string, ) => void; readonly onChangeUserInputCustomAnswer: ( - requestId: ApprovalRequestId, + requestId: RuntimeRequestId, questionId: string, customAnswer: string, ) => void; @@ -377,7 +377,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread feed={props.selectedThreadFeed} contentPresentation={props.contentPresentation} agentLabel={agentLabel} - latestTurn={props.selectedThread.latestTurn} + latestRun={props.selectedThread.latestRun} listRef={listRef} freeze={freeze} anchorMessageId={anchorMessageId} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index 565ce2ae5c..986c944989 100644 --- a/apps/mobile/src/features/threads/ThreadFeed.tsx +++ b/apps/mobile/src/features/threads/ThreadFeed.tsx @@ -1,7 +1,7 @@ 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 type { EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts"; import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList"; import { SymbolView } from "expo-symbols"; import { useRouter } from "expo-router"; @@ -71,7 +71,7 @@ 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 { ThreadWorkLog } from "./thread-work-log"; @@ -98,7 +98,7 @@ export interface ThreadFeedProps { readonly feed: ReadonlyArray; readonly contentPresentation: ThreadContentPresentation; readonly agentLabel: string; - readonly latestTurn: ThreadFeedLatestTurn | null; + readonly latestRun: ThreadFeedLatestRun | null; readonly listRef: RefObject; readonly freeze: SharedValue; readonly anchorMessageId: MessageId | null; @@ -658,11 +658,11 @@ function renderFeedEntry( readonly expandedWorkGroups: Record; readonly expandedWorkRows: Record; readonly terminalAssistantMessageIds: ReadonlySet; - 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 onToggleTurnFold: (runId: RunId) => void; readonly onPressImage: (uri: string, headers?: Record) => void; readonly onMarkdownLinkPress: (href: string) => void; readonly iconSubtleColor: string | import("react-native").ColorValue; @@ -676,12 +676,12 @@ function renderFeedEntry( const entry = info.item; const { markdownStyles, iconSubtleColor, userBubbleColor } = props; - if (entry.type === "turn-fold") { + if (entry.type === "run-fold") { return ( 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]" > @@ -708,7 +708,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) && @@ -1110,14 +1110,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const copyFeedbackTimeoutRef = useRef | null>(null); const foldSettleFrameRef = useRef(null); const foldSettleSecondFrameRef = useRef(null); - const previousLatestTurnRef = useRef(props.latestTurn); + const previousLatestTurnRef = useRef(props.latestRun); const { width: viewportWidth } = useWindowDimensions(); const [foldToggleSettling, setFoldToggleSettling] = useState(false); const [interactionState, setInteractionState] = useState<{ readonly copiedRowId: string | null; readonly expandedWorkGroups: Record; readonly expandedWorkRows: Record; - readonly expandedTurnIds: ReadonlySet; + readonly expandedTurnIds: ReadonlySet; }>({ copiedRowId: null, expandedWorkGroups: {}, @@ -1191,8 +1191,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { ], ); const presentedFeed = useMemo( - () => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds), - [expandedTurnIds, props.feed, props.latestTurn], + () => deriveThreadFeedPresentation(props.feed, props.latestRun, expandedTurnIds), + [expandedTurnIds, props.feed, props.latestRun], ); const anchoredEndSpace = useMemo( () => @@ -1205,29 +1205,29 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { [presentedFeed, props.anchorMessageId, topContentInset], ); const terminalAssistantMessageIds = useMemo(() => { - const terminalIdsByTurn = new Map(); + const terminalIdsByTurn = new Map(); 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), @@ -1236,14 +1236,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 () => { @@ -1296,7 +1296,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { })); }, []); - const onToggleTurnFold = useCallback((turnId: TurnId) => { + const onToggleTurnFold = useCallback((runId: RunId) => { setFoldToggleSettling(true); if (foldSettleFrameRef.current !== null) { cancelAnimationFrame(foldSettleFrameRef.current); @@ -1306,10 +1306,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { } 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 }; }); diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index f8c916974e..8f123a7f11 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -1,4 +1,5 @@ import { Stack, useLocalSearchParams, useRouter } from "expo-router"; +import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; import { useCallback, useMemo, useState } from "react"; import * as Option from "effect/Option"; import { EnvironmentId, type ProjectScript } from "@t3tools/contracts"; @@ -152,20 +153,15 @@ export function ThreadRouteScreen() { void router.push("/connections"); }, [router]); 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]); @@ -191,7 +187,7 @@ export function ThreadRouteScreen() { terminalDebugLog("terminal-menu:open-new", { hasThread: Boolean(selectedThread), hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot), - listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), + listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), }); if (!selectedThread || !selectedThreadProject?.workspaceRoot) { @@ -199,7 +195,7 @@ export function ThreadRouteScreen() { } const nextId = nextOpenTerminalId({ - listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), + listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), }); void router.push(buildThreadTerminalNavigation(selectedThread, nextId)); }, [router, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]); @@ -222,9 +218,9 @@ export function ThreadRouteScreen() { } const targetTerminalId = resolveProjectScriptTerminalId({ - existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId), + existingTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), hasRunningTerminal: terminalMenuSessions.some( - (session) => session.status === "running" || session.status === "starting", + (runtime) => runtime.status === "running" || runtime.status === "starting", ), }); const preferredWorktreePath = resolvePreferredThreadWorktreePath({ diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.ts index cf5eb1817a..8fe661f798 100644 --- a/apps/mobile/src/features/threads/threadPresentation.ts +++ b/apps/mobile/src/features/threads/threadPresentation.ts @@ -7,29 +7,29 @@ export function threadSortValue(thread: EnvironmentThreadShell): number { } export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { - const status = thread.session?.status; - if (status === "running") { + const status = thread.runtime?.status; + if (status === "running" || status === "waiting") { return { label: "Running", pillClassName: "bg-orange-500/12 dark:bg-orange-500/16", textClassName: "text-orange-700 dark:text-orange-300", }; } - if (status === "ready") { + if (status === "completed") { return { label: "Ready", pillClassName: "bg-emerald-500/12 dark:bg-emerald-500/16", textClassName: "text-emerald-700 dark:text-emerald-300", }; } - if (status === "starting") { + if (status === "queued" || status === "starting") { return { label: "Starting", pillClassName: "bg-sky-500/12 dark:bg-sky-500/16", textClassName: "text-sky-700 dark:text-sky-300", }; } - if (status === "error") { + if (status === "failed") { return { label: "Error", pillClassName: "bg-rose-500/12 dark:bg-rose-500/16", diff --git a/apps/mobile/src/features/threads/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts index 9531567f44..96008e4d6d 100644 --- a/apps/mobile/src/features/threads/use-project-actions.ts +++ b/apps/mobile/src/features/threads/use-project-actions.ts @@ -70,6 +70,7 @@ export function useCreateProjectThread() { environmentId: input.project.environmentId, input: { commandId: CommandId.make(metadata.commandId), + creationSource: "mobile", threadId, message: { messageId: MessageId.make(metadata.messageId), diff --git a/apps/mobile/src/lib/repositoryGroups.test.ts b/apps/mobile/src/lib/repositoryGroups.test.ts index 8cea5df230..1e0c83c90f 100644 --- a/apps/mobile/src/lib/repositoryGroups.test.ts +++ b/apps/mobile/src/lib/repositoryGroups.test.ts @@ -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 & Pick, @@ -23,22 +24,20 @@ function makeThread( input: Partial & Pick, ): 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", () => { diff --git a/apps/mobile/src/lib/scopedEntities.ts b/apps/mobile/src/lib/scopedEntities.ts index 34709957fd..6464b35619 100644 --- a/apps/mobile/src/lib/scopedEntities.ts +++ b/apps/mobile/src/lib/scopedEntities.ts @@ -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}`; } diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index e093acee31..f3ee822a54 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -1,409 +1,111 @@ +import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell"; +import { MessageId, RunId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { - EventId, - MessageId, - ProjectId, - ProviderInstanceId, - ThreadId, - TurnId, - type OrchestrationThread, - type OrchestrationThreadActivity, -} from "@t3tools/contracts"; - +import { makeThreadFixture } from "../test-fixtures"; import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity"; -function makeActivity( - input: Partial & - Pick, -): OrchestrationThreadActivity { +const runId = RunId.make("run-1"); + +function message(role: "user" | "assistant", text: string, createdAt: string, id: string) { return { - tone: "info", - payload: {}, - turnId: null, - ...input, - }; + id: MessageId.make(id), + role, + text, + attachments: [], + runId: role === "assistant" ? runId : null, + streaming: false, + createdAt, + updatedAt: createdAt, + } as const; } -function makeThread( - input: Partial & Pick, -): OrchestrationThread { +function commandEntry(overrides: Partial = {}): ThreadWorkEntry { + const structuredPayload = { + type: "command_execution", + input: "vp check", + output: "ok", + } as ThreadWorkEntry["structuredPayload"]; 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, + id: "item-1", + createdAt: "2026-06-20T00:00:02.000Z", + runId, + label: "Ran command", + command: "vp check", + detail: "ok", + tone: "tool", + itemType: "command_execution", + toolLifecycleStatus: "completed", + structuredPayload, + ...overrides, }; } describe("buildThreadFeed", () => { - it("keeps historic work entries attributed to their turns", () => { - const thread = makeThread({ - id: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-1"), - title: "Runtime warning thread", - latestTurn: { - turnId: TurnId.make("turn-latest"), - state: "running", - requestedAt: "2026-04-01T00:00:00.000Z", - startedAt: "2026-04-01T00:00:01.000Z", - completedAt: null, - assistantMessageId: null, - }, - activities: [ - makeActivity({ - id: EventId.make("activity-old"), - kind: "runtime.warning", - summary: "Runtime warning", - createdAt: "2026-04-01T00:00:02.000Z", - turnId: TurnId.make("turn-old"), - payload: { - message: "Old warning", - }, - }), - makeActivity({ - id: EventId.make("activity-latest"), - kind: "runtime.warning", - summary: "Runtime warning", - createdAt: "2026-04-01T00:00:03.000Z", - turnId: TurnId.make("turn-latest"), - payload: { - message: "Latest warning", - }, - }), - ], - }); - - const feed = buildThreadFeed(thread); - expect(feed).toMatchObject([ - { - type: "activity-group", - turnId: "turn-old", - activities: [{ id: "activity-old", turnId: "turn-old" }], - }, - { - type: "activity-group", - turnId: "turn-latest", - activities: [{ id: "activity-latest", turnId: "turn-latest" }], - }, - ]); - }); - - it("collapses matching tool lifecycle rows like desktop", () => { - const thread = makeThread({ - id: ThreadId.make("thread-2"), - projectId: ProjectId.make("project-1"), - title: "Collapsed tools", - latestTurn: { - turnId: TurnId.make("turn-1"), - state: "completed", - requestedAt: "2026-04-01T00:00:00.000Z", - startedAt: "2026-04-01T00:00:01.000Z", - completedAt: "2026-04-01T00:00:03.000Z", - assistantMessageId: null, - }, - activities: [ - makeActivity({ - id: EventId.make("tool-updated"), - kind: "tool.updated", - tone: "tool", - summary: "Run tests", - createdAt: "2026-04-01T00:00:01.000Z", - turnId: TurnId.make("turn-1"), - payload: { - title: "Run tests", - itemType: "command_execution", - detail: "/bin/zsh -lc 'bun run test'", - }, - }), - makeActivity({ - id: EventId.make("tool-completed"), - kind: "tool.completed", - tone: "tool", - summary: "Run tests completed", - createdAt: "2026-04-01T00:00:02.000Z", - turnId: TurnId.make("turn-1"), - payload: { - title: "Run tests", - itemType: "command_execution", - detail: "/bin/zsh -lc 'bun run test'", - }, - }), - ], - }); - - const feed = buildThreadFeed(thread); - const group = feed[0]; - - expect(group).toMatchObject({ - type: "activity-group", - }); - if (!group || group.type !== "activity-group") { - return; - } - - expect(group.activities).toEqual([ - { - 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"), - }, + it("orders V2 messages and work entries while retaining structured tool data", () => { + const thread = makeThreadFixture({ 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", - }, - }), + message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"), + message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"), ], + workEntries: [commandEntry()], }); 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, - }); + expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]); + const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0]; + expect(activity?.runId).toBe(runId); + expect(activity?.fullDetail).toContain('"input": "vp check"'); + }); - 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("folds settled V2 run work while keeping the terminal assistant message visible", () => { + const thread = makeThreadFixture({ + messages: [ + message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"), + message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"), + ], + workEntries: [commandEntry()], + }); + const feed = buildThreadFeed(thread); + 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("measures a steer-superseded turn from its user boundary through trailing work", () => { - const firstTurnId = TurnId.make("turn-1"); - const secondTurnId = TurnId.make("turn-2"); - const thread = makeThread({ - id: ThreadId.make("thread-steered"), - projectId: ProjectId.make("project-1"), - title: "Steered work", - latestTurn: { - turnId: secondTurnId, - state: "running", - requestedAt: "2026-04-01T00:00:14.000Z", - startedAt: "2026-04-01T00:00:14.000Z", - completedAt: null, - assistantMessageId: MessageId.make("assistant-next"), - }, - messages: [ - { - id: MessageId.make("user-1"), - role: "user", - text: "Do it once more.", - turnId: null, - streaming: false, - createdAt: "2026-04-01T00:00:00.000Z", - updatedAt: "2026-04-01T00:00:00.000Z", - }, - { - id: MessageId.make("assistant-commentary"), - role: "assistant", - text: "Kicking off call 1.", - turnId: firstTurnId, - streaming: false, - createdAt: "2026-04-01T00:00:09.000Z", - updatedAt: "2026-04-01T00:00:09.000Z", - }, - { - id: MessageId.make("user-2"), - role: "user", - text: "Actually do 15.", - turnId: null, - streaming: false, - createdAt: "2026-04-01T00:00:14.000Z", - updatedAt: "2026-04-01T00:00:14.000Z", - }, - { - id: MessageId.make("assistant-next"), - role: "assistant", - text: "One down - adjusting.", - turnId: secondTurnId, - streaming: true, - createdAt: "2026-04-01T00:00:17.000Z", - updatedAt: "2026-04-01T00:00:17.000Z", - }, - ], - activities: [ - makeActivity({ - id: EventId.make("work-1"), - kind: "tool.completed", - tone: "tool", - summary: "Ran command", - createdAt: "2026-04-01T00:00:12.000Z", - turnId: firstTurnId, - payload: { - title: "Ran command", - itemType: "command_execution", - status: "completed", - }, - }), - ], + it("keeps an active run expanded and marks failed tools as failures", () => { + const thread = makeThreadFixture({ + messages: [message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user")], + workEntries: [commandEntry({ tone: "error", toolLifecycleStatus: "failed" })], }); - const feed = buildThreadFeed(thread); - const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set()); - expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({ - turnId: firstTurnId, - label: "Worked for 12s", - }); - }); - - it("keeps an active turn expanded and classifies error-shaped tool output", () => { - const turnId = TurnId.make("turn-running"); - const thread = makeThread({ - id: ThreadId.make("thread-4"), - projectId: ProjectId.make("project-1"), - title: "Running work", - latestTurn: { - turnId, - state: "running", - requestedAt: "2026-04-01T00:00:00.000Z", - startedAt: "2026-04-01T00:00:01.000Z", + const presented = deriveThreadFeedPresentation( + feed, + { + runId, + status: "running", + startedAt: "2026-06-20T00: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", - }, - }), - ], - }); + new Set(), + ); - const feed = buildThreadFeed(thread); - expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed); - expect(feed[0]).toMatchObject({ - type: "activity-group", - activities: [{ status: "failure" }], - }); + expect(presented.some((entry) => entry.type === "run-fold")).toBe(false); + expect(presented.find((entry) => entry.type === "activity-group")?.activities[0]?.status).toBe( + "failure", + ); }); }); diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index f6008057a0..a535906a8a 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -1,29 +1,17 @@ -import { ApprovalRequestId, isToolLifecycleItemType } from "@t3tools/contracts"; import type { - OrchestrationLatestTurn, - OrchestrationThread, - OrchestrationThreadActivity, - ToolLifecycleItemType, - TurnId, - UserInputQuestion, -} from "@t3tools/contracts"; + EnvironmentThread, + ThreadConversationMessage, + ThreadPendingApproval, + ThreadPendingUserInput, + ThreadRunSummary, + ThreadUserInputQuestion, + ThreadWorkEntry, +} from "@t3tools/client-runtime/state/shell"; +import type { RunId } from "@t3tools/contracts"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; -import * as Arr from "effect/Array"; -import * as Order from "effect/Order"; - -export interface PendingApproval { - readonly requestId: ApprovalRequestId; - readonly requestKind: "command" | "file-read" | "file-change"; - readonly createdAt: string; - readonly detail?: string; -} - -export interface PendingUserInput { - readonly requestId: ApprovalRequestId; - readonly createdAt: string; - readonly questions: ReadonlyArray; -} +export type PendingApproval = ThreadPendingApproval; +export type PendingUserInput = ThreadPendingUserInput; export interface PendingUserInputDraftAnswer { readonly selectedOptionLabel?: string; @@ -33,7 +21,7 @@ export interface PendingUserInputDraftAnswer { export interface ThreadFeedActivity { readonly id: string; readonly createdAt: string; - readonly turnId: TurnId | null; + readonly runId: RunId | null; readonly summary: string; readonly detail: string | null; readonly fullDetail: string | null; @@ -55,42 +43,18 @@ export interface ThreadFeedActivity { readonly status: "success" | "failure" | "neutral" | null; } -type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped"; - -interface WorkLogEntry { - id: string; - createdAt: string; - turnId: TurnId | null; - label: string; - detail?: string; - command?: string; - rawCommand?: string; - changedFiles?: ReadonlyArray; - tone: "thinking" | "tool" | "info" | "error"; - toolTitle?: string; - itemType?: ToolLifecycleItemType; - requestKind?: PendingApproval["requestKind"]; - toolLifecycleStatus?: WorkLogToolLifecycleStatus; - toolData?: unknown; -} - -interface DerivedWorkLogEntry extends WorkLogEntry { - activityKind: OrchestrationThreadActivity["kind"]; - collapseKey?: string; -} - type RawThreadFeedEntry = | { readonly type: "message"; readonly id: string; readonly createdAt: string; - readonly message: OrchestrationThread["messages"][number]; + readonly message: ThreadConversationMessage; } | { readonly type: "activity"; readonly id: string; readonly createdAt: string; - readonly turnId: TurnId | null; + readonly runId: RunId | null; readonly activity: ThreadFeedActivity; }; @@ -100,109 +64,25 @@ export type ThreadFeedEntry = readonly type: "activity-group"; readonly id: string; readonly createdAt: string; - readonly turnId: TurnId | null; + readonly runId: RunId | null; readonly activities: ReadonlyArray; } | { - readonly type: "turn-fold"; + readonly type: "run-fold"; readonly id: string; readonly createdAt: string; - readonly turnId: TurnId; + readonly runId: RunId; readonly label: string; readonly expanded: boolean; }; -export type ThreadFeedLatestTurn = Pick< - OrchestrationLatestTurn, - "turnId" | "state" | "startedAt" | "completedAt" +export type ThreadFeedLatestRun = Pick< + ThreadRunSummary, + "runId" | "status" | "startedAt" | "completedAt" >; -function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null { - switch (requestType) { - case "command_execution_approval": - case "exec_command_approval": - return "command"; - case "file_read_approval": - return "file-read"; - case "file_change_approval": - case "apply_patch_approval": - return "file-change"; - default: - return null; - } -} - -function isStalePendingRequestFailureDetail(detail: string | undefined): boolean { - const normalized = detail?.toLowerCase(); - if (!normalized) { - return false; - } - return ( - normalized.includes("stale pending approval request") || - normalized.includes("stale pending user-input request") || - normalized.includes("unknown pending approval request") || - normalized.includes("unknown pending permission request") || - normalized.includes("unknown pending user-input request") - ); -} - -function parseApprovalRequestId(value: unknown): ApprovalRequestId | null { - return typeof value === "string" && value.length > 0 ? ApprovalRequestId.make(value) : null; -} - -function parseUserInputQuestions( - payload: Record | null, -): ReadonlyArray | null { - const questions = payload?.questions; - if (!Array.isArray(questions)) { - return null; - } - - const parsed = questions - .map((entry) => { - if (!entry || typeof entry !== "object") return null; - const question = entry as Record; - if ( - typeof question.id !== "string" || - typeof question.header !== "string" || - typeof question.question !== "string" || - !Array.isArray(question.options) - ) { - return null; - } - const options = question.options - .map((option) => { - if (!option || typeof option !== "object") return null; - const record = option as Record; - if (typeof record.label !== "string" || typeof record.description !== "string") { - return null; - } - return { - label: record.label, - description: record.description, - }; - }) - .filter((option): option is UserInputQuestion["options"][number] => option !== null); - if (options.length === 0) { - return null; - } - return { - id: question.id, - header: question.header, - question: question.question, - options, - multiSelect: question.multiSelect === true, - }; - }) - .filter((question): question is UserInputQuestion => question !== null); - - return parsed.length > 0 ? parsed : null; -} - function normalizeDraftAnswer(value: string | undefined): string | null { - if (typeof value !== "string") { - return null; - } + if (typeof value !== "string") return null; const trimmed = value.trim(); return trimmed.length > 0 ? trimmed : null; } @@ -210,857 +90,246 @@ function normalizeDraftAnswer(value: string | undefined): string | null { function resolvePendingUserInputAnswer( draft: PendingUserInputDraftAnswer | undefined, ): string | null { - const customAnswer = normalizeDraftAnswer(draft?.customAnswer); - if (customAnswer) { - return customAnswer; - } - return normalizeDraftAnswer(draft?.selectedOptionLabel); -} - -function deriveWorkLogEntries( - activities: ReadonlyArray, -): DerivedWorkLogEntry[] { - const ordered = Arr.sort(activities, activityOrder); - const entries: DerivedWorkLogEntry[] = []; - for (const activity of ordered) { - if (activity.kind === "tool.started") continue; - if (activity.kind === "task.started") continue; - if (activity.kind === "context-window.updated") continue; - if (activity.summary === "Checkpoint captured") continue; - if (isPlanBoundaryToolActivity(activity)) continue; - entries.push(toDerivedWorkLogEntry(activity)); - } - return collapseDerivedWorkLogEntries(entries); -} - -function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean { - if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") { - return false; - } - - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:"); -} - -function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - const commandPreview = extractToolCommand(payload); - const changedFiles = extractChangedFiles(payload); - const title = extractToolTitle(payload); - const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed"; - const taskSummary = - isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0 - ? payload.summary - : null; - const taskDetailAsLabel = - isTaskActivity && - !taskSummary && - typeof payload?.detail === "string" && - payload.detail.length > 0 - ? payload.detail - : null; - const taskLabel = taskSummary || taskDetailAsLabel; - const entry: DerivedWorkLogEntry = { - id: activity.id, - createdAt: activity.createdAt, - turnId: activity.turnId, - label: taskLabel || activity.summary, - tone: - activity.kind === "task.progress" - ? "thinking" - : activity.tone === "approval" - ? "info" - : activity.tone, - activityKind: activity.kind, - }; - const itemType = extractWorkLogItemType(payload); - const requestKind = extractWorkLogRequestKind(payload); - if ( - !taskDetailAsLabel && - payload && - typeof payload.detail === "string" && - payload.detail.length > 0 - ) { - const detail = stripTrailingExitCode(payload.detail).output; - if (detail) { - entry.detail = detail; - } - } - if (commandPreview.command) { - entry.command = commandPreview.command; - } - if (commandPreview.rawCommand) { - entry.rawCommand = commandPreview.rawCommand; - } - if (changedFiles.length > 0) { - entry.changedFiles = changedFiles; - } - if (title) { - entry.toolTitle = title; - } - if (itemType === "mcp_tool_call") { - const data = asRecord(payload?.data); - if (data?.item !== undefined) { - entry.toolData = data.item; - } - } - if (itemType) { - entry.itemType = itemType; - } - if (requestKind) { - entry.requestKind = requestKind; - } - let toolLifecycleStatus = extractWorkLogToolLifecycleStatus(payload); - if (!toolLifecycleStatus && activity.kind === "tool.completed") { - toolLifecycleStatus = "completed"; - } - if (toolLifecycleStatus) { - entry.toolLifecycleStatus = toolLifecycleStatus; - } - const collapseKey = deriveToolLifecycleCollapseKey(entry); - if (collapseKey) { - entry.collapseKey = collapseKey; - } - return entry; -} - -function collapseDerivedWorkLogEntries( - entries: ReadonlyArray, -): DerivedWorkLogEntry[] { - const collapsed: DerivedWorkLogEntry[] = []; - for (const entry of entries) { - const previous = collapsed.at(-1); - if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) { - collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry); - continue; - } - collapsed.push(entry); - } - return collapsed; -} - -function shouldCollapseToolLifecycleEntries( - previous: DerivedWorkLogEntry, - next: DerivedWorkLogEntry, -): boolean { - if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") { - return false; - } - if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") { - return false; - } - if (previous.activityKind === "tool.completed") { - return false; - } - return previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey; -} - -function mergeDerivedWorkLogEntries( - previous: DerivedWorkLogEntry, - next: DerivedWorkLogEntry, -): DerivedWorkLogEntry { - const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles); - const detail = next.detail ?? previous.detail; - const command = next.command ?? previous.command; - const rawCommand = next.rawCommand ?? previous.rawCommand; - const toolTitle = next.toolTitle ?? previous.toolTitle; - const itemType = next.itemType ?? previous.itemType; - const requestKind = next.requestKind ?? previous.requestKind; - const collapseKey = next.collapseKey ?? previous.collapseKey; - const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus; - const toolData = next.toolData ?? previous.toolData; - return { - ...previous, - ...next, - ...(detail ? { detail } : {}), - ...(command ? { command } : {}), - ...(rawCommand ? { rawCommand } : {}), - ...(changedFiles.length > 0 ? { changedFiles } : {}), - ...(toolTitle ? { toolTitle } : {}), - ...(itemType ? { itemType } : {}), - ...(requestKind ? { requestKind } : {}), - ...(collapseKey ? { collapseKey } : {}), - ...(toolLifecycleStatus ? { toolLifecycleStatus } : {}), - ...(toolData !== undefined ? { toolData } : {}), - }; -} - -function mergeChangedFiles( - previous: ReadonlyArray | undefined, - next: ReadonlyArray | undefined, -): string[] { - const merged = [...(previous ?? []), ...(next ?? [])]; - if (merged.length === 0) { - return []; - } - return [...new Set(merged)]; -} - -function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined { - if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") { - return undefined; - } - const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label); - const detail = entry.detail?.trim() ?? ""; - const itemType = entry.itemType ?? ""; - if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) { - return undefined; - } - return [itemType, normalizedLabel, detail].join("\u001f"); -} - -function normalizeCompactToolLabel(value: string): string { - return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim(); -} - -function workLogEntryIsToolLike(entry: WorkLogEntry): boolean { - if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") { - return true; - } - if (entry.command !== undefined && entry.command.trim().length > 0) { - return true; - } - if (entry.requestKind !== undefined) { - return true; - } - return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType); -} - -function toolDetailTextLooksLikeFailure(text: string): boolean { - const normalized = text.toLowerCase(); return ( - normalized.includes("file not found") || - normalized.includes("no files found") || - normalized.includes("enoent") || - normalized.includes("no such file or directory") || - normalized.includes("no such file") || - normalized.includes("commandnotfoundexception") || - normalized.includes("command not found") || - (normalized.includes("cannot find path") && normalized.includes("because it does not exist")) || - (normalized.includes("is not recognized") && normalized.includes("the term '")) || - //i.test(text) || - /exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) || - /exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text) + normalizeDraftAnswer(draft?.customAnswer) ?? normalizeDraftAnswer(draft?.selectedOptionLabel) ); } -function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean { - if (entry.tone === "error") { - return true; - } - if (entry.toolLifecycleStatus === "failed" || entry.toolLifecycleStatus === "declined") { - return true; - } - if (!workLogEntryIsToolLike(entry)) { - return false; - } - return toolDetailTextLooksLikeFailure([entry.detail, entry.command].filter(Boolean).join("\n")); -} - -function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean { - if (!workLogEntryIsToolLike(entry) || workEntryIndicatesToolFailure(entry)) { - return false; - } - if (entry.tone === "thinking") { - return false; - } - return ( - entry.toolLifecycleStatus !== "inProgress" && - entry.toolLifecycleStatus !== "stopped" && - entry.toolLifecycleStatus !== "failed" && - entry.toolLifecycleStatus !== "declined" - ); -} - -function workEntryStatus(entry: WorkLogEntry): ThreadFeedActivity["status"] { - if (!workLogEntryIsToolLike(entry)) { - return null; - } - if (workEntryIndicatesToolFailure(entry)) { - return "failure"; - } - if (workEntryIndicatesToolSuccess(entry)) { - return "success"; - } - return "neutral"; -} - -function workEntryIcon(entry: DerivedWorkLogEntry): ThreadFeedActivity["icon"] { - if ( - entry.activityKind === "user-input.requested" || - entry.activityKind === "user-input.resolved" - ) { - return "message"; - } - if (entry.activityKind === "runtime.warning") return "warning"; - if (entry.requestKind === "command") return "command"; - if (entry.requestKind === "file-read") return "eye"; - if (entry.requestKind === "file-change") return "edit"; - if (entry.itemType === "command_execution" || entry.command) return "command"; - if (entry.itemType === "file_change" || (entry.changedFiles?.length ?? 0) > 0) return "edit"; - if (entry.itemType === "web_search") return "globe"; - if (entry.itemType === "image_view") return "eye"; - if (entry.itemType === "mcp_tool_call") return "wrench"; - if (entry.itemType === "dynamic_tool_call" || entry.itemType === "collab_agent_tool_call") { - return "hammer"; - } - if (entry.tone === "error") return "alert"; - if (entry.tone === "thinking") return "agent"; - if (entry.tone === "info") return "check"; - return "zap"; -} - -function buildWorkEntryExpandedBody(entry: WorkLogEntry): string | null { - const blocks: string[] = []; - const appendUniqueBlock = (value: string | null | undefined) => { - const trimmed = value?.trim(); - if (trimmed && !blocks.includes(trimmed)) { - blocks.push(trimmed); - } - }; - - if (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) { - appendUniqueBlock(`MCP call\n${JSON.stringify(entry.toolData, null, 2)}`); - } - appendUniqueBlock(entry.rawCommand ?? entry.command); - appendUniqueBlock(entry.detail); - if ((entry.changedFiles?.length ?? 0) > 0) { - appendUniqueBlock(entry.changedFiles!.join("\n")); - } - - return blocks.length > 0 ? blocks.join("\n\n") : null; -} - -function workEntryPreview( - workEntry: Pick, -): string | null { - if (workEntry.command) return workEntry.command; - if (workEntry.detail) return workEntry.detail; - if ((workEntry.changedFiles?.length ?? 0) === 0) return null; - const [firstPath] = workEntry.changedFiles ?? []; - if (!firstPath) return null; - return workEntry.changedFiles!.length === 1 - ? firstPath - : `${firstPath} +${workEntry.changedFiles!.length - 1} more`; -} - function capitalizePhrase(value: string): string { const trimmed = value.trim(); - if (trimmed.length === 0) { - return value; - } - return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`; + return trimmed.length === 0 ? value : `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`; } -function workEntryHeading(workEntry: WorkLogEntry): string { - if (!workEntry.toolTitle) { - return capitalizePhrase(normalizeCompactToolLabel(workEntry.label)); - } - return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle)); -} - -function asRecord(value: unknown): Record | null { - return value && typeof value === "object" ? (value as Record) : null; -} - -function asTrimmedString(value: unknown): string | null { - if (typeof value !== "string") { - return null; - } - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} - -function trimMatchingOuterQuotes(value: string): string { - const trimmed = value.trim(); - if ( - (trimmed.startsWith("'") && trimmed.endsWith("'")) || - (trimmed.startsWith('"') && trimmed.endsWith('"')) - ) { - const unquoted = trimmed.slice(1, -1).trim(); - return unquoted.length > 0 ? unquoted : trimmed; - } - return trimmed; -} - -function executableBasename(value: string): string | null { - const trimmed = trimMatchingOuterQuotes(value); - if (trimmed.length === 0) { - return null; - } - const normalized = trimmed.replace(/\\/g, "/"); - const segments = normalized.split("/"); - const last = segments.at(-1)?.trim() ?? ""; - return last.length > 0 ? last.toLowerCase() : null; -} - -function splitExecutableAndRest(value: string): { executable: string; rest: string } | null { - const trimmed = value.trim(); - if (trimmed.length === 0) { - return null; - } - - if (trimmed.startsWith('"') || trimmed.startsWith("'")) { - const quote = trimmed.charAt(0); - const closeIndex = trimmed.indexOf(quote, 1); - if (closeIndex <= 0) { - return null; - } - return { - executable: trimmed.slice(0, closeIndex + 1), - rest: trimmed.slice(closeIndex + 1).trim(), - }; - } - - const firstWhitespace = trimmed.search(/\s/); - if (firstWhitespace < 0) { - return { - executable: trimmed, - rest: "", - }; - } - - return { - executable: trimmed.slice(0, firstWhitespace), - rest: trimmed.slice(firstWhitespace).trim(), - }; -} - -const SHELL_WRAPPER_SPECS = [ - { - executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"], - wrapperFlagPattern: /(?:^|\s)-command\s+/i, - }, - { - executables: ["cmd", "cmd.exe"], - wrapperFlagPattern: /(?:^|\s)\/c\s+/i, - }, - { - executables: ["bash", "sh", "zsh"], - wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i, - }, -] as const; - -function findShellWrapperSpec(shell: string) { - return SHELL_WRAPPER_SPECS.find((spec) => - (spec.executables as ReadonlyArray).includes(shell), +function workEntryIsToolLike(entry: ThreadWorkEntry): boolean { + return ( + entry.tone === "tool" || + entry.tone === "thinking" || + entry.tone === "error" || + entry.command !== undefined || + entry.requestKind !== undefined ); } -function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null { - const match = wrapperFlagPattern.exec(value); - if (!match) { - return null; +function workEntryStatus(entry: ThreadWorkEntry): ThreadFeedActivity["status"] { + if (!workEntryIsToolLike(entry)) return null; + if ( + entry.tone === "error" || + entry.toolLifecycleStatus === "failed" || + entry.toolLifecycleStatus === "declined" + ) { + return "failure"; } - - const command = value.slice(match.index + match[0].length).trim(); - if (command.length === 0) { - return null; - } - - const unwrapped = trimMatchingOuterQuotes(command); - return unwrapped.length > 0 ? unwrapped : null; + return entry.toolLifecycleStatus === "completed" ? "success" : "neutral"; } -function unwrapKnownShellCommandWrapper(value: string): string { - const split = splitExecutableAndRest(value); - if (!split || split.rest.length === 0) { - return value; +function workEntryIcon(entry: ThreadWorkEntry): ThreadFeedActivity["icon"] { + switch (entry.itemType) { + case "reasoning": + return "agent"; + case "command_execution": + return "command"; + case "file_change": + return "edit"; + case "file_search": + return "eye"; + case "web_search": + return "globe"; + case "approval_request": + case "user_input_request": + return "message"; + case "dynamic_tool": + return "wrench"; + case "subagent": + return "hammer"; + case "run_interrupt_request": + case "run_interrupt_result": + return "warning"; + case "checkpoint": + return "check"; + default: + if (entry.tone === "error") return "alert"; + if (entry.tone === "thinking") return "agent"; + if (entry.tone === "info") return "check"; + return "zap"; } - - const shell = executableBasename(split.executable); - if (!shell) { - return value; - } - - const spec = findShellWrapperSpec(shell); - if (!spec) { - return value; - } - - return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value; } -function formatCommandArrayPart(value: string): string { - return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value; +function workEntryPreview(entry: ThreadWorkEntry): string | null { + if (entry.command) return entry.command; + if (entry.detail) return entry.detail; + const firstPath = entry.changedFiles?.[0]; + if (!firstPath) return null; + return entry.changedFiles?.length === 1 + ? firstPath + : `${firstPath} +${(entry.changedFiles?.length ?? 1) - 1} more`; } -function formatCommandValue(value: unknown): string | null { - const direct = asTrimmedString(value); - if (direct) { - return direct; - } - if (!Array.isArray(value)) { - return null; - } - const parts: Array = []; - for (const entry of value) { - const part = asTrimmedString(entry); - if (part !== null) { - parts.push(part); - } - } - if (parts.length === 0) { - return null; - } - return parts.map((part) => formatCommandArrayPart(part)).join(" "); +function buildWorkEntryExpandedBody(entry: ThreadWorkEntry): string | null { + const blocks: string[] = []; + const append = (value: string | null | undefined) => { + const trimmed = value?.trim(); + if (trimmed && !blocks.includes(trimmed)) blocks.push(trimmed); + }; + append(entry.rawCommand ?? entry.command); + append(entry.detail); + if (entry.changedFiles?.length) append(entry.changedFiles.join("\n")); + append(JSON.stringify(entry.structuredPayload, null, 2)); + return blocks.length === 0 ? null : blocks.join("\n\n"); } -function normalizeCommandValue(value: unknown): string | null { - const formatted = formatCommandValue(value); - return formatted ? unwrapKnownShellCommandWrapper(formatted) : null; -} - -function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null { - const formatted = formatCommandValue(value); - if (!formatted || normalizedCommand === null) { - return null; - } - return formatted === normalizedCommand ? null : formatted; -} - -function extractToolCommand(payload: Record | null): { - command: string | null; - rawCommand: string | null; -} { - const data = asRecord(payload?.data); - const item = asRecord(data?.item); - const itemResult = asRecord(item?.result); - const itemInput = asRecord(item?.input); - const itemType = asTrimmedString(payload?.itemType); - const detail = asTrimmedString(payload?.detail); - const candidates: unknown[] = [ - item?.command, - itemInput?.command, - itemResult?.command, - data?.command, - itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null, - ]; - - for (const candidate of candidates) { - const command = normalizeCommandValue(candidate); - if (!command) { - continue; - } - return { - command, - rawCommand: toRawToolCommand(candidate, command), - }; - } - +function toFeedActivity(entry: ThreadWorkEntry): ThreadFeedActivity { + const summary = capitalizePhrase(entry.toolTitle ?? entry.label); + const detail = workEntryPreview(entry); + const fullDetail = buildWorkEntryExpandedBody(entry); return { - command: null, - rawCommand: null, + id: entry.id, + createdAt: entry.createdAt, + runId: entry.runId, + summary, + detail, + fullDetail, + icon: workEntryIcon(entry), + copyText: [summary, detail, fullDetail] + .filter( + (value, index, values): value is string => + Boolean(value) && values.indexOf(value) === index, + ) + .join("\n"), + toolLike: workEntryIsToolLike(entry), + status: workEntryStatus(entry), }; } -function extractToolTitle(payload: Record | null): string | null { - return asTrimmedString(payload?.title); +function byCreatedAt(left: A, right: A): number { + return left.createdAt.localeCompare(right.createdAt); } -function extractWorkLogToolLifecycleStatus( - payload: Record | null, -): WorkLogToolLifecycleStatus | undefined { - const status = payload?.status; - if ( - status === "inProgress" || - status === "completed" || - status === "failed" || - status === "declined" || - status === "stopped" - ) { - return status; - } - return undefined; -} - -function stripTrailingExitCode(value: string): { - output: string | null; - exitCode?: number | undefined; -} { - const trimmed = value.trim(); - const match = /^(?[\s\S]*?)(?:\s*\d+)>)\s*$/i.exec( - trimmed, - ); - if (!match?.groups) { - return { - output: trimmed.length > 0 ? trimmed : null, - }; - } - const exitCode = Number.parseInt(match.groups.code ?? "", 10); - const normalizedOutput = match.groups.output?.trim() ?? ""; - return { - output: normalizedOutput.length > 0 ? normalizedOutput : null, - ...(Number.isInteger(exitCode) ? { exitCode } : {}), - }; -} - -function extractWorkLogItemType( - payload: Record | null, -): WorkLogEntry["itemType"] | undefined { - if (typeof payload?.itemType === "string" && isToolLifecycleItemType(payload.itemType)) { - return payload.itemType; - } - return undefined; -} - -function extractWorkLogRequestKind( - payload: Record | null, -): WorkLogEntry["requestKind"] | undefined { - if ( - payload?.requestKind === "command" || - payload?.requestKind === "file-read" || - payload?.requestKind === "file-change" - ) { - return payload.requestKind; - } - return requestKindFromRequestType(payload?.requestType) ?? undefined; -} - -function pushChangedFile(target: string[], seen: Set, value: unknown) { - const normalized = asTrimmedString(value); - if (!normalized || seen.has(normalized)) { - return; - } - seen.add(normalized); - target.push(normalized); -} - -function collectChangedFiles(value: unknown, target: string[], seen: Set, depth: number) { - if (depth > 4 || target.length >= 12) { - return; - } - if (Array.isArray(value)) { - for (const entry of value) { - collectChangedFiles(entry, target, seen, depth + 1); - if (target.length >= 12) { - return; - } - } - return; - } - - const record = asRecord(value); - if (!record) { - return; - } - - pushChangedFile(target, seen, record.path); - pushChangedFile(target, seen, record.filePath); - pushChangedFile(target, seen, record.relativePath); - pushChangedFile(target, seen, record.filename); - pushChangedFile(target, seen, record.newPath); - pushChangedFile(target, seen, record.oldPath); - - for (const nestedKey of [ - "item", - "result", - "input", - "data", - "changes", - "files", - "edits", - "patch", - "patches", - "operations", - ]) { - if (!(nestedKey in record)) { - continue; - } - collectChangedFiles(record[nestedKey], target, seen, depth + 1); - if (target.length >= 12) { - return; - } - } -} - -function extractChangedFiles(payload: Record | null): string[] { - const changedFiles: string[] = []; - const seen = new Set(); - collectChangedFiles(asRecord(payload?.data), changedFiles, seen, 0); - return changedFiles; -} - -function compareActivityLifecycleRank(kind: string): number { - if (kind.endsWith(".started") || kind === "tool.started") { - return 0; - } - if (kind.endsWith(".progress") || kind.endsWith(".updated")) { - return 1; - } - if (kind.endsWith(".completed") || kind.endsWith(".resolved")) { - return 2; - } - return 1; -} - -const activityOrder = Order.combineAll([ - Order.mapInput(Order.Number, (activity) => activity.sequence ?? Number.MAX_SAFE_INTEGER), - Order.mapInput(Order.String, (activity) => activity.createdAt), - Order.mapInput(Order.Number, (activity) => compareActivityLifecycleRank(activity.kind)), - Order.mapInput(Order.String, (activity) => activity.id), -]); - function isEmptyMessage(entry: RawThreadFeedEntry): boolean { - if (entry.type !== "message") { - return false; - } - const hasText = entry.message.text.trim().length > 0; - const hasAttachments = (entry.message.attachments ?? []).length > 0; - return !hasText && !hasAttachments; + return ( + entry.type === "message" && + entry.message.text.trim().length === 0 && + (entry.message.attachments ?? []).length === 0 + ); } function groupAdjacentActivities(entries: ReadonlyArray): ThreadFeedEntry[] { const grouped: ThreadFeedEntry[] = []; - for (const entry of entries) { - // Skip empty messages so they don't break activity grouping. - if (isEmptyMessage(entry)) { - continue; - } - + if (isEmptyMessage(entry)) continue; if (entry.type !== "activity") { grouped.push(entry); continue; } - const previous = grouped.at(-1); - if (previous?.type === "activity-group" && previous.turnId === entry.turnId) { + if (previous?.type === "activity-group" && previous.runId === entry.runId) { grouped[grouped.length - 1] = { ...previous, activities: [...previous.activities, entry.activity], }; continue; } - grouped.push({ type: "activity-group", id: entry.id, createdAt: entry.createdAt, - turnId: entry.turnId, + runId: entry.runId, activities: [entry.activity], }); } - return grouped; } function computeElapsedMs(startIso: string, endIso: string): number | null { const start = Date.parse(startIso); const end = Date.parse(endIso); - if (!Number.isFinite(start) || !Number.isFinite(end)) { - return null; - } - return Math.max(0, end - start); + return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null; } -function maxIsoTimestamp(a: string | null, b: string | null): string | null { - if (a === null) return b; - if (b === null) return a; - const aMs = Date.parse(a); - const bMs = Date.parse(b); - if (!Number.isFinite(aMs)) return b; - if (!Number.isFinite(bMs)) return a; - return bMs > aMs ? b : a; +function maxIsoTimestamp(left: string | null, right: string | null): string | null { + if (left === null) return right; + if (right === null) return left; + return Date.parse(right) > Date.parse(left) ? right : left; } -function deriveUnsettledTurnId(latestTurn: ThreadFeedLatestTurn | null): TurnId | null { - if (!latestTurn) { - return null; - } - const settled = latestTurn.completedAt !== null && latestTurn.state !== "running"; - return settled ? null : latestTurn.turnId; +function unsettledRunId(latestRun: ThreadFeedLatestRun | null): RunId | null { + if (!latestRun) return null; + return latestRun.completedAt === null || + latestRun.status === "starting" || + latestRun.status === "running" || + latestRun.status === "waiting" + ? latestRun.runId + : null; } -interface ThreadFeedTurnFold { - readonly turnId: TurnId; +interface ThreadFeedRunFold { + readonly runId: RunId; readonly createdAt: string; readonly hiddenEntryIds: ReadonlySet; readonly label: string; } -function deriveThreadFeedTurnFolds( +function deriveThreadFeedRunFolds( feed: ReadonlyArray, - latestTurn: ThreadFeedLatestTurn | null, -): ReadonlyMap { - const terminalAssistantMessageIdByTurn = new Map(); + latestRun: ThreadFeedLatestRun | null, +): ReadonlyMap { + const terminalAssistantMessageIdByRun = new Map(); for (const entry of feed) { - if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) { - terminalAssistantMessageIdByTurn.set(entry.message.turnId, entry.id); + if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) { + terminalAssistantMessageIdByRun.set(entry.message.runId, entry.id); } } - interface TurnGroup { - readonly entries: ThreadFeedEntry[]; - readonly startBoundary: string | null; - } - const groupsByTurnId = new Map(); + const groupsByRunId = new Map< + RunId, + { entries: ThreadFeedEntry[]; startBoundary: string | null } + >(); let pendingUserBoundary: string | null = null; for (const entry of feed) { if (entry.type === "message" && entry.message.role === "user") { pendingUserBoundary = entry.message.createdAt; continue; } - const turnId = + const runId = entry.type === "message" && entry.message.role === "assistant" - ? entry.message.turnId + ? entry.message.runId : entry.type === "activity-group" - ? entry.turnId + ? entry.runId : null; - if (!turnId) { - continue; - } - let group = groupsByTurnId.get(turnId); + if (!runId) continue; + let group = groupsByRunId.get(runId); if (!group) { - group = { - entries: [], - startBoundary: pendingUserBoundary, - }; + group = { entries: [], startBoundary: pendingUserBoundary }; pendingUserBoundary = null; - groupsByTurnId.set(turnId, group); + groupsByRunId.set(runId, group); } group.entries.push(entry); } - const unsettledTurnId = deriveUnsettledTurnId(latestTurn); - const foldsByAnchorId = new Map(); - for (const [turnId, group] of groupsByTurnId) { - const { entries } = group; - if (turnId === unsettledTurnId) { + const activeRunId = unsettledRunId(latestRun); + const foldsByAnchorId = new Map(); + for (const [runId, group] of groupsByRunId) { + if ( + runId === activeRunId || + group.entries.some((entry) => entry.type === "message" && entry.message.streaming) + ) { continue; } - if (entries.some((entry) => entry.type === "message" && entry.message.streaming)) { - continue; - } - - const terminalAssistantMessageId = terminalAssistantMessageIdByTurn.get(turnId); + const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId); const hiddenEntryIds = new Set( - entries.filter((entry) => entry.id !== terminalAssistantMessageId).map((entry) => entry.id), + group.entries.filter((entry) => entry.id !== terminalAssistantId).map((entry) => entry.id), ); - if (hiddenEntryIds.size === 0) { - continue; - } - - const firstEntry = entries[0]; - const lastEntry = entries.at(-1); - if (!firstEntry || !lastEntry) { - continue; - } - const terminalEntry = terminalAssistantMessageId - ? entries.find((entry) => entry.id === terminalAssistantMessageId) + const firstEntry = group.entries[0]; + const lastEntry = group.entries.at(-1); + if (hiddenEntryIds.size === 0 || !firstEntry || !lastEntry) continue; + const terminalEntry = terminalAssistantId + ? group.entries.find((entry) => entry.id === terminalAssistantId) : null; - const latestTurnMatches = latestTurn?.turnId === turnId; + const latestRunMatches = latestRun?.runId === runId; const lastEntryEnd = lastEntry.type === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt; const elapsedMs = - latestTurnMatches && latestTurn.startedAt && latestTurn.completedAt - ? computeElapsedMs(latestTurn.startedAt, latestTurn.completedAt) + latestRunMatches && latestRun.startedAt && latestRun.completedAt + ? computeElapsedMs(latestRun.startedAt, latestRun.completedAt) : computeElapsedMs( group.startBoundary ?? firstEntry.createdAt, maxIsoTimestamp( @@ -1069,20 +338,19 @@ function deriveThreadFeedTurnFolds( ) ?? lastEntryEnd, ); const duration = elapsedMs === null ? null : formatDuration(elapsedMs); - const interrupted = latestTurnMatches && latestTurn.state === "interrupted"; - const label = interrupted - ? duration - ? `You stopped after ${duration}` - : "You stopped this response" - : duration - ? `Worked for ${duration}` - : "Worked"; - + const interrupted = + latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled"); foldsByAnchorId.set(firstEntry.id, { - turnId, + runId, createdAt: firstEntry.createdAt, hiddenEntryIds, - label, + label: interrupted + ? duration + ? `You stopped after ${duration}` + : "You stopped this response" + : duration + ? `Worked for ${duration}` + : "Worked", }); } return foldsByAnchorId; @@ -1090,218 +358,83 @@ function deriveThreadFeedTurnFolds( export function deriveThreadFeedPresentation( feed: ReadonlyArray, - latestTurn: ThreadFeedLatestTurn | null, - expandedTurnIds: ReadonlySet, + latestRun: ThreadFeedLatestRun | null, + expandedRunIds: ReadonlySet, ): ThreadFeedEntry[] { - const sourceFeed = feed.filter((entry) => entry.type !== "turn-fold"); - const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn); + const sourceFeed = feed.filter((entry) => entry.type !== "run-fold"); + const foldsByAnchorId = deriveThreadFeedRunFolds(sourceFeed, latestRun); const collapsedEntryIds = new Set(); for (const fold of foldsByAnchorId.values()) { - if (!expandedTurnIds.has(fold.turnId)) { - for (const entryId of fold.hiddenEntryIds) { - collapsedEntryIds.add(entryId); - } + if (!expandedRunIds.has(fold.runId)) { + for (const entryId of fold.hiddenEntryIds) collapsedEntryIds.add(entryId); } } - const result: ThreadFeedEntry[] = []; for (const entry of sourceFeed) { const fold = foldsByAnchorId.get(entry.id); if (fold) { result.push({ - type: "turn-fold", - id: `turn-fold:${fold.turnId}`, + type: "run-fold", + id: `run-fold:${fold.runId}`, createdAt: fold.createdAt, - turnId: fold.turnId, + runId: fold.runId, label: fold.label, - expanded: expandedTurnIds.has(fold.turnId), + expanded: expandedRunIds.has(fold.runId), }); } - if (!collapsedEntryIds.has(entry.id)) { - result.push(entry); - } + if (!collapsedEntryIds.has(entry.id)) result.push(entry); } return result; } -export function derivePendingApprovals( - activities: ReadonlyArray, -): PendingApproval[] { - const openByRequestId = new Map(); - const ordered = Arr.sort(activities, activityOrder); - - for (const activity of ordered) { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - const requestId = parseApprovalRequestId(payload?.requestId); - const requestKind = - payload?.requestKind === "command" || - payload?.requestKind === "file-read" || - payload?.requestKind === "file-change" - ? payload.requestKind - : requestKindFromRequestType(payload?.requestType); - const detail = typeof payload?.detail === "string" ? payload.detail : undefined; - - if (activity.kind === "approval.requested" && requestId && requestKind) { - openByRequestId.set(requestId, { - requestId, - requestKind, - createdAt: activity.createdAt, - ...(detail ? { detail } : {}), - }); - continue; - } - - if (activity.kind === "approval.resolved" && requestId) { - openByRequestId.delete(requestId); - continue; - } - - if ( - activity.kind === "provider.approval.respond.failed" && - requestId && - isStalePendingRequestFailureDetail(detail) - ) { - openByRequestId.delete(requestId); - } - } - - return Arr.sortWith([...openByRequestId.values()], (s) => new Date(s.createdAt), Order.Date); -} - -export function derivePendingUserInputs( - activities: ReadonlyArray, -): PendingUserInput[] { - const openByRequestId = new Map(); - const ordered = Arr.sort(activities, activityOrder); - - for (const activity of ordered) { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - const requestId = parseApprovalRequestId(payload?.requestId); - const detail = typeof payload?.detail === "string" ? payload.detail : undefined; - - if (activity.kind === "user-input.requested" && requestId) { - const questions = parseUserInputQuestions(payload); - if (!questions) { - continue; - } - openByRequestId.set(requestId, { - requestId, - createdAt: activity.createdAt, - questions, - }); - continue; - } - - if (activity.kind === "user-input.resolved" && requestId) { - openByRequestId.delete(requestId); - continue; - } - - if ( - activity.kind === "provider.user-input.respond.failed" && - requestId && - isStalePendingRequestFailureDetail(detail) - ) { - openByRequestId.delete(requestId); - } - } - - return Arr.sortWith(openByRequestId.values(), (s) => new Date(s.createdAt), Order.Date); -} - export function setPendingUserInputCustomAnswer( draft: PendingUserInputDraftAnswer | undefined, customAnswer: string, ): PendingUserInputDraftAnswer { const selectedOptionLabel = customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel; - return { - customAnswer, - ...(selectedOptionLabel ? { selectedOptionLabel } : {}), - }; + return { customAnswer, ...(selectedOptionLabel ? { selectedOptionLabel } : {}) }; } export function buildPendingUserInputAnswers( - questions: ReadonlyArray, + questions: ReadonlyArray, draftAnswers: Record, ): Record | null { const answers: Record = {}; - for (const question of questions) { const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]); - if (!answer) { - return null; - } + if (!answer) return null; answers[question.id] = answer; } - return answers; } export function buildThreadFeed( - thread: OrchestrationThread, - options?: { - readonly loadedMessages?: ReadonlyArray; - }, + thread: EnvironmentThread, + options?: { readonly loadedMessages?: ReadonlyArray }, ): ThreadFeedEntry[] { const loadedMessages = options?.loadedMessages ?? thread.messages; const oldestLoadedMessageCreatedAt = - options?.loadedMessages !== undefined ? (loadedMessages[0]?.createdAt ?? null) : null; - const workLogEntries = deriveWorkLogEntries(thread.activities); - const entries = Arr.sortWith( - [ - ...loadedMessages.map((message) => ({ - type: "message", - id: message.id, - createdAt: message.createdAt, - message, + options?.loadedMessages === undefined ? null : (loadedMessages[0]?.createdAt ?? null); + const entries: RawThreadFeedEntry[] = [ + ...loadedMessages.map((message) => ({ + type: "message" as const, + id: message.id, + createdAt: message.createdAt, + message, + })), + ...thread.workEntries + .filter( + (entry) => + oldestLoadedMessageCreatedAt === null || entry.createdAt >= oldestLoadedMessageCreatedAt, + ) + .map((entry) => ({ + type: "activity" as const, + id: entry.id, + createdAt: entry.createdAt, + runId: entry.runId, + activity: toFeedActivity(entry), })), - ...workLogEntries - .filter((entry) => { - if (options?.loadedMessages === undefined) { - return true; - } - return ( - oldestLoadedMessageCreatedAt === null || entry.createdAt >= oldestLoadedMessageCreatedAt - ); - }) - .map((entry) => { - const summary = workEntryHeading(entry); - const detail = workEntryPreview(entry); - const fullDetail = buildWorkEntryExpandedBody(entry); - return { - type: "activity", - id: entry.id, - createdAt: entry.createdAt, - turnId: entry.turnId, - activity: { - id: entry.id, - createdAt: entry.createdAt, - turnId: entry.turnId, - summary, - detail, - fullDetail, - icon: workEntryIcon(entry), - copyText: [summary, detail, fullDetail] - .filter((value, index, values): value is string => { - return Boolean(value) && values.indexOf(value) === index; - }) - .join("\n"), - toolLike: workLogEntryIsToolLike(entry), - status: workEntryStatus(entry), - }, - }; - }), - ], - (s) => new Date(s.createdAt), - Order.Date, - ); - - return groupAdjacentActivities(entries); + ]; + return groupAdjacentActivities(entries.toSorted(byCreatedAt)); } diff --git a/apps/mobile/src/state/queries.ts b/apps/mobile/src/state/queries.ts index ea62599592..3291245006 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -1,4 +1,5 @@ -import type { EnvironmentId, OrchestrationThread, ThreadId } from "@t3tools/contracts"; +import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { useEffect, useMemo, useState } from "react"; @@ -18,7 +19,7 @@ const COMPOSER_PATH_SEARCH_LIMIT = 20; const VCS_REF_LIST_LIMIT = 100; export interface ThreadDetailView { - readonly data: OrchestrationThread | null; + readonly data: EnvironmentThread | null; readonly error: string | null; readonly isPending: boolean; readonly isDeleted: boolean; diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index 7f24712305..09aa68a6fe 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -7,6 +7,7 @@ import { type EnvironmentThreadState, createThreadEnvironmentAtoms, } from "@t3tools/client-runtime/state/threads"; +import { presentThread, type EnvironmentThread } from "@t3tools/client-runtime/state/shell"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/unstable/reactivity"; @@ -32,14 +33,21 @@ const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_ export function useEnvironmentThread( environmentId: EnvironmentId | null, threadId: ThreadId | null, -): EnvironmentThreadState { +): Omit & { readonly data: Option.Option } { const result = useAtomValue( environmentId !== null && threadId !== null ? 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, + data: + environmentId === null + ? Option.none() + : Option.map(state.data, (projection) => presentThread(environmentId, projection)), + }; } diff --git a/apps/mobile/src/state/use-selected-thread-requests.ts b/apps/mobile/src/state/use-selected-thread-requests.ts index c9e9db1253..2845fd7baa 100644 --- a/apps/mobile/src/state/use-selected-thread-requests.ts +++ b/apps/mobile/src/state/use-selected-thread-requests.ts @@ -1,15 +1,13 @@ 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 { 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"; @@ -65,18 +63,16 @@ export function useSelectedThreadRequests() { const { selectedThread: selectedThreadShell } = useThreadSelection(); const selectedThread = useSelectedThreadDetail(); const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom); - const [respondingApprovalId, setRespondingApprovalId] = useState(null); - const [respondingUserInputId, setRespondingUserInputId] = useState( - null, - ); + const [respondingApprovalId, setRespondingApprovalId] = useState(null); + const [respondingUserInputId, setRespondingUserInputId] = useState(null); const activePendingApprovals = useMemo( - () => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []), + () => selectedThread?.pendingApprovals ?? [], [selectedThread], ); const activePendingApproval = activePendingApprovals[0] ?? null; const activePendingUserInputs = useMemo( - () => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []), + () => selectedThread?.pendingUserInputs ?? [], [selectedThread], ); const activePendingUserInput = activePendingUserInputs[0] ?? null; @@ -91,7 +87,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 +99,7 @@ export function useSelectedThreadRequests() { ); const onChangeUserInputCustomAnswer = useCallback( - (requestId: ApprovalRequestId, questionId: string, customAnswer: string) => { + (requestId: RuntimeRequestId, questionId: string, customAnswer: string) => { if (!selectedThreadShell) { return; } @@ -115,10 +111,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 +134,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; } diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 90831f8437..8ae9470c87 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -1,4 +1,5 @@ import { useAtomValue } from "@effect/atom-react"; +import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; import { useCallback, useEffect, useMemo } from "react"; import { @@ -105,13 +106,13 @@ export function useThreadComposerState() { const selectedThreadSessionActivity = useMemo(() => { const selectedThread = selectedThreadDetail ?? selectedThreadShell; - if (!selectedThread?.session) { + if (!selectedThread?.runtime) { return null; } return { - orchestrationStatus: selectedThread.session.status, - activeTurnId: selectedThread.session.activeTurnId ?? undefined, + orchestrationStatus: selectedThread.runtime.status, + activeRunId: selectedThread.runtime.activeRunId ?? undefined, }; }, [selectedThreadDetail, selectedThreadShell]); @@ -122,15 +123,13 @@ export function useThreadComposerState() { } return deriveActiveWorkStartedAt( - selectedThread.latestTurn, + selectedThread.latestRun, selectedThreadSessionActivity, null, ); }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]); - const activeThreadBusy = - !!selectedThread && - (selectedThread.session?.status === "running" || selectedThread.session?.status === "starting"); + const activeThreadBusy = !!selectedThread && threadRuntimeIsActive(selectedThread.runtime); const onSendMessage = useCallback(async () => { if (!selectedThreadShell) { diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.ts index e912d6366b..a8cfc2b1e6 100644 --- a/apps/mobile/src/state/use-thread-outbox-drain.ts +++ b/apps/mobile/src/state/use-thread-outbox-drain.ts @@ -1,5 +1,8 @@ import { useAtomValue } from "@effect/atom-react"; -import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { + threadRuntimeIsActive, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; import { CommandId, type MessageId } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -181,6 +184,7 @@ export function useThreadOutboxDrain(): void { environmentId: queuedMessage.environmentId, input: { commandId: queuedMessage.commandId, + creationSource: "mobile", threadId: queuedMessage.threadId, message: { messageId: queuedMessage.messageId, @@ -225,7 +229,7 @@ export function useThreadOutboxDrain(): void { threadExists: thread !== undefined, shellStatus: shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty", environmentConnected: environment?.connectionState === "connected", - threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting", + threadBusy: threadRuntimeIsActive(thread?.runtime), }); if (deliveryAction === "wait") { continue; diff --git a/apps/mobile/src/test-fixtures.ts b/apps/mobile/src/test-fixtures.ts new file mode 100644 index 0000000000..9b6b6ee08f --- /dev/null +++ b/apps/mobile/src/test-fixtures.ts @@ -0,0 +1,130 @@ +import { + presentThread, + presentThreadShell, + type EnvironmentThread, + type EnvironmentThreadShell, +} from "@t3tools/client-runtime/state/shell"; +import { + EnvironmentId, + ProjectId, + ProviderInstanceId, + ThreadId, + type OrchestrationV2ThreadProjection, + 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 { + 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 { + 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 }; +} + +export function makeThreadFixture(overrides: Partial = {}): EnvironmentThread { + const shell = 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, + }); + const projection: OrchestrationV2ThreadProjection = { + thread: { + id: shell.id, + projectId: shell.projectId, + title: shell.title, + providerInstanceId: shell.providerInstanceId, + modelSelection: shell.modelSelection, + runtimeMode: shell.runtimeMode, + interactionMode: shell.interactionMode, + branch: shell.branch, + worktreePath: shell.worktreePath, + activeProviderThreadId: shell.activeProviderThreadId, + lineage: shell.lineage, + forkedFrom: shell.forkedFrom, + createdBy: shell.createdBy, + creationSource: shell.creationSource, + createdAt: shell.createdAt, + updatedAt: shell.updatedAt, + archivedAt: shell.archivedAt, + deletedAt: shell.deletedAt, + }, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: [], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt: shell.updatedAt, + }; + return { + ...presentThread(overrides.environmentId ?? EnvironmentId.make("environment-test"), projection), + ...overrides, + }; +} diff --git a/apps/server/README.md b/apps/server/README.md new file mode 100644 index 0000000000..5864e80b03 --- /dev/null +++ b/apps/server/README.md @@ -0,0 +1,3 @@ +# Server + +Node.js WebSocket server for the T3 Code app. diff --git a/apps/server/src/attachmentStore.test.ts b/apps/server/src/attachmentStore.test.ts index e21d9cf62c..3de9a8081c 100644 --- a/apps/server/src/attachmentStore.test.ts +++ b/apps/server/src/attachmentStore.test.ts @@ -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(); diff --git a/apps/server/src/attachmentStore.ts b/apps/server/src/attachmentStore.ts index 3d5b531db2..597c75dd91 100644 --- a/apps/server/src/attachmentStore.ts +++ b/apps/server/src/attachmentStore.ts @@ -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(".")) { diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 503933002f..c4ad8ed986 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -11,7 +11,9 @@ import { type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, ProjectId, + ProviderDriverKind, ProviderInstanceId, + ProviderThreadId, RunId, ThreadId, TurnItemId, @@ -60,6 +62,7 @@ const TestLayer = Layer.mergeAll( ); const providerInstanceId = ProviderInstanceId.make("codex"); +const providerDriver = ProviderDriverKind.make("codex"); const modelSelection = { instanceId: providerInstanceId, model: "gpt-5.4", @@ -404,7 +407,32 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { const now = yield* DateTime.now; const threadId = ThreadId.make("thread:foundation-many-items"); const runId = RunId.make("run:foundation-many-items"); + const providerThreadId = ProviderThreadId.make("provider-thread:foundation-many-items"); const thread = makeThread(threadId, now); + const providerThreadEvent = { + id: EventId.make("event:foundation-many-items:provider-thread"), + type: "provider-thread.updated" as const, + threadId, + providerInstanceId, + occurredAt: now, + payload: { + id: providerThreadId, + driver: providerDriver, + providerInstanceId, + providerSessionId: null, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + status: "active" as const, + firstRunOrdinal: 1, + lastRunOrdinal: 1, + handoffIds: [], + forkedFrom: null, + createdAt: now, + updatedAt: now, + }, + } satisfies OrchestrationV2DomainEvent; const runEvent = { id: EventId.make("event:foundation-many-items:run"), type: "run.created" as const, @@ -467,11 +495,13 @@ it.layer(TestLayer)("orchestration V2 foundation persistence", (it) => { yield* eventSink.write({ events: [ threadCreatedEvent({ id: "event:foundation-many-items:thread", thread, now }), + providerThreadEvent, runEvent, ...itemEvents, ], }); const beforeUpdate = yield* projectionStore.getThreadProjection(threadId); + assert.equal(beforeUpdate.thread.activeProviderThreadId, providerThreadId); const ordinals = beforeUpdate.turnItems.map((item) => item.ordinal); assert.lengthOf(ordinals, 151); assert.equal(new Set(ordinals).size, 151); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 745122b3e6..545c3849a4 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1649,6 +1649,54 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const projection = yield* getProjectionWithPendingEvents(command.threadId, events); const modelSelection = command.modelSelection ?? projection.thread.modelSelection; const dispatchMode = command.dispatchMode; + const sourcePlanProjection = + command.sourcePlanRef === undefined + ? null + : yield* getProjectionWithPendingEvents(command.sourcePlanRef.threadId, events); + const sourcePlan = + command.sourcePlanRef === undefined + ? null + : (sourcePlanProjection?.plans.find( + (plan) => plan.id === command.sourcePlanRef?.planId && plan.kind === "proposed_plan", + ) ?? null); + if (command.sourcePlanRef !== undefined && sourcePlan === null) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Proposed plan ${command.sourcePlanRef.planId} does not exist on thread ${command.sourcePlanRef.threadId}.`, + }); + } + if ( + sourcePlanProjection !== null && + sourcePlanProjection.thread.projectId !== projection.thread.projectId + ) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Proposed plan ${command.sourcePlanRef?.planId} belongs to a different project.`, + }); + } + if (sourcePlan !== null && sourcePlan.status !== "active") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Proposed plan ${sourcePlan.id} is not active.`, + }); + } + const completeSourcePlan = (occurredAt: DateTime.Utc) => + sourcePlan === null + ? Effect.void + : emit( + events, + command, + )({ + type: "plan.updated", + threadId: sourcePlan.threadId, + ...(sourcePlan.runId === null ? {} : { runId: sourcePlan.runId }), + nodeId: sourcePlan.nodeId, + occurredAt, + payload: { ...sourcePlan, status: "completed" }, + }); if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { yield* dispatchSteerIntoRun({ @@ -1783,6 +1831,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio completedAt: null, checkpointId: null, contextHandoffId: null, + ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }), }; const attempt: OrchestrationV2RunAttempt = { id: attemptId, @@ -1861,6 +1910,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: run, }); + yield* completeSourcePlan(now); yield* emitEvent({ type: "run-attempt.created", threadId: command.threadId, @@ -2030,6 +2080,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio completedAt: null, checkpointId: null, contextHandoffId: null, + ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }), }; const attempt: OrchestrationV2RunAttempt = { id: attemptId, @@ -2116,6 +2167,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: run, }); + yield* completeSourcePlan(now); yield* emitEvent({ type: "run-attempt.created", threadId: command.threadId, @@ -2613,6 +2665,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio checkpointId: null, contextHandoffId: portableForkHandoff?.id ?? providerSwitchHandoff?.id ?? mergeBackHandoff?.id ?? null, + ...(command.sourcePlanRef === undefined ? {} : { sourcePlanRef: command.sourcePlanRef }), }; const attempt: OrchestrationV2RunAttempt = { id: attemptId, @@ -2917,6 +2970,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio occurredAt: now, payload: run, }); + yield* completeSourcePlan(now); yield* emitEvent({ type: "run-attempt.created", threadId: command.threadId, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index aeb97477c7..0d4fcdce2e 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -223,6 +223,13 @@ export function applyToProjection( case "provider-thread.updated": return { ...base, + thread: + event.payload.appThreadId === base.thread.id + ? { + ...base.thread, + activeProviderThreadId: event.payload.id, + } + : base.thread, providerThreads: upsertById(base.providerThreads, event.payload), }; case "provider-turn.updated": @@ -288,6 +295,8 @@ type ShellThreadRow = { readonly active_run_id: string | null; readonly pending_request_payload_json: string | null; readonly latest_message_payload_json: string | null; + readonly latest_user_message_at: string | null; + readonly has_actionable_proposed_plan: number; readonly item_count: number; }; @@ -638,6 +647,13 @@ export function threadShellFromProjection( (left, right) => DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), )[0] ?? null; + const latestUserMessage = + projection.messages + .filter((message) => message.role === "user") + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), + )[0] ?? null; return { createdBy: projection.thread.createdBy, creationSource: projection.thread.creationSource, @@ -673,6 +689,10 @@ export function threadShellFromProjection( text: latestVisibleMessage.text, updatedAt: latestVisibleMessage.updatedAt, }, + latestUserMessageAt: latestUserMessage?.updatedAt ?? null, + hasActionableProposedPlan: projection.plans.some( + (plan) => plan.kind === "proposed_plan" && plan.status === "active", + ), itemCount: activeLocalTurnItems(projection).length, visibleItemCount: projection.visibleTurnItems.length, createdAt: projection.thread.createdAt, @@ -693,6 +713,8 @@ type ShellThreadState = { readonly activeRunId: RunId | null; readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null; readonly latestVisibleMessage: OrchestrationV2ConversationMessage | null; + readonly latestUserMessageAt: DateTime.Utc | null; + readonly hasActionableProposedPlan: boolean; readonly itemCount: number; readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"]; readonly runOrdinalById: ReadonlyMap; @@ -819,6 +841,8 @@ function shellFromState(input: { text: input.state.latestVisibleMessage.text, updatedAt: input.state.latestVisibleMessage.updatedAt, }, + latestUserMessageAt: input.state.latestUserMessageAt, + hasActionableProposedPlan: input.state.hasActionableProposedPlan, itemCount: input.state.itemCount, visibleItemCount: input.visibleItemCount, createdAt: input.state.thread.createdAt, @@ -1949,6 +1973,21 @@ export const layer: Layer.Layer = ORDER BY message.updated_at DESC, message.message_id DESC LIMIT 1 ) AS latest_message_payload_json, + ( + SELECT message.updated_at + FROM orchestration_v2_projection_messages message + WHERE message.thread_id = t.thread_id + AND message.role = 'user' + ORDER BY message.updated_at DESC, message.message_id DESC + LIMIT 1 + ) AS latest_user_message_at, + EXISTS ( + SELECT 1 + FROM orchestration_v2_projection_plans plan + WHERE plan.thread_id = t.thread_id + AND plan.kind = 'proposed_plan' + AND plan.status = 'active' + ) AS has_actionable_proposed_plan, ( SELECT COUNT(*) FROM orchestration_v2_projection_turn_items i @@ -2015,6 +2054,11 @@ export const layer: Layer.Layer = activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id), pendingRuntimeRequest, latestVisibleMessage, + latestUserMessageAt: + row.latest_user_message_at === null + ? null + : DateTime.makeUnsafe(row.latest_user_message_at), + hasActionableProposedPlan: row.has_actionable_proposed_plan === 1, itemCount: row.item_count, updatedAt: thread.updatedAt, runOrdinalById: diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.test.ts b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts new file mode 100644 index 0000000000..76a8c2a63d --- /dev/null +++ b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts @@ -0,0 +1,99 @@ +import { assert, it } from "@effect/vitest"; +import { + type ModelSelection, + type OrchestrationV2AppThread, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import * as ProjectionProjects from "../persistence/Services/ProjectionProjects.ts"; +import { layerFromProjectRepository, RuntimePolicyV2 } from "./RuntimePolicy.ts"; + +const projectId = ProjectId.make("project:runtime-policy"); +const providerInstanceId = ProviderInstanceId.make("codex"); +const modelSelection = { + instanceId: providerInstanceId, + model: "gpt-5.5", +} satisfies ModelSelection; + +function makeThread(input: { + readonly now: DateTime.Utc; + readonly worktreePath: string | null; +}): OrchestrationV2AppThread { + const threadId = ThreadId.make("thread:runtime-policy"); + return { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId, + title: "Runtime policy", + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: input.worktreePath, + activeProviderThreadId: null, + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: threadId, + }, + forkedFrom: null, + createdAt: input.now, + updatedAt: input.now, + archivedAt: null, + deletedAt: null, + }; +} + +const TestLayer = layerFromProjectRepository.pipe( + Layer.provide( + Layer.mock(ProjectionProjects.ProjectionProjectRepository)({ + getById: () => + Effect.succeed( + Option.some({ + projectId, + title: "Project", + workspaceRoot: "/project-root", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-06-21T00:00:00.000Z", + updatedAt: "2026-06-21T00:00:00.000Z", + deletedAt: null, + }), + ), + }), + ), +); + +it.layer(TestLayer)("RuntimePolicyV2", (it) => { + it.effect("uses the project root for local-checkout threads", () => + Effect.gen(function* () { + const policy = yield* RuntimePolicyV2; + const now = yield* DateTime.now; + const resolved = yield* policy.resolve({ + thread: makeThread({ now, worktreePath: null }), + modelSelection, + }); + assert.equal(resolved.cwd, "/project-root"); + }), + ); + + it.effect("prefers a provisioned worktree over the project root", () => + Effect.gen(function* () { + const policy = yield* RuntimePolicyV2; + const now = yield* DateTime.now; + const resolved = yield* policy.resolve({ + thread: makeThread({ now, worktreePath: "/project-worktree" }), + modelSelection, + }); + assert.equal(resolved.cwd, "/project-worktree"); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.ts b/apps/server/src/orchestration-v2/RuntimePolicy.ts index 8132bc8b53..06bbeae6d7 100644 --- a/apps/server/src/orchestration-v2/RuntimePolicy.ts +++ b/apps/server/src/orchestration-v2/RuntimePolicy.ts @@ -1,9 +1,16 @@ -import { ModelSelection, OrchestrationV2AppThread, ProviderDriverKind } from "@t3tools/contracts"; +import { + ModelSelection, + OrchestrationV2AppThread, + ProjectId, + ProviderInstanceId, +} from "@t3tools/contracts"; 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 ProjectionProjects from "../persistence/Services/ProjectionProjects.ts"; import { ProviderAdapterV2RuntimePolicy, type ProviderAdapterV2RuntimePolicy as ProviderAdapterV2RuntimePolicyType, @@ -15,12 +22,13 @@ import { export class RuntimePolicyResolveError extends Schema.TaggedErrorClass()( "RuntimePolicyResolveError", { - driver: ProviderDriverKind, + projectId: ProjectId, + providerInstanceId: ProviderInstanceId, cause: Schema.optional(Schema.Defect()), }, ) { override get message(): string { - return `Failed to resolve runtime policy for ${this.driver}.`; + return `Failed to resolve runtime policy for provider instance ${this.providerInstanceId} in project ${this.projectId}.`; } } @@ -61,6 +69,51 @@ export const layer: Layer.Layer = Layer.succeed(RuntimePolicyV2 }), }); +export const layerFromProjectRepository: Layer.Layer< + RuntimePolicyV2, + never, + ProjectionProjects.ProjectionProjectRepository +> = Layer.effect( + RuntimePolicyV2, + Effect.gen(function* () { + const projects = yield* ProjectionProjects.ProjectionProjectRepository; + return RuntimePolicyV2.of({ + resolve: Effect.fn("RuntimePolicyV2.resolve")(function* (input) { + const cwd = + input.thread.worktreePath ?? + (yield* projects.getById({ projectId: input.thread.projectId }).pipe( + Effect.mapError( + (cause) => + new RuntimePolicyResolveError({ + projectId: input.thread.projectId, + providerInstanceId: input.modelSelection.instanceId, + cause, + }), + ), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail( + new RuntimePolicyResolveError({ + projectId: input.thread.projectId, + providerInstanceId: input.modelSelection.instanceId, + cause: "Project not found.", + }), + ), + onSome: (project) => Effect.succeed(project.workspaceRoot), + }), + ), + )); + return ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: input.thread.runtimeMode, + interactionMode: input.thread.interactionMode, + cwd, + }); + }), + }); + }), +); + export function layerWithOverride( override: RuntimePolicyV2Override, ): Layer.Layer { diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index e41b601650..ea151f9d06 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -80,6 +80,20 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup ( command: Parameters[0], ): Effect.Effect => { + if (command.type === "thread.metadata.update") { + const existing = projections.get(command.threadId); + if (existing === undefined) return Effect.die("missing existing projection"); + projections.set(command.threadId, { + ...existing, + thread: { + ...existing.thread, + ...(command.title === undefined ? {} : { title: command.title }), + ...(command.branch === undefined ? {} : { branch: command.branch }), + ...(command.worktreePath === undefined ? {} : { worktreePath: command.worktreePath }), + }, + }); + return Effect.succeed({ sequence: 1, storedEvents: [] }); + } if (command.type !== "thread.create") return Effect.die("unexpected command"); if (options?.failCreate) { return Effect.fail( @@ -90,16 +104,37 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup }), ); } - projections.set(command.threadId, projectionFor(command.threadId)); + const projection = projectionFor(command.threadId); + projections.set(command.threadId, { + ...projection, + thread: { + ...projection.thread, + title: command.title, + branch: command.branch, + worktreePath: command.worktreePath, + }, + }); return Effect.succeed({ sequence: 1, storedEvents: [] }); }, ); - const createWorktree = vi.fn(() => - Effect.succeed({ - worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" }, - } as never), + const createWorktree = vi.fn( + (_input: Parameters[0]) => + Effect.succeed({ + worktree: { path: "/repo-worktrees/feature", refName: "feature", headSha: "abc" }, + } as never), ); const removeWorktree = vi.fn(() => Effect.void); + const fetchRemote = vi.fn( + (_input: Parameters[0]) => + Effect.void, + ); + const resolveRemoteTrackingCommit = vi.fn( + ( + _input: Parameters< + GitWorkflow.GitWorkflowService["Service"]["resolveRemoteTrackingCommit"] + >[0], + ) => Effect.succeed({ commitSha: "remote-main-sha", remoteRefName: "origin/main" }), + ); const runForThread = vi.fn(() => options?.failSetup ? Effect.fail( @@ -126,7 +161,12 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup getByWorkspaceRoot: () => Effect.succeed(Option.some(project)), snapshot: Effect.die("unused"), }), - Layer.mock(GitWorkflow.GitWorkflowService)({ createWorktree, removeWorktree }), + Layer.mock(GitWorkflow.GitWorkflowService)({ + createWorktree, + fetchRemote, + removeWorktree, + resolveRemoteTrackingCommit, + }), Layer.succeed(ProjectSetupScriptRunner.ProjectSetupScriptRunner, { runForThread, }), @@ -150,8 +190,11 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup Layer.provideMerge(SqlitePersistenceMemory), ), dispatch, + fetchRemote, createWorktree, + projections, removeWorktree, + resolveRemoteTrackingCommit, runForThread, sendToThread, }; @@ -213,6 +256,104 @@ it.effect( }, ); +it.effect("preserves an existing worktree when launching a new thread", () => { + const test = makeLayer(); + return Effect.gen(function* () { + const service = yield* ThreadLaunch.ThreadLaunchService; + const result = yield* service.launch({ + commandId: CommandId.make("command_launch_existing_worktree"), + threadId: ThreadId.make("thread_existing_worktree"), + projectId, + title: "Thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { + type: "existing_worktree", + worktreePath: "/repo-worktrees/existing", + branch: "existing", + }, + createdBy: "user", + creationSource: "web", + }); + assert.equal(result.projection.thread.worktreePath, "/repo-worktrees/existing"); + assert.equal(result.projection.thread.branch, "existing"); + assert.equal(test.createWorktree.mock.calls.length, 0); + assert.equal(test.removeWorktree.mock.calls.length, 0); + }).pipe(Effect.provide(test.layer)); +}); + +it.effect("fetches and resolves origin before provisioning an origin-based worktree", () => { + const test = makeLayer(); + return Effect.gen(function* () { + const service = yield* ThreadLaunch.ThreadLaunchService; + yield* service.launch({ + commandId: CommandId.make("command_launch_origin_worktree"), + projectId, + title: "Thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { + type: "worktree", + baseRef: "main", + branch: "feature", + startFromOrigin: true, + }, + createdBy: "user", + creationSource: "web", + }); + assert.deepEqual(test.fetchRemote.mock.calls[0]?.[0], { + cwd: "/repo", + remoteName: "origin", + }); + assert.deepEqual(test.resolveRemoteTrackingCommit.mock.calls[0]?.[0], { + cwd: "/repo", + refName: "main", + fallbackRemoteName: "origin", + }); + assert.deepEqual(test.createWorktree.mock.calls[0]?.[0], { + cwd: "/repo", + refName: "remote-main-sha", + newRefName: "feature", + baseRefName: "main", + path: null, + }); + }).pipe(Effect.provide(test.layer)); +}); + +it.effect("provisions a worktree for an existing empty thread before sending", () => { + const test = makeLayer(); + const threadId = ThreadId.make("thread_existing_empty"); + test.projections.set(threadId, projectionFor(threadId)); + return Effect.gen(function* () { + const service = yield* ThreadLaunch.ThreadLaunchService; + yield* service.launch({ + commandId: CommandId.make("command_launch_existing_empty"), + threadId, + reuseExistingThread: true, + projectId, + title: "Thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { type: "worktree", baseRef: "main", branch: "feature" }, + initialMessage: { text: "Implement it", attachments: [] }, + createdBy: "user", + creationSource: "web", + }); + const updateCommand = test.dispatch.mock.calls.find( + ([command]) => command.type === "thread.metadata.update", + )?.[0]; + assert.equal(updateCommand?.type, "thread.metadata.update"); + if (updateCommand?.type === "thread.metadata.update") { + assert.equal(updateCommand.worktreePath, "/repo-worktrees/feature"); + assert.equal(updateCommand.branch, "feature"); + } + assert.equal(test.sendToThread.mock.calls.length, 1); + }).pipe(Effect.provide(test.layer)); +}); + it.effect("removes a new worktree and does not create a thread when setup fails", () => { const test = makeLayer({ failSetup: true }); return Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.ts index 518a13ea78..cef8b049d0 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts @@ -1,6 +1,7 @@ import { CommandId, type ChatAttachment, + type MessageId, type ModelSelection, type OrchestrationV2Actor, type OrchestrationV2CreationSource, @@ -27,20 +28,29 @@ import * as IdAllocator from "./IdAllocator.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; export type ThreadLaunchWorkspaceStrategy = - | { readonly type: "root" } + | { readonly type: "root"; readonly branch?: string | undefined } + | { + readonly type: "existing_worktree"; + readonly worktreePath: string; + readonly branch?: string | undefined; + } | { readonly type: "worktree"; readonly baseRef: string; - readonly branch?: string; + readonly branch?: string | undefined; + readonly startFromOrigin?: boolean | undefined; }; export interface ThreadLaunchInitialMessage { + readonly messageId?: MessageId; readonly text: string; readonly attachments: ReadonlyArray; } export interface ThreadLaunchInput { readonly commandId: CommandId; + readonly threadId?: ThreadId; + readonly reuseExistingThread?: boolean; readonly projectId: ProjectId; readonly title: string; readonly modelSelection: ModelSelection; @@ -69,6 +79,7 @@ export class ThreadLaunchError extends Schema.TaggedErrorClass 0 || + projection.runs.length > 0 + ) { + return yield* mapError( + input, + "update-thread", + threadId, + )( + "Only an empty active thread in the target project can change workspace during launch.", + ); + } + return projection; + }, + ); + if (input.reuseExistingThread === true && stored?.thread_committed !== 1) { + yield* validateReusableThread(); + } + + let branch = + stored?.branch ?? + (input.workspaceStrategy.type === "worktree" + ? null + : (input.workspaceStrategy.branch ?? null)); let title = stored?.title ?? input.title; if (input.initialMessage !== undefined) { if (title === "New thread") { @@ -235,15 +284,36 @@ export const make = Effect.gen(function* () { branch = branch ?? input.workspaceStrategy.branch ?? `thread-${threadId}`; } - let worktreePath = stored?.worktree_path ?? null; + let worktreePath = + stored?.worktree_path ?? + (input.workspaceStrategy.type === "existing_worktree" + ? input.workspaceStrategy.worktreePath + : null); + const ownsProvisionedWorktree = input.workspaceStrategy.type === "worktree"; const threadCommitted = stored?.thread_committed === 1; let setupCommitted = stored?.setup_committed === 1; let messageCommitted = stored?.message_committed === 1; if (input.workspaceStrategy.type === "worktree" && worktreePath === null) { + let startRef = input.workspaceStrategy.baseRef; + if (input.workspaceStrategy.startFromOrigin === true) { + yield* git + .fetchRemote({ cwd: project.workspaceRoot, remoteName: "origin" }) + .pipe(Effect.mapError(mapError(input, "provision-worktree", threadId))); + startRef = yield* git + .resolveRemoteTrackingCommit({ + cwd: project.workspaceRoot, + refName: input.workspaceStrategy.baseRef, + fallbackRemoteName: "origin", + }) + .pipe( + Effect.map((resolved) => resolved.commitSha), + Effect.mapError(mapError(input, "provision-worktree", threadId)), + ); + } const worktree = yield* git .createWorktree({ cwd: project.workspaceRoot, - refName: input.workspaceStrategy.baseRef, + refName: startRef, newRefName: branch!, baseRefName: input.workspaceStrategy.baseRef, path: null, @@ -278,7 +348,7 @@ export const make = Effect.gen(function* () { }), ); if (setupExit._tag === "Failure") { - if (worktreePath !== null && !threadCommitted) { + if (ownsProvisionedWorktree && worktreePath !== null && !threadCommitted) { yield* git .removeWorktree({ cwd: project.workspaceRoot, path: worktreePath }) .pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId))); @@ -313,24 +383,36 @@ export const make = Effect.gen(function* () { } if (!threadCommitted) { - const createExit = yield* Effect.exit( - threads.dispatch({ - type: "thread.create", - commandId: input.commandId, - threadId, - projectId: input.projectId, - title, - modelSelection: input.modelSelection, - runtimeMode: input.runtimeMode, - interactionMode: input.interactionMode, - branch, - worktreePath, - createdBy: input.createdBy, - creationSource: input.creationSource, - }), - ); + const commitThread = + input.reuseExistingThread === true + ? Effect.gen(function* () { + yield* validateReusableThread(); + return yield* threads.dispatch({ + type: "thread.metadata.update", + commandId: input.commandId, + threadId, + title, + branch, + worktreePath, + }); + }) + : threads.dispatch({ + type: "thread.create", + commandId: input.commandId, + threadId, + projectId: input.projectId, + title, + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + branch, + worktreePath, + createdBy: input.createdBy, + creationSource: input.creationSource, + }); + const createExit = yield* Effect.exit(commitThread); if (createExit._tag === "Failure") { - if (worktreePath !== null) { + if (ownsProvisionedWorktree && worktreePath !== null) { yield* git .removeWorktree({ cwd: project.workspaceRoot, path: worktreePath }) .pipe(Effect.mapError(mapError(input, "compensate-worktree", threadId))); @@ -339,17 +421,27 @@ export const make = Effect.gen(function* () { } yield* saveWorkflow(input, { threadId, - status: "thread_create_failed", + status: + input.reuseExistingThread === true ? "thread_update_failed" : "thread_create_failed", title, worktreePath, branch, setupCommitted, threadCommitted: false, messageCommitted, - lastError: "Thread creation failed.", + lastError: + input.reuseExistingThread === true + ? "Thread workspace update failed." + : "Thread creation failed.", }); return yield* Effect.failCause(createExit.cause).pipe( - Effect.mapError(mapError(input, "create-thread", threadId)), + Effect.mapError( + mapError( + input, + input.reuseExistingThread === true ? "update-thread" : "create-thread", + threadId, + ), + ), ); } yield* saveWorkflow(input, { @@ -365,9 +457,11 @@ export const make = Effect.gen(function* () { } if (input.initialMessage !== undefined && !messageCommitted) { - const messageId = yield* ids.allocate - .message({ threadId, ordinal: 1 }) - .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId))); + const messageId = + input.initialMessage.messageId ?? + (yield* ids.allocate + .message({ threadId, ordinal: 1 }) + .pipe(Effect.mapError(mapError(input, "dispatch-message", threadId)))); yield* threads .sendToThread({ projectId: input.projectId, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index fcd997c567..4b10daff25 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -32,7 +32,7 @@ import { layer as providerTurnControlServiceLayer } from "./ProviderTurnControlS import { layer as providerTurnStartServiceLayer } from "./ProviderTurnStartService.ts"; import { layer as runExecutionServiceLayer } from "./RunExecutionService.ts"; import { layer as runFinalizationServiceLayer } from "./RunFinalizationService.ts"; -import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts"; +import { layerFromProjectRepository as runtimePolicyLayerFromProjectRepository } from "./RuntimePolicy.ts"; import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts"; import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts"; import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts"; @@ -40,6 +40,13 @@ import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.t import { layer as threadForkServiceLayer } from "./ThreadForkService.ts"; import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts"; +export const ProjectServiceLayerLive = projectServiceLayer.pipe( + Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)), +); +const runtimePolicyProvided = runtimePolicyLayerFromProjectRepository.pipe( + Layer.provide(ProjectionProjectRepositoryLive), +); + const eventStoreProvided = eventStoreLayer.pipe( Layer.provide(OrchestrationEventInfrastructureLayerLive), ); @@ -104,7 +111,7 @@ const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe( projectionStoreLayer, providerSessionManagerProvided, runExecutionServiceProvided, - runtimePolicyLayer, + runtimePolicyProvided, ), ), ); @@ -123,7 +130,7 @@ const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe( idAllocatorLayer, projectionStoreLayer, providerSessionManagerProvided, - runtimePolicyLayer, + runtimePolicyProvided, ), ), ); @@ -182,7 +189,7 @@ const orchestratorProvided = orchestratorLayer.pipe( idAllocatorLayer, providerAdapterRegistryProvided, providerEventIngestorProvided, - runtimePolicyLayer, + runtimePolicyProvided, providerSessionManagerProvided, providerSwitchServiceProvided, runExecutionServiceProvided, @@ -194,9 +201,6 @@ const orchestratorProvided = orchestratorLayer.pipe( const threadManagementProvided = threadManagementServiceLayer.pipe( Layer.provide(orchestratorProvided), ); -export const ProjectServiceLayerLive = projectServiceLayer.pipe( - Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)), -); export const ProjectSetupScriptRunnerLayerLive = projectSetupScriptRunnerLayer.pipe( Layer.provide(ProjectServiceLayerLive), ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index c5de9004c7..f96b5bc85b 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,8 +1,11 @@ import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; +import * as Encoding from "effect/Encoding"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; 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 Ref from "effect/Ref"; import * as Result from "effect/Result"; @@ -19,9 +22,11 @@ import { type AuthAccessStreamEvent, type AuthEnvironmentScope, AuthSessionId, + CommandId, type DiscoveredLocalServerList, type GitActionProgressEvent, type GitManagerServiceError, + type MessageId, OrchestrationGetFullThreadDiffError, OrchestrationGetTurnDiffError, ORCHESTRATION_V2_WS_METHODS, @@ -33,16 +38,20 @@ import { type ProjectEntriesFailure, type ProjectFileFailure, type ProjectFileOperation, + type ProjectMutation, ProjectListEntriesError, ProjectReadFileError, ProjectSearchEntriesError, ProjectWriteFileError, + ProjectMutationError, RelayClientInstallFailedError, type RelayClientInstallProgressEvent, type FilesystemBrowseFailure, FilesystemBrowseError, AssetWorkspaceContextNotFoundError, AssetWorkspaceContextResolutionError, + ChatAttachmentId, + PersistChatAttachmentsError, EnvironmentAuthorizationError, ThreadId, type TerminalAttachStreamEvent, @@ -83,6 +92,8 @@ import * as TerminalManager from "./terminal/Manager.ts"; import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts"; import * as PreviewManager from "./preview/Manager.ts"; import { issueAssetUrl } from "./assets/AssetAccess.ts"; +import { attachmentRelativePath, createDeterministicAttachmentId } from "./attachmentStore.ts"; +import { parseBase64DataUrl } from "./imageMime.ts"; import * as PortScanner from "./preview/PortScanner.ts"; import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts"; import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts"; @@ -117,6 +128,73 @@ function unexpectedCompatibilityError(error: never): never { throw new Error(`Unhandled compatibility error: ${String(error)}`); } +const persistChatAttachments = Effect.fn("ws.assets.persistChatAttachments")(function* (input: { + readonly threadId: ThreadId; + readonly messageId: MessageId; + readonly attachments: ReadonlyArray<{ + readonly type: "image"; + readonly name: string; + readonly mimeType: string; + readonly sizeBytes: number; + readonly dataUrl: string; + }>; +}) { + const config = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + return yield* Effect.forEach( + input.attachments.map((attachment, index) => ({ attachment, index })), + Effect.fn("ws.assets.persistChatAttachment")(function* ({ attachment, index }) { + const parsed = parseBase64DataUrl(attachment.dataUrl); + if (parsed === null || parsed.mimeType !== attachment.mimeType.toLowerCase()) { + return yield* new PersistChatAttachmentsError({ + message: `Attachment ${attachment.name} has an invalid image payload.`, + }); + } + const bytes = yield* Effect.fromResult(Encoding.decodeBase64(parsed.base64)).pipe( + Effect.mapError( + (cause) => + new PersistChatAttachmentsError({ + message: `Attachment ${attachment.name} is not valid base64.`, + cause, + }), + ), + ); + if (bytes.byteLength !== attachment.sizeBytes) { + return yield* new PersistChatAttachmentsError({ + message: `Attachment ${attachment.name} size does not match its payload.`, + }); + } + const rawId = createDeterministicAttachmentId(input.threadId, `${input.messageId}:${index}`); + if (rawId === null) { + return yield* new PersistChatAttachmentsError({ + message: "Could not allocate an attachment identifier.", + }); + } + const persisted = { + type: "image" as const, + id: ChatAttachmentId.make(rawId), + name: attachment.name, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + }; + yield* fileSystem + .writeFile(path.join(config.attachmentsDir, attachmentRelativePath(persisted)), bytes) + .pipe( + Effect.mapError( + (cause) => + new PersistChatAttachmentsError({ + message: `Could not persist attachment ${attachment.name}.`, + cause, + }), + ), + ); + return persisted; + }), + { concurrency: 2 }, + ); +}); + function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): { readonly failure: ProjectEntriesFailure; readonly normalizedCwd?: string; @@ -254,9 +332,11 @@ const RPC_REQUIRED_SCOPE = new Map([ [WS_METHODS.projectsReadFile, AuthOrchestrationReadScope], [WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope], [WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope], + [WS_METHODS.projectsMutate, AuthOrchestrationOperateScope], [WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope], [WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope], [WS_METHODS.assetsCreateUrl, AuthOrchestrationReadScope], + [WS_METHODS.assetsPersistChatAttachments, AuthOrchestrationOperateScope], [WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope], [WS_METHODS.vcsRefreshStatus, AuthOrchestrationReadScope], [WS_METHODS.vcsPull, AuthOrchestrationOperateScope], @@ -633,20 +713,28 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => }, ); - const getOrchestrationV2ArchivedShellSnapshot = threadManagement.getShellSnapshot().pipe( - Effect.map((snapshot) => ({ - schemaVersion: snapshot.schemaVersion, - snapshotSequence: snapshot.snapshotSequence, - threads: snapshot.archivedThreads, - })), - Effect.mapError( - (cause) => - new OrchestrationV2GetShellSnapshotError({ - message: "Failed to load archived thread snapshot", - cause, - }), - ), - ); + const getOrchestrationV2ArchivedShellSnapshot = sql + .withTransaction( + Effect.gen(function* () { + const projects = yield* projectionSnapshotQuery.getShellSnapshot(); + const threads = yield* threadManagement.getShellSnapshot(); + return { + schemaVersion: threads.schemaVersion, + snapshotSequence: yield* applicationEvents.latestApplicationSequence, + projects: projects.projects, + threads: threads.archivedThreads, + } as const; + }), + ) + .pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed to load archived thread snapshot", + cause, + }), + ), + ); const subscribeOrchestrationV2ArchivedShell = Effect.fn( "ws.orchestrationV2.subscribeArchivedShell", @@ -681,6 +769,64 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => return Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live); }); + const mutateProject = Effect.fn("ws.projects.mutate")(function* (mutation: ProjectMutation) { + switch (mutation.type) { + case "project.create": + return yield* projectService.create({ + commandId: mutation.commandId, + projectId: mutation.projectId, + title: mutation.title, + workspaceRoot: mutation.workspaceRoot, + ...(mutation.createWorkspaceRootIfMissing === undefined + ? {} + : { createWorkspaceRootIfMissing: mutation.createWorkspaceRootIfMissing }), + ...(mutation.defaultModelSelection === undefined + ? {} + : { defaultModelSelection: mutation.defaultModelSelection }), + ...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }), + }); + case "project.update": + return yield* projectService.update({ + commandId: mutation.commandId, + projectId: mutation.projectId, + ...(mutation.title === undefined ? {} : { title: mutation.title }), + ...(mutation.workspaceRoot === undefined + ? {} + : { workspaceRoot: mutation.workspaceRoot }), + ...(mutation.defaultModelSelection === undefined + ? {} + : { defaultModelSelection: mutation.defaultModelSelection }), + ...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }), + }); + case "project.delete": { + const snapshot = yield* threadManagement.getShellSnapshot(); + const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].filter( + (thread) => thread.projectId === mutation.projectId, + ); + if (projectThreads.length > 0 && mutation.force !== true) { + return yield* new ProjectMutationError({ + commandId: mutation.commandId, + message: `Project ${mutation.projectId} is not empty.`, + }); + } + yield* Effect.forEach( + projectThreads, + (thread) => + threadManagement.dispatch({ + type: "thread.delete", + commandId: CommandId.make(`${mutation.commandId}:delete-thread:${thread.id}`), + threadId: thread.id, + }), + { concurrency: 1, discard: true }, + ); + return yield* projectService.delete({ + commandId: mutation.commandId, + projectId: mutation.projectId, + }); + } + } + }); + const handlers = ServerWsRpcGroup.of({ [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) => observeRpcEffect( @@ -690,7 +836,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => threadManagement.dispatch( ThreadManagementService.withCreationProvenance(command, { createdBy: "user", - creationSource: "web", + creationSource: "creationSource" in command ? command.creationSource : "web", }), ), ) @@ -781,26 +927,29 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => .enqueueCommand( threadLaunch.launch({ commandId: input.commandId, + ...(input.threadId === undefined ? {} : { threadId: input.threadId }), + ...(input.reuseExistingThread === undefined + ? {} + : { reuseExistingThread: input.reuseExistingThread }), projectId: input.projectId, title: input.title, modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, - workspaceStrategy: - input.workspaceStrategy.type === "root" - ? { type: "root" } - : { - type: "worktree", - baseRef: input.workspaceStrategy.baseRef, - ...(input.workspaceStrategy.branch === undefined - ? {} - : { branch: input.workspaceStrategy.branch }), - }, + workspaceStrategy: input.workspaceStrategy, ...(input.initialMessage === undefined ? {} - : { initialMessage: input.initialMessage }), + : { + initialMessage: { + ...(input.initialMessage.messageId === undefined + ? {} + : { messageId: input.initialMessage.messageId }), + text: input.initialMessage.text, + attachments: input.initialMessage.attachments, + }, + }), createdBy: "user", - creationSource: "web", + creationSource: input.creationSource ?? "web", }), ) .pipe( @@ -1059,6 +1208,22 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => ), { "rpc.aggregate": "workspace" }, ), + [WS_METHODS.projectsMutate]: (mutation) => + observeRpcEffect( + WS_METHODS.projectsMutate, + startup.enqueueCommand(mutateProject(mutation)).pipe( + Effect.mapError((cause) => + cause._tag === "ProjectMutationError" + ? cause + : new ProjectMutationError({ + commandId: mutation.commandId, + message: "Failed to mutate project.", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), [WS_METHODS.shellOpenInEditor]: (input) => observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), { "rpc.aggregate": "workspace", @@ -1117,6 +1282,12 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => }), { "rpc.aggregate": "workspace" }, ), + [WS_METHODS.assetsPersistChatAttachments]: (input) => + observeRpcEffect( + WS_METHODS.assetsPersistChatAttachments, + persistChatAttachments(input).pipe(Effect.map((attachments) => ({ attachments }))), + { "rpc.aggregate": "orchestration" }, + ), [WS_METHODS.subscribeVcsStatus]: (input) => observeRpcStream( WS_METHODS.subscribeVcsStatus, diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index e2ee24c360..ba1a53b358 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -126,7 +126,7 @@ export function BranchToolbarBranchSelector({ [environmentId, threadId], ); const serverThread = useThread(threadRef); - const serverSession = serverThread?.session ?? null; + const serverSession = serverThread?.runtime ?? null; const draftThread = useComposerDraftStore((store) => draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef), ); diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index 43ed895c0d..4ae4464cfd 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1,7 +1,8 @@ -import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts"; +import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, RunId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import type { Thread } from "../types"; +import { makeThreadFixture } from "../test-fixtures"; import { MAX_HIDDEN_MOUNTED_PREVIEW_THREADS, MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, @@ -22,7 +23,7 @@ const threadId = ThreadId.make("thread-1"); const now = "2026-03-29T00:00:00.000Z"; function makeThread(overrides: Partial = {}): Thread { - return { + return makeThreadFixture({ id: threadId, environmentId, projectId, @@ -33,25 +34,23 @@ function makeThread(overrides: Partial = {}): Thread { }, runtimeMode: "full-access", interactionMode: "default", - session: null, + runtime: null, messages: [], proposedPlans: [], - activities: [], - checkpoints: [], createdAt: now, updatedAt: now, archivedAt: null, deletedAt: null, - latestTurn: null, + latestRun: null, branch: null, worktreePath: null, ...overrides, - }; + }); } const completedTurn = { - turnId: TurnId.make("turn-1"), - state: "completed" as const, + runId: RunId.make("turn-1"), + status: "completed" as const, requestedAt: now, startedAt: "2026-03-29T00:00:01.000Z", completedAt: "2026-03-29T00:00:10.000Z", @@ -59,12 +58,10 @@ const completedTurn = { }; const readySession = { - threadId, - status: "ready" as const, + status: "completed" as const, providerName: "codex", providerInstanceId: ProviderInstanceId.make("codex"), - runtimeMode: "full-access" as const, - activeTurnId: null, + activeRunId: null, lastError: null, updatedAt: "2026-03-29T00:00:10.000Z", }; @@ -326,15 +323,15 @@ describe("shouldWriteThreadErrorToCurrentServerThread", () => { describe("hasServerAcknowledgedLocalDispatch", () => { it("does not acknowledge unchanged server state", () => { const localDispatch = createLocalDispatchSnapshot( - makeThread({ latestTurn: completedTurn, session: readySession }), + makeThread({ latestRun: completedTurn, runtime: readySession }), ); expect( hasServerAcknowledgedLocalDispatch({ localDispatch, phase: "ready", - latestTurn: completedTurn, - session: readySession, + latestRun: completedTurn, + runtime: readySession, hasPendingApproval: false, hasPendingUserInput: false, threadError: null, @@ -344,11 +341,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => { it("acknowledges a settled newer turn", () => { const localDispatch = createLocalDispatchSnapshot( - makeThread({ latestTurn: completedTurn, session: readySession }), + makeThread({ latestRun: completedTurn, runtime: readySession }), ); const newerTurn = { ...completedTurn, - turnId: TurnId.make("turn-2"), + runId: RunId.make("turn-2"), requestedAt: "2026-03-29T00:01:00.000Z", startedAt: "2026-03-29T00:01:01.000Z", completedAt: "2026-03-29T00:01:30.000Z", @@ -358,8 +355,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => { hasServerAcknowledgedLocalDispatch({ localDispatch, phase: "ready", - latestTurn: newerTurn, - session: { ...readySession, updatedAt: newerTurn.completedAt }, + latestRun: newerTurn, + runtime: { ...readySession, updatedAt: newerTurn.completedAt }, hasPendingApproval: false, hasPendingUserInput: false, threadError: null, @@ -369,12 +366,12 @@ describe("hasServerAcknowledgedLocalDispatch", () => { it("waits for the matching running turn before acknowledging", () => { const localDispatch = createLocalDispatchSnapshot( - makeThread({ latestTurn: completedTurn, session: readySession }), + makeThread({ latestRun: completedTurn, runtime: readySession }), ); const runningTurn = { ...completedTurn, - turnId: TurnId.make("turn-2"), - state: "running" as const, + runId: RunId.make("turn-2"), + status: "running" as const, requestedAt: "2026-03-29T00:01:00.000Z", startedAt: "2026-03-29T00:01:01.000Z", completedAt: null, @@ -384,11 +381,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => { hasServerAcknowledgedLocalDispatch({ localDispatch, phase: "running", - latestTurn: runningTurn, - session: { + latestRun: runningTurn, + runtime: { ...readySession, status: "running", - activeTurnId: TurnId.make("turn-other"), + activeRunId: RunId.make("turn-other"), }, hasPendingApproval: false, hasPendingUserInput: false, @@ -399,11 +396,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => { hasServerAcknowledgedLocalDispatch({ localDispatch, phase: "running", - latestTurn: runningTurn, - session: { + latestRun: runningTurn, + runtime: { ...readySession, status: "running", - activeTurnId: runningTurn.turnId, + activeRunId: runningTurn.runId, }, hasPendingApproval: false, hasPendingUserInput: false, @@ -417,8 +414,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => { const common = { localDispatch, phase: "ready" as const, - latestTurn: null, - session: null, + latestRun: null, + runtime: null, hasPendingApproval: false, hasPendingUserInput: false, threadError: null, diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 36947caae6..d00b18151e 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -7,8 +7,10 @@ import { type ServerProvider, type ScopedThreadRef, type ThreadId, - type TurnId, + type RunId, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { presentThread } from "@t3tools/client-runtime/state/shell"; import { type ChatMessage, type SessionPhase, type Thread } from "../types"; import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore"; import * as Schema from "effect/Schema"; @@ -32,27 +34,46 @@ export function buildLocalDraftThread( draftThread: DraftThreadState, fallbackModelSelection: ModelSelection, ): Thread { - return { - id: threadId, - environmentId: draftThread.environmentId, - projectId: draftThread.projectId, - title: "New thread", - modelSelection: fallbackModelSelection, - runtimeMode: draftThread.runtimeMode, - interactionMode: draftThread.interactionMode, - session: null, + const timestamp = DateTime.makeUnsafe(draftThread.createdAt); + return presentThread(draftThread.environmentId, { + thread: { + id: threadId, + projectId: draftThread.projectId, + title: "New thread", + providerInstanceId: fallbackModelSelection.instanceId, + modelSelection: fallbackModelSelection, + runtimeMode: draftThread.runtimeMode, + interactionMode: draftThread.interactionMode, + branch: draftThread.branch, + worktreePath: draftThread.worktreePath, + activeProviderThreadId: null, + lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + createdAt: timestamp, + updatedAt: timestamp, + archivedAt: null, + deletedAt: null, + }, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], messages: [], - createdAt: draftThread.createdAt, - updatedAt: draftThread.createdAt, - archivedAt: null, - deletedAt: null, - latestTurn: null, - branch: draftThread.branch, - worktreePath: draftThread.worktreePath, + plans: [], + turnItems: [], + checkpointScopes: [], checkpoints: [], - activities: [], - proposedPlans: [], - }; + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt: timestamp, + }); } export function shouldWriteThreadErrorToCurrentServerThread(input: { @@ -251,7 +272,7 @@ export function buildExpiredTerminalContextToastCopy( export function threadHasStarted(thread: Thread | null | undefined): boolean { return Boolean( - thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null), + thread && (thread.latestRun !== null || thread.messages.length > 0 || thread.runtime !== null), ); } @@ -275,7 +296,7 @@ export function deriveLockedProvider(input: { if (!threadHasStarted(input.thread)) { return null; } - const sessionProvider = input.thread?.session?.providerName ?? null; + const sessionProvider = input.thread?.runtime?.providerName ?? null; if (sessionProvider && isProviderDriverKind(sessionProvider)) { return sessionProvider; } @@ -376,37 +397,37 @@ export async function waitForStartedServerThread( export interface LocalDispatchSnapshot { startedAt: string; preparingWorktree: boolean; - latestTurnTurnId: TurnId | null; - latestTurnRequestedAt: string | null; - latestTurnStartedAt: string | null; - latestTurnCompletedAt: string | null; - sessionStatus: NonNullable["status"] | null; - sessionUpdatedAt: string | null; + latestRunId: RunId | null; + latestRunRequestedAt: string | null; + latestRunStartedAt: string | null; + latestRunCompletedAt: string | null; + runtimeStatus: NonNullable["status"] | null; + runtimeUpdatedAt: string | null; } export function createLocalDispatchSnapshot( activeThread: Thread | undefined, options?: { preparingWorktree?: boolean }, ): LocalDispatchSnapshot { - const latestTurn = activeThread?.latestTurn ?? null; - const session = activeThread?.session ?? null; + const latestRun = activeThread?.latestRun ?? null; + const runtime = activeThread?.runtime ?? null; return { startedAt: new Date().toISOString(), preparingWorktree: Boolean(options?.preparingWorktree), - latestTurnTurnId: latestTurn?.turnId ?? null, - latestTurnRequestedAt: latestTurn?.requestedAt ?? null, - latestTurnStartedAt: latestTurn?.startedAt ?? null, - latestTurnCompletedAt: latestTurn?.completedAt ?? null, - sessionStatus: session?.status ?? null, - sessionUpdatedAt: session?.updatedAt ?? null, + latestRunId: latestRun?.runId ?? null, + latestRunRequestedAt: latestRun?.requestedAt ?? null, + latestRunStartedAt: latestRun?.startedAt ?? null, + latestRunCompletedAt: latestRun?.completedAt ?? null, + runtimeStatus: runtime?.status ?? null, + runtimeUpdatedAt: runtime?.updatedAt ?? null, }; } export function hasServerAcknowledgedLocalDispatch(input: { localDispatch: LocalDispatchSnapshot | null; phase: SessionPhase; - latestTurn: Thread["latestTurn"] | null; - session: Thread["session"] | null; + latestRun: Thread["latestRun"] | null; + runtime: Thread["runtime"] | null; hasPendingApproval: boolean; hasPendingUserInput: boolean; threadError: string | null | undefined; @@ -418,25 +439,25 @@ export function hasServerAcknowledgedLocalDispatch(input: { return true; } - const latestTurn = input.latestTurn ?? null; - const session = input.session ?? null; - const latestTurnChanged = - input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) || - input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) || - input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) || - input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null); + const latestRun = input.latestRun ?? null; + const runtime = input.runtime ?? null; + const latestRunChanged = + input.localDispatch.latestRunId !== (latestRun?.runId ?? null) || + input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) || + input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) || + input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null); if (input.phase === "running") { - if (!latestTurnChanged) { + if (!latestRunChanged) { return false; } - if (latestTurn?.startedAt === null || latestTurn === null) { + if (latestRun?.startedAt === null || latestRun === null) { return false; } if ( - session?.activeTurnId !== null && - session?.activeTurnId !== undefined && - latestTurn?.turnId !== session.activeTurnId + runtime?.activeRunId !== null && + runtime?.activeRunId !== undefined && + latestRun?.runId !== runtime.activeRunId ) { return false; } @@ -444,8 +465,8 @@ export function hasServerAcknowledgedLocalDispatch(input: { } return ( - latestTurnChanged || - input.localDispatch.sessionStatus !== (session?.status ?? null) || - input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null) + latestRunChanged || + input.localDispatch.runtimeStatus !== (runtime?.status ?? null) || + input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null) ); } diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 9fb8d647b4..06a4c4e10b 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1,5 +1,4 @@ import { - type ApprovalRequestId, DEFAULT_MODEL, defaultInstanceIdForDriver, type EnvironmentId, @@ -13,14 +12,15 @@ import { type ResolvedKeybindingsConfig, type ScopedThreadRef, type ThreadId, - type TurnId, + type RunId, + type RuntimeRequestId, type KeybindingCommand, - OrchestrationThreadActivity, ProviderInteractionMode, ProviderDriverKind, RuntimeMode, TerminalOpenInput, } from "@t3tools/contracts"; +import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell"; import { connectionStatusText, type EnvironmentConnectionPresentation, @@ -75,13 +75,14 @@ import { derivePendingUserInputs, derivePhase, deriveTimelineEntries, + deriveTimelineEntriesFromVisibleTurnItems, deriveActiveWorkStartedAt, deriveActivePlanState, findSidebarProposedPlan, findLatestProposedPlan, deriveWorkLogEntries, hasActionableProposedPlan, - isLatestTurnSettled, + isLatestRunSettled, } from "../session-logic"; import { type LegendListRef } from "@legendapp/list/react"; import { @@ -197,6 +198,7 @@ import { useThread, useThreadProposedPlans, useThreadRefs, + useThreadVisibleTurnItems, } from "../state/entities"; import { environmentShell } from "../state/shell"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; @@ -250,7 +252,7 @@ import { useAssetUrls } from "../assets/assetUrls"; const IMAGE_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]"; -const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = []; +const EMPTY_WORK_ENTRIES: ThreadWorkEntry[] = []; const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; @@ -359,10 +361,10 @@ type PersistentTerminalLaunchContext = Pick(null); @@ -376,17 +378,17 @@ function useLocalDispatchState(input: { hasServerAcknowledgedLocalDispatch({ localDispatch, phase: input.phase, - latestTurn: input.activeLatestTurn, - session: input.activeThread?.session ?? null, + latestRun: input.activeLatestRun, + runtime: input.activeThread?.runtime ?? null, hasPendingApproval: input.activePendingApproval !== null, hasPendingUserInput: input.activePendingUserInput !== null, threadError: input.threadError, }), [ - input.activeLatestTurn, + input.activeLatestRun, input.activePendingApproval, input.activePendingUserInput, - input.activeThread?.session, + input.activeThread?.runtime, input.phase, input.threadError, localDispatch, @@ -1034,6 +1036,9 @@ function ChatViewContent(props: ChatViewProps) { const composerDraftTarget: ScopedThreadRef | DraftId = routeKind === "server" ? routeThreadRef : props.draftId; const serverThread = useThread(routeKind === "server" ? routeThreadRef : null); + const serverVisibleTurnItems = useThreadVisibleTurnItems( + routeKind === "server" ? routeThreadRef : null, + ); const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); const activeThreadLastVisitedAt = useUiStateStore((store) => routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined, @@ -1111,9 +1116,9 @@ function ChatViewContent(props: ChatViewProps) { const [maximizedRightPanelThreadKey, setMaximizedRightPanelThreadKey] = useState( null, ); - const [respondingRequestIds, setRespondingRequestIds] = useState([]); + const [respondingRequestIds, setRespondingRequestIds] = useState([]); const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState< - ApprovalRequestId[] + RuntimeRequestId[] >([]); const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState< Record> @@ -1237,7 +1242,7 @@ function ChatViewContent(props: ChatViewProps) { const isServerThread = routeKind === "server" && serverThread !== null; const activeThread = isServerThread ? serverThread : localDraftThread; const threadError = isServerThread - ? (localServerError ?? serverThread?.session?.lastError ?? null) + ? (localServerError ?? serverThread?.runtime?.lastError ?? null) : localDraftError; const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE; const interactionMode = @@ -1334,14 +1339,14 @@ function ChatViewContent(props: ChatViewProps) { const existingThreadKeys = new Set([...serverThreadKeys, ...draftThreadKeys]); return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey)); }, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]); - const activeLatestTurn = activeThread?.latestTurn ?? null; + const activeLatestRun = activeThread?.latestRun ?? null; const sourcePlanThreadRef = useMemo(() => { - const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId; + const sourceThreadId = activeLatestRun?.sourcePlanRef?.threadId; if (!activeThread || !sourceThreadId || sourceThreadId === activeThread.id) { return null; } return scopeThreadRef(activeThread.environmentId, sourceThreadId); - }, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread]); + }, [activeLatestRun?.sourcePlanRef?.threadId, activeThread]); const sourceThreadProposedPlans = useThreadProposedPlans(sourcePlanThreadRef); const threadPlanCatalog = useMemo(() => { if (!activeThread) { @@ -1373,7 +1378,7 @@ function ChatViewContent(props: ChatViewProps) { : nextThreadIds; }); }, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]); - const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null); + const latestRunSettled = isLatestRunSettled(activeLatestRun, activeThread?.runtime ?? null); const activeProjectRef = activeThread ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) : null; @@ -1721,16 +1726,19 @@ function ChatViewContent(props: ChatViewProps) { selectedProviderByThreadId ?? threadProvider ?? ProviderDriverKind.make("codex"), ); const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; - const phase = derivePhase(activeThread?.session ?? null); - const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; - const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]); + const phase = derivePhase(activeThread?.runtime ?? null); + const threadWorkEntries = activeThread?.workEntries ?? EMPTY_WORK_ENTRIES; + const workLogEntries = useMemo( + () => deriveWorkLogEntries(threadWorkEntries), + [threadWorkEntries], + ); const pendingApprovals = useMemo( - () => derivePendingApprovals(threadActivities), - [threadActivities], + () => derivePendingApprovals(activeThread?.pendingApprovals ?? []), + [activeThread?.pendingApprovals], ); const pendingUserInputs = useMemo( - () => derivePendingUserInputs(threadActivities), - [threadActivities], + () => derivePendingUserInputs(activeThread?.pendingUserInputs ?? []), + [activeThread?.pendingUserInputs], ); const activePendingUserInput = pendingUserInputs[0] ?? null; const activePendingDraftAnswers = useMemo( @@ -1763,36 +1771,37 @@ function ChatViewContent(props: ChatViewProps) { [activePendingDraftAnswers, activePendingUserInput], ); const activePendingIsResponding = activePendingUserInput - ? respondingUserInputRequestIds.includes(activePendingUserInput.requestId) + ? activePendingUserInput.responseCapability !== "live" || + respondingUserInputRequestIds.includes(activePendingUserInput.requestId) : false; const activeProposedPlan = useMemo(() => { - if (!latestTurnSettled) { + if (!latestRunSettled) { return null; } return findLatestProposedPlan( activeThread?.proposedPlans ?? [], - activeLatestTurn?.turnId ?? null, + activeLatestRun?.runId ?? null, ); - }, [activeLatestTurn?.turnId, activeThread?.proposedPlans, latestTurnSettled]); + }, [activeLatestRun?.runId, activeThread?.proposedPlans, latestRunSettled]); const sidebarProposedPlan = useMemo( () => findSidebarProposedPlan({ threads: threadPlanCatalog, - latestTurn: activeLatestTurn, - latestTurnSettled, + latestRun: activeLatestRun, + latestRunSettled, threadId: activeThread?.id ?? null, }), - [activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog], + [activeLatestRun, activeThread?.id, latestRunSettled, threadPlanCatalog], ); const activePlan = useMemo( - () => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined), - [activeLatestTurn?.turnId, threadActivities], + () => deriveActivePlanState(activeThread?.todoPlans ?? [], activeLatestRun?.runId ?? undefined), + [activeLatestRun?.runId, activeThread?.todoPlans], ); const planSidebarLabel = sidebarProposedPlan || interactionMode === "plan" ? "Plan" : "Tasks"; const showPlanFollowUpPrompt = pendingUserInputs.length === 0 && interactionMode === "plan" && - latestTurnSettled && + latestRunSettled && hasActionableProposedPlan(activeProposedPlan); const activePendingApproval = pendingApprovals[0] ?? null; const { @@ -1803,7 +1812,7 @@ function ChatViewContent(props: ChatViewProps) { isSendBusy, } = useLocalDispatchState({ activeThread, - activeLatestTurn, + activeLatestRun, phase, activePendingApproval: activePendingApproval?.requestId ?? null, activePendingUserInput: activePendingUserInput?.requestId ?? null, @@ -1811,8 +1820,8 @@ function ChatViewContent(props: ChatViewProps) { }); const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; const activeWorkStartedAt = deriveActiveWorkStartedAt( - activeLatestTurn, - activeThread?.session ?? null, + activeLatestRun, + activeThread?.runtime ?? null, localDispatchStartedAt, ); useEffect(() => { @@ -1876,7 +1885,17 @@ function ChatViewContent(props: ChatViewProps) { }); }, []); const serverMessages = activeThread?.messages; - const serverAttachmentIds = useMemo(() => { + const committedServerAttachmentIds = useMemo(() => { + const attachmentIds = new Set(); + for (const row of serverVisibleTurnItems) { + if (row.item.type !== "user_message") continue; + for (const attachment of row.item.attachments) { + attachmentIds.add(attachment.id); + } + } + return [...attachmentIds]; + }, [serverVisibleTurnItems]); + const draftAttachmentIds = useMemo(() => { const attachmentIds = new Set(); for (const message of serverMessages ?? []) { for (const attachment of message.attachments ?? []) { @@ -1885,6 +1904,7 @@ function ChatViewContent(props: ChatViewProps) { } return [...attachmentIds]; }, [serverMessages]); + const serverAttachmentIds = isServerThread ? committedServerAttachmentIds : draftAttachmentIds; const serverAttachmentResources = useMemo( () => serverAttachmentIds.map((attachmentId) => ({ @@ -2056,12 +2076,22 @@ function ChatViewContent(props: ChatViewProps) { } return [...serverMessagesWithPreviewHandoff, ...pendingMessages]; }, [attachmentPreviewHandoffByMessageId, displayServerMessages, optimisticUserMessages]); - const timelineEntries = useMemo( + const serverTimelineEntries = useMemo( + () => + deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: serverVisibleTurnItems, + optimisticMessages: optimisticUserMessages, + attachmentUrlById: serverAttachmentUrlById, + }), + [optimisticUserMessages, serverVisibleTurnItems, serverAttachmentUrlById], + ); + const draftTimelineEntries = useMemo( () => deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries), [activeThread?.proposedPlans, timelineMessages, workLogEntries], ); - const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } = + const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries; + const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } = useTurnDiffSummaries(activeThread); const turnDiffSummaryByAssistantMessageId = useMemo(() => { const byMessageId = new Map(); @@ -2092,7 +2122,7 @@ function ChatViewContent(props: ChatViewProps) { continue; } const turnCount = - summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId]; + summary.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[summary.runId]; if (typeof turnCount !== "number") { break; } @@ -2102,7 +2132,7 @@ function ChatViewContent(props: ChatViewProps) { } return byUserMessageId; - }, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]); + }, [inferredCheckpointTurnCountByRunId, timelineEntries, turnDiffSummaryByAssistantMessageId]); const gitCwd = activeProject ? projectScriptCwd({ @@ -2129,7 +2159,7 @@ function ChatViewContent(props: ChatViewProps) { ?.instanceId ?? null; const activeProviderInstanceId = selectedProviderInstanceId ?? - activeThread?.session?.providerInstanceId ?? + activeThread?.runtime?.providerInstanceId ?? activeThread?.modelSelection.instanceId ?? activeProject?.defaultModelSelection?.instanceId ?? null; @@ -2188,9 +2218,7 @@ function ChatViewContent(props: ChatViewProps) { }, [activeThreadRef, diffOpen, isServerThread, onDiffPanelOpen]); const envLocked = Boolean( - activeThread && - (activeThread.messages.length > 0 || - (activeThread.session !== null && activeThread.session.status !== "stopped")), + activeThread && (activeThread.messages.length > 0 || activeThread.runtime !== null), ); // Handle environment change for draft threads. When the user picks a @@ -2746,8 +2774,8 @@ function ChatViewContent(props: ChatViewProps) { }, [handleInteractionModeChange, interactionMode]); const dismissPlanSidebarForCurrentTurn = useCallback(() => { planSidebarDismissedForTurnRef.current = - activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__"; - }, [activePlan?.turnId, sidebarProposedPlan?.turnId]); + activePlan?.runId ?? sidebarProposedPlan?.runId ?? "__dismissed__"; + }, [activePlan?.runId, sidebarProposedPlan?.runId]); const togglePlanSidebar = useCallback(() => { if (!activeThreadRef) return; if (planSidebarOpen) { @@ -3191,20 +3219,20 @@ function ChatViewContent(props: ChatViewProps) { if (!autoOpenPlanSidebar) return; if (!activePlan) return; if (planSidebarOpen) return; - const latestTurnId = activeLatestTurn?.turnId ?? null; - if (latestTurnId && activePlan.turnId !== latestTurnId) return; - const turnKey = activePlan.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__"; + const latestRunId = activeLatestRun?.runId ?? null; + if (latestRunId && activePlan.runId !== latestRunId) return; + const turnKey = activePlan.runId ?? sidebarProposedPlan?.runId ?? "__dismissed__"; if (planSidebarDismissedForTurnRef.current === turnKey) return; if (activeThreadRef) { useRightPanelStore.getState().open(activeThreadRef, "plan"); } }, [ activePlan, - activeLatestTurn?.turnId, + activeLatestRun?.runId, activeThreadRef, autoOpenPlanSidebar, planSidebarOpen, - sidebarProposedPlan?.turnId, + sidebarProposedPlan?.runId, ]); useEffect(() => { @@ -3745,7 +3773,7 @@ function ChatViewContent(props: ChatViewProps) { role: "user", text: outgoingMessageText, ...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}), - turnId: null, + runId: null, createdAt: messageCreatedAt, updatedAt: messageCreatedAt, streaming: false, @@ -3956,8 +3984,13 @@ function ChatViewContent(props: ChatViewProps) { }; const onRespondToApproval = useCallback( - async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => { + async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => { if (!activeThreadId) return; + if ( + pendingApprovals.find((approval) => approval.requestId === requestId) + ?.responseCapability !== "live" + ) + return; setRespondingRequestIds((existing) => existing.includes(requestId) ? existing : [...existing, requestId], @@ -3980,12 +4013,17 @@ function ChatViewContent(props: ChatViewProps) { setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId)); return result; }, - [activeThreadId, environmentId, respondToThreadApproval, setThreadError], + [activeThreadId, environmentId, pendingApprovals, respondToThreadApproval, setThreadError], ); const onRespondToUserInput = useCallback( - async (requestId: ApprovalRequestId, answers: Record) => { + async (requestId: RuntimeRequestId, answers: Record) => { if (!activeThreadId) return; + if ( + pendingUserInputs.find((input) => input.requestId === requestId)?.responseCapability !== + "live" + ) + return; setRespondingUserInputRequestIds((existing) => existing.includes(requestId) ? existing : [...existing, requestId], @@ -4008,7 +4046,7 @@ function ChatViewContent(props: ChatViewProps) { setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId)); return result; }, - [activeThreadId, environmentId, respondToThreadUserInput, setThreadError], + [activeThreadId, environmentId, pendingUserInputs, respondToThreadUserInput, setThreadError], ); const setActivePendingUserInputQuestionIndex = useCallback( @@ -4092,7 +4130,11 @@ function ChatViewContent(props: ChatViewProps) { ); const onAdvanceActivePendingUserInput = useCallback(() => { - if (!activePendingUserInput || !activePendingProgress) { + if ( + !activePendingUserInput || + activePendingUserInput.responseCapability !== "live" || + !activePendingProgress + ) { return; } if (activePendingProgress.isLastQuestion) { @@ -4179,7 +4221,7 @@ function ChatViewContent(props: ChatViewProps) { id: messageIdForSend, role: "user", text: outgoingMessageText, - turnId: null, + runId: null, createdAt: messageCreatedAt, updatedAt: messageCreatedAt, streaming: false, @@ -4445,9 +4487,9 @@ function ChatViewContent(props: ChatViewProps) { } const reason = getStartedThreadModelChangeBlockReason({ providers: providerStatuses, - hasStartedSession: activeThread.session !== null, + hasStartedSession: activeThread.runtime !== null, currentModelSelection: activeThread.modelSelection, - currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null, + currentProviderInstanceId: activeThread.runtime?.providerInstanceId ?? null, nextModelSelection: { instanceId, model }, }); return reason ? `${reason.description} Start a new thread to use this model.` : null; @@ -4471,9 +4513,9 @@ function ChatViewContent(props: ChatViewProps) { scheduleComposerFocus(); return; } - if (lockedProvider !== null && activeThread.session?.providerInstanceId) { + if (lockedProvider !== null && activeThread.runtime?.providerInstanceId) { const currentEntry = providerStatuses.find( - (snapshot) => snapshot.instanceId === activeThread.session?.providerInstanceId, + (snapshot) => snapshot.instanceId === activeThread.runtime?.providerInstanceId, ); if ( currentEntry?.continuation?.groupKey && @@ -4500,9 +4542,9 @@ function ChatViewContent(props: ChatViewProps) { }; const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({ providers: providerStatuses, - hasStartedSession: activeThread.session !== null, + hasStartedSession: activeThread.runtime !== null, currentModelSelection: activeThread.modelSelection, - currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null, + currentProviderInstanceId: activeThread.runtime?.providerInstanceId ?? null, nextModelSelection, }); if (modelChangeBlockReason) { @@ -4582,9 +4624,9 @@ function ChatViewContent(props: ChatViewProps) { setExpandedImage(preview); }, []); const onOpenTurnDiff = useCallback( - (turnId: TurnId, filePath?: string) => { + (runId: RunId, filePath?: string) => { if (!isServerThread || !activeThreadRef) return; - useDiffPanelStore.getState().selectTurn(activeThreadRef, turnId, filePath); + useDiffPanelStore.getState().selectTurn(activeThreadRef, runId, filePath); useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); }, @@ -4770,11 +4812,11 @@ function ChatViewContent(props: ChatViewProps) { = {}): Thread { - return { + return makeThreadFixture({ id: ThreadId.make("thread-1"), environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID, @@ -19,20 +20,18 @@ function makeThread(overrides: Partial = {}): Thread { modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, runtimeMode: "full-access", interactionMode: "default", - session: null, + runtime: null, messages: [], proposedPlans: [], createdAt: "2026-03-01T00:00:00.000Z", archivedAt: null, deletedAt: null, updatedAt: "2026-03-01T00:00:00.000Z", - latestTurn: null, + latestRun: null, branch: null, worktreePath: null, - checkpoints: [], - activities: [], ...overrides, - }; + }); } describe("buildThreadActionItems", () => { diff --git a/apps/web/src/components/DiffPanel.tsx b/apps/web/src/components/DiffPanel.tsx index cbcd36ce05..bf57f2055a 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -5,7 +5,7 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; -import type { ScopedThreadRef, TurnId } from "@t3tools/contracts"; +import type { ScopedThreadRef, RunId } from "@t3tools/contracts"; import { ArrowRightIcon, CheckIcon, @@ -230,55 +230,55 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff : null, ); const isGitRepo = gitStatusQuery.data?.isRepo ?? true; - const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } = + const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } = useTurnDiffSummaries(activeThread); const orderedTurnDiffSummaries = useMemo( () => [...turnDiffSummaries].toSorted((left, right) => { const leftTurnCount = - left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0; + left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0; const rightTurnCount = - right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0; + right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0; if (leftTurnCount !== rightTurnCount) { return rightTurnCount - leftTurnCount; } return right.completedAt.localeCompare(left.completedAt); }), - [inferredCheckpointTurnCountByTurnId, turnDiffSummaries], + [inferredCheckpointTurnCountByRunId, turnDiffSummaries], ); useEffect(() => { if (!routeThreadRef || diffSelection.kind !== "turn") return; useDiffPanelStore.getState().reconcileTurnSelection( routeThreadRef, - orderedTurnDiffSummaries.map((summary) => summary.turnId), + orderedTurnDiffSummaries.map((summary) => summary.runId), ); }, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]); - const selectedTurnId = diffSelection.kind === "turn" ? diffSelection.turnId : null; + const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null; const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch"; const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null; const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null; const selectedFileRevealRequestId = diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0; const selectedTurn = - selectedTurnId === null + selectedRunId === null ? undefined - : (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ?? + : (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ?? orderedTurnDiffSummaries[0]); const selectedCheckpointTurnCount = selectedTurn && - (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]); + (selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[selectedTurn.runId]); const latestTurn = orderedTurnDiffSummaries[0]; const selectedScopeLabel = - selectedTurnId === null + selectedRunId === null ? selectedGitScope === "unstaged" ? "Working tree" : "Branch changes" - : selectedTurn?.turnId === latestTurn?.turnId + : selectedTurn?.runId === latestTurn?.runId ? "Latest turn" : `Turn ${selectedCheckpointTurnCount ?? "?"}`; - const reviewSectionId = selectedTurn ? `turn:${selectedTurn.turnId}` : selectedGitScope; + const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope; const collapseScopeKey = routeThreadRef ? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}` : null; @@ -308,12 +308,12 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null, toTurnCount: selectedCheckpointRange?.toTurnCount ?? null, ignoreWhitespace: diffIgnoreWhitespace, - cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : null, + cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null, }, { enabled: isGitRepo && selectedTurn !== undefined }, ); const primaryBranchDiffPreview = useEnvironmentQuery( - selectedTurnId === null && activeThread && activeCwd + selectedRunId === null && activeThread && activeCwd ? reviewEnvironment.diffPreview({ environmentId: activeThread.environmentId, input: { @@ -325,7 +325,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff : null, ); const shouldRetryBranchDiffAtEnvironmentCwd = - selectedTurnId === null && + selectedRunId === null && primaryBranchDiffPreview.error?.includes("configured workspace root") === true && serverConfig?.cwd !== undefined && serverConfig.cwd !== activeCwd; @@ -348,7 +348,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff (source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"), ); const localBranchRefs = useEnvironmentQuery( - selectedTurnId === null && + selectedRunId === null && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd @@ -365,7 +365,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff : null, ); const remoteBranchRefs = useEnvironmentQuery( - selectedTurnId === null && + selectedRunId === null && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd @@ -408,9 +408,9 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff const renderablePatch = useMemo( () => getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, { - compactPartialHunkOffsets: selectedTurnId === null, + compactPartialHunkOffsets: selectedRunId === null, }), - [resolvedTheme, selectedPatch, selectedTurnId], + [resolvedTheme, selectedPatch, selectedRunId], ); const renderableFiles = useMemo(() => { if (!renderablePatch || renderablePatch.kind !== "files") { @@ -486,9 +486,9 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff [collapseScopeKey], ); - const selectTurn = (turnId: TurnId) => { + const selectTurn = (runId: RunId) => { if (!routeThreadRef) return; - useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId); + useDiffPanelStore.getState().selectTurn(routeThreadRef, runId); }; const selectGitScope = (scope: "branch" | "unstaged") => { if (!routeThreadRef) return; @@ -513,23 +513,23 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff selectGitScope("unstaged")}> Working tree - {selectedTurnId === null && selectedGitScope === "unstaged" && ( + {selectedRunId === null && selectedGitScope === "unstaged" && ( )} selectGitScope("branch")}> Branch changes - {selectedTurnId === null && selectedGitScope === "branch" && ( + {selectedRunId === null && selectedGitScope === "branch" && ( )} { - if (latestTurn) selectTurn(latestTurn.turnId); + if (latestTurn) selectTurn(latestTurn.runId); }} > Latest turn - {selectedTurnId !== null && selectedTurn?.turnId === latestTurn?.turnId && ( + {selectedRunId !== null && selectedTurn?.runId === latestTurn?.runId && ( )} @@ -539,18 +539,15 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff {orderedTurnDiffSummaries.map((summary) => { const turnCount = summary.checkpointTurnCount ?? - inferredCheckpointTurnCountByTurnId[summary.turnId] ?? + inferredCheckpointTurnCountByRunId[summary.runId] ?? "?"; return ( - selectTurn(summary.turnId)} - > + selectTurn(summary.runId)}> Turn {turnCount} {formatShortTimestamp(summary.completedAt, settings.timestampFormat)} - {summary.turnId === selectedTurn?.turnId && } + {summary.runId === selectedTurn?.runId && } ); })} @@ -558,7 +555,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff - {selectedTurnId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && ( + {selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
Turn diffs are unavailable because this project is not a git repository.
- ) : selectedTurnId !== null && orderedTurnDiffSummaries.length === 0 ? ( + ) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
No completed turns yet.
diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 574e33d4da..b2b882ab30 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -21,19 +21,14 @@ import { sortProjectsForSidebar, THREAD_JUMP_HINT_SHOW_DELAY_MS, } from "./Sidebar.logic"; -import { - EnvironmentId, - OrchestrationLatestTurn, - ProjectId, - ProviderInstanceId, - ThreadId, -} from "@t3tools/contracts"; +import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Project, type Thread, } from "../types"; +import { makeThreadFixture } from "../test-fixtures"; const localEnvironmentId = EnvironmentId.make("environment-local"); @@ -75,13 +70,13 @@ describe("resolveSidebarStageBadgeLabel", () => { }); }); -function makeLatestTurn(overrides?: { +function makeLatestRun(overrides?: { completedAt?: string | null; startedAt?: string | null; -}): OrchestrationLatestTurn { +}): NonNullable { return { - turnId: "turn-1" as never, - state: "completed", + runId: "turn-1" as never, + status: "completed", assistantMessageId: null, requestedAt: "2026-03-09T10:00:00.000Z", startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z", @@ -97,9 +92,9 @@ describe("hasUnseenCompletion", () => { hasPendingApprovals: false, hasPendingUserInput: false, interactionMode: "default", - latestTurn: makeLatestTurn(), + latestRun: makeLatestRun(), lastVisitedAt: "2026-03-09T10:04:00.000Z", - session: null, + runtime: null, }), ).toBe(true); }); @@ -111,9 +106,9 @@ describe("hasUnseenCompletion", () => { hasPendingApprovals: false, hasPendingUserInput: false, interactionMode: "default", - latestTurn: makeLatestTurn(), + latestRun: makeLatestRun(), lastVisitedAt: undefined, - session: null, + runtime: null, }), ).toBe(false); }); @@ -570,15 +565,13 @@ describe("resolveThreadStatusPill", () => { hasPendingApprovals: false, hasPendingUserInput: false, interactionMode: "plan" as const, - latestTurn: null, + latestRun: null, lastVisitedAt: undefined, - session: { - threadId: ThreadId.make("thread-1"), + runtime: { status: "running" as const, providerName: "Codex", providerInstanceId: ProviderInstanceId.make("codex"), - runtimeMode: DEFAULT_RUNTIME_MODE, - activeTurnId: "turn-1" as never, + activeRunId: "turn-1" as never, lastError: null, updatedAt: "2026-03-09T10:00:00.000Z", }, @@ -621,11 +614,11 @@ describe("resolveThreadStatusPill", () => { thread: { ...baseThread, hasActionableProposedPlan: true, - latestTurn: makeLatestTurn(), - session: { - ...baseThread.session, - status: "ready", - activeTurnId: null, + latestRun: makeLatestRun(), + runtime: { + ...baseThread.runtime, + status: "completed", + activeRunId: null, }, }, }), @@ -637,11 +630,11 @@ describe("resolveThreadStatusPill", () => { resolveThreadStatusPill({ thread: { ...baseThread, - latestTurn: makeLatestTurn(), - session: { - ...baseThread.session, - status: "ready", - activeTurnId: null, + latestRun: makeLatestRun(), + runtime: { + ...baseThread.runtime, + status: "completed", + activeRunId: null, }, }, }), @@ -654,12 +647,12 @@ describe("resolveThreadStatusPill", () => { thread: { ...baseThread, interactionMode: "default", - latestTurn: makeLatestTurn(), + latestRun: makeLatestRun(), lastVisitedAt: "2026-03-09T10:04:00.000Z", - session: { - ...baseThread.session, - status: "ready", - activeTurnId: null, + runtime: { + ...baseThread.runtime, + status: "completed", + activeRunId: null, }, }, }), @@ -813,7 +806,7 @@ function makeProject(overrides: Partial = {}): Project { } function makeThread(overrides: Partial = {}): Thread { - return { + return makeThreadFixture({ id: ThreadId.make("thread-1"), environmentId: localEnvironmentId, projectId: ProjectId.make("project-1"), @@ -825,20 +818,18 @@ function makeThread(overrides: Partial = {}): Thread { }, runtimeMode: DEFAULT_RUNTIME_MODE, interactionMode: DEFAULT_INTERACTION_MODE, - session: null, + runtime: null, messages: [], proposedPlans: [], createdAt: "2026-03-09T10:00:00.000Z", archivedAt: null, deletedAt: null, updatedAt: "2026-03-09T10:00:00.000Z", - latestTurn: null, + latestRun: null, branch: null, worktreePath: null, - checkpoints: [], - activities: [], ...overrides, - }; + }); } describe("getFallbackThreadIdAfterDelete", () => { @@ -922,7 +913,7 @@ describe("sortProjectsForSidebar", () => { id: "message-1" as never, role: "user", text: "older project user message", - turnId: null, + runId: null, createdAt: "2026-03-09T10:01:00.000Z", updatedAt: "2026-03-09T10:01:00.000Z", streaming: false, @@ -938,7 +929,7 @@ describe("sortProjectsForSidebar", () => { id: "message-2" as never, role: "user", text: "newer project user message", - turnId: null, + runId: null, createdAt: "2026-03-09T10:05:00.000Z", updatedAt: "2026-03-09T10:05:00.000Z", streaming: false, diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 4e7614ed55..9b2cb61c4e 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -8,7 +8,7 @@ import { } from "../lib/threadSort"; import type { SidebarThreadSummary, Thread } from "../types"; import { cn } from "../lib/utils"; -import { isLatestTurnSettled } from "../session-logic"; +import { isLatestRunSettled } from "../session-logic"; import { resolveServerBackedAppStageLabel } from "../branding.logic"; export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]"; @@ -54,8 +54,8 @@ type ThreadStatusInput = Pick< | "hasPendingApprovals" | "hasPendingUserInput" | "interactionMode" - | "latestTurn" - | "session" + | "latestRun" + | "runtime" > & { lastVisitedAt?: string | undefined; }; @@ -153,8 +153,8 @@ export function useThreadJumpHintVisibility(): { } export function hasUnseenCompletion(thread: ThreadStatusInput): boolean { - if (!thread.latestTurn?.completedAt) return false; - const completedAt = Date.parse(thread.latestTurn.completedAt); + if (!thread.latestRun?.completedAt) return false; + const completedAt = Date.parse(thread.latestRun.completedAt); if (Number.isNaN(completedAt)) return false; if (!thread.lastVisitedAt) return false; @@ -380,7 +380,7 @@ export function resolveThreadStatusPill(input: { }; } - if (thread.session?.status === "running") { + if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") { return { label: "Working", colorClass: "text-sky-600 dark:text-sky-300/80", @@ -389,7 +389,7 @@ export function resolveThreadStatusPill(input: { }; } - if (thread.session?.status === "starting") { + if (thread.runtime?.status === "starting" || thread.runtime?.status === "queued") { return { label: "Connecting", colorClass: "text-sky-600 dark:text-sky-300/80", @@ -401,7 +401,7 @@ export function resolveThreadStatusPill(input: { const hasPlanReadyPrompt = !thread.hasPendingUserInput && thread.interactionMode === "plan" && - isLatestTurnSettled(thread.latestTurn, thread.session) && + isLatestRunSettled(thread.latestRun, thread.runtime) && thread.hasActionableProposedPlan; if (hasPlanReadyPrompt) { return { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index ce925618ca..77d4398778 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -445,7 +445,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr [discoveredPorts, navigateToThread, openPreview, threadRef], ); const isThreadRunning = - thread.session?.status === "running" && thread.session.activeTurnId != null; + thread.runtime?.status === "running" && thread.runtime.activeRunId != null; const threadStatus = resolveThreadStatusPill({ thread: { ...thread, @@ -1771,7 +1771,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec if (clicked === "mark-unread") { for (const threadKey of threadKeys) { const thread = sidebarThreadByKeyRef.current.get(threadKey); - markThreadUnread(threadKey, thread?.latestTurn?.completedAt); + markThreadUnread(threadKey, thread?.latestRun?.completedAt); } clearSelection(); return; @@ -2127,7 +2127,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec } if (clicked === "mark-unread") { - markThreadUnread(threadKey, thread.latestTurn?.completedAt); + markThreadUnread(threadKey, thread.latestRun?.completedAt); return; } if (clicked === "copy-path") { diff --git a/apps/web/src/components/chat/ChangedFilesTree.test.tsx b/apps/web/src/components/chat/ChangedFilesTree.test.tsx index c371acdb36..b6e026b9e3 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.test.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.test.tsx @@ -1,4 +1,4 @@ -import { TurnId } from "@t3tools/contracts"; +import { RunId } from "@t3tools/contracts"; import { renderToStaticMarkup } from "react-dom/server"; import { describe, expect, it } from "vite-plus/test"; @@ -54,7 +54,7 @@ describe("ChangedFilesTree", () => { ({ files, visibleLabels, hiddenLabels }) => { const markup = renderToStaticMarkup( { ({ files, visibleLabels }) => { const markup = renderToStaticMarkup( = {}; export const ChangedFilesCard = memo(function ChangedFilesCard(props: { - turnId: TurnId; + runId: RunId; files: ReadonlyArray; allDirectoriesExpanded: boolean; resolvedTheme: "light" | "dark"; onToggleAllDirectories: () => void; - onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; + onOpenTurnDiff: (runId: RunId, filePath?: string) => void; }) { const { - turnId, + runId, files, allDirectoriesExpanded, resolvedTheme, @@ -60,7 +60,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { type="button" size="xs" variant="outline" - onClick={() => onOpenTurnDiff(turnId, files[0]?.path)} + onClick={() => onOpenTurnDiff(runId, files[0]?.path)} > View diff @@ -68,8 +68,8 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
; allDirectoriesExpanded: boolean; resolvedTheme: "light" | "dark"; - onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; + onOpenTurnDiff: (runId: RunId, filePath?: string) => void; }) { - const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props; + const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId } = props; const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]); const directoryPathsKey = useMemo( () => collectDirectoryPaths(treeNodes).join("\u0000"), @@ -172,7 +172,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: { type="button" className="group flex w-full items-center gap-1.5 rounded-xl py-1 pr-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background" style={{ paddingLeft: `${leftPadding}px` }} - onClick={() => onOpenTurnDiff(turnId, node.path)} + onClick={() => onOpenTurnDiff(runId, node.path)} > {hasDirectoryNodes || depth > 0 ? (
@@ -2455,6 +2478,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) diff --git a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx index 64c3acc7bf..33734c63c8 100644 --- a/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx +++ b/apps/web/src/components/chat/ComposerPendingApprovalActions.tsx @@ -1,12 +1,13 @@ -import { type ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts"; +import { type RuntimeRequestId, type ProviderApprovalDecision } from "@t3tools/contracts"; import { memo } from "react"; import { Button } from "../ui/button"; interface ComposerPendingApprovalActionsProps { - requestId: ApprovalRequestId; + requestId: RuntimeRequestId; isResponding: boolean; + canRespond: boolean; onRespondToApproval: ( - requestId: ApprovalRequestId, + requestId: RuntimeRequestId, decision: ProviderApprovalDecision, ) => Promise; } @@ -14,6 +15,7 @@ interface ComposerPendingApprovalActionsProps { export const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActions({ requestId, isResponding, + canRespond, onRespondToApproval, }: ComposerPendingApprovalActionsProps) { return ( @@ -21,7 +23,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro @@ -910,15 +1080,15 @@ function AssistantChangedFilesSectionInner({ type="button" size="xs" variant="outline" - onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)} + onClick={() => onOpenTurnDiff(turnSummary.runId, checkpointFiles[0]?.path)} > View diff 0 ? blocks.join("\n\n") : null; } function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName { - if ( - workEntry.sourceActivityKind === "user-input.requested" || - workEntry.sourceActivityKind === "user-input.resolved" - ) { + if (workEntry.itemType === "user_input_request") { return "message-circle"; } if (workEntry.requestKind === "command") return "terminal"; @@ -1514,13 +1695,12 @@ function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName { return "square-pen"; } if (workEntry.itemType === "web_search") return "globe"; - if (workEntry.itemType === "image_view") return "eye"; + if (workEntry.itemType === "file_search") return "eye"; switch (workEntry.itemType) { - case "mcp_tool_call": + case "dynamic_tool": return "wrench"; - case "dynamic_tool_call": - case "collab_agent_tool_call": + case "subagent": return "hammer"; } @@ -1552,7 +1732,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { const activity = use(TimelineRowActivityCtx); const [expanded, setExpanded] = useState(false); const iconConfig = workToneIcon(workEntry.tone); - const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning"; + const showWarningIndicator = false; const entryIconName = showWarningIndicator ? "x" : workEntryIconName(workEntry); const heading = toolWorkEntryHeading(workEntry); const rawPreview = workEntryPreview(workEntry, workspaceRoot); @@ -1566,9 +1746,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { const expandedBody = buildToolCallExpandedBody(workEntry, workspaceRoot); const canExpand = expandedBody !== null; const showFailedIndicator = workEntryIndicatesToolFailure(workEntry); - const showDestructiveRowStyle = - showFailedIndicator && - (workEntry.sourceActivityKind === "runtime.error" || !workLogEntryIsToolLike(workEntry)); + const showDestructiveRowStyle = showFailedIndicator && !workLogEntryIsToolLike(workEntry); const iconWrapperClass = cn( "flex size-5 shrink-0 items-center justify-center", showWarningIndicator @@ -1611,6 +1789,8 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: { canExpand && "cursor-pointer hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70", )} + data-v2-item-type={workEntry.projectedItem?.item.type} + data-v2-item-visibility={workEntry.projectedItem?.visibility} {...rowToggleProps} >
@@ -1624,6 +1804,12 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {

{heading} + {workEntry.projectedItem?.visibility !== undefined && + workEntry.projectedItem.visibility !== "local" ? ( + + {workEntry.projectedItem.visibility === "inherited" ? "Inherited" : "Synthetic"} + + ) : null} {preview && ( {preview} )} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 0a34d89fcd..4376b2026c 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -12,6 +12,7 @@ import { type ScopedThreadRef, } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { presentThreadShell } from "@t3tools/client-runtime/state/shell"; import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; import { isAtomCommandInterrupted, @@ -1459,10 +1460,7 @@ export function ArchivedThreadsPanel() { ), ); const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) => - snapshot.threads.map((thread) => ({ - ...thread, - environmentId, - })), + snapshot.threads.map((thread) => presentThreadShell(environmentId, thread)), ); const archivedProjects = Array.from(projectsByEnvironmentAndId.values()); diff --git a/apps/web/src/connection/storage.ts b/apps/web/src/connection/storage.ts index d118a428ed..b3f0633bb4 100644 --- a/apps/web/src/connection/storage.ts +++ b/apps/web/src/connection/storage.ts @@ -6,6 +6,10 @@ import { ConnectionTargetStore, EMPTY_CONNECTION_CATALOG_DOCUMENT, EnvironmentCacheStore, + ORCHESTRATION_CACHE_SCHEMA_VERSION, + StoredOrchestrationShellSnapshot, + StoredOrchestrationThreadSnapshot, + decodeOrDiscardOrchestrationCache, registerConnectionInCatalog, removeCatalogValue, removeConnectionFromCatalog, @@ -17,12 +21,7 @@ import { CredentialStore, ProfileStore, } from "@t3tools/client-runtime/connection"; -import { - EnvironmentId, - OrchestrationShellSnapshot, - OrchestrationThread, - 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"; @@ -37,20 +36,9 @@ const CATALOG_STORE_NAME = "catalog"; const SHELL_STORE_NAME = "shell"; const THREAD_STORE_NAME = "thread"; const CATALOG_KEY = "document"; -const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1; - -const StoredShellSnapshot = Schema.Struct({ - schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION), - environmentId: EnvironmentId, - snapshot: OrchestrationShellSnapshot, -}); +const StoredShellSnapshot = StoredOrchestrationShellSnapshot; const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot); -const StoredThreadSnapshot = Schema.Struct({ - schemaVersion: Schema.Literal(1), - environmentId: EnvironmentId, - threadId: ThreadId, - thread: OrchestrationThread, -}); +const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot; const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot); const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument); const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson); @@ -429,25 +417,24 @@ export const connectionStorageLayer = Layer.effectContext( if (typeof raw !== "string") { return Effect.succeed(Option.none()); } - return decodeStoredShellSnapshot(raw).pipe( - Effect.mapError((cause) => persistenceError("load-shell", cause)), - Effect.map((stored) => - stored.environmentId === environmentId - ? Option.some(stored.snapshot) - : Option.none(), + return decodeOrDiscardOrchestrationCache( + decodeStoredShellSnapshot(raw).pipe( + Effect.mapError((cause) => persistenceError("load-shell", cause)), + Effect.map((stored) => + stored.environmentId === environmentId + ? Option.some(stored.snapshot) + : Option.none(), + ), ), + removeDatabaseValue(database, SHELL_STORE_NAME, environmentId), ); }), - Effect.mapError((cause) => - cause._tag === "ConnectionPersistenceError" - ? cause - : persistenceError("load-shell", cause), - ), + Effect.mapError((cause) => persistenceError("load-shell", cause)), ), saveShell: (environmentId, snapshot) => Effect.gen(function* () { const encoded = yield* encodeStoredShellSnapshot({ - schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, + schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, environmentId, snapshot, }).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause))); @@ -469,33 +456,36 @@ export const connectionStorageLayer = Layer.effectContext( if (typeof raw !== "string") { return Effect.succeed(Option.none()); } - return decodeStoredThreadSnapshot(raw).pipe( - Effect.mapError((cause) => persistenceError("load-thread", cause)), - Effect.map((stored) => - stored.environmentId === environmentId && stored.threadId === threadId - ? Option.some(stored.thread) - : Option.none(), + return decodeOrDiscardOrchestrationCache( + decodeStoredThreadSnapshot(raw).pipe( + Effect.mapError((cause) => persistenceError("load-thread", cause)), + Effect.map((stored) => + stored.environmentId === environmentId && stored.threadId === threadId + ? Option.some(stored.thread) + : Option.none(), + ), + ), + removeDatabaseValue( + database, + THREAD_STORE_NAME, + threadCacheKey(environmentId, threadId), ), ); }), - Effect.mapError((cause) => - cause._tag === "ConnectionPersistenceError" - ? cause - : persistenceError("load-thread", cause), - ), + Effect.mapError((cause) => persistenceError("load-thread", cause)), ), saveThread: (environmentId, thread) => Effect.gen(function* () { const encoded = yield* encodeStoredThreadSnapshot({ - schemaVersion: 1, + schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, environmentId, - threadId: thread.id, + threadId: thread.thread.id, thread, }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause))); yield* writeDatabaseValue( database, THREAD_STORE_NAME, - threadCacheKey(environmentId, thread.id), + threadCacheKey(environmentId, thread.thread.id), encoded, ); }).pipe( diff --git a/apps/web/src/diffPanelStore.test.ts b/apps/web/src/diffPanelStore.test.ts index 64846e8e9f..49b2dd5db5 100644 --- a/apps/web/src/diffPanelStore.test.ts +++ b/apps/web/src/diffPanelStore.test.ts @@ -1,5 +1,5 @@ import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts"; +import { EnvironmentId, ThreadId, RunId } from "@t3tools/contracts"; import { beforeEach, describe, expect, it } from "vite-plus/test"; import { selectThreadDiffPanelSelection, useDiffPanelStore } from "./diffPanelStore"; @@ -17,7 +17,7 @@ describe("diffPanelStore", () => { it("clears incompatible selection fields when changing scopes", () => { const store = useDiffPanelStore.getState(); - store.selectTurn(THREAD_REF, TurnId.make("turn-1"), "src/app.ts"); + store.selectTurn(THREAD_REF, RunId.make("turn-1"), "src/app.ts"); store.selectGitScope(THREAD_REF, "unstaged"); expect( @@ -31,7 +31,7 @@ describe("diffPanelStore", () => { }); it("increments the reveal request when opening the same turn file again", () => { - const turnId = TurnId.make("turn-1"); + const turnId = RunId.make("turn-1"); useDiffPanelStore.getState().selectTurn(THREAD_REF, turnId, "src/app.ts"); useDiffPanelStore.getState().selectTurn(THREAD_REF, turnId, "src/app.ts"); @@ -51,8 +51,8 @@ describe("diffPanelStore", () => { }); it("reconciles a missing turn selection to the latest available turn", () => { - const missingTurnId = TurnId.make("turn-missing"); - const latestTurnId = TurnId.make("turn-latest"); + const missingTurnId = RunId.make("turn-missing"); + const latestTurnId = RunId.make("turn-latest"); useDiffPanelStore.getState().selectTurn(THREAD_REF, missingTurnId, "src/app.ts"); useDiffPanelStore.getState().reconcileTurnSelection(THREAD_REF, [latestTurnId]); diff --git a/apps/web/src/diffPanelStore.ts b/apps/web/src/diffPanelStore.ts index c946b286d1..a4d5bd274f 100644 --- a/apps/web/src/diffPanelStore.ts +++ b/apps/web/src/diffPanelStore.ts @@ -1,5 +1,5 @@ import { scopedThreadKey } from "@t3tools/client-runtime/environment"; -import type { ScopedThreadRef, TurnId } from "@t3tools/contracts"; +import type { RunId, ScopedThreadRef } from "@t3tools/contracts"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; @@ -8,7 +8,7 @@ import { resolveStorage } from "./lib/storage"; export type DiffPanelSelection = | { kind: "branch"; baseRef: string | null } | { kind: "unstaged" } - | { kind: "turn"; turnId: TurnId; filePath: string | null; revealRequestId: number }; + | { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number }; const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null }; @@ -17,8 +17,8 @@ interface DiffPanelStoreState { branchBaseRefByThreadKey: Record; selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void; selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void; - selectTurn: (ref: ScopedThreadRef, turnId: TurnId, filePath?: string) => void; - reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray) => void; + selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void; + reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray) => void; removeThread: (ref: ScopedThreadRef) => void; } @@ -118,7 +118,7 @@ export const useDiffPanelStore = create()( }), { name: "t3code:diff-panel-state:v1", - version: 1, + version: 2, storage: createJSONStorage(() => resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined), ), diff --git a/apps/web/src/historyBootstrap.test.ts b/apps/web/src/historyBootstrap.test.ts index b4be13716e..8c35fef269 100644 --- a/apps/web/src/historyBootstrap.test.ts +++ b/apps/web/src/historyBootstrap.test.ts @@ -14,7 +14,7 @@ describe("buildBootstrapInput", () => { role: "user", text: "hello", createdAt: "2026-02-09T00:00:00.000Z", - turnId: null, + runId: null, updatedAt: "2026-02-09T00:00:00.000Z", streaming: false, }, @@ -23,7 +23,7 @@ describe("buildBootstrapInput", () => { role: "assistant", text: "world", createdAt: "2026-02-09T00:00:01.000Z", - turnId: null, + runId: null, updatedAt: "2026-02-09T00:00:01.000Z", streaming: false, }, @@ -49,7 +49,7 @@ describe("buildBootstrapInput", () => { role: "user", text: "first question with details", createdAt: "2026-02-09T00:00:00.000Z", - turnId: null, + runId: null, updatedAt: "2026-02-09T00:00:00.000Z", streaming: false, }, @@ -58,7 +58,7 @@ describe("buildBootstrapInput", () => { role: "assistant", text: "first answer with details", createdAt: "2026-02-09T00:00:01.000Z", - turnId: null, + runId: null, updatedAt: "2026-02-09T00:00:01.000Z", streaming: false, }, @@ -67,7 +67,7 @@ describe("buildBootstrapInput", () => { role: "user", text: "second question with details", createdAt: "2026-02-09T00:00:02.000Z", - turnId: null, + runId: null, updatedAt: "2026-02-09T00:00:02.000Z", streaming: false, }, @@ -92,7 +92,7 @@ describe("buildBootstrapInput", () => { role: "user", text: "old context", createdAt: "2026-02-09T00:00:00.000Z", - turnId: null, + runId: null, updatedAt: "2026-02-09T00:00:00.000Z", streaming: false, }, @@ -124,7 +124,7 @@ describe("buildBootstrapInput", () => { }, ], createdAt: "2026-02-09T00:00:00.000Z", - turnId: null, + runId: null, updatedAt: "2026-02-09T00:00:00.000Z", streaming: false, }, diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 07655ad30d..cfaa842b3f 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -93,7 +93,7 @@ export function useThreadActions() { const resolved = resolveThreadTarget(target); if (!resolved) return AsyncResult.success(undefined); const { thread, threadRef } = resolved; - if (thread.session?.status === "running" && thread.session.activeTurnId != null) { + if (thread.runtime?.status === "running" && thread.runtime.activeRunId != null) { return AsyncResult.failure( Cause.fail( new ThreadArchiveBlockedError({ @@ -210,7 +210,7 @@ export function useThreadActions() { shouldDeleteWorktree = confirmationResult.value; } - if (thread.session && thread.session.status !== "stopped") { + if (thread.runtime !== null) { await stopThreadSession({ environmentId: threadRef.environmentId, input: { threadId: threadRef.threadId }, diff --git a/apps/web/src/hooks/useTurnDiffSummaries.ts b/apps/web/src/hooks/useTurnDiffSummaries.ts index f51acc15cc..21e28be7bb 100644 --- a/apps/web/src/hooks/useTurnDiffSummaries.ts +++ b/apps/web/src/hooks/useTurnDiffSummaries.ts @@ -1,5 +1,5 @@ import { useMemo } from "react"; -import { inferCheckpointTurnCountByTurnId } from "../session-logic"; +import { inferCheckpointTurnCountByRunId } from "../session-logic"; import type { Thread, TurnDiffSummary } from "../types"; export function useTurnDiffSummaries(activeThread: Thread | null | undefined) { @@ -10,10 +10,10 @@ export function useTurnDiffSummaries(activeThread: Thread | null | undefined) { return activeThread.checkpoints; }, [activeThread]); - const inferredCheckpointTurnCountByTurnId = useMemo( - () => inferCheckpointTurnCountByTurnId(turnDiffSummaries), + const inferredCheckpointTurnCountByRunId = useMemo( + () => inferCheckpointTurnCountByRunId(turnDiffSummaries), [turnDiffSummaries], ); - return { turnDiffSummaries, inferredCheckpointTurnCountByTurnId }; + return { turnDiffSummaries, inferredCheckpointTurnCountByRunId }; } diff --git a/apps/web/src/lib/contextWindow.test.ts b/apps/web/src/lib/contextWindow.test.ts index c3226884a3..3a56d20f0d 100644 --- a/apps/web/src/lib/contextWindow.test.ts +++ b/apps/web/src/lib/contextWindow.test.ts @@ -1,84 +1,44 @@ import { describe, expect, it } from "vite-plus/test"; -import { EventId, type OrchestrationThreadActivity, TurnId } from "@t3tools/contracts"; - import { deriveLatestContextWindowSnapshot, formatContextWindowTokens } from "./contextWindow"; -function makeActivity(id: string, kind: string, payload: unknown): OrchestrationThreadActivity { - return { - id: EventId.make(id), - tone: "info", - kind, - summary: kind, - payload, - turnId: TurnId.make("turn-1"), - createdAt: "2026-03-23T00:00:00.000Z", - }; -} - -describe("contextWindow", () => { - it("derives the latest valid context window snapshot", () => { +describe("V2 context window presentation", () => { + it("uses retained compaction token data when available", () => { const snapshot = deriveLatestContextWindowSnapshot([ - makeActivity("activity-1", "context-window.updated", { - usedTokens: 1000, - }), - makeActivity("activity-2", "tool.started", {}), - makeActivity("activity-3", "context-window.updated", { - usedTokens: 14_000, - maxTokens: 258_000, - compactsAutomatically: true, - }), + { + id: "compaction-1", + createdAt: "2026-06-20T00:00:00.000Z", + runId: null, + label: "Context compacted", + tone: "info", + itemType: "compaction", + toolLifecycleStatus: "completed", + structuredPayload: { + id: "compaction-1" as never, + threadId: "thread-1" as never, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: null, + startedAt: null, + completedAt: null, + updatedAt: {} as never, + type: "compaction", + driver: null, + beforeTokenCount: 10_000, + afterTokenCount: 2_000, + }, + }, ]); - - expect(snapshot).not.toBeNull(); - expect(snapshot?.usedTokens).toBe(14_000); - expect(snapshot?.totalProcessedTokens).toBeNull(); - expect(snapshot?.maxTokens).toBe(258_000); - expect(snapshot?.compactsAutomatically).toBe(true); + expect(snapshot?.usedTokens).toBe(2_000); + expect(snapshot?.totalProcessedTokens).toBe(10_000); }); - it("ignores malformed payloads", () => { - const snapshot = deriveLatestContextWindowSnapshot([ - makeActivity("activity-1", "context-window.updated", {}), - ]); - - expect(snapshot).toBeNull(); - }); - - it("keeps valid zero-usage snapshots", () => { - const snapshot = deriveLatestContextWindowSnapshot([ - makeActivity("activity-1", "context-window.updated", { - usedTokens: 0, - maxTokens: 100_000, - }), - ]); - - expect(snapshot).toMatchObject({ - usedTokens: 0, - maxTokens: 100_000, - remainingTokens: 100_000, - usedPercentage: 0, - remainingPercentage: 100, - }); - }); - - it("formats compact token counts", () => { - expect(formatContextWindowTokens(999)).toBe("999"); - expect(formatContextWindowTokens(1400)).toBe("1.4k"); - expect(formatContextWindowTokens(14_000)).toBe("14k"); - expect(formatContextWindowTokens(258_000)).toBe("258k"); - }); - - it("includes total processed tokens when available", () => { - const snapshot = deriveLatestContextWindowSnapshot([ - makeActivity("activity-1", "context-window.updated", { - usedTokens: 81_659, - totalProcessedTokens: 748_126, - maxTokens: 258_400, - lastUsedTokens: 81_659, - }), - ]); - - expect(snapshot?.usedTokens).toBe(81_659); - expect(snapshot?.totalProcessedTokens).toBe(748_126); + it("formats compact token values", () => { + expect(formatContextWindowTokens(1_500)).toBe("1.5k"); }); }); diff --git a/apps/web/src/lib/contextWindow.ts b/apps/web/src/lib/contextWindow.ts index 80f7d31cf2..d7254211c8 100644 --- a/apps/web/src/lib/contextWindow.ts +++ b/apps/web/src/lib/contextWindow.ts @@ -1,17 +1,10 @@ -import type { OrchestrationThreadActivity, ThreadTokenUsageSnapshot } from "@t3tools/contracts"; - -function asRecord(value: unknown): Record | null { - return value && typeof value === "object" ? (value as Record) : null; -} +import type { ThreadTokenUsageSnapshot } from "@t3tools/contracts"; +import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell"; function asFiniteNumber(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; } -function asBoolean(value: unknown): boolean | null { - return typeof value === "boolean" ? value : null; -} - type NullableContextWindowUsage = { readonly [Key in keyof ThreadTokenUsageSnapshot]: undefined extends ThreadTokenUsageSnapshot[Key] ? Exclude | null @@ -48,21 +41,20 @@ export function formatProviderDisplayName(provider: string | null | undefined): } export function deriveLatestContextWindowSnapshot( - activities: ReadonlyArray, + entries: ReadonlyArray, ): ContextWindowSnapshot | null { - for (let index = activities.length - 1; index >= 0; index -= 1) { - const activity = activities[index]; - if (!activity || activity.kind !== "context-window.updated") { + for (let index = entries.length - 1; index >= 0; index -= 1) { + const entry = entries[index]; + if (!entry || entry.structuredPayload.type !== "compaction") { continue; } - - const payload = asRecord(activity.payload); - const usedTokens = asFiniteNumber(payload?.usedTokens); + const payload = entry.structuredPayload; + const usedTokens = asFiniteNumber(payload.afterTokenCount); if (usedTokens === null || usedTokens < 0) { continue; } - const maxTokens = asFiniteNumber(payload?.maxTokens); + const maxTokens = null; const usedPercentage = maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null; const remainingTokens = @@ -71,24 +63,24 @@ export function deriveLatestContextWindowSnapshot( return { usedTokens, - totalProcessedTokens: asFiniteNumber(payload?.totalProcessedTokens), + totalProcessedTokens: asFiniteNumber(payload.beforeTokenCount), maxTokens, remainingTokens, usedPercentage, remainingPercentage, - inputTokens: asFiniteNumber(payload?.inputTokens), - cachedInputTokens: asFiniteNumber(payload?.cachedInputTokens), - outputTokens: asFiniteNumber(payload?.outputTokens), - reasoningOutputTokens: asFiniteNumber(payload?.reasoningOutputTokens), - lastUsedTokens: asFiniteNumber(payload?.lastUsedTokens), - lastInputTokens: asFiniteNumber(payload?.lastInputTokens), - lastCachedInputTokens: asFiniteNumber(payload?.lastCachedInputTokens), - lastOutputTokens: asFiniteNumber(payload?.lastOutputTokens), - lastReasoningOutputTokens: asFiniteNumber(payload?.lastReasoningOutputTokens), - toolUses: asFiniteNumber(payload?.toolUses), - durationMs: asFiniteNumber(payload?.durationMs), - compactsAutomatically: asBoolean(payload?.compactsAutomatically) ?? false, - updatedAt: activity.createdAt, + inputTokens: null, + cachedInputTokens: null, + outputTokens: null, + reasoningOutputTokens: null, + lastUsedTokens: null, + lastInputTokens: null, + lastCachedInputTokens: null, + lastOutputTokens: null, + lastReasoningOutputTokens: null, + toolUses: null, + durationMs: null, + compactsAutomatically: true, + updatedAt: entry.createdAt, }; } diff --git a/apps/web/src/lib/threadSort.test.ts b/apps/web/src/lib/threadSort.test.ts index b9981bc2e3..2ae3c0c524 100644 --- a/apps/web/src/lib/threadSort.test.ts +++ b/apps/web/src/lib/threadSort.test.ts @@ -7,13 +7,14 @@ import { ThreadId, } from "@t3tools/contracts"; import type { Thread } from "../types"; +import { makeThreadFixture } from "../test-fixtures"; import { getLatestThreadForProject, sortThreads } from "./threadSort"; const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local"); const PROJECT_ID = ProjectId.make("project-1"); function makeThread(overrides: Partial = {}): Thread { - return { + return makeThreadFixture({ id: ThreadId.make("thread-1"), environmentId: LOCAL_ENVIRONMENT_ID, projectId: PROJECT_ID, @@ -21,20 +22,18 @@ function makeThread(overrides: Partial = {}): Thread { modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, runtimeMode: DEFAULT_RUNTIME_MODE, interactionMode: "default", - session: null, + runtime: null, messages: [], proposedPlans: [], createdAt: "2026-03-09T10:00:00.000Z", archivedAt: null, deletedAt: null, updatedAt: "2026-03-09T10:00:00.000Z", - latestTurn: null, + latestRun: null, branch: null, worktreePath: null, - checkpoints: [], - activities: [], ...overrides, - }; + }); } describe("sortThreads", () => { @@ -49,7 +48,7 @@ describe("sortThreads", () => { id: "message-1" as never, role: "user", text: "older", - turnId: null, + runId: null, createdAt: "2026-03-09T10:01:00.000Z", updatedAt: "2026-03-09T10:01:00.000Z", streaming: false, @@ -65,7 +64,7 @@ describe("sortThreads", () => { id: "message-2" as never, role: "user", text: "newer", - turnId: null, + runId: null, createdAt: "2026-03-09T10:06:00.000Z", updatedAt: "2026-03-09T10:06:00.000Z", streaming: false, @@ -93,7 +92,7 @@ describe("sortThreads", () => { id: "message-1" as never, role: "assistant", text: "assistant only", - turnId: null, + runId: null, createdAt: "2026-03-09T10:02:00.000Z", updatedAt: "2026-03-09T10:02:00.000Z", streaming: false, diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index 0f12e672f6..c7e5293cfc 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -1,1688 +1,159 @@ import { - EventId, MessageId, + PlanId, + RunId, ThreadId, - TurnId, - 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 { - deriveActiveWorkStartedAt, - deriveActivePlanState, - derivePendingApprovals, - derivePendingUserInputs, deriveTimelineEntries, - deriveWorkLogEntries, + deriveTimelineEntriesFromVisibleTurnItems, findLatestProposedPlan, - findSidebarProposedPlan, - hasActionableProposedPlan, - isLatestTurnSettled, - workEntryIndicatesToolFailure, - workEntryIndicatesToolNeutralStatus, - workEntryIndicatesToolSuccess, + isLatestRunSettled, } from "./session-logic"; -let nextActivityId = 0; - -function makeActivity(overrides: { - id?: string; - createdAt?: string; - kind?: string; - summary?: string; - tone?: OrchestrationThreadActivity["tone"]; - payload?: Record; - turnId?: string; - sequence?: number; -}): OrchestrationThreadActivity { - const payload = overrides.payload ?? {}; - return { - id: EventId.make(overrides.id ?? `activity-${nextActivityId++}`), - createdAt: overrides.createdAt ?? "2026-02-23T00:00:00.000Z", - kind: overrides.kind ?? "tool.started", - summary: overrides.summary ?? "Tool call", - tone: overrides.tone ?? "tool", - payload, - turnId: overrides.turnId ? TurnId.make(overrides.turnId) : null, - ...(overrides.sequence !== undefined ? { sequence: overrides.sequence } : {}), - }; -} - -describe("derivePendingApprovals", () => { - it("tracks open approvals and removes resolved ones", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "approval-open", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "approval.requested", - summary: "Command approval requested", - tone: "approval", - payload: { - requestId: "req-1", - requestKind: "command", - detail: "bun run lint", - }, - }), - makeActivity({ - id: "approval-close", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "approval.resolved", - summary: "Approval resolved", - tone: "info", - payload: { requestId: "req-2" }, - }), - makeActivity({ - id: "approval-closed-request", - createdAt: "2026-02-23T00:00:01.500Z", - kind: "approval.requested", - summary: "File-change approval requested", - tone: "approval", - payload: { requestId: "req-2", requestKind: "file-change" }, - }), - ]; - - expect(derivePendingApprovals(activities)).toEqual([ - { - requestId: "req-1", - requestKind: "command", - createdAt: "2026-02-23T00:00:01.000Z", - detail: "bun run lint", - }, - ]); - }); - - it("maps canonical requestType payloads into pending approvals", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "approval-open-request-type", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "approval.requested", - summary: "Command approval requested", - tone: "approval", - payload: { - requestId: "req-request-type", - requestType: "command_execution_approval", - detail: "pwd", - }, - }), - ]; - - expect(derivePendingApprovals(activities)).toEqual([ - { - requestId: "req-request-type", - requestKind: "command", - createdAt: "2026-02-23T00:00:01.000Z", - detail: "pwd", - }, - ]); - }); - - it("clears stale pending approvals when provider reports unknown pending request", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "approval-open-stale", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "approval.requested", - summary: "Command approval requested", - tone: "approval", - payload: { - requestId: "req-stale-1", - requestKind: "command", - }, - }), - makeActivity({ - id: "approval-failed-stale", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "provider.approval.respond.failed", - summary: "Provider approval response failed", - tone: "error", - payload: { - requestId: "req-stale-1", - detail: "Unknown pending permission request: req-stale-1", - }, - }), - ]; - - expect(derivePendingApprovals(activities)).toEqual([]); - }); - - it("clears stale pending approvals when the backend marks them stale after restart", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "approval-open-stale-restart", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "approval.requested", - summary: "Command approval requested", - tone: "approval", - payload: { - requestId: "req-stale-restart-1", - requestKind: "command", - }, - }), - makeActivity({ - id: "approval-failed-stale-restart", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "provider.approval.respond.failed", - summary: "Provider approval response failed", - tone: "error", - payload: { - requestId: "req-stale-restart-1", - detail: - "Stale pending approval request: req-stale-restart-1. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.", - }, - }), - ]; - - expect(derivePendingApprovals(activities)).toEqual([]); - }); -}); - -describe("derivePendingUserInputs", () => { - it("tracks open structured prompts and removes resolved ones", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "user-input-open", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "user-input.requested", - summary: "User input requested", - tone: "info", - payload: { - requestId: "req-user-input-1", - questions: [ - { - id: "sandbox_mode", - header: "Sandbox", - question: "Which mode should be used?", - options: [ - { - label: "workspace-write", - description: "Allow workspace writes only", - }, - ], - multiSelect: true, - }, - ], - }, - }), - makeActivity({ - id: "user-input-resolved", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "user-input.resolved", - summary: "User input submitted", - tone: "info", - payload: { - requestId: "req-user-input-2", - answers: { - sandbox_mode: "workspace-write", - }, - }, - }), - makeActivity({ - id: "user-input-open-2", - createdAt: "2026-02-23T00:00:01.500Z", - kind: "user-input.requested", - summary: "User input requested", - tone: "info", - payload: { - requestId: "req-user-input-2", - questions: [ - { - id: "approval", - header: "Approval", - question: "Continue?", - options: [ - { - label: "yes", - description: "Continue execution", - }, - ], - multiSelect: false, - }, - ], - }, - }), - ]; - - expect(derivePendingUserInputs(activities)).toEqual([ - { - requestId: "req-user-input-1", - createdAt: "2026-02-23T00:00:01.000Z", - questions: [ - { - id: "sandbox_mode", - header: "Sandbox", - question: "Which mode should be used?", - options: [ - { - label: "workspace-write", - description: "Allow workspace writes only", - }, - ], - multiSelect: true, - }, - ], - }, - ]); - }); - - it("clears stale pending user-input prompts when the provider reports an orphaned request", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "user-input-open-stale", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "user-input.requested", - summary: "User input requested", - tone: "info", - payload: { - requestId: "req-user-input-stale-1", - questions: [ - { - id: "sandbox_mode", - header: "Sandbox", - question: "Which mode should be used?", - options: [ - { - label: "workspace-write", - description: "Allow workspace writes only", - }, - ], - multiSelect: false, - }, - ], - }, - }), - makeActivity({ - id: "user-input-failed-stale", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "provider.user-input.respond.failed", - summary: "Provider user input response failed", - tone: "error", - payload: { - requestId: "req-user-input-stale-1", - detail: - "Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: req-user-input-stale-1", - }, - }), - ]; - - expect(derivePendingUserInputs(activities)).toEqual([]); - }); -}); - -describe("deriveActivePlanState", () => { - it("returns the latest plan update for the active turn", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "plan-old", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "turn.plan.updated", - summary: "Plan updated", - tone: "info", - turnId: "turn-1", - payload: { - explanation: "Initial plan", - plan: [{ step: "Inspect code", status: "pending" }], - }, - }), - makeActivity({ - id: "plan-latest", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "turn.plan.updated", - summary: "Plan updated", - tone: "info", - turnId: "turn-1", - payload: { - explanation: "Refined plan", - plan: [{ step: "Implement Codex user input", status: "inProgress" }], - }, - }), - ]; - - expect(deriveActivePlanState(activities, TurnId.make("turn-1"))).toEqual({ - createdAt: "2026-02-23T00:00:02.000Z", - turnId: "turn-1", - explanation: "Refined plan", - steps: [{ step: "Implement Codex user input", status: "inProgress" }], - }); - }); - - it("falls back to the most recent plan from a previous turn", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "plan-from-turn-1", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "turn.plan.updated", - summary: "Plan updated", - tone: "info", - turnId: "turn-1", - payload: { - plan: [{ step: "Write tests", status: "completed" }], - }, - }), - ]; - - // Current turn is turn-2, which has no plan activity — should fall back to turn-1's plan - const result = deriveActivePlanState(activities, TurnId.make("turn-2")); - expect(result).toEqual({ - createdAt: "2026-02-23T00:00:01.000Z", - turnId: "turn-1", - steps: [{ step: "Write tests", status: "completed" }], - }); - }); -}); - -describe("findLatestProposedPlan", () => { - it("prefers the latest proposed plan for the active turn", () => { +describe("V2 session presentation", () => { + it("uses run status as the settlement boundary", () => { + const runId = RunId.make("run-1"); expect( - findLatestProposedPlan( - [ - { - id: "plan:thread-1:turn:turn-1", - turnId: TurnId.make("turn-1"), - planMarkdown: "# Older", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:01.000Z", - updatedAt: "2026-02-23T00:00:01.000Z", - }, - { - id: "plan:thread-1:turn:turn-1", - turnId: TurnId.make("turn-1"), - planMarkdown: "# Latest", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:01.000Z", - updatedAt: "2026-02-23T00:00:02.000Z", - }, - { - id: "plan:thread-1:turn:turn-2", - turnId: TurnId.make("turn-2"), - planMarkdown: "# Different turn", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:03.000Z", - updatedAt: "2026-02-23T00:00:03.000Z", - }, - ], - TurnId.make("turn-1"), + isLatestRunSettled( + { + runId, + status: "completed", + startedAt: "2026-06-20T00:00:00.000Z", + completedAt: "2026-06-20T00:01:00.000Z", + }, + null, ), - ).toEqual({ - id: "plan:thread-1:turn:turn-1", - turnId: "turn-1", - planMarkdown: "# Latest", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:01.000Z", - updatedAt: "2026-02-23T00:00:02.000Z", - }); + ).toBe(true); + expect( + isLatestRunSettled( + { runId, status: "running", startedAt: null, completedAt: null }, + { status: "running", activeRunId: runId }, + ), + ).toBe(false); }); - it("falls back to the most recently updated proposed plan", () => { - const latestPlan = findLatestProposedPlan( + it("selects the latest proposed plan for a run", () => { + const runId = RunId.make("run-1"); + const plan = findLatestProposedPlan( [ { - id: "plan:thread-1:turn:turn-1", - turnId: TurnId.make("turn-1"), - planMarkdown: "# First", + id: PlanId.make("plan-1"), + runId, + planMarkdown: "Plan", + status: "active", implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:01.000Z", - updatedAt: "2026-02-23T00:00:01.000Z", - }, - { - id: "plan:thread-1:turn:turn-2", - turnId: TurnId.make("turn-2"), - planMarkdown: "# Latest", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:02.000Z", - updatedAt: "2026-02-23T00:00:03.000Z", + implementationThreadId: ThreadId.make("thread-implementation"), + createdAt: "2026-06-20T00:00:00.000Z", + updatedAt: "2026-06-20T00:00:01.000Z", }, ], - null, + runId, ); - - expect(latestPlan?.planMarkdown).toBe("# Latest"); - }); -}); - -describe("hasActionableProposedPlan", () => { - it("returns true for an unimplemented proposed plan", () => { - expect( - hasActionableProposedPlan({ - id: "plan-1", - turnId: TurnId.make("turn-1"), - planMarkdown: "# Plan", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:00.000Z", - updatedAt: "2026-02-23T00:00:01.000Z", - }), - ).toBe(true); + expect(plan?.planMarkdown).toBe("Plan"); }); - it("returns false for a proposed plan already implemented elsewhere", () => { - expect( - hasActionableProposedPlan({ - id: "plan-1", - turnId: TurnId.make("turn-1"), - planMarkdown: "# Plan", - implementedAt: "2026-02-23T00:00:02.000Z", - implementationThreadId: ThreadId.make("thread-implement"), - createdAt: "2026-02-23T00:00:00.000Z", - updatedAt: "2026-02-23T00:00:02.000Z", - }), - ).toBe(false); - }); -}); - -describe("findSidebarProposedPlan", () => { - it("prefers the running turn source proposed plan when available on the same thread", () => { - expect( - findSidebarProposedPlan({ - threads: [ - { - id: ThreadId.make("thread-1"), - proposedPlans: [ - { - id: "plan-1", - turnId: TurnId.make("turn-plan"), - planMarkdown: "# Source plan", - implementedAt: "2026-02-23T00:00:03.000Z", - implementationThreadId: ThreadId.make("thread-2"), - createdAt: "2026-02-23T00:00:01.000Z", - updatedAt: "2026-02-23T00:00:02.000Z", - }, - ], - }, - { - id: ThreadId.make("thread-2"), - proposedPlans: [ - { - id: "plan-2", - turnId: TurnId.make("turn-other"), - planMarkdown: "# Latest elsewhere", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:04.000Z", - updatedAt: "2026-02-23T00:00:05.000Z", - }, - ], - }, - ], - latestTurn: { - turnId: TurnId.make("turn-implementation"), - sourceProposedPlan: { - threadId: ThreadId.make("thread-1"), - planId: "plan-1", - }, - }, - latestTurnSettled: false, - threadId: ThreadId.make("thread-1"), - }), - ).toEqual({ - id: "plan-1", - turnId: "turn-plan", - planMarkdown: "# Source plan", - implementedAt: "2026-02-23T00:00:03.000Z", - implementationThreadId: "thread-2", - createdAt: "2026-02-23T00:00:01.000Z", - updatedAt: "2026-02-23T00:00:02.000Z", - }); - }); - - it("falls back to the latest proposed plan once the turn is settled", () => { - expect( - findSidebarProposedPlan({ - threads: [ - { - id: ThreadId.make("thread-1"), - proposedPlans: [ - { - id: "plan-1", - turnId: TurnId.make("turn-plan"), - planMarkdown: "# Older", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:01.000Z", - updatedAt: "2026-02-23T00:00:02.000Z", - }, - { - id: "plan-2", - turnId: TurnId.make("turn-latest"), - planMarkdown: "# Latest", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:03.000Z", - updatedAt: "2026-02-23T00:00:04.000Z", - }, - ], - }, - ], - latestTurn: { - turnId: TurnId.make("turn-implementation"), - sourceProposedPlan: { - threadId: ThreadId.make("thread-1"), - planId: "plan-1", - }, - }, - latestTurnSettled: true, - threadId: ThreadId.make("thread-1"), - })?.planMarkdown, - ).toBe("# Latest"); - }); -}); - -describe("workEntryIndicatesToolFailure", () => { - const base = { - id: "w1", - createdAt: "2026-01-01T00:00:00.000Z", - label: "Read", - }; - - it("is true for error tone", () => { - expect( - workEntryIndicatesToolFailure({ - ...base, - tone: "error", - detail: "nothing special", - }), - ).toBe(true); - }); - - it("is true when lifecycle says failed even if detail is empty", () => { - expect( - workEntryIndicatesToolFailure({ - ...base, - tone: "tool", - toolLifecycleStatus: "failed", - }), - ).toBe(true); - }); - - it("detects file-not-found style tool output with completed lifecycle", () => { - expect( - workEntryIndicatesToolFailure({ - ...base, - tone: "tool", - toolLifecycleStatus: "completed", - detail: "File not found: C:\\foo\\nonexistent.ts", - }), - ).toBe(true); - }); - - it("detects glob no files and PowerShell command errors", () => { - expect( - workEntryIndicatesToolFailure({ - ...base, - label: "Glob", - tone: "tool", - detail: "No files found", - }), - ).toBe(true); - expect( - workEntryIndicatesToolFailure({ - ...base, - label: "Bash", - tone: "tool", - detail: - "The term 'this_is_not_a_command' is not recognized as the name of a cmdlet, function, script file, or operable program.", - }), - ).toBe(true); - }); - - it("is false for successful completed tools", () => { - expect( - workEntryIndicatesToolFailure({ - ...base, - tone: "tool", - toolLifecycleStatus: "completed", - detail: "Found 3 matching files", - }), - ).toBe(false); - }); - - it("treats successful tool rows as success candidates", () => { - expect( - workEntryIndicatesToolSuccess({ - ...base, - tone: "tool", - toolLifecycleStatus: "completed", - detail: "ok", - }), - ).toBe(true); - expect( - workEntryIndicatesToolSuccess({ - ...base, - tone: "tool", - toolLifecycleStatus: "inProgress", - detail: "…", - }), - ).toBe(false); - expect(workEntryIndicatesToolSuccess({ ...base, tone: "thinking", detail: "…" })).toBe(false); - expect( - workEntryIndicatesToolNeutralStatus({ - ...base, - tone: "tool", - toolLifecycleStatus: "inProgress", - detail: "…", - }), - ).toBe(true); - expect( - workEntryIndicatesToolNeutralStatus({ - ...base, - tone: "tool", - toolLifecycleStatus: "completed", - detail: "ok", - }), - ).toBe(false); - }); - - it("does not run heuristics on non-tool info rows", () => { - expect( - workEntryIndicatesToolFailure({ - ...base, - label: "Context compacted", - tone: "info", - detail: "File not found in conversation", - }), - ).toBe(false); - }); -}); - -describe("deriveWorkLogEntries", () => { - it("omits tool started entries and keeps completed entries", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "tool-complete", - createdAt: "2026-02-23T00:00:03.000Z", - summary: "Tool call complete", - kind: "tool.completed", - }), - makeActivity({ - id: "tool-start", - createdAt: "2026-02-23T00:00:02.000Z", - summary: "Tool call", - kind: "tool.started", - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]); - }); - - it("omits task.started but shows task.progress and task.completed", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "task-start", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "task.started", - summary: "default task started", - tone: "info", - }), - makeActivity({ - id: "task-progress", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "task.progress", - summary: "Updating files", - tone: "info", - }), - makeActivity({ - id: "task-complete", - createdAt: "2026-02-23T00:00:03.000Z", - kind: "task.completed", - summary: "Task completed", - tone: "info", - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries.map((entry) => entry.id)).toEqual(["task-progress", "task-complete"]); - }); - - it("uses payload summary as label for task entries when available", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "task-progress-with-summary", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "task.progress", - summary: "Reasoning update", - tone: "info", - payload: { summary: "Searching for API endpoints" }, - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries[0]?.label).toBe("Searching for API endpoints"); - }); - - it("uses payload detail as label for task.completed and preserves error tone", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "task-completed-failed", - createdAt: "2026-02-23T00:00:03.000Z", - kind: "task.completed", - summary: "Task failed", - tone: "error", - payload: { detail: "Failed to deploy changes" }, - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries[0]?.label).toBe("Failed to deploy changes"); - expect(entries[0]?.tone).toBe("error"); - }); - - it("keeps tool entries from every turn and tags each with its turn id", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "turn-1-tool", - turnId: "turn-1", - summary: "Tool call complete", - kind: "tool.completed", - }), - makeActivity({ - id: "turn-2-tool", - turnId: "turn-2", - summary: "Tool call complete", - kind: "tool.completed", - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries.map((entry) => entry.id)).toEqual(["turn-1-tool", "turn-2-tool"]); - expect(entries.map((entry) => entry.turnId)).toEqual([ - TurnId.make("turn-1"), - TurnId.make("turn-2"), - ]); - }); - - it("omits checkpoint captured info entries", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "checkpoint", - createdAt: "2026-02-23T00:00:01.000Z", - summary: "Checkpoint captured", - tone: "info", - }), - makeActivity({ - id: "tool-complete", - createdAt: "2026-02-23T00:00:02.000Z", - summary: "Ran command", - tone: "tool", - kind: "tool.completed", - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]); - }); - - it("omits ExitPlanMode lifecycle entries once the plan card is shown", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "exit-plan-updated", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "tool.updated", - summary: "Tool call", - payload: { - detail: 'ExitPlanMode: {"allowedPrompts":[{"tool":"Bash","prompt":"run tests"}]}', - }, - }), - makeActivity({ - id: "exit-plan-completed", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "tool.completed", - summary: "Tool call", - payload: { - detail: "ExitPlanMode: {}", - }, - }), - makeActivity({ - id: "real-work-log", - createdAt: "2026-02-23T00:00:03.000Z", - kind: "tool.completed", - summary: "Ran command", - payload: { - itemType: "command_execution", - detail: "Bash: bun test", - }, - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries.map((entry) => entry.id)).toEqual(["real-work-log"]); - }); - - it("orders work log by activity sequence when present", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "second", - createdAt: "2026-02-23T00:00:03.000Z", - sequence: 2, - summary: "Tool call complete", - kind: "tool.completed", - }), - makeActivity({ - id: "first", - createdAt: "2026-02-23T00:00:04.000Z", - sequence: 1, - summary: "Tool call complete", - kind: "tool.completed", - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries.map((entry) => entry.id)).toEqual(["first", "second"]); - }); - - it("extracts command text for command tool activities", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "command-tool", - kind: "tool.completed", - summary: "Ran command", - payload: { - itemType: "command_execution", - data: { - item: { - command: ["bun", "run", "lint"], - }, - }, - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.command).toBe("bun run lint"); - }); - - it("extracts failed tool lifecycle status from item payloads", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "tool-failed", - kind: "tool.updated", - summary: "Glob", - tone: "tool", - payload: { - itemType: "mcp_tool_call", - status: "failed", - detail: "No files found", - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.toolLifecycleStatus).toBe("failed"); - }); - - it("defaults tool.completed entries to completed lifecycle status", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "tool-done", - kind: "tool.completed", - summary: "Glob", - tone: "tool", - payload: { - itemType: "mcp_tool_call", - detail: "Found 3 files", - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.toolLifecycleStatus).toBe("completed"); - }); - - it("preserves MCP server, tool, arguments, and results for expanded display", () => { - const item = { - type: "mcpToolCall", - server: "t3-code", - tool: "preview_status", - arguments: {}, - status: "completed", - result: { content: [{ type: "text", text: "attached" }] }, - }; - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "mcp-tool-done", - kind: "tool.completed", - summary: "t3-code · preview_status", - payload: { - itemType: "mcp_tool_call", - title: "t3-code · preview_status", - data: { item }, - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.toolTitle).toBe("t3-code · preview_status"); - expect(entry?.toolData).toEqual(item); - }); - - it("keeps MCP payloads while collapsing lifecycle updates", () => { - const item = { - type: "mcpToolCall", - server: "t3-code", - tool: "preview_snapshot", - arguments: { interactiveOnly: true }, - status: "completed", - }; - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "mcp-tool-progress", - kind: "tool.updated", - summary: "t3-code · preview_snapshot", - payload: { - itemType: "mcp_tool_call", - toolCallId: "call-1", - data: { item }, - }, - }), - makeActivity({ - id: "mcp-tool-complete", - kind: "tool.completed", - summary: "t3-code · preview_snapshot", - payload: { - itemType: "mcp_tool_call", - toolCallId: "call-1", - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.toolData).toEqual(item); - }); - - it("unwraps PowerShell command wrappers for displayed command text", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "command-tool-windows-wrapper", - kind: "tool.completed", - summary: "Ran command", - payload: { - itemType: "command_execution", - data: { - item: { - command: "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'", - }, - }, - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.command).toBe("bun run lint"); - expect(entry?.rawCommand).toBe( - "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'", - ); - }); - - it("unwraps PowerShell command wrappers from argv-style command payloads", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "command-tool-windows-wrapper-argv", - kind: "tool.completed", - summary: "Ran command", - payload: { - itemType: "command_execution", - data: { - item: { - command: ["C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command", "rg -n foo ."], - }, - }, - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.command).toBe("rg -n foo ."); - expect(entry?.rawCommand).toBe( - '"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -Command "rg -n foo ."', - ); - }); - - it("extracts command text from command detail when structured command metadata is missing", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "command-tool-windows-detail-fallback", - kind: "tool.completed", - summary: "Ran command", - payload: { - itemType: "command_execution", - detail: - '"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command \'rg -n -F "new Date()" .\' ', - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.command).toBe('rg -n -F "new Date()" .'); - expect(entry?.rawCommand).toBe( - `"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command 'rg -n -F "new Date()" .'`, - ); - }); - - it("does not unwrap shell commands when no wrapper flag is present", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "command-tool-shell-script", - kind: "tool.completed", - summary: "Ran command", - payload: { - itemType: "command_execution", - data: { - item: { - command: "bash script.sh", - }, - }, - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.command).toBe("bash script.sh"); - expect(entry?.rawCommand).toBeUndefined(); - }); - - it("keeps compact Codex tool metadata used for icons and labels", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "tool-with-metadata", - kind: "tool.completed", - summary: "bash", - payload: { - itemType: "command_execution", - title: "bash", - status: "completed", - detail: '{ "dev": "vite dev --port 3000" } ', - data: { - item: { - command: ["bun", "run", "dev"], - result: { - content: '{ "dev": "vite dev --port 3000" } ', - exitCode: 0, - }, - }, - }, - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry).toMatchObject({ - command: "bun run dev", - detail: '{ "dev": "vite dev --port 3000" }', - itemType: "command_execution", - toolTitle: "bash", - }); - }); - - it("extracts changed file paths for file-change tool activities", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "file-tool", - kind: "tool.completed", - summary: "File change", - payload: { - itemType: "file_change", - data: { - item: { - changes: [ - { path: "apps/web/src/components/ChatView.tsx" }, - { filename: "apps/web/src/session-logic.ts" }, - ], - }, - }, - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.changedFiles).toEqual([ - "apps/web/src/components/ChatView.tsx", - "apps/web/src/session-logic.ts", - ]); - }); - - it("drops duplicated tool detail when it only repeats the title", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "read-file-generic", - kind: "tool.completed", - summary: "Read File", - payload: { - itemType: "dynamic_tool_call", - title: "Read File", - detail: "Read File", - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry?.toolTitle).toBe("Read File"); - expect(entry?.detail).toBeUndefined(); - }); - - it("uses grep raw output summaries instead of repeating the generic tool label", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "grep-update", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "tool.updated", - summary: "grep", - payload: { - itemType: "web_search", - title: "grep", - detail: "grep", - data: { - toolCallId: "tool-grep-1", - kind: "search", - rawInput: {}, - }, - }, - }), - makeActivity({ - id: "grep-complete", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "tool.completed", - summary: "grep", - payload: { - itemType: "web_search", - title: "grep", - detail: "grep", - data: { - toolCallId: "tool-grep-1", - kind: "search", - rawOutput: { - totalFiles: 19, - truncated: false, - }, - }, - }, - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries).toHaveLength(1); - expect(entries[0]).toMatchObject({ - id: "grep-complete", - toolTitle: "grep", - detail: "19 files", - itemType: "web_search", - }); - }); - - it("uses completed read-file output previews and still collapses the same tool call", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "read-update", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "tool.updated", - summary: "Read File", - payload: { - itemType: "dynamic_tool_call", - title: "Read File", - detail: "Read File", - data: { - toolCallId: "tool-read-1", - kind: "read", - rawInput: {}, - }, - }, - }), - makeActivity({ - id: "read-complete", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "tool.completed", - summary: "Read File", - payload: { - itemType: "dynamic_tool_call", - title: "Read File", - detail: "Read File", - data: { - toolCallId: "tool-read-1", - kind: "read", - rawOutput: { - content: - 'import * as Effect from "effect/Effect"\nimport * as Layer from "effect/Layer"\n', - }, - }, - }, - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries).toHaveLength(1); - expect(entries[0]).toMatchObject({ - id: "read-complete", - toolTitle: "Read File", - detail: 'import * as Effect from "effect/Effect"', - itemType: "dynamic_tool_call", - }); - }); - - it("does not use command stdout as the detail when Cursor omits the command input", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "cursor-command-complete", - createdAt: "2026-04-16T22:40:42.221Z", - kind: "tool.completed", - summary: "Ran command", - payload: { - itemType: "command_execution", - title: "Ran command", - data: { - toolCallId: "toolu_vrtx_01WypXgRM8PPygBtrVAZwzy5", - kind: "execute", - rawInput: {}, - rawOutput: { - exitCode: 0, - stdout: "total 960\napps\npackages\n", - stderr: "", - }, - }, - }, - }), - ]; - - const [entry] = deriveWorkLogEntries(activities); - expect(entry).toMatchObject({ - id: "cursor-command-complete", - label: "Ran command", - itemType: "command_execution", - toolTitle: "Ran command", - }); - expect(entry?.detail).toBeUndefined(); - expect(entry?.command).toBeUndefined(); - }); - - it("collapses legacy completed tool rows that are missing tool metadata", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "legacy-read-update", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "tool.updated", - summary: "Read File", - payload: { - itemType: "dynamic_tool_call", - title: "Read File", - detail: "Read File", - data: { - toolCallId: "tool-read-legacy", - kind: "read", - rawInput: {}, - }, - }, - }), - makeActivity({ - id: "legacy-read-complete", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "tool.completed", - summary: "Read File", - payload: { - itemType: "dynamic_tool_call", - title: "Read File", - detail: "Read File", - }, - }), - ]; - - const entries = deriveWorkLogEntries(activities); - expect(entries).toHaveLength(1); - expect(entries[0]).toMatchObject({ - id: "legacy-read-complete", - toolTitle: "Read File", - itemType: "dynamic_tool_call", - }); - expect(entries[0]?.detail).toBeUndefined(); - }); - - it("collapses repeated lifecycle updates for the same tool call into one entry", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "tool-update-1", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "tool.updated", - summary: "Tool call", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - }, - }), - makeActivity({ - id: "tool-update-2", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "tool.updated", - summary: "Tool call", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - data: { - item: { - command: ["sed", "-n", "1,40p", "/tmp/app.ts"], - }, - }, - }, - }), - makeActivity({ - id: "tool-complete", - createdAt: "2026-02-23T00:00:03.000Z", - kind: "tool.completed", - summary: "Tool call completed", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - }, - }), - ]; - - const entries = deriveWorkLogEntries(activities); - - expect(entries).toHaveLength(1); - expect(entries[0]).toMatchObject({ - id: "tool-complete", - createdAt: "2026-02-23T00:00:03.000Z", - label: "Tool call completed", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - command: "sed -n 1,40p /tmp/app.ts", - itemType: "dynamic_tool_call", - toolTitle: "Tool call", - }); - }); - - it("keeps separate tool entries when an identical call starts after the prior one completed", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "tool-1-update", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "tool.updated", - summary: "Tool call", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - }, - }), - makeActivity({ - id: "tool-1-complete", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "tool.completed", - summary: "Tool call completed", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - }, - }), - makeActivity({ - id: "tool-2-update", - createdAt: "2026-02-23T00:00:03.000Z", - kind: "tool.updated", - summary: "Tool call", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - }, - }), - makeActivity({ - id: "tool-2-complete", - createdAt: "2026-02-23T00:00:04.000Z", - kind: "tool.completed", - summary: "Tool call completed", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - }, - }), - ]; - - const entries = deriveWorkLogEntries(activities); - - expect(entries.map((entry) => entry.id)).toEqual(["tool-1-complete", "tool-2-complete"]); - }); - - it("collapses same-timestamp lifecycle rows even when completed sorts before updated by id", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "z-update-earlier", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "tool.updated", - summary: "Tool call", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - }, - }), - makeActivity({ - id: "a-complete-same-timestamp", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "tool.completed", - summary: "Tool call", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - }, - }), - makeActivity({ - id: "z-update-same-timestamp", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "tool.updated", - summary: "Tool call", - payload: { - itemType: "dynamic_tool_call", - title: "Tool call", - detail: 'Read: {"file_path":"/tmp/app.ts"}', - }, - }), - ]; - - const entries = deriveWorkLogEntries(activities); - - expect(entries).toHaveLength(1); - expect(entries[0]?.id).toBe("a-complete-same-timestamp"); - }); -}); - -describe("deriveTimelineEntries", () => { - it("includes proposed plans alongside messages and work entries in chronological order", () => { + it("orders conversation and generic V2 work entries", () => { const entries = deriveTimelineEntries( [ { - id: MessageId.make("message-1"), - role: "assistant", - text: "hello", - createdAt: "2026-02-23T00:00:01.000Z", - turnId: null, - updatedAt: "2026-02-23T00:00:01.000Z", + id: "message-1" as never, + role: "user", + text: "Hello", + runId: null, streaming: false, + createdAt: "2026-06-20T00:00:00.000Z", + updatedAt: "2026-06-20T00:00:00.000Z", }, ], - [ - { - id: "plan:thread-1:turn:turn-1", - turnId: TurnId.make("turn-1"), - planMarkdown: "# Ship it", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-02-23T00:00:02.000Z", - updatedAt: "2026-02-23T00:00:02.000Z", - }, - ], - [ - { - id: "work-1", - createdAt: "2026-02-23T00:00:03.000Z", - label: "Ran tests", - tone: "tool", - }, - ], + [], + [], ); + expect(entries.map((entry) => entry.kind)).toEqual(["message"]); + }); - expect(entries.map((entry) => entry.kind)).toEqual(["message", "proposed-plan", "work"]); - expect(entries[1]).toMatchObject({ - kind: "proposed-plan", - proposedPlan: { - planMarkdown: "# Ship it", - implementedAt: null, - implementationThreadId: null, - }, + it("uses visible turn item order and keeps interruption lifecycle entries standalone", () => { + const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); + const threadId = ThreadId.make("thread-visible"); + const runId = RunId.make("run-visible"); + const base = (id: string, ordinal: number) => ({ + id: TurnItemId.make(id), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed" as const, + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, }); - }); -}); + const userItem = { + ...base("item-user", 0), + type: "user_message" as const, + messageId: MessageId.make("message-user"), + inputIntent: "turn_start" as const, + text: "Start", + attachments: [], + createdBy: "user" as const, + creationSource: "web" as const, + } satisfies OrchestrationV2TurnItem; + const requestItem = { + ...base("item-interrupt-request", 1), + type: "run_interrupt_request" as const, + message: "Stopping", + } satisfies OrchestrationV2TurnItem; + const commandItem = { + ...base("item-command", 2), + type: "command_execution" as const, + input: "sleep 1", + output: "done", + exitCode: 0, + } satisfies OrchestrationV2TurnItem; + const resultItem = { + ...base("item-interrupt-result", 3), + type: "run_interrupt_result" as const, + message: "Stopped", + } satisfies OrchestrationV2TurnItem; + const visibleTurnItems: ReadonlyArray = [ + userItem, + requestItem, + commandItem, + resultItem, + ].map((item, position) => ({ + position, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: item.id, + item, + })); -describe("deriveWorkLogEntries context window handling", () => { - it("excludes context window updates from the work log", () => { - const entries = deriveWorkLogEntries([ - makeActivity({ - id: "context-1", - turnId: "turn-1", - kind: "context-window.updated", - summary: "Context window updated", - tone: "info", - }), - makeActivity({ - id: "tool-1", - turnId: "turn-1", - kind: "tool.completed", - summary: "Ran command", - tone: "tool", - }), + const entries = deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems, + optimisticMessages: [], + }); + + expect(entries.map((entry) => [entry.kind, entry.id])).toEqual([ + ["message", userItem.messageId], + ["event", requestItem.id], + ["work", commandItem.id], + ["event", resultItem.id], ]); - - expect(entries).toHaveLength(1); - expect(entries[0]?.label).toBe("Ran command"); - }); - - it("keeps context compaction activities as normal work log entries", () => { - const entries = deriveWorkLogEntries([ - makeActivity({ - id: "compaction-1", - turnId: "turn-1", - kind: "context-compaction", - summary: "Context compacted", - tone: "info", - }), - ]); - - expect(entries).toHaveLength(1); - expect(entries[0]?.label).toBe("Context compacted"); - }); -}); - -describe("isLatestTurnSettled", () => { - const latestTurn = { - turnId: TurnId.make("turn-1"), - startedAt: "2026-02-27T21:10:00.000Z", - completedAt: "2026-02-27T21:10:06.000Z", - } as const; - - it("returns false while the same turn is still active in a running session", () => { - expect( - isLatestTurnSettled(latestTurn, { - status: "running", - activeTurnId: TurnId.make("turn-1"), - }), - ).toBe(false); - }); - - it("returns false while any turn is running to avoid stale latest-turn banners", () => { - expect( - isLatestTurnSettled(latestTurn, { - status: "running", - activeTurnId: TurnId.make("turn-2"), - }), - ).toBe(false); - }); - - it("returns true once the session is no longer running that turn", () => { - expect( - isLatestTurnSettled(latestTurn, { - status: "ready", - activeTurnId: null, - }), - ).toBe(true); - }); - - it("returns false when turn timestamps are incomplete", () => { - expect( - isLatestTurnSettled( - { - turnId: TurnId.make("turn-1"), - startedAt: null, - completedAt: "2026-02-27T21:10:06.000Z", - }, - null, - ), - ).toBe(false); - }); -}); - -describe("deriveActiveWorkStartedAt", () => { - const latestTurn = { - turnId: TurnId.make("turn-1"), - startedAt: "2026-02-27T21:10:00.000Z", - completedAt: "2026-02-27T21:10:06.000Z", - } as const; - - it("prefers the in-flight turn start when the latest turn is not settled", () => { - expect( - deriveActiveWorkStartedAt( - latestTurn, - { - status: "running", - activeTurnId: TurnId.make("turn-1"), - }, - "2026-02-27T21:11:00.000Z", - ), - ).toBe("2026-02-27T21:10:00.000Z"); - }); - - it("uses the new send start while the session is running a different turn", () => { - expect( - deriveActiveWorkStartedAt( - latestTurn, - { - status: "running", - activeTurnId: TurnId.make("turn-2"), - }, - "2026-02-27T21:11:00.000Z", - ), - ).toBe("2026-02-27T21:11:00.000Z"); - }); - - it("falls back to sendStartedAt once the latest turn is settled", () => { - expect( - deriveActiveWorkStartedAt( - latestTurn, - { - status: "ready", - activeTurnId: null, - }, - "2026-02-27T21:11:00.000Z", - ), - ).toBe("2026-02-27T21:11:00.000Z"); - }); - - it("uses sendStartedAt for a fresh send after the prior turn completed", () => { - expect( - deriveActiveWorkStartedAt( - { - turnId: TurnId.make("turn-1"), - startedAt: "2026-02-27T21:10:00.000Z", - completedAt: "2026-02-27T21:10:06.000Z", - }, - null, - "2026-02-27T21:11:00.000Z", - ), - ).toBe("2026-02-27T21:11:00.000Z"); + const commandEntry = entries[2]; + expect(commandEntry?.kind).toBe("work"); + if (commandEntry?.kind === "work") { + expect(commandEntry.entry.projectedItem).toBe(visibleTurnItems[2]); + expect(commandEntry.entry.structuredPayload).toBe(commandItem); + } }); }); diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 5d5051f748..65a0c66e26 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -1,26 +1,24 @@ -import * as Option from "effect/Option"; -import * as Arr from "effect/Array"; import { - ApprovalRequestId, - isToolLifecycleItemType, - type OrchestrationLatestTurn, - type OrchestrationThreadActivity, - type OrchestrationProposedPlanId, ProviderDriverKind, - type ToolLifecycleItemType, - type UserInputQuestion, + type OrchestrationV2ProjectedTurnItem, + type OrchestrationV2TurnItem, + type PlanId, + type RunId, type ThreadId, - type TurnId, } from "@t3tools/contracts"; - import type { - ChatMessage, - ProposedPlan, - SessionPhase, - Thread, - ThreadSession, - TurnDiffSummary, -} from "./types"; + ThreadCheckpointSummary, + ThreadPendingApproval, + ThreadPendingUserInput, + ThreadProposedPlan, + ThreadRunSummary, + ThreadRuntimeSummary, + ThreadTodoPlan, + ThreadWorkEntry, +} from "@t3tools/client-runtime/state/shell"; + +import type { ChatMessage, ProposedPlan, SessionPhase, TurnDiffSummary } from "./types"; +import * as DateTime from "effect/DateTime"; export type ProviderPickerKind = ProviderDriverKind; @@ -28,7 +26,6 @@ export const PROVIDER_OPTIONS: Array<{ value: ProviderPickerKind; label: string; available: boolean; - /** Shown on the model picker sidebar when relevant */ pickerSidebarBadge?: "new" | "soon"; }> = [ { value: ProviderDriverKind.make("codex"), label: "Codex", available: true }, @@ -45,221 +42,101 @@ export const PROVIDER_OPTIONS: Array<{ available: true, pickerSidebarBadge: "new", }, - { - value: ProviderDriverKind.make("grok"), - label: "Grok", - available: true, - pickerSidebarBadge: "new", - }, + { value: ProviderDriverKind.make("grok"), label: "Grok", available: true }, ]; -export type WorkLogToolLifecycleStatus = - | "inProgress" - | "completed" - | "failed" - | "declined" - | "stopped"; +export type WorkLogToolLifecycleStatus = ThreadWorkEntry["toolLifecycleStatus"]; -export interface WorkLogEntry { - id: string; - createdAt: string; - turnId?: TurnId | null; - label: string; - detail?: string; - command?: string; - rawCommand?: string; - changedFiles?: ReadonlyArray; - tone: "thinking" | "tool" | "info" | "error"; - toolTitle?: string; - toolData?: unknown; - itemType?: ToolLifecycleItemType; - requestKind?: PendingApproval["requestKind"]; - /** From runtime item / task payload `status` when present (e.g. tool.updated). */ - toolLifecycleStatus?: WorkLogToolLifecycleStatus; - /** Originating orchestration activity kind (e.g. `user-input.requested`) for row chrome. */ - sourceActivityKind?: OrchestrationThreadActivity["kind"]; +export interface WorkLogEntry extends Omit< + ThreadWorkEntry, + "structuredPayload" | "runId" | "itemType" | "toolLifecycleStatus" +> { + readonly runId?: RunId | null; + readonly itemType?: ThreadWorkEntry["itemType"]; + readonly toolLifecycleStatus?: ThreadWorkEntry["toolLifecycleStatus"]; + readonly structuredPayload?: ThreadWorkEntry["structuredPayload"]; + readonly sourceItemType?: ThreadWorkEntry["itemType"]; + readonly projectedItem?: OrchestrationV2ProjectedTurnItem; } -interface DerivedWorkLogEntry extends WorkLogEntry { - activityKind: OrchestrationThreadActivity["kind"]; - collapseKey?: string; - toolCallId?: string; -} - -export interface PendingApproval { - requestId: ApprovalRequestId; - requestKind: "command" | "file-read" | "file-change"; - createdAt: string; - detail?: string; -} - -export interface PendingUserInput { - requestId: ApprovalRequestId; - createdAt: string; - questions: ReadonlyArray; -} +export type PendingApproval = ThreadPendingApproval; +export type PendingUserInput = ThreadPendingUserInput; export interface ActivePlanState { - createdAt: string; - turnId: TurnId | null; - explanation?: string | null; - steps: Array<{ - step: string; - status: "pending" | "inProgress" | "completed"; + readonly createdAt: string; + readonly runId: RunId | null; + readonly explanation?: string | null; + readonly steps: Array<{ + readonly step: string; + readonly status: "pending" | "inProgress" | "completed"; }>; } export interface LatestProposedPlanState { - id: OrchestrationProposedPlanId; - createdAt: string; - updatedAt: string; - turnId: TurnId | null; - planMarkdown: string; - implementedAt: string | null; - implementationThreadId: ThreadId | null; + readonly id: PlanId; + readonly createdAt: string; + readonly updatedAt: string; + readonly runId: RunId | null; + readonly planMarkdown: string; + readonly implementedAt: string | null; + readonly implementationThreadId: ThreadId | null; + readonly status: ThreadProposedPlan["status"]; } export type TimelineEntry = | { - id: string; - kind: "message"; - createdAt: string; - message: ChatMessage; + readonly id: string; + readonly kind: "message"; + readonly createdAt: string; + readonly message: ChatMessage; } | { - id: string; - kind: "proposed-plan"; - createdAt: string; - proposedPlan: ProposedPlan; + readonly id: string; + readonly kind: "proposed-plan"; + readonly createdAt: string; + readonly proposedPlan: ProposedPlan; } | { - id: string; - kind: "work"; - createdAt: string; - entry: WorkLogEntry; + readonly id: string; + readonly kind: "work"; + readonly createdAt: string; + readonly entry: WorkLogEntry; + } + | { + readonly id: string; + readonly kind: "event"; + readonly createdAt: string; + readonly projectedItem: OrchestrationV2ProjectedTurnItem; }; export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean { - if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") { - return true; - } - if (entry.command !== undefined && entry.command.trim().length > 0) { - return true; - } - if (entry.requestKind !== undefined) { - return true; - } - return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType); + return ( + entry.tone === "tool" || + entry.tone === "thinking" || + entry.tone === "error" || + entry.command !== undefined || + entry.requestKind !== undefined + ); } -/** Heuristic: providers often emit successful lifecycle status while error text lives in `detail` / `command`. */ -function toolDetailTextLooksLikeFailure(text: string): boolean { - const t = text.toLowerCase(); - if (t.includes("file not found")) { - return true; - } - if (t.includes("no files found")) { - return true; - } - if ( - t.includes("enoent") || - t.includes("no such file or directory") || - t.includes("no such file") - ) { - return true; - } - if (t.includes("cannot find path") && t.includes("because it does not exist")) { - return true; - } - if (t.includes("commandnotfoundexception")) { - return true; - } - if (t.includes("is not recognized as the name of a cmdlet")) { - return true; - } - if (t.includes("is not recognized") && t.includes("the term '")) { - return true; - } - if (t.includes("a parameter cannot be found that matches parameter name")) { - return true; - } - if (t.includes("command not found")) { - return true; - } - if (//i.test(text)) { - return true; - } - if (/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text)) { - return true; - } - if (/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)) { - return true; - } - return false; -} - -/** True when the row should show a failure affordance (explicit status/tone or error-shaped tool output). */ export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean { - if (entry.tone === "error") { - return true; - } - const ls = entry.toolLifecycleStatus; - if (ls === "failed" || ls === "declined") { - return true; - } - if (!workLogEntryIsToolLike(entry)) { - return false; - } - const parts: string[] = []; - if (entry.detail) { - parts.push(entry.detail); - } - if (entry.command) { - parts.push(entry.command); - } - const blob = parts.join("\n"); - if (blob.length === 0) { - return false; - } - return toolDetailTextLooksLikeFailure(blob); + return ( + entry.tone === "error" || + entry.toolLifecycleStatus === "failed" || + entry.toolLifecycleStatus === "declined" + ); } -/** Tool/command row completed without failure (blue check affordance). */ export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean { - if (!workLogEntryIsToolLike(entry)) { - return false; - } - if (workEntryIndicatesToolFailure(entry)) { - return false; - } - if (entry.tone === "thinking") { - return false; - } - const ls = entry.toolLifecycleStatus; - if (ls === "failed" || ls === "declined") { - return false; - } - if (ls === "inProgress") { - return false; - } - if (ls === "stopped") { - return false; - } - return true; + return workLogEntryIsToolLike(entry) && entry.toolLifecycleStatus === "completed"; } -/** Tool-like row with neither clear success nor failure (empty, incomplete, in progress, etc.). */ export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean { - if (!workLogEntryIsToolLike(entry)) { - return false; - } - if (workEntryIndicatesToolFailure(entry)) { - return false; - } - if (workEntryIndicatesToolSuccess(entry)) { - return false; - } - return true; + return ( + workLogEntryIsToolLike(entry) && + !workEntryIndicatesToolFailure(entry) && + !workEntryIndicatesToolSuccess(entry) + ); } export function formatDuration(durationMs: number): string { @@ -267,7 +144,6 @@ export function formatDuration(durationMs: number): string { if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`; if (durationMs < 10_000) { const tenths = Math.round(durationMs / 100) / 10; - // 9.95s+ rounds up to the next bucket — render "10s", not "10.0s". return tenths >= 10 ? "10s" : `${tenths.toFixed(1)}s`; } if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`; @@ -282,1112 +158,384 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str if (!endIso) return null; const startedAt = Date.parse(startIso); const endedAt = Date.parse(endIso); - if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) { - return null; - } + if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) return null; return formatDuration(endedAt - startedAt); } -type LatestTurnTiming = Pick; -type SessionActivityState = Pick, "status" | "activeTurnId">; - -export function isLatestTurnSettled( - latestTurn: LatestTurnTiming | null, - session: SessionActivityState | null, +export function isLatestRunSettled( + latestRun: Pick | null, + runtime: Pick | null, ): boolean { - if (!latestTurn?.startedAt) return false; - if (!latestTurn.completedAt) return false; - if (!session) return true; - if (session.status === "running") return false; - return true; + if (latestRun === null) return false; + if ( + latestRun.status === "starting" || + latestRun.status === "running" || + latestRun.status === "waiting" + ) + return false; + return runtime?.activeRunId !== latestRun.runId; } export function deriveActiveWorkStartedAt( - latestTurn: LatestTurnTiming | null, - session: SessionActivityState | null, + latestRun: Pick | null, + runtime: Pick | null, sendStartedAt: string | null, ): string | null { - const runningTurnId = session?.status === "running" ? session.activeTurnId : null; - if (runningTurnId !== null) { - if (latestTurn?.turnId === runningTurnId) { - return latestTurn.startedAt ?? sendStartedAt; - } - return sendStartedAt; + if (runtime?.activeRunId !== null && runtime?.activeRunId !== undefined) { + return latestRun?.runId === runtime.activeRunId + ? (latestRun.startedAt ?? sendStartedAt) + : sendStartedAt; } - if (!isLatestTurnSettled(latestTurn, session)) { - return latestTurn?.startedAt ?? sendStartedAt; - } - return sendStartedAt; -} - -function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null { - switch (requestType) { - case "command_execution_approval": - case "exec_command_approval": - case "dynamic_tool_call": - return "command"; - case "file_read_approval": - return "file-read"; - case "file_change_approval": - case "apply_patch_approval": - return "file-change"; - default: - return null; - } -} - -function isStalePendingRequestFailureDetail(detail: string | undefined): boolean { - const normalized = detail?.toLowerCase(); - if (!normalized) { - return false; - } - return ( - normalized.includes("stale pending approval request") || - normalized.includes("stale pending user-input request") || - normalized.includes("unknown pending approval request") || - normalized.includes("unknown pending permission request") || - normalized.includes("unknown pending user-input request") || - normalized.includes("unknown pending user input request") || - normalized.includes("unknown pending codex user input request") - ); + return isLatestRunSettled(latestRun, runtime) + ? sendStartedAt + : (latestRun?.startedAt ?? sendStartedAt); } export function derivePendingApprovals( - activities: ReadonlyArray, -): PendingApproval[] { - const openByRequestId = new Map(); - const ordered = [...activities].toSorted(compareActivitiesByOrder); - - for (const activity of ordered) { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - const requestId = - payload && typeof payload.requestId === "string" - ? ApprovalRequestId.make(payload.requestId) - : null; - const requestKind = - payload && - (payload.requestKind === "command" || - payload.requestKind === "file-read" || - payload.requestKind === "file-change") - ? payload.requestKind - : payload - ? requestKindFromRequestType(payload.requestType) - : null; - const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined; - - if (activity.kind === "approval.requested" && requestId && requestKind) { - openByRequestId.set(requestId, { - requestId, - requestKind, - createdAt: activity.createdAt, - ...(detail ? { detail } : {}), - }); - continue; - } - - if (activity.kind === "approval.resolved" && requestId) { - openByRequestId.delete(requestId); - continue; - } - - if ( - activity.kind === "provider.approval.respond.failed" && - requestId && - isStalePendingRequestFailureDetail(detail) - ) { - openByRequestId.delete(requestId); - continue; - } - } - - return [...openByRequestId.values()].toSorted((left, right) => - left.createdAt.localeCompare(right.createdAt), - ); -} - -function parseUserInputQuestions( - payload: Record | null, -): ReadonlyArray | null { - const questions = payload?.questions; - if (!Array.isArray(questions)) { - return null; - } - const parsed = questions - .map((entry) => { - if (!entry || typeof entry !== "object") return null; - const question = entry as Record; - if ( - typeof question.id !== "string" || - typeof question.header !== "string" || - typeof question.question !== "string" || - !Array.isArray(question.options) - ) { - return null; - } - const options = question.options - .map((option) => { - if (!option || typeof option !== "object") return null; - const optionRecord = option as Record; - if ( - typeof optionRecord.label !== "string" || - typeof optionRecord.description !== "string" - ) { - return null; - } - return { - label: optionRecord.label, - description: optionRecord.description, - }; - }) - .filter((option): option is UserInputQuestion["options"][number] => option !== null); - if (options.length === 0) { - return null; - } - return { - id: question.id, - header: question.header, - question: question.question, - options, - multiSelect: question.multiSelect === true, - }; - }) - .filter((question): question is UserInputQuestion => question !== null); - return parsed.length > 0 ? parsed : null; + approvals: ReadonlyArray, +): ThreadPendingApproval[] { + return [...approvals].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)); } export function derivePendingUserInputs( - activities: ReadonlyArray, -): PendingUserInput[] { - const openByRequestId = new Map(); - const ordered = [...activities].toSorted(compareActivitiesByOrder); - - for (const activity of ordered) { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - const requestId = - payload && typeof payload.requestId === "string" - ? ApprovalRequestId.make(payload.requestId) - : null; - const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined; - - if (activity.kind === "user-input.requested" && requestId) { - const questions = parseUserInputQuestions(payload); - if (!questions) { - continue; - } - openByRequestId.set(requestId, { - requestId, - createdAt: activity.createdAt, - questions, - }); - continue; - } - - if (activity.kind === "user-input.resolved" && requestId) { - openByRequestId.delete(requestId); - continue; - } - - if ( - activity.kind === "provider.user-input.respond.failed" && - requestId && - isStalePendingRequestFailureDetail(detail) - ) { - openByRequestId.delete(requestId); - } - } - - return [...openByRequestId.values()].toSorted((left, right) => - left.createdAt.localeCompare(right.createdAt), - ); + inputs: ReadonlyArray, +): ThreadPendingUserInput[] { + return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt)); } export function deriveActivePlanState( - activities: ReadonlyArray, - latestTurnId: TurnId | undefined, + plans: ReadonlyArray, + latestRunId: RunId | undefined, ): ActivePlanState | null { - const ordered = [...activities].toSorted(compareActivitiesByOrder); - const allPlanActivities = ordered.filter((activity) => activity.kind === "turn.plan.updated"); - // Prefer plan from the current turn; fall back to the most recent plan from any turn - // so that TodoWrite tasks persist across follow-up messages. - const latest = Option.firstSomeOf([ - ...(latestTurnId - ? Arr.findLast(allPlanActivities, (activity) => activity.turnId === latestTurnId) - : Option.none()), - Arr.last(allPlanActivities), - ]).pipe(Option.getOrNull); - if (!latest) { - return null; - } - const payload = - latest.payload && typeof latest.payload === "object" - ? (latest.payload as Record) - : null; - const rawPlan = payload?.plan; - if (!Array.isArray(rawPlan)) { - return null; - } - const steps: Array<{ - step: string; - status: "pending" | "inProgress" | "completed"; - }> = []; - for (const entry of rawPlan) { - if (!entry || typeof entry !== "object") { - continue; - } - const record = entry as Record; - if (typeof record.step !== "string") { - continue; - } - const status = - record.status === "completed" || record.status === "inProgress" ? record.status : "pending"; - steps.push({ - step: record.step, - status, - }); - } - if (steps.length === 0) { - return null; - } + const plan = + [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ?? + plans.at(-1) ?? + null; + if (plan === null || plan.steps.length === 0) return null; return { - createdAt: latest.createdAt, - turnId: latest.turnId, - ...(payload && "explanation" in payload - ? { explanation: payload.explanation as string | null } - : {}), - steps, + createdAt: plan.updatedAt, + runId: plan.runId, + explanation: plan.explanation, + steps: plan.steps.map(({ step, status }) => ({ step, status })), + }; +} + +function toLatestProposedPlanState(plan: ThreadProposedPlan): LatestProposedPlanState { + return { + id: plan.id, + createdAt: plan.createdAt, + updatedAt: plan.updatedAt, + runId: plan.runId, + planMarkdown: plan.planMarkdown, + implementedAt: plan.implementedAt, + implementationThreadId: plan.implementationThreadId, + status: plan.status, }; } export function findLatestProposedPlan( - proposedPlans: ReadonlyArray, - latestTurnId: TurnId | string | null | undefined, + plans: ReadonlyArray, + latestRunId: RunId | string | null | undefined, ): LatestProposedPlanState | null { - if (latestTurnId) { - const matchingTurnPlan = [...proposedPlans] - .filter((proposedPlan) => proposedPlan.turnId === latestTurnId) - .toSorted( - (left, right) => - left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id), - ) - .at(-1); - if (matchingTurnPlan) { - return toLatestProposedPlanState(matchingTurnPlan); - } - } - - const latestPlan = [...proposedPlans] + const candidates = latestRunId ? plans.filter((plan) => plan.runId === latestRunId) : plans; + const plan = [...(candidates.length > 0 ? candidates : plans)] .toSorted( (left, right) => left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id), ) .at(-1); - if (!latestPlan) { - return null; - } - - return toLatestProposedPlanState(latestPlan); + return plan === undefined ? null : toLatestProposedPlanState(plan); } export function findSidebarProposedPlan(input: { - threads: ReadonlyArray>; - latestTurn: Pick | null; - latestTurnSettled: boolean; - threadId: ThreadId | string | null | undefined; + readonly threads: ReadonlyArray< + Pick< + { readonly id: ThreadId; readonly proposedPlans: ReadonlyArray }, + "id" | "proposedPlans" + > + >; + readonly latestRun: Pick | null; + readonly latestRunSettled: boolean; + readonly threadId: ThreadId | string | null | undefined; }): LatestProposedPlanState | null { - const activeThreadPlans = - input.threads.find((thread) => thread.id === input.threadId)?.proposedPlans ?? []; - - if (!input.latestTurnSettled) { - const sourceProposedPlan = input.latestTurn?.sourceProposedPlan; - if (sourceProposedPlan) { - const sourcePlan = input.threads - .find((thread) => thread.id === sourceProposedPlan.threadId) - ?.proposedPlans.find((plan) => plan.id === sourceProposedPlan.planId); - if (sourcePlan) { - return toLatestProposedPlanState(sourcePlan); - } - } + if (!input.latestRunSettled && input.latestRun?.sourcePlanRef !== undefined) { + const source = input.latestRun.sourcePlanRef; + const plan = input.threads + .find((thread) => thread.id === source.threadId) + ?.proposedPlans.find((candidate) => candidate.id === source.planId); + if (plan !== undefined) return toLatestProposedPlanState(plan); } - - return findLatestProposedPlan(activeThreadPlans, input.latestTurn?.turnId ?? null); + const activePlans = + input.threads.find((thread) => thread.id === input.threadId)?.proposedPlans ?? []; + return findLatestProposedPlan(activePlans, input.latestRun?.runId); } export function hasActionableProposedPlan( - proposedPlan: LatestProposedPlanState | Pick | null, + plan: LatestProposedPlanState | Pick | null, ): boolean { - return proposedPlan !== null && proposedPlan.implementedAt === null; + return plan !== null && plan.implementedAt === null; } -export function deriveWorkLogEntries( - activities: ReadonlyArray, -): WorkLogEntry[] { - const ordered = [...activities].toSorted(compareActivitiesByOrder); - const entries: DerivedWorkLogEntry[] = []; - for (const activity of ordered) { - if (activity.kind === "tool.started") continue; - if (activity.kind === "task.started") continue; - if (activity.kind === "context-window.updated") continue; - if (activity.summary === "Checkpoint captured") continue; - if (isPlanBoundaryToolActivity(activity)) continue; - entries.push(toDerivedWorkLogEntry(activity)); - } - return collapseDerivedWorkLogEntries(entries).map((entry) => { - const { activityKind, collapseKey: _collapseKey, ...rest } = entry; - return Object.assign(rest, { sourceActivityKind: activityKind }); - }); -} - -function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean { - if (activity.kind !== "tool.updated" && activity.kind !== "tool.completed") { - return false; - } - - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:"); -} - -function extractWorkLogToolLifecycleStatus( - payload: Record | null, -): WorkLogToolLifecycleStatus | undefined { - if (!payload) { - return undefined; - } - const s = payload.status; - if ( - s === "inProgress" || - s === "completed" || - s === "failed" || - s === "declined" || - s === "stopped" - ) { - return s; - } - return undefined; -} - -function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - const commandPreview = extractToolCommand(payload); - const changedFiles = extractChangedFiles(payload); - const title = extractToolTitle(payload); - const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed"; - const taskSummary = - isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0 - ? payload.summary - : null; - const taskDetailAsLabel = - isTaskActivity && - !taskSummary && - typeof payload?.detail === "string" && - payload.detail.length > 0 - ? payload.detail - : null; - const taskLabel = taskSummary || taskDetailAsLabel; - const detail = isTaskActivity - ? !taskDetailAsLabel && - payload && - typeof payload.detail === "string" && - payload.detail.length > 0 - ? stripTrailingExitCode(payload.detail).output - : null - : extractToolDetail(payload, title ?? activity.summary); - const toolCallId = isTaskActivity ? null : extractToolCallId(payload); - const entry: DerivedWorkLogEntry = { - id: activity.id, - createdAt: activity.createdAt, - turnId: activity.turnId, - label: taskLabel || activity.summary, - tone: - activity.kind === "task.progress" - ? "thinking" - : activity.tone === "approval" - ? "info" - : activity.tone, - activityKind: activity.kind, - }; - const itemType = extractWorkLogItemType(payload); - const requestKind = extractWorkLogRequestKind(payload); - if (detail) { - entry.detail = detail; - } - if (commandPreview.command) { - entry.command = commandPreview.command; - } - if (commandPreview.rawCommand) { - entry.rawCommand = commandPreview.rawCommand; - } - if (changedFiles.length > 0) { - entry.changedFiles = changedFiles; - } - if (title) { - entry.toolTitle = title; - } - if (itemType === "mcp_tool_call") { - const data = asRecord(payload?.data); - if (data?.item !== undefined) { - entry.toolData = data.item; - } - } - if (itemType) { - entry.itemType = itemType; - } - if (requestKind) { - entry.requestKind = requestKind; - } - if (toolCallId) { - entry.toolCallId = toolCallId; - } - let toolLifecycleStatus = extractWorkLogToolLifecycleStatus(payload); - if (!toolLifecycleStatus && activity.kind === "tool.completed") { - toolLifecycleStatus = "completed"; - } - if (toolLifecycleStatus) { - entry.toolLifecycleStatus = toolLifecycleStatus; - } - const collapseKey = deriveToolLifecycleCollapseKey(entry); - if (collapseKey) { - entry.collapseKey = collapseKey; - } - return entry; -} - -function collapseDerivedWorkLogEntries( - entries: ReadonlyArray, -): DerivedWorkLogEntry[] { - const collapsed: DerivedWorkLogEntry[] = []; - for (const entry of entries) { - const previous = collapsed.at(-1); - if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) { - collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry); - continue; - } - collapsed.push(entry); - } - return collapsed; -} - -function shouldCollapseToolLifecycleEntries( - previous: DerivedWorkLogEntry, - next: DerivedWorkLogEntry, -): boolean { - if (previous.activityKind !== "tool.updated" && previous.activityKind !== "tool.completed") { - return false; - } - if (next.activityKind !== "tool.updated" && next.activityKind !== "tool.completed") { - return false; - } - if (previous.activityKind === "tool.completed") { - return false; - } - if (previous.collapseKey !== undefined && previous.collapseKey === next.collapseKey) { - return true; - } - return ( - previous.toolCallId !== undefined && - next.toolCallId === undefined && - previous.itemType === next.itemType && - normalizeCompactToolLabel(previous.toolTitle ?? previous.label) === - normalizeCompactToolLabel(next.toolTitle ?? next.label) - ); -} - -function mergeDerivedWorkLogEntries( - previous: DerivedWorkLogEntry, - next: DerivedWorkLogEntry, -): DerivedWorkLogEntry { - const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles); - const detail = next.detail ?? previous.detail; - const command = next.command ?? previous.command; - const rawCommand = next.rawCommand ?? previous.rawCommand; - const toolTitle = next.toolTitle ?? previous.toolTitle; - const itemType = next.itemType ?? previous.itemType; - const requestKind = next.requestKind ?? previous.requestKind; - const collapseKey = next.collapseKey ?? previous.collapseKey; - const toolCallId = next.toolCallId ?? previous.toolCallId; - const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus; - const toolData = next.toolData ?? previous.toolData; - return { - ...previous, - ...next, - ...(detail ? { detail } : {}), - ...(command ? { command } : {}), - ...(rawCommand ? { rawCommand } : {}), - ...(changedFiles.length > 0 ? { changedFiles } : {}), - ...(toolTitle ? { toolTitle } : {}), - ...(itemType ? { itemType } : {}), - ...(requestKind ? { requestKind } : {}), - ...(collapseKey ? { collapseKey } : {}), - ...(toolCallId ? { toolCallId } : {}), - ...(toolLifecycleStatus !== undefined ? { toolLifecycleStatus } : {}), - ...(toolData !== undefined ? { toolData } : {}), - }; -} - -function mergeChangedFiles( - previous: ReadonlyArray | undefined, - next: ReadonlyArray | undefined, -): string[] { - const merged = [...(previous ?? []), ...(next ?? [])]; - if (merged.length === 0) { - return []; - } - return [...new Set(merged)]; -} - -function deriveToolLifecycleCollapseKey(entry: DerivedWorkLogEntry): string | undefined { - if (entry.activityKind !== "tool.updated" && entry.activityKind !== "tool.completed") { - return undefined; - } - if (entry.toolCallId) { - return `tool:${entry.toolCallId}`; - } - const normalizedLabel = normalizeCompactToolLabel(entry.toolTitle ?? entry.label); - const detail = entry.detail?.trim() ?? ""; - const itemType = entry.itemType ?? ""; - if (normalizedLabel.length === 0 && detail.length === 0 && itemType.length === 0) { - return undefined; - } - return [itemType, normalizedLabel, detail].join("\u001f"); -} - -function normalizeCompactToolLabel(value: string): string { - return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim(); -} - -function toLatestProposedPlanState(proposedPlan: ProposedPlan): LatestProposedPlanState { - return { - id: proposedPlan.id, - createdAt: proposedPlan.createdAt, - updatedAt: proposedPlan.updatedAt, - turnId: proposedPlan.turnId, - planMarkdown: proposedPlan.planMarkdown, - implementedAt: proposedPlan.implementedAt, - implementationThreadId: proposedPlan.implementationThreadId, - }; -} - -function asRecord(value: unknown): Record | null { - return value && typeof value === "object" ? (value as Record) : null; -} - -function asTrimmedString(value: unknown): string | null { - if (typeof value !== "string") { - return null; - } - const trimmed = value.trim(); - return trimmed.length > 0 ? trimmed : null; -} - -function asNumber(value: unknown): number | null { - return typeof value === "number" && Number.isFinite(value) ? value : null; -} - -function trimMatchingOuterQuotes(value: string): string { - const trimmed = value.trim(); - if ( - (trimmed.startsWith("'") && trimmed.endsWith("'")) || - (trimmed.startsWith('"') && trimmed.endsWith('"')) - ) { - const unquoted = trimmed.slice(1, -1).trim(); - return unquoted.length > 0 ? unquoted : trimmed; - } - return trimmed; -} - -function executableBasename(value: string): string | null { - const trimmed = trimMatchingOuterQuotes(value); - if (trimmed.length === 0) { - return null; - } - const normalized = trimmed.replace(/\\/g, "/"); - const segments = normalized.split("/"); - const last = segments.at(-1)?.trim() ?? ""; - return last.length > 0 ? last.toLowerCase() : null; -} - -function splitExecutableAndRest(value: string): { executable: string; rest: string } | null { - const trimmed = value.trim(); - if (trimmed.length === 0) { - return null; - } - - if (trimmed.startsWith('"') || trimmed.startsWith("'")) { - const quote = trimmed.charAt(0); - const closeIndex = trimmed.indexOf(quote, 1); - if (closeIndex <= 0) { - return null; - } - return { - executable: trimmed.slice(0, closeIndex + 1), - rest: trimmed.slice(closeIndex + 1).trim(), - }; - } - - const firstWhitespace = trimmed.search(/\s/); - if (firstWhitespace < 0) { - return { - executable: trimmed, - rest: "", - }; - } - - return { - executable: trimmed.slice(0, firstWhitespace), - rest: trimmed.slice(firstWhitespace).trim(), - }; -} - -const SHELL_WRAPPER_SPECS = [ - { - executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"], - wrapperFlagPattern: /(?:^|\s)-command\s+/i, - }, - { - executables: ["cmd", "cmd.exe"], - wrapperFlagPattern: /(?:^|\s)\/c\s+/i, - }, - { - executables: ["bash", "sh", "zsh"], - wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i, - }, -] as const; - -function findShellWrapperSpec(shell: string) { - return SHELL_WRAPPER_SPECS.find((spec) => - (spec.executables as ReadonlyArray).includes(shell), - ); -} - -function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null { - const match = wrapperFlagPattern.exec(value); - if (!match) { - return null; - } - - const command = value.slice(match.index + match[0].length).trim(); - if (command.length === 0) { - return null; - } - - const unwrapped = trimMatchingOuterQuotes(command); - return unwrapped.length > 0 ? unwrapped : null; -} - -function unwrapKnownShellCommandWrapper(value: string): string { - const split = splitExecutableAndRest(value); - if (!split || split.rest.length === 0) { - return value; - } - - const shell = executableBasename(split.executable); - if (!shell) { - return value; - } - - const spec = findShellWrapperSpec(shell); - if (!spec) { - return value; - } - - return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value; -} - -function formatCommandArrayPart(value: string): string { - return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value; -} - -function formatCommandValue(value: unknown): string | null { - const direct = asTrimmedString(value); - if (direct) { - return direct; - } - if (!Array.isArray(value)) { - return null; - } - const parts: Array = []; - for (const entry of value) { - const part = asTrimmedString(entry); - if (part !== null) { - parts.push(part); - } - } - if (parts.length === 0) { - return null; - } - return parts.map((part) => formatCommandArrayPart(part)).join(" "); -} - -function normalizeCommandValue(value: unknown): string | null { - const formatted = formatCommandValue(value); - return formatted ? unwrapKnownShellCommandWrapper(formatted) : null; -} - -function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null { - const formatted = formatCommandValue(value); - if (!formatted || normalizedCommand === null) { - return null; - } - return formatted === normalizedCommand ? null : formatted; -} - -function extractToolCommand(payload: Record | null): { - command: string | null; - rawCommand: string | null; -} { - const data = asRecord(payload?.data); - const item = asRecord(data?.item); - const itemResult = asRecord(item?.result); - const itemInput = asRecord(item?.input); - const itemType = asTrimmedString(payload?.itemType); - const detail = asTrimmedString(payload?.detail); - const candidates: unknown[] = [ - item?.command, - itemInput?.command, - itemResult?.command, - data?.command, - itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null, - ]; - - for (const candidate of candidates) { - const command = normalizeCommandValue(candidate); - if (!command) { - continue; - } - return { - command, - rawCommand: toRawToolCommand(candidate, command), - }; - } - - return { - command: null, - rawCommand: null, - }; -} - -function extractToolTitle(payload: Record | null): string | null { - return asTrimmedString(payload?.title); -} - -function extractToolCallId(payload: Record | null): string | null { - const data = asRecord(payload?.data); - return asTrimmedString(data?.toolCallId); -} - -function normalizeInlinePreview(value: string): string { - return value.replace(/\s+/g, " ").trim(); -} - -function truncateInlinePreview(value: string, maxLength = 84): string { - if (value.length <= maxLength) { - return value; - } - return `${value.slice(0, maxLength - 1).trimEnd()}…`; -} - -function normalizePreviewForComparison(value: string | null | undefined): string | null { - const normalized = asTrimmedString(value); - if (!normalized) { - return null; - } - return normalizeCompactToolLabel(normalizeInlinePreview(normalized)).toLowerCase(); -} - -function summarizeToolTextOutput(value: string): string | null { - const lines: Array = []; - for (const rawLine of value.split(/\r?\n/u)) { - const line = normalizeInlinePreview(rawLine); - if (line.length > 0) { - lines.push(line); - } - } - const firstLine = lines.find((line) => line !== "```"); - if (firstLine) { - return truncateInlinePreview(firstLine); - } - if (lines.length > 1) { - return `${lines.length.toLocaleString()} lines`; - } - return null; -} - -function summarizeToolRawOutput(payload: Record | null): string | null { - const data = asRecord(payload?.data); - const rawOutput = asRecord(data?.rawOutput); - if (!rawOutput) { - return null; - } - - const totalFiles = asNumber(rawOutput.totalFiles); - if (totalFiles !== null) { - const suffix = rawOutput.truncated === true ? "+" : ""; - return `${totalFiles.toLocaleString()} file${totalFiles === 1 ? "" : "s"}${suffix}`; - } - - const content = asTrimmedString(rawOutput.content); - if (content) { - return summarizeToolTextOutput(content); - } - - const stdout = asTrimmedString(rawOutput.stdout); - if (stdout) { - return summarizeToolTextOutput(stdout); - } - - return null; -} - -function isCommandToolDetail(payload: Record | null, heading: string): boolean { - const data = asRecord(payload?.data); - const kind = asTrimmedString(data?.kind)?.toLowerCase(); - const title = asTrimmedString(payload?.title ?? heading)?.toLowerCase(); - return ( - extractWorkLogItemType(payload) === "command_execution" || - kind === "execute" || - title === "terminal" || - title === "ran command" - ); -} - -function extractToolDetail( - payload: Record | null, - heading: string, -): string | null { - const rawDetail = asTrimmedString(payload?.detail); - const detail = rawDetail ? stripTrailingExitCode(rawDetail).output : null; - const normalizedHeading = normalizePreviewForComparison(heading); - const normalizedDetail = normalizePreviewForComparison(detail); - - if (detail && normalizedHeading !== normalizedDetail) { - return detail; - } - - if (isCommandToolDetail(payload, heading)) { - return null; - } - - const rawOutputSummary = summarizeToolRawOutput(payload); - if (rawOutputSummary) { - const normalizedRawOutputSummary = normalizePreviewForComparison(rawOutputSummary); - if (normalizedRawOutputSummary !== normalizedHeading) { - return rawOutputSummary; - } - } - - return null; -} - -function stripTrailingExitCode(value: string): { - output: string | null; - exitCode?: number | undefined; -} { - const trimmed = value.trim(); - const match = /^(?[\s\S]*?)(?:\s*\d+)>)\s*$/i.exec( - trimmed, - ); - if (!match?.groups) { - return { - output: trimmed.length > 0 ? trimmed : null, - }; - } - const exitCode = Number.parseInt(match.groups.code ?? "", 10); - const normalizedOutput = match.groups.output?.trim() ?? ""; - return { - output: normalizedOutput.length > 0 ? normalizedOutput : null, - ...(Number.isInteger(exitCode) ? { exitCode } : {}), - }; -} - -function extractWorkLogItemType( - payload: Record | null, -): WorkLogEntry["itemType"] | undefined { - if (typeof payload?.itemType === "string" && isToolLifecycleItemType(payload.itemType)) { - return payload.itemType; - } - return undefined; -} - -function extractWorkLogRequestKind( - payload: Record | null, -): WorkLogEntry["requestKind"] | undefined { - if ( - payload?.requestKind === "command" || - payload?.requestKind === "file-read" || - payload?.requestKind === "file-change" - ) { - return payload.requestKind; - } - return requestKindFromRequestType(payload?.requestType) ?? undefined; -} - -function pushChangedFile(target: string[], seen: Set, value: unknown) { - const normalized = asTrimmedString(value); - if (!normalized || seen.has(normalized)) { - return; - } - seen.add(normalized); - target.push(normalized); -} - -function collectChangedFiles(value: unknown, target: string[], seen: Set, depth: number) { - if (depth > 4 || target.length >= 12) { - return; - } - if (Array.isArray(value)) { - for (const entry of value) { - collectChangedFiles(entry, target, seen, depth + 1); - if (target.length >= 12) { - return; - } - } - return; - } - - const record = asRecord(value); - if (!record) { - return; - } - - pushChangedFile(target, seen, record.path); - pushChangedFile(target, seen, record.filePath); - pushChangedFile(target, seen, record.relativePath); - pushChangedFile(target, seen, record.filename); - pushChangedFile(target, seen, record.newPath); - pushChangedFile(target, seen, record.oldPath); - - for (const nestedKey of [ - "item", - "result", - "input", - "data", - "changes", - "files", - "edits", - "patch", - "patches", - "operations", - ]) { - if (!(nestedKey in record)) { - continue; - } - collectChangedFiles(record[nestedKey], target, seen, depth + 1); - if (target.length >= 12) { - return; - } - } -} - -function extractChangedFiles(payload: Record | null): string[] { - const changedFiles: string[] = []; - const seen = new Set(); - collectChangedFiles(asRecord(payload?.data), changedFiles, seen, 0); - return changedFiles; -} - -function compareActivitiesByOrder( - left: OrchestrationThreadActivity, - right: OrchestrationThreadActivity, -): number { - if (left.sequence !== undefined && right.sequence !== undefined) { - if (left.sequence !== right.sequence) { - return left.sequence - right.sequence; - } - } else if (left.sequence !== undefined) { - return 1; - } else if (right.sequence !== undefined) { - return -1; - } - - const createdAtComparison = left.createdAt.localeCompare(right.createdAt); - if (createdAtComparison !== 0) { - return createdAtComparison; - } - - const lifecycleRankComparison = - compareActivityLifecycleRank(left.kind) - compareActivityLifecycleRank(right.kind); - if (lifecycleRankComparison !== 0) { - return lifecycleRankComparison; - } - - return left.id.localeCompare(right.id); -} - -function compareActivityLifecycleRank(kind: string): number { - if (kind.endsWith(".started") || kind === "tool.started") { - return 0; - } - if (kind.endsWith(".progress") || kind.endsWith(".updated")) { - return 1; - } - if (kind.endsWith(".completed") || kind.endsWith(".resolved")) { - return 2; - } - return 1; +export function deriveWorkLogEntries(entries: ReadonlyArray): WorkLogEntry[] { + return entries.map((entry) => ({ ...entry, sourceItemType: entry.itemType })); } export function deriveTimelineEntries( messages: ReadonlyArray, - proposedPlans: ReadonlyArray, + proposedPlans: ReadonlyArray, workEntries: ReadonlyArray, ): TimelineEntry[] { - const messageRows: TimelineEntry[] = messages.map((message) => ({ - id: message.id, - kind: "message", - createdAt: message.createdAt, - message, - })); - const proposedPlanRows: TimelineEntry[] = proposedPlans.map((proposedPlan) => ({ - id: proposedPlan.id, - kind: "proposed-plan", - createdAt: proposedPlan.createdAt, - proposedPlan, - })); - const workRows: TimelineEntry[] = workEntries.map((entry) => ({ - id: entry.id, - kind: "work", - createdAt: entry.createdAt, - entry, - })); - return [...messageRows, ...proposedPlanRows, ...workRows].toSorted((a, b) => - a.createdAt.localeCompare(b.createdAt), + return [ + ...messages.map( + (message): TimelineEntry => ({ + id: message.id, + kind: "message", + createdAt: message.createdAt, + message, + }), + ), + ...proposedPlans.map( + (proposedPlan): TimelineEntry => ({ + id: proposedPlan.id, + kind: "proposed-plan", + createdAt: proposedPlan.createdAt, + proposedPlan, + }), + ), + ...workEntries.map( + (entry): TimelineEntry => ({ + id: entry.id, + kind: "work", + createdAt: entry.createdAt, + entry, + }), + ), + ].toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), ); } -export function inferCheckpointTurnCountByTurnId( - summaries: ReadonlyArray, -): Record { - const sorted = [...summaries].toSorted((a, b) => a.completedAt.localeCompare(b.completedAt)); - const result: Record = {}; - for (let index = 0; index < sorted.length; index += 1) { - const summary = sorted[index]; - if (!summary) continue; - result[summary.turnId] = index + 1; - } - return result; +const STANDALONE_V2_ITEM_TYPES = new Set([ + "approval_request", + "compaction", + "fork", + "handoff", + "run_interrupt_request", + "run_interrupt_result", + "subagent", + "todo_list", + "user_input_request", +]); + +function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string { + return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt); } -export function derivePhase(session: ThreadSession | null): SessionPhase { - if ( - !session || - session.status === "stopped" || - session.status === "interrupted" || - session.status === "error" - ) { - return "disconnected"; +function projectedWorkEntryStatus( + item: OrchestrationV2TurnItem, +): NonNullable { + switch (item.status) { + case "pending": + case "running": + case "waiting": + return "inProgress"; + case "completed": + return "completed"; + case "failed": + return "failed"; + case "cancelled": + case "interrupted": + return "stopped"; } - if (session.status === "starting") return "connecting"; - if (session.status === "running") return "running"; +} + +function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] { + if (item.status === "failed") return "error"; + if (item.type === "reasoning") return "thinking"; + switch (item.type) { + case "command_execution": + case "file_change": + case "file_search": + case "web_search": + case "dynamic_tool": + case "subagent": + return "tool"; + default: + return "info"; + } +} + +function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry { + const { item } = row; + const title = item.title?.trim() || null; + const common = { + id: item.id, + createdAt: projectedItemCreatedAt(row), + runId: item.runId, + tone: projectedWorkEntryTone(item), + itemType: item.type, + toolLifecycleStatus: projectedWorkEntryStatus(item), + structuredPayload: item, + projectedItem: row, + } as const; + + switch (item.type) { + case "reasoning": + return { + ...common, + label: title ?? "Thinking", + ...(item.text ? { detail: item.text } : {}), + }; + case "command_execution": + return { + ...common, + label: title ?? "Ran command", + command: item.input, + rawCommand: item.input, + ...(item.output ? { detail: item.output } : {}), + toolTitle: title ?? "Command", + toolData: item, + }; + case "file_change": + return { + ...common, + label: title ?? `Changed ${item.fileName}`, + changedFiles: [item.fileName], + ...(item.diffStr ? { detail: item.diffStr } : {}), + toolTitle: title ?? "File change", + toolData: item, + }; + case "file_search": + return { + ...common, + label: title ?? "Searched files", + ...(item.pattern ? { detail: item.pattern } : {}), + toolTitle: title ?? "File search", + toolData: item, + }; + case "web_search": + return { + ...common, + label: title ?? "Searched the web", + ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}), + toolTitle: title ?? "Web search", + toolData: item, + }; + case "checkpoint": + return { + ...common, + label: title ?? "Checkpoint captured", + changedFiles: item.files.map((file) => file.path), + toolData: item, + }; + case "dynamic_tool": + return { + ...common, + label: title ?? item.toolName ?? "Tool call", + toolTitle: title ?? item.toolName ?? "Tool", + toolData: { input: item.input, output: item.output }, + }; + default: + return { + ...common, + label: title ?? item.type.replaceAll("_", " "), + toolData: item, + }; + } +} + +/** + * Builds the web timeline in the exact order committed by `visibleTurnItems`. + * Committed rows are presented directly from their projected item. Optimistic + * messages are the only client-owned entries appended to that sequence. + */ +export function deriveTimelineEntriesFromVisibleTurnItems(input: { + readonly visibleTurnItems: ReadonlyArray; + readonly optimisticMessages: ReadonlyArray; + readonly attachmentUrlById?: ReadonlyMap; +}): TimelineEntry[] { + const committedMessageIds = new Set(); + const entries: TimelineEntry[] = []; + + for (const row of input.visibleTurnItems) { + const { item } = row; + const createdAt = projectedItemCreatedAt(row); + if (item.type === "user_message" || item.type === "assistant_message") { + const message: ChatMessage = { + id: item.messageId, + role: item.type === "user_message" ? "user" : "assistant", + text: item.text, + ...(item.type === "user_message" && item.attachments.length > 0 + ? { + attachments: item.attachments.map((attachment) => { + const previewUrl = input.attachmentUrlById?.get(attachment.id); + return previewUrl ? { ...attachment, previewUrl } : attachment; + }), + } + : {}), + runId: item.runId, + streaming: item.type === "assistant_message" && item.streaming, + createdAt, + updatedAt: DateTime.formatIso(item.updatedAt), + }; + committedMessageIds.add(message.id); + entries.push({ id: message.id, kind: "message", createdAt, message }); + continue; + } + + if (item.type === "proposed_plan") { + const proposedPlan = { + id: item.planId, + runId: item.runId, + planMarkdown: item.markdown, + status: "active" as const, + implementedAt: null, + implementationThreadId: null, + createdAt, + updatedAt: DateTime.formatIso(item.updatedAt), + }; + entries.push({ id: item.id, kind: "proposed-plan", createdAt, proposedPlan }); + continue; + } + + if (STANDALONE_V2_ITEM_TYPES.has(item.type)) { + entries.push({ id: item.id, kind: "event", createdAt, projectedItem: row }); + continue; + } + + entries.push({ id: item.id, kind: "work", createdAt, entry: projectedWorkEntry(row) }); + } + + for (const message of input.optimisticMessages) { + if (!committedMessageIds.has(message.id)) { + entries.push({ + id: message.id, + kind: "message", + createdAt: message.createdAt, + message, + }); + } + } + + return entries; +} + +export function inferCheckpointTurnCountByRunId( + summaries: ReadonlyArray, +): Record { + return Object.fromEntries( + summaries.flatMap((summary) => + summary.runId === null ? [] : [[summary.runId, summary.checkpointTurnCount] as const], + ), + ); +} + +export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase { + if (runtime === null) return "disconnected"; + if (runtime.status === "starting" || runtime.status === "queued") return "connecting"; + if (runtime.status === "running" || runtime.status === "waiting") return "running"; return "ready"; } + +export type { TurnDiffSummary }; diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index b4fc8cc5e8..0e70ef306e 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -3,18 +3,14 @@ import type { EnvironmentProject, EnvironmentThread, EnvironmentThreadShell, + ThreadConversationMessage, + ThreadProposedPlan, + ThreadRuntimeSummary, + ThreadWorkEntry, } from "@t3tools/client-runtime/state/shell"; import { mergeEnvironmentThread } from "@t3tools/client-runtime/state/threads"; -import type { - OrchestrationMessage, - OrchestrationProposedPlan, - OrchestrationSession, - OrchestrationThreadActivity, - ScopedProjectRef, - ScopedThreadRef, - ServerConfig, -} from "@t3tools/contracts"; -import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts"; +import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, ThreadId } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; import { useMemo } from "react"; import { appAtomRegistry } from "../rpc/atomRegistry"; @@ -24,9 +20,10 @@ import { environmentThreadDetails, environmentThreadShells } from "./threads"; const EMPTY_PROJECT_REFS: ReadonlyArray = Object.freeze([]); const EMPTY_THREAD_REFS: ReadonlyArray = Object.freeze([]); -const EMPTY_MESSAGES: ReadonlyArray = Object.freeze([]); -const EMPTY_ACTIVITIES: ReadonlyArray = Object.freeze([]); -const EMPTY_PROPOSED_PLANS: ReadonlyArray = Object.freeze([]); +const EMPTY_MESSAGES: ReadonlyArray = Object.freeze([]); +const EMPTY_WORK_ENTRIES: ReadonlyArray = Object.freeze([]); +const EMPTY_PROPOSED_PLANS: ReadonlyArray = Object.freeze([]); +const EMPTY_VISIBLE_TURN_ITEMS: ReadonlyArray = Object.freeze([]); const EMPTY_PROJECT_ATOM = Atom.make(null).pipe( Atom.withLabel("web-project:empty"), @@ -46,14 +43,17 @@ const EMPTY_THREAD_DETAIL_ATOM = Atom.make(null).pipe( const EMPTY_MESSAGES_ATOM = Atom.make(EMPTY_MESSAGES).pipe( Atom.withLabel("web-thread-messages:empty"), ); -const EMPTY_ACTIVITIES_ATOM = Atom.make(EMPTY_ACTIVITIES).pipe( - Atom.withLabel("web-thread-activities:empty"), +const EMPTY_WORK_ENTRIES_ATOM = Atom.make(EMPTY_WORK_ENTRIES).pipe( + Atom.withLabel("web-thread-work-entries:empty"), ); const EMPTY_PROPOSED_PLANS_ATOM = Atom.make(EMPTY_PROPOSED_PLANS).pipe( Atom.withLabel("web-thread-proposed-plans:empty"), ); -const EMPTY_SESSION_ATOM = Atom.make(null).pipe( - Atom.withLabel("web-thread-session:empty"), +const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make(EMPTY_VISIBLE_TURN_ITEMS).pipe( + Atom.withLabel("web-thread-visible-turn-items:empty"), +); +const EMPTY_RUNTIME_ATOM = Atom.make(null).pipe( + Atom.withLabel("web-thread-runtime:empty"), ); export const activeEnvironmentIdAtom = Atom.make(null).pipe( @@ -144,31 +144,39 @@ export function useThread(ref: ScopedThreadRef | null): EnvironmentThread | null export function useThreadMessages( ref: ScopedThreadRef | null, -): ReadonlyArray { +): ReadonlyArray { return useAtomValue( ref === null ? EMPTY_MESSAGES_ATOM : environmentThreadDetails.messagesAtom(ref), ); } -export function useThreadActivities( - ref: ScopedThreadRef | null, -): ReadonlyArray { +export function useThreadWorkEntries(ref: ScopedThreadRef | null): ReadonlyArray { return useAtomValue( - ref === null ? EMPTY_ACTIVITIES_ATOM : environmentThreadDetails.activitiesAtom(ref), + ref === null ? EMPTY_WORK_ENTRIES_ATOM : environmentThreadDetails.workEntriesAtom(ref), ); } export function useThreadProposedPlans( ref: ScopedThreadRef | null, -): ReadonlyArray { +): ReadonlyArray { return useAtomValue( ref === null ? EMPTY_PROPOSED_PLANS_ATOM : environmentThreadDetails.proposedPlansAtom(ref), ); } -export function useThreadSession(ref: ScopedThreadRef | null): OrchestrationSession | null { +export function useThreadVisibleTurnItems( + ref: ScopedThreadRef | null, +): ReadonlyArray { return useAtomValue( - ref === null ? EMPTY_SESSION_ATOM : environmentThreadDetails.sessionAtom(ref), + ref === null + ? EMPTY_VISIBLE_TURN_ITEMS_ATOM + : environmentThreadDetails.visibleTurnItemsAtom(ref), + ); +} + +export function useThreadRuntime(ref: ScopedThreadRef | null): ThreadRuntimeSummary | null { + return useAtomValue( + ref === null ? EMPTY_RUNTIME_ATOM : environmentThreadDetails.runtimeAtom(ref), ); } diff --git a/apps/web/src/state/queries.ts b/apps/web/src/state/queries.ts index 79737e6109..b564b2668a 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -4,13 +4,8 @@ import { type ComposerPathSearchTarget, } from "@t3tools/client-runtime/state/threads"; import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs"; -import type { - EnvironmentId, - OrchestrationThread, - ThreadId, - VcsListRefsResult, - VcsRef, -} from "@t3tools/contracts"; +import type { EnvironmentId, ThreadId, VcsListRefsResult, VcsRef } from "@t3tools/contracts"; +import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell"; import * as Cause from "effect/Cause"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/unstable/reactivity"; @@ -30,7 +25,7 @@ const EMPTY_REFS: ReadonlyArray = []; const INITIAL_BRANCH_CURSORS = [undefined] as const; export interface ThreadDetailView { - readonly data: OrchestrationThread | null; + readonly data: EnvironmentThread | null; readonly error: string | null; readonly isPending: boolean; readonly isDeleted: boolean; diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.ts index fd936f99ff..3986e56c1a 100644 --- a/apps/web/src/state/threads.ts +++ b/apps/web/src/state/threads.ts @@ -7,6 +7,7 @@ import { type EnvironmentThreadState, createThreadEnvironmentAtoms, } from "@t3tools/client-runtime/state/threads"; +import { presentThread, type EnvironmentThread } from "@t3tools/client-runtime/state/shell"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/unstable/reactivity"; @@ -32,14 +33,21 @@ const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_ export function useEnvironmentThread( environmentId: EnvironmentId | null, threadId: ThreadId | null, -): EnvironmentThreadState { +): Omit & { readonly data: Option.Option } { const result = useAtomValue( environmentId !== null && threadId !== null ? 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, + data: + environmentId === null + ? Option.none() + : Option.map(state.data, (projection) => presentThread(environmentId, projection)), + }; } diff --git a/apps/web/src/test-fixtures.ts b/apps/web/src/test-fixtures.ts new file mode 100644 index 0000000000..4182dbed2c --- /dev/null +++ b/apps/web/src/test-fixtures.ts @@ -0,0 +1,89 @@ +import { presentThread } from "@t3tools/client-runtime/state/shell"; +import { + EnvironmentId, + ProjectId, + ProviderInstanceId, + ThreadId, + type OrchestrationV2ThreadProjection, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +import type { Thread } from "./types"; + +const DEFAULT_TIMESTAMP = "2026-01-01T00:00:00.000Z"; + +/** Creates a structurally complete V2 thread for UI unit tests. */ +export function makeThreadFixture(overrides: Partial = {}): Thread { + const environmentId = overrides.environmentId ?? EnvironmentId.make("environment-test"); + const id = overrides.id ?? ThreadId.make("thread-test"); + const projectId = overrides.projectId ?? ProjectId.make("project-test"); + const providerInstanceId = + overrides.providerInstanceId ?? + overrides.modelSelection?.instanceId ?? + ProviderInstanceId.make("codex"); + const modelSelection = overrides.modelSelection ?? { + instanceId: providerInstanceId, + model: "gpt-5.4", + }; + // Presentation-level overrides are applied after projection. Keep the source + // projection valid so tests can deliberately exercise malformed persisted + // timestamps without failing inside Effect's DateTime constructor first. + const createdAt = DateTime.makeUnsafe(DEFAULT_TIMESTAMP); + const updatedAt = DateTime.makeUnsafe(DEFAULT_TIMESTAMP); + const archivedAt = + overrides.archivedAt === null || overrides.archivedAt === undefined + ? null + : DateTime.makeUnsafe(overrides.archivedAt); + const deletedAt = + overrides.deletedAt === null || overrides.deletedAt === undefined + ? null + : DateTime.makeUnsafe(overrides.deletedAt); + const projection: OrchestrationV2ThreadProjection = { + thread: { + id, + projectId, + title: overrides.title ?? "Thread", + providerInstanceId, + modelSelection, + runtimeMode: overrides.runtimeMode ?? "full-access", + interactionMode: overrides.interactionMode ?? "default", + branch: overrides.branch ?? null, + worktreePath: overrides.worktreePath ?? null, + activeProviderThreadId: overrides.activeProviderThreadId ?? null, + lineage: overrides.lineage ?? { + rootThreadId: id, + parentThreadId: null, + relationshipToParent: null, + }, + forkedFrom: overrides.forkedFrom ?? null, + createdBy: "user", + creationSource: "web", + createdAt, + updatedAt, + archivedAt, + deletedAt, + }, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: [], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt, + }; + + return { + ...presentThread(environmentId, projection), + ...overrides, + }; +} diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index 45a8539a15..20af209a7b 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -1,11 +1,5 @@ import type { ChatImageAttachment as ContractChatImageAttachment, - OrchestrationCheckpointFile, - OrchestrationCheckpointSummary, - OrchestrationLatestTurn, - OrchestrationMessage, - OrchestrationProposedPlan, - OrchestrationSession, ProjectScript as ContractProjectScript, ProviderInteractionMode, RuntimeMode, @@ -14,6 +8,11 @@ import type { EnvironmentProject, EnvironmentThread, EnvironmentThreadShell, + ThreadCheckpointSummary, + ThreadConversationMessage, + ThreadProposedPlan, + ThreadRunSummary, + ThreadRuntimeSummary, } from "@t3tools/client-runtime/state/shell"; export type SessionPhase = "disconnected" | "connecting" | "ready" | "running"; @@ -37,21 +36,21 @@ export interface ChatImageAttachment extends ContractChatImageAttachment { export type ChatAttachment = ChatImageAttachment; -export interface ChatMessage extends Omit { +export interface ChatMessage extends Omit { readonly attachments?: ReadonlyArray | undefined; } -export type ProposedPlan = OrchestrationProposedPlan; -export type TurnDiffFileChange = OrchestrationCheckpointFile; -export type TurnDiffSummary = OrchestrationCheckpointSummary; +export type ProposedPlan = ThreadProposedPlan; +export type TurnDiffFileChange = ThreadCheckpointSummary["files"][number]; +export type TurnDiffSummary = ThreadCheckpointSummary; export type Project = EnvironmentProject; export type Thread = EnvironmentThread; export type ThreadShell = EnvironmentThreadShell; export interface ThreadTurnState { - latestTurn: OrchestrationLatestTurn | null; + latestRun: ThreadRunSummary | null; } export type SidebarThreadSummary = EnvironmentThreadShell; -export type ThreadSession = OrchestrationSession; +export type ThreadSession = ThreadRuntimeSummary; diff --git a/apps/web/src/worktreeCleanup.test.ts b/apps/web/src/worktreeCleanup.test.ts index 13ff2f0f73..846f860613 100644 --- a/apps/web/src/worktreeCleanup.test.ts +++ b/apps/web/src/worktreeCleanup.test.ts @@ -2,12 +2,13 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools import { describe, expect, it } from "vite-plus/test"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types"; +import { makeThreadFixture } from "./test-fixtures"; import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "./worktreeCleanup"; const localEnvironmentId = EnvironmentId.make("environment-local"); function makeThread(overrides: Partial = {}): Thread { - return { + return makeThreadFixture({ id: ThreadId.make("thread-1"), environmentId: localEnvironmentId, projectId: ProjectId.make("project-1"), @@ -18,20 +19,18 @@ function makeThread(overrides: Partial = {}): Thread { }, runtimeMode: DEFAULT_RUNTIME_MODE, interactionMode: DEFAULT_INTERACTION_MODE, - session: null, + runtime: null, messages: [], - checkpoints: [], - activities: [], proposedPlans: [], createdAt: "2026-02-13T00:00:00.000Z", updatedAt: "2026-02-13T00:00:00.000Z", archivedAt: null, deletedAt: null, - latestTurn: null, + latestRun: null, branch: null, worktreePath: null, ...overrides, - }; + }); } describe("getOrphanedWorktreePathForThread", () => { diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.ts index 885ba4cb78..646dca1e9f 100644 --- a/packages/client-runtime/src/connection/registry.test.ts +++ b/packages/client-runtime/src/connection/registry.test.ts @@ -1,7 +1,7 @@ import { type DesktopSshEnvironmentTarget, EnvironmentId, - type OrchestrationShellSnapshot, + type OrchestrationV2ShellSnapshot, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; @@ -46,6 +46,7 @@ import * as EnvironmentRegistry from "./registry.ts"; import * as RpcSession from "../rpc/session.ts"; import * as EnvironmentSupervisor from "./supervisor.ts"; import * as ConnectionWakeups from "./wakeups.ts"; +import { v2ShellSnapshot } from "../state/orchestrationV2TestFixtures.ts"; const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), @@ -112,11 +113,9 @@ const SSH_PROFILE = new SshConnectionProfile({ target: SSH_TARGET, }); -const CACHED_SNAPSHOT: OrchestrationShellSnapshot = { +const CACHED_SNAPSHOT: OrchestrationV2ShellSnapshot = { + ...v2ShellSnapshot, snapshotSequence: 1, - projects: [], - threads: [], - updatedAt: "2026-06-06T00:00:00.000Z", }; interface SessionControl { diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index 5cc3f0c1a8..50b57124ab 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -1,13 +1,22 @@ import { CommandId, EnvironmentId, - ORCHESTRATION_WS_METHODS, + MessageId, + ORCHESTRATION_V2_WS_METHODS, + PlanId, ProjectId, + ProviderInstanceId, + RunId, ThreadId, - type ClientOrchestrationCommand, + WS_METHODS, + type OrchestrationV2Command, + type OrchestrationV2ThreadLaunchInput, + type OrchestrationV2ThreadProjection, + type ProjectMutation, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Crypto from "effect/Crypto"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -21,7 +30,8 @@ import { import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as RpcSession from "../rpc/session.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; -import { archiveThread, createProject, stopThreadSession } from "./commands.ts"; +import { v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts"; +import { archiveThread, createProject, startThreadTurn } from "./commands.ts"; const TEST_CRYPTO_LAYER = Layer.succeed( Crypto.Crypto, @@ -38,14 +48,45 @@ const TARGET = new PrimaryConnectionTarget({ wsBaseUrl: "wss://environment.example.test", }); -const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* ( - dispatched: ClientOrchestrationCommand[], -) { +const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (input: { + readonly commands: OrchestrationV2Command[]; + readonly projects: ProjectMutation[]; + readonly launches?: OrchestrationV2ThreadLaunchInput[]; + readonly projection?: OrchestrationV2ThreadProjection; +}) { const client = { - [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command: ClientOrchestrationCommand) => + [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) => Effect.sync(() => { - dispatched.push(command); - return { sequence: dispatched.length }; + input.commands.push(command); + return { sequence: input.commands.length }; + }), + [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: () => + Effect.succeed(input.projection ?? v2Projection), + [ORCHESTRATION_V2_WS_METHODS.launchThread]: (launchInput: OrchestrationV2ThreadLaunchInput) => + Effect.sync(() => { + input.launches?.push(launchInput); + return { + threadId: launchInput.threadId ?? v2ThreadId, + projection: input.projection ?? v2Projection, + resumed: false, + }; + }), + [WS_METHODS.projectsMutate]: (mutation: ProjectMutation) => + Effect.sync(() => { + input.projects.push(mutation); + return { + id: mutation.projectId, + title: mutation.type === "project.create" ? mutation.title : "Project", + workspaceRoot: + mutation.type === "project.create" ? mutation.workspaceRoot : "/workspace/project", + repositoryIdentity: null, + faviconPath: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-06-06T00:00:00.000Z", + updatedAt: "2026-06-06T00:00:00.000Z", + deletedAt: null, + }; }), } as unknown as WsRpcProtocolClient; const session: RpcSession.RpcSession = { @@ -66,72 +107,222 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); }); -describe("environment commands", () => { - it.effect("adds generated command metadata", () => +describe("V2 environment commands", () => { + it.effect("routes projects through the event-sourced project transport", () => Effect.gen(function* () { - const dispatched: ClientOrchestrationCommand[] = []; - const supervisor = yield* makeSupervisor(dispatched); + const projects: ProjectMutation[] = []; + const supervisor = yield* makeSupervisor({ commands: [], projects }); - const result = yield* createProject({ + yield* createProject({ projectId: ProjectId.make("project-1"), title: "Project", workspaceRoot: "/workspace/project", - createdAt: "2026-06-06T00:00:00.000Z", + createWorkspaceRootIfMissing: true, }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); - expect(result).toEqual({ sequence: 1 }); - expect(dispatched).toEqual([ + expect(projects).toEqual([ { type: "project.create", commandId: "00000000-0000-4000-8000-000000000000", projectId: "project-1", title: "Project", workspaceRoot: "/workspace/project", - createdAt: "2026-06-06T00:00:00.000Z", + createWorkspaceRootIfMissing: true, }, ]); }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), ); - it.effect("preserves caller metadata for idempotent queued commands", () => + it.effect("preserves caller command ids for idempotent V2 commands", () => Effect.gen(function* () { - const dispatched: ClientOrchestrationCommand[] = []; - const supervisor = yield* makeSupervisor(dispatched); - - yield* stopThreadSession({ - commandId: CommandId.make("queued-command"), - threadId: ThreadId.make("thread-1"), - createdAt: "2026-06-06T00:01:00.000Z", - }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); - - expect(dispatched).toEqual([ - { - type: "thread.session.stop", - commandId: "queued-command", - threadId: "thread-1", - createdAt: "2026-06-06T00:01:00.000Z", - }, - ]); - }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), - ); - - it.effect("does not add timestamps to commands without createdAt", () => - Effect.gen(function* () { - const dispatched: ClientOrchestrationCommand[] = []; - const supervisor = yield* makeSupervisor(dispatched); + const commands: OrchestrationV2Command[] = []; + const supervisor = yield* makeSupervisor({ commands, projects: [] }); yield* archiveThread({ - commandId: CommandId.make("archive-command"), + commandId: CommandId.make("queued-command"), threadId: ThreadId.make("thread-1"), }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); - expect(dispatched).toEqual([ - { - type: "thread.archive", - commandId: "archive-command", - threadId: "thread-1", - }, + expect(commands).toEqual([ + { type: "thread.archive", commandId: "queued-command", threadId: "thread-1" }, ]); }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), ); + + it.effect("preserves plan implementation provenance on V2 runs", () => + Effect.gen(function* () { + const commands: OrchestrationV2Command[] = []; + const supervisor = yield* makeSupervisor({ commands, projects: [] }); + + yield* startThreadTurn({ + commandId: CommandId.make("implement-plan"), + threadId: v2ThreadId, + message: { + messageId: MessageId.make("message-implementation"), + role: "user", + text: "Implement the plan", + attachments: [], + }, + modelSelection: { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.4", + }, + runtimeMode: "full-access", + interactionMode: "default", + sourceProposedPlan: { + threadId: ThreadId.make("thread-plan"), + planId: PlanId.make("plan-1"), + }, + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); + + expect(commands).toHaveLength(1); + expect(commands[0]).toMatchObject({ + type: "message.dispatch", + commandId: "implement-plan", + threadId: v2ThreadId, + sourcePlanRef: { threadId: "thread-plan", planId: "plan-1" }, + dispatchMode: { type: "start_immediately" }, + }); + }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), + ); + + it.effect("preserves an existing worktree and branch during first-message launch", () => + Effect.gen(function* () { + const launches: OrchestrationV2ThreadLaunchInput[] = []; + const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches }); + + yield* startThreadTurn({ + commandId: CommandId.make("launch-existing-worktree"), + threadId: v2ThreadId, + message: { + messageId: MessageId.make("message-existing-worktree"), + role: "user", + text: "Continue here", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: ProjectId.make("project-1"), + title: "Thread", + modelSelection: v2Projection.thread.modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: "feature", + worktreePath: "/workspace/project-worktrees/feature", + createdAt: "2026-06-20T00:00:00.000Z", + }, + }, + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); + + expect(launches[0]).toMatchObject({ + threadId: v2ThreadId, + workspaceStrategy: { + type: "existing_worktree", + worktreePath: "/workspace/project-worktrees/feature", + branch: "feature", + }, + }); + }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), + ); + + it.effect("provisions an origin-based worktree for an existing empty thread", () => + Effect.gen(function* () { + const launches: OrchestrationV2ThreadLaunchInput[] = []; + const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches }); + + yield* startThreadTurn({ + commandId: CommandId.make("launch-existing-thread-worktree"), + threadId: v2ThreadId, + message: { + messageId: MessageId.make("message-existing-thread-worktree"), + role: "user", + text: "Move to a worktree", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + prepareWorktree: { + projectCwd: "/workspace/project", + baseBranch: "main", + branch: "feature", + startFromOrigin: true, + }, + }, + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); + + expect(launches[0]).toMatchObject({ + threadId: v2ThreadId, + reuseExistingThread: true, + projectId: v2Projection.thread.projectId, + workspaceStrategy: { + type: "worktree", + baseRef: "main", + branch: "feature", + startFromOrigin: true, + }, + }); + }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), + ); + + it.effect("maps explicit active-run delivery modes to V2 dispatch semantics", () => + Effect.gen(function* () { + const activeRunId = RunId.make("run-active"); + const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"); + const projection: OrchestrationV2ThreadProjection = { + ...v2Projection, + runs: [ + { + id: activeRunId, + threadId: v2ThreadId, + ordinal: 1, + providerInstanceId: v2Projection.thread.providerInstanceId, + modelSelection: v2Projection.thread.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("message-active"), + rootNodeId: null, + activeAttemptId: null, + status: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + ], + }; + const commands: OrchestrationV2Command[] = []; + const supervisor = yield* makeSupervisor({ commands, projects: [], projection }); + + for (const [mode, expectedType] of [ + ["queue", "queue_after_active"], + ["steer", "steer_active"], + ["restart", "restart_active"], + ] as const) { + yield* startThreadTurn({ + commandId: CommandId.make(`command-${mode}`), + threadId: v2ThreadId, + message: { + messageId: MessageId.make(`message-${mode}`), + role: "user", + text: mode, + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + dispatchMode: mode, + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); + + expect(commands.at(-1)).toMatchObject({ + type: "message.dispatch", + dispatchMode: { + type: expectedType, + ...(mode === "queue" ? {} : { targetRunId: activeRunId }), + }, + }); + } + }).pipe(Effect.provide(TEST_CRYPTO_LAYER)), + ); }); diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index a0c3cbe771..e660ac44db 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -1,256 +1,548 @@ import { CommandId, - ORCHESTRATION_WS_METHODS, - type ClientOrchestrationCommand, + ORCHESTRATION_V2_WS_METHODS, + WS_METHODS, + type ChatAttachment, + type MessageId, + type ModelSelection, + type OrchestrationV2Command, + type OrchestrationV2CreationSource, + type PlanId, + type ProjectId, + type ProjectScript, + type ProviderApprovalDecision, + type ProviderInteractionMode, + type ProviderUserInputAnswers, + type RunId, + type RuntimeMode, + type RuntimeRequestId, + type ThreadId, + type UploadChatAttachment, } from "@t3tools/contracts"; import * as Crypto from "effect/Crypto"; -import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; -import type { EnvironmentSupervisor } from "../connection/supervisor.ts"; -import { - type EnvironmentRpcFailure, - type EnvironmentRpcSuccess, - type EnvironmentRpcUnavailableError, - request, -} from "../rpc/client.ts"; +import { request } from "../rpc/client.ts"; -type CommandType = ClientOrchestrationCommand["type"]; -type CommandOf = Extract; -type CommandInput = Omit< - CommandOf, - "type" | "commandId" | "createdAt" -> & { - readonly commandId?: CommandId; -} & ("createdAt" extends keyof CommandOf - ? { - readonly createdAt?: CommandOf["createdAt"]; - } - : {}); - -export type CreateProjectInput = CommandInput<"project.create">; -export type UpdateProjectInput = CommandInput<"project.meta.update">; -export type DeleteProjectInput = CommandInput<"project.delete">; -export type CreateThreadInput = CommandInput<"thread.create">; -export type DeleteThreadInput = CommandInput<"thread.delete">; -export type ArchiveThreadInput = CommandInput<"thread.archive">; -export type UnarchiveThreadInput = CommandInput<"thread.unarchive">; -export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">; -export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">; -export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">; -export type StartThreadTurnInput = CommandInput<"thread.turn.start">; -export type InterruptThreadTurnInput = CommandInput<"thread.turn.interrupt">; -export type RespondToThreadApprovalInput = CommandInput<"thread.approval.respond">; -export type RespondToThreadUserInputInput = CommandInput<"thread.user-input.respond">; -export type RevertThreadCheckpointInput = CommandInput<"thread.checkpoint.revert">; -export type StopThreadSessionInput = CommandInput<"thread.session.stop">; - -type DispatchTag = typeof ORCHESTRATION_WS_METHODS.dispatchCommand; -type CommandEffect = Effect.Effect< - EnvironmentRpcSuccess, - EnvironmentRpcFailure | EnvironmentRpcUnavailableError, - Crypto.Crypto | EnvironmentSupervisor ->; - -function commandId(input: { readonly commandId?: CommandId }) { - return Effect.gen(function* () { - if (input.commandId !== undefined) { - return input.commandId; - } - const crypto = yield* Crypto.Crypto; - return yield* crypto.randomUUIDv4.pipe(Effect.orDie, Effect.map(CommandId.make)); - }); -} - -function timestampedCommandMetadata(input: { +interface CommandMetadata { readonly commandId?: CommandId; readonly createdAt?: string; -}) { - return Effect.all({ - commandId: commandId(input), - createdAt: - input.createdAt === undefined - ? DateTime.now.pipe(Effect.map(DateTime.formatIso)) - : Effect.succeed(input.createdAt), + readonly creationSource?: OrchestrationV2CreationSource; +} + +export interface CreateProjectInput extends CommandMetadata { + readonly projectId: ProjectId; + readonly title: string; + readonly workspaceRoot: string; + readonly createWorkspaceRootIfMissing?: boolean; + readonly defaultModelSelection?: ModelSelection | null; + readonly scripts?: ReadonlyArray; +} + +export interface UpdateProjectInput extends CommandMetadata { + readonly projectId: ProjectId; + readonly title?: string; + readonly workspaceRoot?: string; + readonly defaultModelSelection?: ModelSelection | null; + readonly scripts?: ReadonlyArray; +} + +export interface DeleteProjectInput extends CommandMetadata { + readonly projectId: ProjectId; + readonly force?: boolean; +} + +export interface CreateThreadInput extends CommandMetadata { + readonly threadId: ThreadId; + readonly projectId: ProjectId; + readonly title: string; + readonly modelSelection: ModelSelection; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + readonly branch: string | null; + readonly worktreePath: string | null; +} + +export interface ThreadCommandInput extends CommandMetadata { + readonly threadId: ThreadId; +} + +export type DeleteThreadInput = ThreadCommandInput; +export type ArchiveThreadInput = ThreadCommandInput; +export type UnarchiveThreadInput = ThreadCommandInput; + +export interface UpdateThreadMetadataInput extends ThreadCommandInput { + readonly title?: string; + readonly modelSelection?: ModelSelection; + readonly branch?: string | null; + readonly worktreePath?: string | null; +} + +export interface SetThreadRuntimeModeInput extends ThreadCommandInput { + readonly runtimeMode: RuntimeMode; +} + +export interface SetThreadInteractionModeInput extends ThreadCommandInput { + readonly interactionMode: ProviderInteractionMode; +} + +interface StartThreadBootstrap { + readonly createThread?: { + readonly projectId: ProjectId; + readonly title: string; + readonly modelSelection: ModelSelection; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + readonly branch: string | null; + readonly worktreePath: string | null; + readonly createdAt: string; + }; + readonly prepareWorktree?: { + readonly projectCwd: string; + readonly baseBranch: string; + readonly branch?: string; + readonly startFromOrigin?: boolean; + }; + readonly runSetupScript?: boolean; +} + +export interface StartThreadTurnInput extends ThreadCommandInput { + readonly message: { + readonly messageId: MessageId; + readonly role: "user"; + readonly text: string; + readonly attachments: ReadonlyArray; + }; + readonly modelSelection?: ModelSelection; + readonly titleSeed?: string; + readonly runtimeMode: RuntimeMode; + readonly interactionMode: ProviderInteractionMode; + readonly bootstrap?: StartThreadBootstrap; + readonly sourceProposedPlan?: { readonly threadId: ThreadId; readonly planId: PlanId }; + readonly dispatchMode?: "auto" | "queue" | "steer" | "restart"; +} + +export interface InterruptThreadTurnInput extends ThreadCommandInput { + readonly runId?: RunId; + /** Temporary caller compatibility while UI naming moves from turns to runs. */ + readonly turnId?: string; +} + +export interface RespondToThreadApprovalInput extends ThreadCommandInput { + readonly requestId: RuntimeRequestId; + readonly decision: ProviderApprovalDecision; +} + +export interface RespondToThreadUserInputInput extends ThreadCommandInput { + readonly requestId: RuntimeRequestId; + readonly answers: ProviderUserInputAnswers; +} + +export interface RevertThreadCheckpointInput extends ThreadCommandInput { + readonly checkpointId?: string; + readonly scopeId?: string; + readonly turnCount?: number; +} + +export type StopThreadSessionInput = ThreadCommandInput; + +const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* ( + input: CommandMetadata, +) { + if (input.commandId !== undefined) return input.commandId; + const crypto = yield* Crypto.Crypto; + return CommandId.make(yield* crypto.randomUUIDv4.pipe(Effect.orDie)); +}); + +const dispatch = (command: OrchestrationV2Command) => + request(ORCHESTRATION_V2_WS_METHODS.dispatchCommand, command); + +const getProjection = (threadId: ThreadId) => + request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }); + +const persistAttachments = Effect.fn("EnvironmentCommands.persistAttachments")(function* ( + threadId: ThreadId, + messageId: MessageId, + attachments: ReadonlyArray, +) { + const stored = attachments.filter( + (attachment): attachment is ChatAttachment => "id" in attachment, + ); + const uploads = attachments.filter( + (attachment): attachment is UploadChatAttachment => "dataUrl" in attachment, + ); + if (uploads.length === 0) return stored; + const result = yield* request(WS_METHODS.assetsPersistChatAttachments, { + threadId, + messageId, + attachments: uploads, }); -} + if (stored.length === 0) return result.attachments; + const byUpload = new Map( + uploads.map((attachment, index) => [attachment, result.attachments[index]]), + ); + return attachments.flatMap((attachment) => { + if ("id" in attachment) return [attachment]; + const persisted = byUpload.get(attachment); + return persisted === undefined ? [] : [persisted]; + }); +}); -function dispatch(command: ClientOrchestrationCommand) { - return request(ORCHESTRATION_WS_METHODS.dispatchCommand, command); -} +const mutateProject = Effect.fn("EnvironmentCommands.mutateProject")(function* ( + mutation: + | { + readonly type: "project.create"; + readonly commandId: CommandId; + readonly projectId: ProjectId; + readonly title: string; + readonly workspaceRoot: string; + readonly createWorkspaceRootIfMissing?: boolean; + readonly defaultModelSelection?: ModelSelection | null; + readonly scripts?: ReadonlyArray; + } + | { + readonly type: "project.update"; + readonly commandId: CommandId; + readonly projectId: ProjectId; + readonly title?: string; + readonly workspaceRoot?: string; + readonly defaultModelSelection?: ModelSelection | null; + readonly scripts?: ReadonlyArray; + } + | { + readonly type: "project.delete"; + readonly commandId: CommandId; + readonly projectId: ProjectId; + readonly force?: boolean; + }, +) { + return yield* request(WS_METHODS.projectsMutate, mutation); +}); -export const createProject: (input: CreateProjectInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.createProject", -)(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); - return yield* dispatch({ - ...input, +export const createProject = Effect.fn("EnvironmentCommands.createProject")(function* ( + input: CreateProjectInput, +) { + return yield* mutateProject({ type: "project.create", - commandId: metadata.commandId, - createdAt: metadata.createdAt, + commandId: yield* allocateCommandId(input), + projectId: input.projectId, + title: input.title, + workspaceRoot: input.workspaceRoot, + ...(input.createWorkspaceRootIfMissing === undefined + ? {} + : { createWorkspaceRootIfMissing: input.createWorkspaceRootIfMissing }), + ...(input.defaultModelSelection === undefined + ? {} + : { defaultModelSelection: input.defaultModelSelection }), + ...(input.scripts === undefined ? {} : { scripts: input.scripts }), }); }); -export const updateProject: (input: UpdateProjectInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.updateProject", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "project.meta.update", - commandId: yield* commandId(input), +export const updateProject = Effect.fn("EnvironmentCommands.updateProject")(function* ( + input: UpdateProjectInput, +) { + return yield* mutateProject({ + type: "project.update", + commandId: yield* allocateCommandId(input), + projectId: input.projectId, + ...(input.title === undefined ? {} : { title: input.title }), + ...(input.workspaceRoot === undefined ? {} : { workspaceRoot: input.workspaceRoot }), + ...(input.defaultModelSelection === undefined + ? {} + : { defaultModelSelection: input.defaultModelSelection }), + ...(input.scripts === undefined ? {} : { scripts: input.scripts }), }); }); -export const deleteProject: (input: DeleteProjectInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.deleteProject", -)(function* (input) { - return yield* dispatch({ - ...input, +export const deleteProject = Effect.fn("EnvironmentCommands.deleteProject")(function* ( + input: DeleteProjectInput, +) { + return yield* mutateProject({ type: "project.delete", - commandId: yield* commandId(input), + commandId: yield* allocateCommandId(input), + projectId: input.projectId, + ...(input.force === undefined ? {} : { force: input.force }), }); }); -export const createThread: (input: CreateThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.createThread", -)(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); +export const createThread = Effect.fn("EnvironmentCommands.createThread")(function* ( + input: CreateThreadInput, +) { return yield* dispatch({ - ...input, type: "thread.create", - commandId: metadata.commandId, - createdAt: metadata.createdAt, + commandId: yield* allocateCommandId(input), + createdBy: "user", + creationSource: input.creationSource ?? "web", + threadId: input.threadId, + projectId: input.projectId, + title: input.title, + modelSelection: input.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + branch: input.branch, + worktreePath: input.worktreePath, }); }); -export const deleteThread: (input: DeleteThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.deleteThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.delete", - commandId: yield* commandId(input), - }); +function simpleThreadCommand( + type: "thread.delete" | "thread.archive" | "thread.unarchive", + input: ThreadCommandInput, +) { + return allocateCommandId(input).pipe( + Effect.flatMap((commandId) => dispatch({ type, commandId, threadId: input.threadId })), + ); +} + +export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* ( + input: DeleteThreadInput, +) { + return yield* simpleThreadCommand("thread.delete", input); }); -export const archiveThread: (input: ArchiveThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.archiveThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.archive", - commandId: yield* commandId(input), - }); +export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* ( + input: ArchiveThreadInput, +) { + return yield* simpleThreadCommand("thread.archive", input); }); -export const unarchiveThread: (input: UnarchiveThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.unarchiveThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.unarchive", - commandId: yield* commandId(input), - }); +export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(function* ( + input: UnarchiveThreadInput, +) { + return yield* simpleThreadCommand("thread.unarchive", input); }); -export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.updateThreadMetadata", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.meta.update", - commandId: yield* commandId(input), - }); -}); +export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")( + function* (input: UpdateThreadMetadataInput) { + const commandId = yield* allocateCommandId(input); + let result = null; + if ( + input.title !== undefined || + input.branch !== undefined || + input.worktreePath !== undefined + ) { + result = yield* dispatch({ + type: "thread.metadata.update", + commandId, + threadId: input.threadId, + ...(input.title === undefined ? {} : { title: input.title }), + ...(input.branch === undefined ? {} : { branch: input.branch }), + ...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }), + }); + } + if (input.modelSelection !== undefined) { + result = yield* dispatch({ + type: "thread.model-selection.set", + commandId: result === null ? commandId : CommandId.make(`${commandId}:model-selection`), + threadId: input.threadId, + modelSelection: input.modelSelection, + }); + } + return result ?? { sequence: 0 }; + }, +); -export const setThreadRuntimeMode: (input: SetThreadRuntimeModeInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.setThreadRuntimeMode", -)(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); - return yield* dispatch({ - ...input, - type: "thread.runtime-mode.set", - commandId: metadata.commandId, - createdAt: metadata.createdAt, - }); -}); - -export const setThreadInteractionMode: (input: SetThreadInteractionModeInput) => CommandEffect = - Effect.fn("EnvironmentCommands.setThreadInteractionMode")(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); +export const setThreadRuntimeMode = Effect.fn("EnvironmentCommands.setThreadRuntimeMode")( + function* (input: SetThreadRuntimeModeInput) { + return yield* dispatch({ + type: "thread.runtime-mode.set", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + runtimeMode: input.runtimeMode, + }); + }, +); + +export const setThreadInteractionMode = Effect.fn("EnvironmentCommands.setThreadInteractionMode")( + function* (input: SetThreadInteractionModeInput) { return yield* dispatch({ - ...input, type: "thread.interaction-mode.set", - commandId: metadata.commandId, - createdAt: metadata.createdAt, + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + interactionMode: input.interactionMode, }); - }); + }, +); -export const startThreadTurn: (input: StartThreadTurnInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.startThreadTurn", -)(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); +export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(function* ( + input: StartThreadTurnInput, +) { + const commandId = yield* allocateCommandId(input); + const attachments = yield* persistAttachments( + input.threadId, + input.message.messageId, + input.message.attachments, + ); + const bootstrap = input.bootstrap?.createThread; + const prepareWorktree = input.bootstrap?.prepareWorktree; + if (bootstrap !== undefined || prepareWorktree !== undefined) { + const existingProjection = + bootstrap === undefined ? yield* getProjection(input.threadId) : null; + const thread = bootstrap ?? existingProjection!.thread; + const workspaceStrategy = + prepareWorktree !== undefined + ? { + type: "worktree" as const, + baseRef: prepareWorktree.baseBranch, + ...(prepareWorktree.branch === undefined ? {} : { branch: prepareWorktree.branch }), + ...(prepareWorktree.startFromOrigin === undefined + ? {} + : { startFromOrigin: prepareWorktree.startFromOrigin }), + } + : bootstrap?.worktreePath + ? { + type: "existing_worktree" as const, + worktreePath: bootstrap.worktreePath, + ...(bootstrap.branch === null ? {} : { branch: bootstrap.branch }), + } + : { + type: "root" as const, + ...(bootstrap?.branch === null || bootstrap?.branch === undefined + ? {} + : { branch: bootstrap.branch }), + }; + return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { + commandId, + creationSource: input.creationSource ?? "web", + threadId: input.threadId, + ...(bootstrap === undefined ? { reuseExistingThread: true } : {}), + projectId: thread.projectId, + title: thread.title, + modelSelection: input.modelSelection ?? thread.modelSelection, + runtimeMode: input.runtimeMode, + interactionMode: input.interactionMode, + workspaceStrategy, + initialMessage: { + messageId: input.message.messageId, + text: input.message.text, + attachments, + }, + }); + } + + const projection = yield* getProjection(input.threadId); + const activeRun = projection.runs.findLast( + (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", + ); + const requestedMode = input.dispatchMode ?? "auto"; + const activeProviderThread = + activeRun === undefined + ? undefined + : projection.providerThreads.find((thread) => thread.id === activeRun.providerThreadId); + const activeProviderSession = + activeProviderThread?.providerSessionId === null || + activeProviderThread?.providerSessionId === undefined + ? undefined + : projection.providerSessions.find( + (session) => session.id === activeProviderThread.providerSessionId, + ); + const turnCapabilities = activeProviderSession?.capabilities.turns; + const dispatchMode = + activeRun === undefined + ? ({ type: "start_immediately" } as const) + : requestedMode === "steer" + ? ({ type: "steer_active", targetRunId: activeRun.id } as const) + : requestedMode === "restart" + ? ({ type: "restart_active", targetRunId: activeRun.id } as const) + : requestedMode === "queue" + ? ({ type: "queue_after_active" } as const) + : turnCapabilities?.supportsActiveSteering === true + ? ({ type: "steer_active", targetRunId: activeRun.id } as const) + : turnCapabilities?.supportsQueuedMessages === true + ? ({ type: "queue_after_active" } as const) + : turnCapabilities?.supportsSteeringByInterruptRestart === true + ? ({ type: "restart_active", targetRunId: activeRun.id } as const) + : ({ type: "queue_after_active" } as const); return yield* dispatch({ - ...input, - type: "thread.turn.start", - commandId: metadata.commandId, - createdAt: metadata.createdAt, + type: "message.dispatch", + commandId, + createdBy: "user", + creationSource: input.creationSource ?? "web", + threadId: input.threadId, + messageId: input.message.messageId, + text: input.message.text, + attachments, + ...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }), + ...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }), + dispatchMode, }); }); -export const interruptThreadTurn: (input: InterruptThreadTurnInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.interruptThreadTurn", -)(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); +export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* ( + input: InterruptThreadTurnInput, +) { + const projection = yield* getProjection(input.threadId); + const runId = + input.runId ?? + (input.turnId as RunId | undefined) ?? + projection.runs.findLast( + (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", + )?.id; + if (runId === undefined) return { sequence: 0 }; return yield* dispatch({ - ...input, - type: "thread.turn.interrupt", - commandId: metadata.commandId, - createdAt: metadata.createdAt, + type: "run.interrupt", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + runId, }); }); -export const respondToThreadApproval: (input: RespondToThreadApprovalInput) => CommandEffect = - Effect.fn("EnvironmentCommands.respondToThreadApproval")(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); +export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")( + function* (input: RespondToThreadApprovalInput) { return yield* dispatch({ - ...input, - type: "thread.approval.respond", - commandId: metadata.commandId, - createdAt: metadata.createdAt, + type: "runtime-request.respond", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + requestId: input.requestId, + decision: input.decision, }); - }); + }, +); -export const respondToThreadUserInput: (input: RespondToThreadUserInputInput) => CommandEffect = - Effect.fn("EnvironmentCommands.respondToThreadUserInput")(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); +export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")( + function* (input: RespondToThreadUserInputInput) { return yield* dispatch({ - ...input, - type: "thread.user-input.respond", - commandId: metadata.commandId, - createdAt: metadata.createdAt, + type: "runtime-request.respond", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + requestId: input.requestId, + answers: input.answers, }); - }); + }, +); -export const revertThreadCheckpoint: (input: RevertThreadCheckpointInput) => CommandEffect = - Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); +export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")( + function* (input: RevertThreadCheckpointInput) { + const projection = yield* getProjection(input.threadId); + const checkpoint = + projection.checkpoints.find( + (candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId, + ) ?? + projection.checkpoints.findLast((candidate) => candidate.appRunOrdinal === input.turnCount); + if (checkpoint === undefined) return { sequence: 0 }; return yield* dispatch({ - ...input, - type: "thread.checkpoint.revert", - commandId: metadata.commandId, - createdAt: metadata.createdAt, + type: "checkpoint.rollback", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + scopeId: checkpoint.scopeId, + checkpointId: checkpoint.id, }); - }); + }, +); -export const stopThreadSession: (input: StopThreadSessionInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.stopThreadSession", -)(function* (input) { - const metadata = yield* timestampedCommandMetadata(input); - return yield* dispatch({ - ...input, - type: "thread.session.stop", - commandId: metadata.commandId, - createdAt: metadata.createdAt, - }); +export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* ( + input: StopThreadSessionInput, +) { + const projection = yield* getProjection(input.threadId); + const commandId = yield* allocateCommandId(input); + let result = { sequence: 0 }; + for (const session of projection.providerSessions) { + result = yield* dispatch({ + type: "provider-session.detach", + commandId: CommandId.make(`${commandId}:detach:${session.id}`), + threadId: input.threadId, + providerSessionId: session.id, + reason: "client-requested", + }); + } + return result; }); diff --git a/packages/client-runtime/src/platform/index.ts b/packages/client-runtime/src/platform/index.ts index 0c93754977..1006aa347a 100644 --- a/packages/client-runtime/src/platform/index.ts +++ b/packages/client-runtime/src/platform/index.ts @@ -1,4 +1,5 @@ export * from "./capabilities.ts"; export * from "./persistence.ts"; +export * from "./orchestrationCache.ts"; export * from "./source.ts"; export * from "./storageDocument.ts"; diff --git a/packages/client-runtime/src/platform/orchestrationCache.test.ts b/packages/client-runtime/src/platform/orchestrationCache.test.ts new file mode 100644 index 0000000000..1e69708edb --- /dev/null +++ b/packages/client-runtime/src/platform/orchestrationCache.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "@effect/vitest"; +import { EnvironmentId } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +import { + ORCHESTRATION_CACHE_SCHEMA_VERSION, + StoredOrchestrationShellSnapshot, + StoredOrchestrationThreadSnapshot, + decodeOrDiscardOrchestrationCache, +} from "./orchestrationCache.ts"; +import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts"; + +const environmentId = EnvironmentId.make("environment-cache-test"); +const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(StoredOrchestrationShellSnapshot); +const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(StoredOrchestrationThreadSnapshot); + +describe("orchestration cache envelopes", () => { + it.effect("accepts V2 shell and thread cache envelopes", () => + Effect.gen(function* () { + const shell = yield* decodeStoredShellSnapshot({ + schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, + environmentId, + snapshot: v2ShellSnapshot, + }); + const thread = yield* decodeStoredThreadSnapshot({ + schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, + environmentId, + threadId: v2ThreadId, + thread: v2Projection, + }); + + expect(shell.snapshot).toEqual(v2ShellSnapshot); + expect(thread.thread).toEqual(v2Projection); + }), + ); + + it.effect("discards V1-versioned cache envelopes after a decode failure", () => + Effect.gen(function* () { + let discardCount = 0; + const decoded = decodeStoredShellSnapshot({ + schemaVersion: 1, + environmentId, + snapshot: v2ShellSnapshot, + }).pipe(Effect.map(Option.some)); + + const result = yield* decodeOrDiscardOrchestrationCache( + decoded, + Effect.sync(() => { + discardCount += 1; + }), + ); + + expect(Option.isNone(result)).toBe(true); + expect(discardCount).toBe(1); + }), + ); +}); diff --git a/packages/client-runtime/src/platform/orchestrationCache.ts b/packages/client-runtime/src/platform/orchestrationCache.ts new file mode 100644 index 0000000000..a970709ae2 --- /dev/null +++ b/packages/client-runtime/src/platform/orchestrationCache.ts @@ -0,0 +1,32 @@ +import { + EnvironmentId, + OrchestrationV2ShellSnapshot, + OrchestrationV2ThreadProjection, + ThreadId, +} from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +export const ORCHESTRATION_CACHE_SCHEMA_VERSION = 2 as const; + +export const StoredOrchestrationShellSnapshot = Schema.Struct({ + schemaVersion: Schema.Literal(ORCHESTRATION_CACHE_SCHEMA_VERSION), + environmentId: EnvironmentId, + snapshot: OrchestrationV2ShellSnapshot, +}); + +export const StoredOrchestrationThreadSnapshot = Schema.Struct({ + schemaVersion: Schema.Literal(ORCHESTRATION_CACHE_SCHEMA_VERSION), + environmentId: EnvironmentId, + threadId: ThreadId, + thread: OrchestrationV2ThreadProjection, +}); + +/** Invalid orchestration caches are disposable and must never block live synchronization. */ +export function decodeOrDiscardOrchestrationCache( + decode: Effect.Effect, E, R>, + discard: Effect.Effect, +) { + return decode.pipe(Effect.catch(() => discard.pipe(Effect.as(Option.none())))); +} diff --git a/packages/client-runtime/src/platform/persistence.ts b/packages/client-runtime/src/platform/persistence.ts index 71664bf460..110b3e7b12 100644 --- a/packages/client-runtime/src/platform/persistence.ts +++ b/packages/client-runtime/src/platform/persistence.ts @@ -1,7 +1,7 @@ import { type EnvironmentId, - type OrchestrationThread, - type OrchestrationShellSnapshot, + type OrchestrationV2ShellSnapshot, + type OrchestrationV2ThreadProjection, type ThreadId, } from "@t3tools/contracts"; import * as Context from "effect/Context"; @@ -52,18 +52,18 @@ export class EnvironmentCacheStore extends Context.Service< { readonly loadShell: ( environmentId: EnvironmentId, - ) => Effect.Effect, ConnectionPersistenceError>; + ) => Effect.Effect, ConnectionPersistenceError>; readonly saveShell: ( environmentId: EnvironmentId, - snapshot: OrchestrationShellSnapshot, + snapshot: OrchestrationV2ShellSnapshot, ) => Effect.Effect; readonly loadThread: ( environmentId: EnvironmentId, threadId: ThreadId, - ) => Effect.Effect, ConnectionPersistenceError>; + ) => Effect.Effect, ConnectionPersistenceError>; readonly saveThread: ( environmentId: EnvironmentId, - thread: OrchestrationThread, + thread: OrchestrationV2ThreadProjection, ) => Effect.Effect; readonly removeThread: ( environmentId: EnvironmentId, diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index f7e616ab09..7072fc9fc7 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -1,8 +1,4 @@ -import { - ORCHESTRATION_V2_WS_METHODS, - ORCHESTRATION_WS_METHODS, - WS_METHODS, -} from "@t3tools/contracts"; +import { ORCHESTRATION_V2_WS_METHODS, WS_METHODS } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import type * as Duration from "effect/Duration"; @@ -43,8 +39,6 @@ export type EnvironmentRpcTag = keyof WsRpcProtocolClient & string; type RpcMethod = WsRpcProtocolClient[TTag]; export type EnvironmentSubscriptionRpcTag = - | typeof ORCHESTRATION_WS_METHODS.subscribeShell - | typeof ORCHESTRATION_WS_METHODS.subscribeThread | typeof ORCHESTRATION_V2_WS_METHODS.subscribeShell | typeof ORCHESTRATION_V2_WS_METHODS.subscribeThread | typeof WS_METHODS.subscribeAuthAccess diff --git a/packages/client-runtime/src/state/archivedThreads.test.ts b/packages/client-runtime/src/state/archivedThreads.test.ts index aa16b9cadc..4928b1f811 100644 --- a/packages/client-runtime/src/state/archivedThreads.test.ts +++ b/packages/client-runtime/src/state/archivedThreads.test.ts @@ -1,4 +1,4 @@ -import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts"; +import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity"; import { expect, it } from "vite-plus/test"; @@ -22,7 +22,7 @@ it("does not expose an archived snapshot failure message", () => { const snapshotsAtom = createArchivedThreadSnapshotsAtomFamily({ getSnapshotAtom: () => Atom.make( - AsyncResult.failure( + AsyncResult.failure( Cause.fail(new Error("credential=secret-value")), ), ), diff --git a/packages/client-runtime/src/state/archivedThreads.ts b/packages/client-runtime/src/state/archivedThreads.ts index 8c64f1ae50..8b71479b45 100644 --- a/packages/client-runtime/src/state/archivedThreads.ts +++ b/packages/client-runtime/src/state/archivedThreads.ts @@ -1,4 +1,4 @@ -import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts"; +import { EnvironmentId, type OrchestrationV2ArchivedShellSnapshot } from "@t3tools/contracts"; import * as Arr from "effect/Array"; import { pipe } from "effect/Function"; import * as Option from "effect/Option"; @@ -7,7 +7,7 @@ import { AsyncResult, Atom } from "effect/unstable/reactivity"; export interface ArchivedSnapshotEntry { readonly environmentId: EnvironmentId; - readonly snapshot: OrchestrationShellSnapshot; + readonly snapshot: OrchestrationV2ArchivedShellSnapshot; } export interface ArchivedThreadSnapshotsState { @@ -40,7 +40,7 @@ export function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray(options: { readonly getSnapshotAtom: ( environmentId: EnvironmentId, - ) => Atom.Atom>; + ) => Atom.Atom>; readonly labelPrefix: string; }) { return Atom.family((environmentKey: string) => diff --git a/packages/client-runtime/src/state/entities.test.ts b/packages/client-runtime/src/state/entities.test.ts index c772d134a6..cbf3a3ef48 100644 --- a/packages/client-runtime/src/state/entities.test.ts +++ b/packages/client-runtime/src/state/entities.test.ts @@ -1,368 +1,115 @@ -import { - EnvironmentId, - ProjectId, - ProviderInstanceId, - ThreadId, - type OrchestrationShellSnapshot, - type OrchestrationThread, -} from "@t3tools/contracts"; -import { describe, expect, it } from "@effect/vitest"; -import * as Option from "effect/Option"; -import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity"; +import { EnvironmentId, MessageId, RunId, TurnItemId } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; -import { PrimaryConnectionTarget } from "../connection/model.ts"; -import { - InvalidScopedProjectKeyError, - InvalidScopedProjectRefCollectionKeyError, - InvalidScopedThreadKeyError, - parseProjectKey, - parseProjectRefCollectionKey, - parseThreadKey, -} from "./entities.ts"; -import type { EnvironmentShellState } from "./shell.ts"; -import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts"; -import { createEnvironmentProjectAtoms } from "./projectEntities.ts"; -import { createEnvironmentSnapshotAtom } from "./snapshots.ts"; -import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts"; -import { mergeEnvironmentThread } from "./threadDetail.ts"; -import { createEnvironmentThreadShellAtoms } from "./threadShell.ts"; +import { presentThread, presentThreadShell } from "./models.ts"; +import { v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; -const ENVIRONMENT_ID = EnvironmentId.make("environment-1"); -const PROJECT_ID = ProjectId.make("project-1"); -const OTHER_PROJECT_ID = ProjectId.make("project-2"); -const THREAD_ID = ThreadId.make("thread-1"); -const OTHER_THREAD_ID = ThreadId.make("thread-2"); +const environmentId = EnvironmentId.make("environment-v2"); -describe("scoped entity keys", () => { - it("preserves an invalid project key as structured error data", () => { - const key = "missing-project-key-separator"; - let error: unknown; - - try { - parseProjectKey(key); - } catch (cause) { - error = cause; - } - - expect(error).toEqual(new InvalidScopedProjectKeyError({ key })); +describe("V2 client presentation", () => { + it("presents shell timestamps and status without constructing V1 state", () => { + const shell = presentThreadShell(environmentId, v2ThreadShell); + expect(shell.environmentId).toBe(environmentId); + expect(shell.createdAt).toBe("2026-06-20T00:00:00.000Z"); + expect(shell.runtime).toBeNull(); + expect(shell.source).toBe(v2ThreadShell); }); - it("preserves an invalid thread key as structured error data", () => { - const key = "missing-thread-key-separator"; - let error: unknown; - - try { - parseThreadKey(key); - } catch (cause) { - error = cause; - } - - expect(error).toEqual(new InvalidScopedThreadKeyError({ key })); - }); - - it("preserves malformed project reference collection input and its cause", () => { - const key = "not-json"; - let error: unknown; - - try { - parseProjectRefCollectionKey(key); - } catch (cause) { - error = cause; - } - - expect(error).toBeInstanceOf(InvalidScopedProjectRefCollectionKeyError); - expect(error).toMatchObject({ key, cause: expect.anything() }); - }); - - it("rejects invalid project reference collection shapes", () => { - const key = JSON.stringify([["environment-1"]]); - - expect(() => parseProjectRefCollectionKey(key)).toThrowError( - InvalidScopedProjectRefCollectionKeyError, - ); - }); -}); - -const THREAD_SHELL = { - id: THREAD_ID, - projectId: PROJECT_ID, - title: "Thread", - 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, -} as const; - -const SNAPSHOT: OrchestrationShellSnapshot = { - snapshotSequence: 1, - updatedAt: "2026-06-01T00:00:00.000Z", - projects: [ - { - id: PROJECT_ID, - title: "Project", - workspaceRoot: "/repo", - repositoryIdentity: null, - defaultModelSelection: null, - scripts: [], - createdAt: "2026-06-01T00:00:00.000Z", - updatedAt: "2026-06-01T00:00:00.000Z", - }, - { - id: OTHER_PROJECT_ID, - title: "Other project", - workspaceRoot: "/other-repo", - repositoryIdentity: null, - defaultModelSelection: null, - scripts: [], - createdAt: "2026-06-01T00:00:00.000Z", - updatedAt: "2026-06-01T00:00:00.000Z", - }, - ], - threads: [ - THREAD_SHELL, - { - ...THREAD_SHELL, - id: OTHER_THREAD_ID, - projectId: OTHER_PROJECT_ID, - title: "Other thread", - }, - ], -}; - -function shellState(snapshot: OrchestrationShellSnapshot): EnvironmentShellState { - return { - snapshot: Option.some(snapshot), - status: "live", - error: Option.none(), - }; -} - -function makeHarness() { - const shellStateAtoms = Atom.family((_environmentId: EnvironmentId) => - Atom.make(AsyncResult.success(shellState(SNAPSHOT))), - ); - const threadStateAtoms = Atom.family((_key: string) => - Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)), - ); - const catalogValueAtom = Atom.make({ - isReady: true, - entries: new Map([ - [ - ENVIRONMENT_ID, + it("retains the complete projection while deriving conversation parity", () => { + const runId = RunId.make("run-1"); + const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"); + const projection = { + ...v2Projection, + runs: [ { - target: new PrimaryConnectionTarget({ - environmentId: ENVIRONMENT_ID, - label: "Environment", - httpBaseUrl: "https://example.test", - wsBaseUrl: "wss://example.test", - }), - profile: Option.none(), + id: runId, + threadId: v2Projection.thread.id, + ordinal: 1, + providerInstanceId: v2Projection.thread.providerInstanceId, + modelSelection: v2Projection.thread.modelSelection, + providerThreadId: null, + userMessageId: MessageId.make("message-user"), + rootNodeId: null, + activeAttemptId: null, + status: "running" as const, + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, }, ], - ]), - }); - const snapshotAtom = createEnvironmentSnapshotAtom(shellStateAtoms); - const projects = createEnvironmentProjectAtoms({ - catalogValueAtom, - snapshotAtom, - }); - const threadShells = createEnvironmentThreadShellAtoms({ - catalogValueAtom, - snapshotAtom, - }); - const threadDetails = createEnvironmentThreadDetailAtoms((environmentId, threadId) => - threadStateAtoms(`${environmentId}\u0000${threadId}`), - ); - - return { - registry: AtomRegistry.make(), - shellStateAtom: shellStateAtoms(ENVIRONMENT_ID), - threadStateAtom: (threadId: ThreadId) => threadStateAtoms(`${ENVIRONMENT_ID}\u0000${threadId}`), - projects, - threadShells, - threadDetails, - }; -} - -describe("environment entity projections", () => { - it("composes detail collections with authoritative shell workspace metadata", () => { - const messages: OrchestrationThread["messages"] = []; - const detail = { - ...THREAD_SHELL, - environmentId: ENVIRONMENT_ID, - title: "Cached thread", - branch: "stale-branch", - worktreePath: "/repo/stale-worktree", - deletedAt: null, - messages, - proposedPlans: [], - activities: [], - checkpoints: [], - } satisfies OrchestrationThread & { readonly environmentId: EnvironmentId }; - const shell = { - ...THREAD_SHELL, - environmentId: ENVIRONMENT_ID, - title: "Current thread", - branch: "current-branch", - worktreePath: "/repo/current-worktree", + messages: [ + { + id: MessageId.make("message-user"), + threadId: v2Projection.thread.id, + runId, + nodeId: null, + role: "user" as const, + text: "Hello", + attachments: [], + streaming: false, + createdBy: "user" as const, + creationSource: "web" as const, + createdAt: now, + updatedAt: now, + }, + ], + updatedAt: now, }; - const merged = mergeEnvironmentThread(detail, shell); + const thread = presentThread(environmentId, projection); + expect(thread.projection).toBe(projection); + expect(thread.latestRun?.runId).toBe(runId); + expect(thread.runtime?.status).toBe("running"); + expect(thread.runs).toHaveLength(1); + expect(thread.availableActions.canInterrupt).toBe(true); + expect(thread.messages[0]).toMatchObject({ text: "Hello", runId }); + }); - expect(merged).toMatchObject({ - title: "Current thread", - branch: "current-branch", - worktreePath: "/repo/current-worktree", + it("keeps the complete payload for generic V2 work-item rendering", () => { + const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"); + const item = { + id: TurnItemId.make("item-dynamic"), + threadId: v2Projection.thread.id, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed" as const, + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "dynamic_tool" as const, + toolName: "custom_tool", + input: { nested: { value: 1 } }, + output: { ok: true }, + }; + const projection = { + ...v2Projection, + turnItems: [item], + visibleTurnItems: [ + { + position: 0, + visibility: "local" as const, + sourceThreadId: v2Projection.thread.id, + sourceItemId: item.id, + item, + }, + ], + updatedAt: now, + }; + + const thread = presentThread(environmentId, projection); + expect(thread.workEntries[0]).toMatchObject({ + itemType: "dynamic_tool", + label: "custom_tool", + structuredPayload: item, }); - expect(merged?.messages).toBe(messages); - }); - - it("preserves untouched project and thread identities across unrelated shell updates", () => { - const harness = makeHarness(); - const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID); - const threadRefsAtom = harness.threadShells.environmentThreadRefsAtom(ENVIRONMENT_ID); - const projectsAtom = harness.projects.projectsAtom; - const projectAtom = harness.projects.projectAtom({ - environmentId: ENVIRONMENT_ID, - projectId: PROJECT_ID, - }); - const threadAtom = harness.threadShells.threadShellAtom({ - environmentId: ENVIRONMENT_ID, - threadId: THREAD_ID, - }); - const projectRefs = harness.registry.get(projectRefsAtom); - const threadRefs = harness.registry.get(threadRefsAtom); - const projects = harness.registry.get(projectsAtom); - const project = harness.registry.get(projectAtom); - const thread = harness.registry.get(threadAtom); - - harness.registry.set( - harness.shellStateAtom, - AsyncResult.success( - shellState({ - ...SNAPSHOT, - snapshotSequence: 2, - threads: SNAPSHOT.threads.map((candidate) => - candidate.id === OTHER_THREAD_ID - ? { ...candidate, title: "Renamed other thread" } - : candidate, - ), - }), - ), - ); - - expect(harness.registry.get(projectRefsAtom)).toBe(projectRefs); - expect(harness.registry.get(threadRefsAtom)).toBe(threadRefs); - expect(harness.registry.get(projectsAtom)).toBe(projects); - expect(harness.registry.get(projectAtom)).toBe(project); - expect(harness.registry.get(threadAtom)).toBe(thread); - }); - - it("preserves project-scoped thread collections across unrelated project updates", () => { - const harness = makeHarness(); - const projectRef = { - environmentId: ENVIRONMENT_ID, - projectId: PROJECT_ID, - }; - const refsByProjectAtom = - harness.threadShells.environmentThreadRefsByProjectAtom(ENVIRONMENT_ID); - const threadsAtom = harness.threadShells.threadShellsForProjectRefsAtom([projectRef]); - const refs = harness.registry.get(refsByProjectAtom).get(PROJECT_ID); - const threads = harness.registry.get(threadsAtom); - - expect(threads).toHaveLength(1); - expect(threads[0]?.id).toBe(THREAD_ID); - - harness.registry.set( - harness.shellStateAtom, - AsyncResult.success( - shellState({ - ...SNAPSHOT, - snapshotSequence: 2, - threads: SNAPSHOT.threads.map((thread) => - thread.id === OTHER_THREAD_ID ? { ...thread, title: "Updated elsewhere" } : thread, - ), - }), - ), - ); - - expect(harness.registry.get(refsByProjectAtom).get(PROJECT_ID)).toBe(refs); - expect(harness.registry.get(threadsAtom)).toBe(threads); - }); - - it("updates only the requested thread detail and preserves untouched field identities", () => { - const harness = makeHarness(); - const threadRef = { - environmentId: ENVIRONMENT_ID, - threadId: THREAD_ID, - }; - const otherThreadRef = { - environmentId: ENVIRONMENT_ID, - threadId: OTHER_THREAD_ID, - }; - const threadDetailAtom = harness.threadDetails.detailAtom(threadRef); - const messagesAtom = harness.threadDetails.messagesAtom(threadRef); - const activitiesAtom = harness.threadDetails.activitiesAtom(threadRef); - const statusAtom = harness.threadDetails.statusAtom(threadRef); - const otherThreadDetailAtom = harness.threadDetails.detailAtom(otherThreadRef); - const otherValue = harness.registry.get(otherThreadDetailAtom); - const detail = { - ...THREAD_SHELL, - deletedAt: null, - messages: [], - proposedPlans: [], - activities: [], - checkpoints: [], - } satisfies OrchestrationThread; - - harness.registry.set( - harness.threadStateAtom(THREAD_ID), - AsyncResult.success({ - data: Option.some(detail), - status: "live", - error: Option.none(), - }), - ); - - const scopedDetail = harness.registry.get(threadDetailAtom); - const messages = harness.registry.get(messagesAtom); - const activities = harness.registry.get(activitiesAtom); - - expect(scopedDetail).toEqual({ ...detail, environmentId: ENVIRONMENT_ID }); - expect(harness.registry.get(statusAtom)).toBe("live"); - expect(harness.registry.get(otherThreadDetailAtom)).toBe(otherValue); - - harness.registry.set( - harness.threadStateAtom(THREAD_ID), - AsyncResult.success({ - data: Option.some({ - ...detail, - session: { - threadId: THREAD_ID, - status: "ready", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: "2026-06-01T00:01:00.000Z", - }, - }), - status: "live", - error: Option.none(), - }), - ); - - expect(harness.registry.get(messagesAtom)).toBe(messages); - expect(harness.registry.get(activitiesAtom)).toBe(activities); }); }); diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index b601b59bfa..f37ab18f75 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -1,25 +1,459 @@ import type { + ChatAttachment, + CheckpointId, + CheckpointRef, + CheckpointScopeId, EnvironmentId, - OrchestrationMessage, + MessageId, OrchestrationProjectShell, - OrchestrationShellSnapshot, - OrchestrationThread, - OrchestrationThreadShell, + OrchestrationV2PlanArtifact, + OrchestrationV2ProviderCapabilities, + OrchestrationV2RunStatus, + OrchestrationV2ShellSnapshot, + OrchestrationV2ThreadProjection, + OrchestrationV2ThreadShell, + OrchestrationV2TurnItem, + PlanId, + ProjectId, + ProviderApprovalDecision, + ProviderInstanceId, + ProviderRequestKind, + RunId, + RuntimeRequestId, ThreadId, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; export interface EnvironmentProject extends OrchestrationProjectShell { readonly environmentId: EnvironmentId; } -export interface EnvironmentThreadShell extends OrchestrationThreadShell { +/** + * A pristine V2 thread projection paired with the environment that produced it. + * + * Keep the projection nested so its identity and every structurally shared + * collection remain intact. This is the scoped detail boundary for rich V2 + * consumers; it is intentionally not another presentation-shaped thread. + */ +export interface ScopedThreadProjection { readonly environmentId: EnvironmentId; + readonly projection: OrchestrationV2ThreadProjection; } -export type EnvironmentMessage = OrchestrationMessage; +export interface ThreadRunSummary { + readonly runId: RunId; + readonly status: OrchestrationV2RunStatus; + readonly requestedAt: string | null; + readonly startedAt: string | null; + readonly completedAt: string | null; + readonly assistantMessageId: MessageId | null; + readonly sourcePlanRef?: { + readonly threadId: ThreadId; + readonly planId: PlanId; + }; +} -export interface EnvironmentThread extends OrchestrationThread { +export interface ThreadRuntimeSummary { + readonly status: OrchestrationV2RunStatus | "idle"; + readonly activeRunId: RunId | null; + readonly providerInstanceId: ProviderInstanceId; + readonly providerName: string | null; + readonly lastError: string | null; + readonly updatedAt: string; +} + +export function threadRuntimeIsActive(runtime: ThreadRuntimeSummary | null | undefined): boolean { + return runtime !== null && runtime !== undefined && threadRunStatusIsActive(runtime.status); +} + +export function threadRunStatusIsActive(status: ThreadRuntimeSummary["status"]): boolean { + return ( + status === "queued" || status === "starting" || status === "running" || status === "waiting" + ); +} + +export interface ThreadConversationMessage { + readonly id: MessageId; + readonly role: "user" | "assistant" | "system"; + readonly text: string; + readonly attachments?: ReadonlyArray; + readonly runId: RunId | null; + readonly streaming: boolean; + readonly createdAt: string; + readonly updatedAt: string; +} + +export interface ThreadProposedPlan { + readonly id: PlanId; + readonly runId: RunId | null; + readonly planMarkdown: string; + readonly status: OrchestrationV2PlanArtifact["status"]; + readonly implementedAt: string | null; + readonly implementationThreadId: ThreadId | null; + readonly createdAt: string; + readonly updatedAt: string; +} + +export interface ThreadTodoPlan { + readonly id: PlanId; + readonly runId: RunId | null; + readonly status: OrchestrationV2PlanArtifact["status"]; + readonly explanation: string | null; + readonly steps: ReadonlyArray<{ + readonly id: string; + readonly step: string; + readonly status: "pending" | "inProgress" | "completed"; + }>; + readonly updatedAt: string; +} + +export interface ThreadCheckpointSummary { + readonly checkpointId?: CheckpointId; + readonly scopeId?: CheckpointScopeId; + readonly runId: RunId; + readonly checkpointTurnCount: number; + readonly checkpointRef: CheckpointRef; + readonly status: "ready" | "missing" | "error" | "stale"; + readonly files: ReadonlyArray<{ + readonly path: string; + readonly kind: string; + readonly additions: number; + readonly deletions: number; + }>; + readonly assistantMessageId: MessageId | null; + readonly completedAt: string; +} + +export interface ThreadPendingApproval { + readonly requestId: RuntimeRequestId; + readonly requestKind: ProviderRequestKind; + readonly createdAt: string; + readonly detail?: string; + readonly responseCapability: "live" | "not_resumable"; +} + +export interface ThreadUserInputQuestion { + readonly id: string; + readonly header: string; + readonly question: string; + readonly options: ReadonlyArray<{ + readonly label: string; + readonly description: string; + }>; + readonly multiSelect: boolean; +} + +export interface ThreadPendingUserInput { + readonly requestId: RuntimeRequestId; + readonly createdAt: string; + readonly questions: ReadonlyArray; + readonly responseCapability: "live" | "not_resumable"; +} + +export type ThreadWorkEntryTone = "thinking" | "tool" | "info" | "error"; +export type ThreadWorkEntryStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped"; + +/** + * Stable parity presentation for a V2 turn item. `structuredPayload` always + * retains the complete source item so generic rendering never loses provider + * or tool data. + */ +export interface ThreadWorkEntry { + readonly id: string; + readonly createdAt: string; + readonly runId: RunId | null; + readonly label: string; + readonly detail?: string; + readonly command?: string; + readonly rawCommand?: string; + readonly changedFiles?: ReadonlyArray; + readonly tone: ThreadWorkEntryTone; + readonly toolTitle?: string; + readonly toolData?: unknown; + readonly itemType: OrchestrationV2TurnItem["type"]; + readonly requestKind?: ProviderRequestKind; + readonly toolLifecycleStatus: ThreadWorkEntryStatus; + readonly structuredPayload: OrchestrationV2TurnItem; +} + +export interface EnvironmentThreadShell { readonly environmentId: EnvironmentId; + readonly id: ThreadId; + readonly projectId: ProjectId; + readonly title: string; + readonly providerInstanceId: ProviderInstanceId; + readonly modelSelection: OrchestrationV2ThreadShell["modelSelection"]; + readonly runtimeMode: OrchestrationV2ThreadShell["runtimeMode"]; + readonly interactionMode: OrchestrationV2ThreadShell["interactionMode"]; + readonly branch: string | null; + readonly worktreePath: string | null; + readonly lineage: OrchestrationV2ThreadShell["lineage"]; + readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"]; + readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"]; + readonly latestRun: ThreadRunSummary | null; + readonly runtime: ThreadRuntimeSummary | null; + readonly latestUserMessageAt: string | null; + readonly hasPendingApprovals: boolean; + readonly hasPendingUserInput: boolean; + readonly hasActionableProposedPlan: boolean; + readonly itemCount: number; + readonly visibleItemCount: number; + readonly createdAt: string; + readonly updatedAt: string; + readonly archivedAt: string | null; + readonly deletedAt: string | null; + readonly source: OrchestrationV2ThreadShell; +} + +export interface EnvironmentThread extends EnvironmentThreadShell { + readonly projection: OrchestrationV2ThreadProjection; + readonly runs: ReadonlyArray; + readonly capabilities: OrchestrationV2ProviderCapabilities | null; + readonly availableActions: { + readonly canSendMessage: boolean; + readonly canInterrupt: boolean; + readonly canRespondToApproval: boolean; + readonly canRespondToUserInput: boolean; + readonly canRollback: boolean; + readonly canArchive: boolean; + readonly canUnarchive: boolean; + readonly canDelete: boolean; + readonly canUpdateSettings: boolean; + }; + readonly messages: ReadonlyArray; + readonly workEntries: ReadonlyArray; + readonly proposedPlans: ReadonlyArray; + readonly todoPlans: ReadonlyArray; + readonly pendingApprovals: ReadonlyArray; + readonly pendingUserInputs: ReadonlyArray; + readonly checkpoints: ReadonlyArray; +} + +function iso(value: DateTime.Utc): string { + return DateTime.formatIso(value); +} + +function nullableIso(value: DateTime.Utc | null): string | null { + return value === null ? null : iso(value); +} + +function terminalRunStatus(status: OrchestrationV2RunStatus): boolean { + return ( + status === "completed" || + status === "interrupted" || + status === "failed" || + status === "cancelled" || + status === "rolled_back" + ); +} + +function workEntryStatus(item: OrchestrationV2TurnItem): ThreadWorkEntryStatus { + switch (item.status) { + case "pending": + case "running": + case "waiting": + return "inProgress"; + case "completed": + return "completed"; + case "failed": + return "failed"; + case "cancelled": + case "interrupted": + return "stopped"; + } +} + +function workEntryTone(item: OrchestrationV2TurnItem): ThreadWorkEntryTone { + if (item.status === "failed") return "error"; + if (item.type === "reasoning") return "thinking"; + switch (item.type) { + case "command_execution": + case "file_change": + case "file_search": + case "web_search": + case "dynamic_tool": + case "subagent": + return "tool"; + default: + return "info"; + } +} + +function summarizeWorkItem(item: OrchestrationV2TurnItem): { + readonly label: string; + readonly detail?: string; + readonly command?: string; + readonly rawCommand?: string; + readonly changedFiles?: ReadonlyArray; + readonly toolTitle?: string; + readonly toolData?: unknown; + readonly requestKind?: ProviderRequestKind; +} { + const title = item.title?.trim() || null; + switch (item.type) { + case "reasoning": + return { label: title ?? "Thinking", ...(item.text ? { detail: item.text } : {}) }; + case "command_execution": + return { + label: title ?? "Ran command", + command: item.input, + rawCommand: item.input, + ...(item.output ? { detail: item.output } : {}), + toolTitle: title ?? "Command", + toolData: item, + }; + case "file_change": + return { + label: title ?? `Changed ${item.fileName}`, + changedFiles: [item.fileName], + ...(item.diffStr ? { detail: item.diffStr } : {}), + toolTitle: title ?? "File change", + toolData: item, + }; + case "file_search": + return { + label: title ?? "Searched files", + ...(item.pattern ? { detail: item.pattern } : {}), + toolTitle: title ?? "File search", + toolData: item, + }; + case "web_search": + return { + label: title ?? "Searched the web", + ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}), + toolTitle: title ?? "Web search", + toolData: item, + }; + case "approval_request": + return { + label: title ?? "Approval requested", + ...(item.prompt ? { detail: item.prompt } : {}), + requestKind: item.requestKind, + toolData: item, + }; + case "user_input_request": + return { + label: title ?? "Input requested", + detail: item.questions.map((question) => question.question).join("\n"), + toolData: item, + }; + case "checkpoint": + return { + label: title ?? "Checkpoint captured", + changedFiles: item.files.map((file) => file.path), + toolData: item, + }; + case "run_interrupt_request": + return { label: title ?? "Interrupt requested", detail: item.message, toolData: item }; + case "run_interrupt_result": + return { label: title ?? "Run interrupted", detail: item.message, toolData: item }; + case "compaction": + return { + label: title ?? "Context compacted", + ...(item.summary ? { detail: item.summary } : {}), + toolData: item, + }; + case "handoff": + return { + label: title ?? "Context handed off", + ...(item.summary ? { detail: item.summary } : {}), + toolData: item, + }; + case "fork": + return { label: title ?? "Thread forked", detail: item.targetThreadId, toolData: item }; + case "subagent": + return { + label: title ?? "Subagent", + detail: item.result ?? item.prompt, + toolTitle: title ?? "Subagent", + toolData: item, + }; + case "dynamic_tool": + return { + label: title ?? item.toolName ?? "Tool call", + toolTitle: title ?? item.toolName ?? "Tool", + toolData: { input: item.input, output: item.output }, + }; + case "user_message": + return { label: title ?? "User message", detail: item.text, toolData: item }; + case "assistant_message": + return { label: title ?? "Assistant message", detail: item.text, toolData: item }; + case "proposed_plan": + return { label: title ?? "Proposed plan", detail: item.markdown, toolData: item }; + case "todo_list": + return { + label: title ?? "Plan updated", + detail: item.steps.map((step) => step.text).join("\n"), + toolData: item, + }; + } +} + +function presentWorkEntries( + projection: OrchestrationV2ThreadProjection, +): ReadonlyArray { + return projection.visibleTurnItems + .filter( + ({ item }) => + item.type !== "user_message" && + item.type !== "assistant_message" && + item.type !== "proposed_plan" && + item.type !== "todo_list", + ) + .map(({ item }) => { + const summary = summarizeWorkItem(item); + return { + id: item.id, + createdAt: iso(item.startedAt ?? item.updatedAt), + runId: item.runId, + ...summary, + tone: workEntryTone(item), + itemType: item.type, + toolLifecycleStatus: workEntryStatus(item), + structuredPayload: item, + } satisfies ThreadWorkEntry; + }); +} + +function presentRuns(projection: OrchestrationV2ThreadProjection): ReadonlyArray { + return projection.runs + .toSorted((left, right) => left.ordinal - right.ordinal) + .map((run) => ({ + runId: run.id, + status: run.status, + requestedAt: iso(run.requestedAt), + startedAt: nullableIso(run.startedAt), + completedAt: nullableIso(run.completedAt), + assistantMessageId: + projection.messages.findLast( + (message) => message.runId === run.id && message.role === "assistant", + )?.id ?? null, + ...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }), + })); +} + +function presentLatestRun(projection: OrchestrationV2ThreadProjection): ThreadRunSummary | null { + return presentRuns(projection).at(-1) ?? null; +} + +function presentRuntime( + shell: OrchestrationV2ThreadShell, + projection?: OrchestrationV2ThreadProjection, +): ThreadRuntimeSummary | null { + const latestRun = projection === undefined ? null : presentLatestRun(projection); + const hasRuntime = shell.latestRunId !== null || shell.activeProviderThreadId !== null; + if (!hasRuntime && latestRun === null) return null; + const providerSession = projection?.providerSessions.findLast( + (session) => session.providerInstanceId === shell.providerInstanceId, + ); + return { + status: latestRun?.status ?? shell.status, + activeRunId: shell.activeRunId, + providerInstanceId: shell.providerInstanceId, + providerName: providerSession?.driver ?? null, + lastError: providerSession?.lastError ?? null, + updatedAt: iso(projection?.updatedAt ?? shell.updatedAt), + }; } export function scopeProject( @@ -29,25 +463,281 @@ export function scopeProject( return { ...project, environmentId }; } -export function scopeThreadShell( +export function presentThreadShell( environmentId: EnvironmentId, - thread: OrchestrationThreadShell, + thread: OrchestrationV2ThreadShell, ): EnvironmentThreadShell { - return { ...thread, environmentId }; + const updatedAt = iso(thread.updatedAt); + const latestRun = + thread.latestRunId === null + ? null + : ({ + runId: thread.latestRunId, + status: thread.status === "idle" ? "completed" : thread.status, + requestedAt: null, + startedAt: null, + completedAt: + thread.status === "idle" || terminalRunStatus(thread.status) ? updatedAt : null, + assistantMessageId: null, + } satisfies ThreadRunSummary); + return { + 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, + lineage: thread.lineage, + forkedFrom: thread.forkedFrom, + activeProviderThreadId: thread.activeProviderThreadId, + latestRun, + runtime: presentRuntime(thread), + latestUserMessageAt: nullableIso(thread.latestUserMessageAt), + hasPendingApprovals: + thread.pendingRuntimeRequest !== null && + thread.pendingRuntimeRequest.kind !== "user_input" && + thread.pendingRuntimeRequest.kind !== "auth_refresh", + hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input", + hasActionableProposedPlan: thread.hasActionableProposedPlan, + itemCount: thread.itemCount, + visibleItemCount: thread.visibleItemCount, + createdAt: iso(thread.createdAt), + updatedAt, + archivedAt: nullableIso(thread.archivedAt), + deletedAt: nullableIso(thread.deletedAt), + source: thread, + }; } -export function scopeThread( +export const scopeThreadShell = presentThreadShell; + +function presentMessages( + projection: OrchestrationV2ThreadProjection, +): ReadonlyArray { + return projection.messages.map((message) => ({ + id: message.id, + role: message.role, + text: message.text, + attachments: message.attachments, + runId: message.runId, + streaming: message.streaming, + createdAt: iso(message.createdAt), + updatedAt: iso(message.updatedAt), + })); +} + +function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string { + const item = projection.turnItems.findLast( + (candidate) => + (candidate.type === "proposed_plan" || candidate.type === "todo_list") && + candidate.planId === planId, + ); + return iso(item?.updatedAt ?? projection.updatedAt); +} + +function presentProposedPlans( + projection: OrchestrationV2ThreadProjection, +): ReadonlyArray { + return projection.plans.flatMap((plan) => { + if (plan.kind !== "proposed_plan") return []; + const updatedAt = planItemTime(projection, plan.id); + return [ + { + id: plan.id, + runId: plan.runId, + planMarkdown: plan.markdown, + status: plan.status, + implementedAt: plan.status === "completed" ? updatedAt : null, + implementationThreadId: null, + createdAt: updatedAt, + updatedAt, + } satisfies ThreadProposedPlan, + ]; + }); +} + +function presentTodoPlans( + projection: OrchestrationV2ThreadProjection, +): ReadonlyArray { + return projection.plans.flatMap((plan) => { + if (plan.kind !== "todo_list") return []; + return [ + { + id: plan.id, + runId: plan.runId, + status: plan.status, + explanation: plan.explanation ?? null, + steps: plan.steps.map((step) => ({ + id: step.id, + step: step.text, + status: step.status === "running" ? "inProgress" : step.status, + })), + updatedAt: planItemTime(projection, plan.id), + } satisfies ThreadTodoPlan, + ]; + }); +} + +function presentPendingRequests(projection: OrchestrationV2ThreadProjection): { + readonly approvals: ReadonlyArray; + readonly userInputs: ReadonlyArray; +} { + const approvals: ThreadPendingApproval[] = []; + const userInputs: ThreadPendingUserInput[] = []; + for (const request of projection.runtimeRequests) { + if (request.status !== "pending") continue; + const responseCapability = request.responseCapability.type; + if (request.kind === "user_input") { + const item = projection.turnItems.findLast( + (candidate) => + candidate.type === "user_input_request" && candidate.requestId === request.id, + ); + if (item === undefined || item.type !== "user_input_request") continue; + userInputs.push({ + requestId: request.id, + createdAt: iso(request.createdAt), + questions: item.questions.map((question) => ({ ...question, multiSelect: false })), + responseCapability, + }); + continue; + } + if (request.kind === "auth_refresh" || request.kind === "dynamic_tool_call") continue; + const item = projection.turnItems.findLast( + (candidate) => candidate.type === "approval_request" && candidate.requestId === request.id, + ); + approvals.push({ + requestId: request.id, + requestKind: request.kind, + createdAt: iso(request.createdAt), + ...(item?.type === "approval_request" && item.prompt ? { detail: item.prompt } : {}), + responseCapability, + }); + } + return { approvals, userInputs }; +} + +function presentCheckpoints( + projection: OrchestrationV2ThreadProjection, +): ReadonlyArray { + return projection.checkpoints.flatMap((checkpoint) => { + if (checkpoint.appRunOrdinal === null || checkpoint.runId === null) return []; + const assistantMessageId = + projection.messages.findLast( + (message) => message.runId === checkpoint.runId && message.role === "assistant", + )?.id ?? null; + return [ + { + checkpointId: checkpoint.id, + scopeId: checkpoint.scopeId, + runId: checkpoint.runId, + checkpointTurnCount: checkpoint.appRunOrdinal, + checkpointRef: checkpoint.ref, + status: checkpoint.status, + files: checkpoint.files, + assistantMessageId, + completedAt: iso(checkpoint.capturedAt), + } satisfies ThreadCheckpointSummary, + ]; + }); +} + +export function presentThread( environmentId: EnvironmentId, - thread: OrchestrationThread, + projection: OrchestrationV2ThreadProjection, ): EnvironmentThread { - return { ...thread, environmentId }; + const shell = presentThreadShell(environmentId, { + ...projection.thread, + latestRunId: + projection.runs.reduce<(typeof projection.runs)[number] | null>( + (latest, candidate) => + latest === null || candidate.ordinal > latest.ordinal ? candidate : latest, + null, + )?.id ?? null, + activeRunId: + projection.runs.findLast( + (run) => run.status === "starting" || run.status === "running" || run.status === "waiting", + )?.id ?? null, + status: presentLatestRun(projection)?.status ?? "idle", + pendingRuntimeRequest: + projection.runtimeRequests.findLast((request) => request.status === "pending") ?? null, + latestVisibleMessage: + projection.messages.length === 0 + ? null + : (() => { + const message = projection.messages.at(-1)!; + return { + id: message.id, + role: message.role, + text: message.text, + updatedAt: message.updatedAt, + }; + })(), + latestUserMessageAt: + projection.messages.findLast((message) => message.role === "user")?.updatedAt ?? null, + hasActionableProposedPlan: projection.plans.some( + (plan) => plan.kind === "proposed_plan" && plan.status === "active", + ), + itemCount: projection.turnItems.length, + visibleItemCount: projection.visibleTurnItems.length, + }); + const requests = presentPendingRequests(projection); + const proposedPlans = presentProposedPlans(projection); + const checkpoints = presentCheckpoints(projection); + const runs = presentRuns(projection); + const capabilities = + projection.providerSessions.findLast( + (session) => session.providerInstanceId === projection.thread.providerInstanceId, + )?.capabilities ?? null; + const active = runs.some((run) => threadRunStatusIsActive(run.status)); + const mutable = projection.thread.archivedAt === null && projection.thread.deletedAt === null; + return { + ...shell, + latestRun: presentLatestRun(projection), + runtime: presentRuntime(shell.source, projection), + hasPendingApprovals: requests.approvals.length > 0, + hasPendingUserInput: requests.userInputs.length > 0, + hasActionableProposedPlan: proposedPlans.some((plan) => plan.status === "active"), + projection, + runs, + capabilities, + availableActions: { + canSendMessage: mutable, + canInterrupt: mutable && active && (capabilities?.turns.supportsInterrupt ?? true), + canRespondToApproval: requests.approvals.some( + (request) => request.responseCapability === "live", + ), + canRespondToUserInput: requests.userInputs.some( + (request) => request.responseCapability === "live", + ), + canRollback: mutable && checkpoints.some((checkpoint) => checkpoint.status === "ready"), + canArchive: projection.thread.archivedAt === null && projection.thread.deletedAt === null, + canUnarchive: projection.thread.archivedAt !== null && projection.thread.deletedAt === null, + canDelete: projection.thread.deletedAt === null, + canUpdateSettings: mutable, + }, + messages: presentMessages(projection), + workEntries: presentWorkEntries(projection), + proposedPlans, + todoPlans: presentTodoPlans(projection), + pendingApprovals: requests.approvals, + pendingUserInputs: requests.userInputs, + checkpoints, + }; } export function selectEnvironmentThreadShell( - snapshot: OrchestrationShellSnapshot | null, + snapshot: OrchestrationV2ShellSnapshot | null, environmentId: EnvironmentId, threadId: ThreadId, ): EnvironmentThreadShell | null { const thread = snapshot?.threads.find((candidate) => candidate.id === threadId) ?? null; - return thread ? scopeThreadShell(environmentId, thread) : null; + return thread ? presentThreadShell(environmentId, thread) : null; +} + +export function providerApprovalDecisionIsFinal(_decision: ProviderApprovalDecision): boolean { + return true; } diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index 66cba9d215..a8975e9282 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -1,4 +1,4 @@ -import { ORCHESTRATION_V2_WS_METHODS, ORCHESTRATION_WS_METHODS } from "@t3tools/contracts"; +import { ORCHESTRATION_V2_WS_METHODS } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; import { @@ -35,15 +35,15 @@ export function createOrchestrationEnvironmentAtoms( }, turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:turn-diff", - tag: ORCHESTRATION_WS_METHODS.getTurnDiff, + tag: ORCHESTRATION_V2_WS_METHODS.getTurnDiff, }), fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:full-thread-diff", - tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff, + tag: ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff, }), archivedShellSnapshot: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:archived-shell-snapshot", - tag: ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, + tag: ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot, }), }; } diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts index 839a4480d4..9b56b194ca 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.test.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.test.ts @@ -1,10 +1,15 @@ import { describe, expect, it } from "vite-plus/test"; import { type OrchestrationV2DomainEvent, + type OrchestrationV2Run, type OrchestrationV2ThreadProjection, + type OrchestrationV2TurnItem, + MessageId, ProjectId, ProviderInstanceId, + RunId, ThreadId, + TurnItemId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; @@ -12,6 +17,47 @@ import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); const threadId = ThreadId.make("thread-reducer"); +const runId = RunId.make("run-reducer"); +const run = { + id: runId, + threadId, + ordinal: 1, + providerInstanceId: ProviderInstanceId.make("codex"), + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + providerThreadId: null, + userMessageId: MessageId.make("message-reducer"), + rootNodeId: null, + activeAttemptId: null, + status: "completed", + requestedAt: now, + startedAt: now, + completedAt: now, + checkpointId: null, + contextHandoffId: null, +} satisfies OrchestrationV2Run; + +function commandItem(id: string, output = "done"): OrchestrationV2TurnItem { + return { + id: TurnItemId.make(id), + threadId, + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "completed", + title: null, + startedAt: now, + completedAt: now, + updatedAt: now, + type: "command_execution", + input: "pwd", + output, + exitCode: 0, + }; +} const emptyProjection = { thread: { id: threadId, @@ -79,4 +125,112 @@ describe("applyOrchestrationV2ProjectionEvent", () => { expect(applyOrchestrationV2ProjectionEvent(emptyProjection, event)).toBe(emptyProjection); }); + + it("preserves visible row identity when run updates do not change membership", () => { + const item = commandItem("item-stable"); + const visibleTurnItems = [ + { + position: 0, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: item.id, + item, + }, + ]; + const projection = { + ...emptyProjection, + runs: [run], + turnItems: [item], + visibleTurnItems, + }; + const event = { + id: "event-run-update", + type: "run.updated", + threadId, + runId, + occurredAt: now, + payload: { ...run, status: "completed" }, + } as OrchestrationV2DomainEvent; + + const next = applyOrchestrationV2ProjectionEvent(projection, event); + expect(next?.visibleTurnItems).toBe(visibleTurnItems); + expect(next?.visibleTurnItems[0]).toBe(visibleTurnItems[0]); + }); + + it("replaces only the updated visible item when membership is unchanged", () => { + const first = commandItem("item-first", "first"); + const second = commandItem("item-second", "second"); + const firstRow = { + position: 0, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: first.id, + item: first, + }; + const secondRow = { + position: 1, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: second.id, + item: second, + }; + const updated = commandItem("item-first", "streamed output"); + const projection = { + ...emptyProjection, + runs: [run], + turnItems: [first, second], + visibleTurnItems: [firstRow, secondRow], + }; + const event = { + id: "event-item-update", + type: "turn-item.updated", + threadId, + runId, + occurredAt: now, + payload: updated, + } as OrchestrationV2DomainEvent; + + const next = applyOrchestrationV2ProjectionEvent(projection, event); + expect(next?.visibleTurnItems).not.toBe(projection.visibleTurnItems); + expect(next?.visibleTurnItems[0]).not.toBe(firstRow); + expect(next?.visibleTurnItems[0]?.item).toBe(updated); + expect(next?.visibleTurnItems[1]).toBe(secondRow); + }); + + it("removes only hidden local items while preserving inherited rows", () => { + const inherited = commandItem("item-inherited"); + const local = commandItem("item-local"); + const inheritedRow = { + position: 0, + visibility: "inherited" as const, + sourceThreadId: ThreadId.make("thread-source"), + sourceItemId: inherited.id, + item: inherited, + }; + const localRow = { + position: 1, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: local.id, + item: local, + }; + const projection = { + ...emptyProjection, + runs: [run], + turnItems: [local], + visibleTurnItems: [inheritedRow, localRow], + }; + const event = { + id: "event-run-rollback", + type: "run.updated", + threadId, + runId, + occurredAt: now, + payload: { ...run, status: "rolled_back" }, + } as OrchestrationV2DomainEvent; + + const next = applyOrchestrationV2ProjectionEvent(projection, event); + expect(next?.visibleTurnItems).toEqual([inheritedRow]); + expect(next?.visibleTurnItems[0]).toBe(inheritedRow); + }); }); diff --git a/packages/client-runtime/src/state/orchestrationV2Projection.ts b/packages/client-runtime/src/state/orchestrationV2Projection.ts index 7d5b6230c2..c8b7335e6b 100644 --- a/packages/client-runtime/src/state/orchestrationV2Projection.ts +++ b/packages/client-runtime/src/state/orchestrationV2Projection.ts @@ -20,9 +20,15 @@ function removeVisibleItem( rows: OrchestrationV2ThreadProjection["visibleTurnItems"], sourceItemId: OrchestrationV2TurnItem["id"], ): OrchestrationV2ThreadProjection["visibleTurnItems"] { - return rows - .filter((row) => row.sourceItemId !== sourceItemId) - .map((row, position) => ({ ...row, position })); + const index = rows.findIndex((row) => row.sourceItemId === sourceItemId); + if (index === -1) return rows; + return renumberVisibleItems([...rows.slice(0, index), ...rows.slice(index + 1)]); +} + +function renumberVisibleItems( + rows: OrchestrationV2ThreadProjection["visibleTurnItems"], +): OrchestrationV2ThreadProjection["visibleTurnItems"] { + return rows.map((row, position) => (row.position === position ? row : { ...row, position })); } function shouldShowLocalTurnItem( @@ -39,9 +45,18 @@ function shouldShowLocalTurnItem( function activeVisibleTurnItems( projection: OrchestrationV2ThreadProjection, ): OrchestrationV2ThreadProjection["visibleTurnItems"] { - return projection.visibleTurnItems - .filter((row) => row.visibility !== "local" || shouldShowLocalTurnItem(projection, row.item)) - .map((row, position) => ({ ...row, position })); + const rows = projection.visibleTurnItems; + let next: Array<(typeof rows)[number]> | null = null; + for (let index = 0; index < rows.length; index += 1) { + const row = rows[index]!; + const keep = row.visibility !== "local" || shouldShowLocalTurnItem(projection, row.item); + if (!keep) { + next ??= rows.slice(0, index); + continue; + } + next?.push(row); + } + return next === null ? rows : renumberVisibleItems(next); } function upsertVisibleTurnItem( @@ -57,9 +72,19 @@ function upsertVisibleTurnItem( sourceItemId: item.id, item, }; - return index === -1 - ? [...rows, next] - : rows.map((row, rowIndex) => (rowIndex === index ? next : row)); + if (index === -1) return [...rows, next]; + const previous = rows[index]!; + if ( + previous.visibility === next.visibility && + previous.sourceThreadId === next.sourceThreadId && + previous.sourceItemId === next.sourceItemId && + previous.item === item + ) { + return rows; + } + const updated = [...rows]; + updated[index] = next; + return updated; } /** Applies one committed event to a matching thread projection. */ diff --git a/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts b/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts new file mode 100644 index 0000000000..b2f902978f --- /dev/null +++ b/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts @@ -0,0 +1,104 @@ +import { + ProjectId, + ProviderInstanceId, + ThreadId, + type OrchestrationProjectShell, + type OrchestrationV2ShellSnapshot, + type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; + +export const v2Now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z"); +export const v2ProjectId = ProjectId.make("project-v2"); +export const v2ThreadId = ThreadId.make("thread-v2"); +export const v2ProviderInstanceId = ProviderInstanceId.make("codex"); + +export const v2Project: OrchestrationProjectShell = { + id: v2ProjectId, + title: "Project", + workspaceRoot: "/workspace/project", + repositoryIdentity: null, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-06-20T00:00:00.000Z", + updatedAt: "2026-06-20T00:00:00.000Z", +}; + +export const v2ThreadShell: OrchestrationV2ThreadShell = { + id: v2ThreadId, + projectId: v2ProjectId, + title: "Thread", + providerInstanceId: v2ProviderInstanceId, + modelSelection: { instanceId: v2ProviderInstanceId, model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { rootThreadId: v2ThreadId, parentThreadId: null, relationshipToParent: null }, + forkedFrom: null, + createdBy: "user", + creationSource: "web", + latestRunId: null, + activeRunId: null, + status: "idle", + pendingRuntimeRequest: null, + latestVisibleMessage: null, + latestUserMessageAt: null, + hasActionableProposedPlan: false, + itemCount: 0, + visibleItemCount: 0, + createdAt: v2Now, + updatedAt: v2Now, + archivedAt: null, + deletedAt: null, +}; + +export const v2Projection: OrchestrationV2ThreadProjection = { + thread: { + id: v2ThreadShell.id, + projectId: v2ThreadShell.projectId, + title: v2ThreadShell.title, + providerInstanceId: v2ThreadShell.providerInstanceId, + modelSelection: v2ThreadShell.modelSelection, + runtimeMode: v2ThreadShell.runtimeMode, + interactionMode: v2ThreadShell.interactionMode, + branch: v2ThreadShell.branch, + worktreePath: v2ThreadShell.worktreePath, + activeProviderThreadId: v2ThreadShell.activeProviderThreadId, + lineage: v2ThreadShell.lineage, + forkedFrom: v2ThreadShell.forkedFrom, + createdBy: v2ThreadShell.createdBy, + creationSource: v2ThreadShell.creationSource, + createdAt: v2Now, + updatedAt: v2Now, + archivedAt: null, + deletedAt: null, + }, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: [], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt: v2Now, +}; + +export const v2ShellSnapshot: OrchestrationV2ShellSnapshot = { + schemaVersion: 1, + snapshotSequence: 0, + projects: [v2Project], + threads: [v2ThreadShell], + archivedThreads: [], +}; diff --git a/packages/client-runtime/src/state/projectEntities.ts b/packages/client-runtime/src/state/projectEntities.ts index 4d51b4d427..ca440b07d2 100644 --- a/packages/client-runtime/src/state/projectEntities.ts +++ b/packages/client-runtime/src/state/projectEntities.ts @@ -1,7 +1,7 @@ import type { EnvironmentId, OrchestrationProjectShell, - OrchestrationShellSnapshot, + OrchestrationV2ShellSnapshot, ProjectId, ScopedProjectRef, } from "@t3tools/contracts"; @@ -19,7 +19,7 @@ export function createEnvironmentProjectAtoms(input: { readonly catalogValueAtom: Atom.Atom; readonly snapshotAtom: ( environmentId: EnvironmentId, - ) => Atom.Atom; + ) => Atom.Atom; }) { const environmentProjectsAtom = Atom.family((environmentId: EnvironmentId) => Atom.make( diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.ts index 2eab721422..350390b482 100644 --- a/packages/client-runtime/src/state/shell-sync.test.ts +++ b/packages/client-runtime/src/state/shell-sync.test.ts @@ -1,8 +1,8 @@ import { EnvironmentId, - ORCHESTRATION_WS_METHODS, - type OrchestrationShellSnapshot, - type OrchestrationShellStreamItem, + ORCHESTRATION_V2_WS_METHODS, + type OrchestrationV2ShellSnapshot, + type OrchestrationV2ShellStreamItem, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -21,6 +21,7 @@ import * as Persistence from "../platform/persistence.ts"; import * as RpcSession from "../rpc/session.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import { makeEnvironmentShellState } from "./shell.ts"; +import { v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts"; const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), @@ -29,11 +30,9 @@ const TARGET = new PrimaryConnectionTarget({ wsBaseUrl: "wss://environment.example.test", }); -const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = { +const LIVE_SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = { + ...v2ShellSnapshot, snapshotSequence: 1, - projects: [], - threads: [], - updatedAt: "2026-06-06T00:00:00.000Z", }; function session(client: WsRpcProtocolClient): RpcSession.RpcSession { @@ -49,9 +48,9 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession { describe("environment shell synchronization", () => { it.effect("publishes live state before persistence and preserves it when ready", () => Effect.gen(function* () { - const events = yield* Queue.unbounded(); + const events = yield* Queue.unbounded(); const client = { - [ORCHESTRATION_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events), + [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: () => Stream.fromQueue(events), } as unknown as WsRpcProtocolClient; const supervisorState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE); const activeSession = yield* SubscriptionRef.make>( diff --git a/packages/client-runtime/src/state/shell.test.ts b/packages/client-runtime/src/state/shell.test.ts index f1326e0a5c..90ee256c8e 100644 --- a/packages/client-runtime/src/state/shell.test.ts +++ b/packages/client-runtime/src/state/shell.test.ts @@ -2,11 +2,13 @@ import type { ServerConfig } from "@t3tools/contracts"; import { EnvironmentId } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Option from "effect/Option"; +import * as DateTime from "effect/DateTime"; import { Atom, AtomRegistry } from "effect/unstable/reactivity"; import { PrimaryConnectionTarget } from "../connection/model.ts"; import type { EnvironmentShellState } from "./shell.ts"; import { createEnvironmentServerConfigsAtom, createEnvironmentShellSummaryAtom } from "./shell.ts"; +import { v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; const ENVIRONMENT_ID = EnvironmentId.make("environment-1"); const OTHER_ENVIRONMENT_ID = EnvironmentId.make("environment-2"); @@ -34,10 +36,16 @@ function shellState(input: { input.updatedAt === undefined ? Option.none() : Option.some({ + schemaVersion: 1, snapshotSequence: input.snapshotSequence ?? 1, - updatedAt: input.updatedAt, projects: [], - threads: [], + threads: [ + { + ...v2ThreadShell, + updatedAt: DateTime.makeUnsafe(input.updatedAt), + }, + ], + archivedThreads: [], }), status: input.status, error: input.error === undefined ? Option.none() : Option.some(input.error), diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 2b0ba6346f..86021a10a9 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -1,11 +1,12 @@ import { - ORCHESTRATION_WS_METHODS, + ORCHESTRATION_V2_WS_METHODS, type EnvironmentId, - type OrchestrationShellSnapshot, - type OrchestrationShellStreamItem, + type OrchestrationV2ShellSnapshot, + type OrchestrationV2ShellStreamItem, type ServerConfig, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; @@ -26,7 +27,7 @@ import { followStreamInEnvironment } from "./runtime.ts"; export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live"; export interface EnvironmentShellState { - readonly snapshot: Option.Option; + readonly snapshot: Option.Option; readonly status: EnvironmentShellStatus; readonly error: Option.Option; } @@ -38,7 +39,7 @@ const EMPTY_SHELL_STATE: EnvironmentShellState = { }; function shellStatusForSnapshot( - snapshot: Option.Option, + snapshot: Option.Option, ): EnvironmentShellStatus { return Option.isSome(snapshot) ? "cached" : "empty"; } @@ -56,7 +57,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") environmentId, ...safeErrorLogAttributes(error), }), - Effect.as(Option.none()), + Effect.as(Option.none()), ), ), ); @@ -65,10 +66,10 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") status: shellStatusForSnapshot(cachedSnapshot), error: Option.none(), }); - const persistence = yield* Queue.sliding(1); + const persistence = yield* Queue.sliding(1); const persist = Effect.fn("EnvironmentShellState.persist")(function* ( - snapshot: OrchestrationShellSnapshot, + snapshot: OrchestrationV2ShellSnapshot, ) { yield* cache.saveShell(environmentId, snapshot).pipe( Effect.catch((error) => @@ -122,7 +123,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") ); const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* ( - item: OrchestrationShellStreamItem, + item: OrchestrationV2ShellStreamItem, ) { const current = yield* SubscriptionRef.get(state); const nextSnapshot = @@ -148,7 +149,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") }); yield* subscribe( - ORCHESTRATION_WS_METHODS.subscribeShell, + ORCHESTRATION_V2_WS_METHODS.subscribeShell, {}, { onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)), @@ -249,8 +250,20 @@ export function createEnvironmentShellSummaryAtom(input: { continue; } hasSnapshot = true; - const updatedAt = state.snapshot.value.updatedAt; - if (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) { + const snapshot = state.snapshot.value; + const updatedAt = snapshot.threads.concat(snapshot.archivedThreads).reduce( + (latest, thread) => { + const value = DateTime.formatIso(thread.updatedAt); + return latest === null || value > latest ? value : latest; + }, + snapshot.projects.reduce((latest, project) => { + return latest === null || project.updatedAt > latest ? project.updatedAt : latest; + }, null), + ); + if ( + updatedAt !== null && + (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) + ) { latestSnapshotUpdatedAt = updatedAt; } } diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.ts index a069460e63..80a68c21ad 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -1,183 +1,84 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; -import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts"; - +import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts"; import { applyShellStreamEvent } from "./shellReducer.ts"; -const baseSnapshot: OrchestrationShellSnapshot = { - snapshotSequence: 0, - projects: [], - threads: [], - updatedAt: "2026-04-01T00:00:00.000Z", -}; - -const stubProject = { - id: ProjectId.make("project-1"), - title: "Test Project", - workspaceRoot: "/workspace/test", - repositoryIdentity: null, - defaultModelSelection: null, - scripts: [], - createdAt: "2026-04-01T00:00:00.000Z", - updatedAt: "2026-04-01T00:00:00.000Z", -} as const; - -const stubThread = { - id: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-1"), - title: "Test Thread", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, - runtimeMode: "full-access" as const, - interactionMode: "default" as const, - branch: null, - worktreePath: null, - latestTurn: null, - createdAt: "2026-04-01T00:00:00.000Z", - updatedAt: "2026-04-01T00:00:00.000Z", - archivedAt: null, - latestUserMessageAt: null, - hasPendingApprovals: false, - hasPendingUserInput: false, - hasActionableProposedPlan: false, - session: null, -} as const; - describe("applyShellStreamEvent", () => { - it("ignores stale project upserts without mutating the snapshot", () => { - const snapshotWithProject: OrchestrationShellSnapshot = { - ...baseSnapshot, + it("ignores stale project updates without mutating the snapshot", () => { + const snapshotWithProject = { + ...v2ShellSnapshot, snapshotSequence: 4, - projects: [stubProject], + projects: [v2Project], }; for (const sequence of [3, 4]) { const next = applyShellStreamEvent(snapshotWithProject, { - kind: "project-upserted", + kind: "project.updated", sequence, - project: { ...stubProject, title: "Stale Title" }, + project: { ...v2Project, title: "Stale Title" }, }); expect(next).toBe(snapshotWithProject); expect(next.snapshotSequence).toBe(4); - expect(next.projects[0]?.title).toBe("Test Project"); + expect(next.projects[0]?.title).toBe(v2Project.title); } }); - describe("project-upserted", () => { - it("adds a new project", () => { - const event: OrchestrationShellStreamEvent = { - kind: "project-upserted", - sequence: 1, - project: stubProject, - }; - - const next = applyShellStreamEvent(baseSnapshot, event); - - expect(next.projects).toHaveLength(1); - expect(next.projects[0]?.id).toBe("project-1"); - expect(next.snapshotSequence).toBe(1); + it("applies project updates and removals", () => { + const updated = applyShellStreamEvent(v2ShellSnapshot, { + kind: "project.updated", + sequence: 1, + project: { ...v2Project, title: "Updated" }, }); + expect(updated.projects[0]?.title).toBe("Updated"); + expect(updated.snapshotSequence).toBe(1); - it("updates an existing project", () => { - const snapshotWithProject: OrchestrationShellSnapshot = { - ...baseSnapshot, - projects: [stubProject], - }; - - const updatedProject = { ...stubProject, title: "Updated Title" }; - const event: OrchestrationShellStreamEvent = { - kind: "project-upserted", - sequence: 2, - project: updatedProject, - }; - - const next = applyShellStreamEvent(snapshotWithProject, event); - - expect(next.projects).toHaveLength(1); - expect(next.projects[0]?.title).toBe("Updated Title"); - expect(next.snapshotSequence).toBe(2); + const removed = applyShellStreamEvent(updated, { + kind: "project.removed", + sequence: 2, + projectId: ProjectId.make(v2Project.id), }); + expect(removed.projects).toEqual([]); }); - describe("project-removed", () => { - it("removes a project by id", () => { - const snapshotWithProject: OrchestrationShellSnapshot = { - ...baseSnapshot, - projects: [stubProject], - }; - - const event: OrchestrationShellStreamEvent = { - kind: "project-removed", - sequence: 3, - projectId: ProjectId.make("project-1"), - }; - - const next = applyShellStreamEvent(snapshotWithProject, event); - - expect(next.projects).toHaveLength(0); - expect(next.snapshotSequence).toBe(3); + it("moves a thread between active and archive without duplicating it", () => { + const archived = applyShellStreamEvent(v2ShellSnapshot, { + kind: "thread.updated", + sequence: 3, + location: "archive", + thread: { ...v2ThreadShell, archivedAt: v2ThreadShell.updatedAt }, }); + expect(archived.threads).toEqual([]); + expect(archived.archivedThreads).toHaveLength(1); + + const active = applyShellStreamEvent(archived, { + kind: "thread.updated", + sequence: 4, + location: "active", + thread: v2ThreadShell, + }); + expect(active.threads).toHaveLength(1); + expect(active.archivedThreads).toEqual([]); }); - describe("thread-upserted", () => { - it("adds a new thread", () => { - const event: OrchestrationShellStreamEvent = { - kind: "thread-upserted", - sequence: 4, - thread: stubThread, - }; - - const next = applyShellStreamEvent(baseSnapshot, event); - - expect(next.threads).toHaveLength(1); - expect(next.threads[0]?.id).toBe("thread-1"); - expect(next.snapshotSequence).toBe(4); - }); - - it("updates an existing thread", () => { - const snapshotWithThread: OrchestrationShellSnapshot = { - ...baseSnapshot, - threads: [stubThread], - }; - - const updatedThread = { ...stubThread, title: "Updated Thread" }; - const event: OrchestrationShellStreamEvent = { - kind: "thread-upserted", - sequence: 5, - thread: updatedThread, - }; - - const next = applyShellStreamEvent(snapshotWithThread, event); - - expect(next.threads).toHaveLength(1); - expect(next.threads[0]?.title).toBe("Updated Thread"); + it("removes a thread from either collection", () => { + const next = applyShellStreamEvent(v2ShellSnapshot, { + kind: "thread.removed", + sequence: 5, + location: "active", + threadId: ThreadId.make(v2ThreadShell.id), }); + expect(next.threads).toEqual([]); + expect(next.snapshotSequence).toBe(5); }); - describe("thread-removed", () => { - it("removes a thread by id", () => { - const snapshotWithThread: OrchestrationShellSnapshot = { - ...baseSnapshot, - threads: [stubThread], - }; + it("leaves unknown future events unchanged", () => { + const next = applyShellStreamEvent( + v2ShellSnapshot, + { kind: "future.event", sequence: 99 } as never, + ); - const event: OrchestrationShellStreamEvent = { - kind: "thread-removed", - sequence: 6, - threadId: ThreadId.make("thread-1"), - }; - - const next = applyShellStreamEvent(snapshotWithThread, event); - - expect(next.threads).toHaveLength(0); - expect(next.snapshotSequence).toBe(6); - }); - }); - - it("returns original snapshot for unrecognized event kinds", () => { - const unknownEvent = { kind: "unknown-future-event", sequence: 99 } as any; - const next = applyShellStreamEvent(baseSnapshot, unknownEvent); - expect(next).toBe(baseSnapshot); + expect(next).toBe(v2ShellSnapshot); }); }); diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.ts index 3d3b22a128..3e18a9ed89 100644 --- a/packages/client-runtime/src/state/shellReducer.ts +++ b/packages/client-runtime/src/state/shellReducer.ts @@ -1,43 +1,58 @@ -import * as Arr from "effect/Array"; -import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts"; +import type { + OrchestrationV2ShellSnapshot, + OrchestrationV2ShellStreamItem, +} from "@t3tools/contracts"; -/** - * Reduce a single shell stream event into an existing snapshot, returning a new - * snapshot with the event's changes applied. This is a pure reducer that both - * web and mobile can use to keep their local shell snapshot in sync. - * - * Returns the original snapshot reference unchanged if the event is not - * recognized (forward-compatible). - */ +function upsertById( + items: ReadonlyArray, + item: T, +): ReadonlyArray { + const index = items.findIndex((candidate) => candidate.id === item.id); + if (index === -1) return [...items, item]; + return items.map((candidate, candidateIndex) => (candidateIndex === index ? item : candidate)); +} + +/** Applies one committed V2 shell delta while preserving active/archive exclusivity. */ export function applyShellStreamEvent( - snapshot: OrchestrationShellSnapshot, - event: OrchestrationShellStreamEvent, -): OrchestrationShellSnapshot { + snapshot: OrchestrationV2ShellSnapshot, + event: Exclude, +): OrchestrationV2ShellSnapshot { if (event.sequence <= snapshot.snapshotSequence) return snapshot; switch (event.kind) { - case "project-upserted": { - const projects = snapshot.projects.some((p) => p.id === event.project.id) - ? Arr.map(snapshot.projects, (p) => (p.id === event.project.id ? event.project : p)) - : Arr.append(snapshot.projects, event.project); - return { ...snapshot, projects, snapshotSequence: event.sequence }; - } - case "project-removed": + case "project.updated": return { ...snapshot, - projects: Arr.filter(snapshot.projects, (p) => p.id !== event.projectId), + projects: upsertById(snapshot.projects, event.project), snapshotSequence: event.sequence, }; - case "thread-upserted": { - const threads = snapshot.threads.some((t) => t.id === event.thread.id) - ? Arr.map(snapshot.threads, (t) => (t.id === event.thread.id ? event.thread : t)) - : Arr.append(snapshot.threads, event.thread); - return { ...snapshot, threads, snapshotSequence: event.sequence }; - } - case "thread-removed": + case "project.removed": return { ...snapshot, - threads: Arr.filter(snapshot.threads, (t) => t.id !== event.threadId), + projects: snapshot.projects.filter((project) => project.id !== event.projectId), + snapshotSequence: event.sequence, + }; + case "thread.updated": { + const withoutThread = (threads: OrchestrationV2ShellSnapshot["threads"]) => + threads.filter((thread) => thread.id !== event.thread.id); + return { + ...snapshot, + threads: + event.location === "active" + ? upsertById(withoutThread(snapshot.threads), event.thread) + : withoutThread(snapshot.threads), + archivedThreads: + event.location === "archive" + ? upsertById(withoutThread(snapshot.archivedThreads), event.thread) + : withoutThread(snapshot.archivedThreads), + snapshotSequence: event.sequence, + }; + } + case "thread.removed": + return { + ...snapshot, + threads: snapshot.threads.filter((thread) => thread.id !== event.threadId), + archivedThreads: snapshot.archivedThreads.filter((thread) => thread.id !== event.threadId), snapshotSequence: event.sequence, }; default: diff --git a/packages/client-runtime/src/state/snapshots.ts b/packages/client-runtime/src/state/snapshots.ts index 0000dcb12c..f265fb3c47 100644 --- a/packages/client-runtime/src/state/snapshots.ts +++ b/packages/client-runtime/src/state/snapshots.ts @@ -1,4 +1,4 @@ -import type { EnvironmentId, OrchestrationShellSnapshot } from "@t3tools/contracts"; +import type { EnvironmentId, OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/unstable/reactivity"; @@ -10,7 +10,7 @@ export function createEnvironmentSnapshotAtom( ) => Atom.Atom>, ) { return Atom.family((environmentId: EnvironmentId) => - Atom.make((get): OrchestrationShellSnapshot | null => + Atom.make((get): OrchestrationV2ShellSnapshot | null => Option.match(AsyncResult.value(get(shellStateAtom(environmentId))), { onNone: () => null, onSome: (state) => Option.getOrNull(state.snapshot), diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index aab5110e9c..b164308b52 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -44,6 +44,7 @@ export type { SetThreadRuntimeModeInput, StartThreadTurnInput, StopThreadSessionInput, + ThreadCommandInput, UnarchiveThreadInput, UpdateThreadMetadataInput, } from "../operations/commands.ts"; diff --git a/packages/client-runtime/src/state/threadDetail.test.ts b/packages/client-runtime/src/state/threadDetail.test.ts new file mode 100644 index 0000000000..c235263609 --- /dev/null +++ b/packages/client-runtime/src/state/threadDetail.test.ts @@ -0,0 +1,45 @@ +import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity"; +import { describe, expect, it } from "vite-plus/test"; + +import { v2Projection } from "./orchestrationV2TestFixtures.ts"; +import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts"; +import type { EnvironmentThreadState } from "./threads.ts"; + +const ref: ScopedThreadRef = { + environmentId: EnvironmentId.make("environment-detail"), + threadId: ThreadId.make(v2Projection.thread.id), +}; + +describe("createEnvironmentThreadDetailAtoms", () => { + it("adds environment scope while preserving the pristine projection", () => { + const initial: AsyncResult.AsyncResult = AsyncResult.success({ + data: Option.some(v2Projection), + status: "cached", + error: Option.none(), + }); + const sourceAtom = Atom.make(initial); + const details = createEnvironmentThreadDetailAtoms(() => sourceAtom); + const registry = AtomRegistry.make(); + + const thread = registry.get(details.threadAtom(ref)); + expect(thread).toEqual({ environmentId: ref.environmentId, projection: v2Projection }); + expect(thread?.projection).toBe(v2Projection); + expect(registry.get(details.visibleTurnItemsAtom(ref))).toBe(v2Projection.visibleTurnItems); + expect(registry.get(details.statusAtom(ref))).toBe("cached"); + + registry.set( + sourceAtom, + AsyncResult.success({ + data: Option.some(v2Projection), + status: "synchronizing", + error: Option.none(), + }), + ); + + expect(registry.get(details.threadAtom(ref))).toBe(thread); + expect(registry.get(details.statusAtom(ref))).toBe("synchronizing"); + registry.dispose(); + }); +}); diff --git a/packages/client-runtime/src/state/threadDetail.ts b/packages/client-runtime/src/state/threadDetail.ts index f048573c2e..a54b4469c1 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -1,63 +1,48 @@ -import type { - OrchestrationCheckpointSummary, - OrchestrationLatestTurn, - OrchestrationMessage, - OrchestrationProposedPlan, - OrchestrationSession, - OrchestrationThread, - OrchestrationThreadActivity, - ScopedThreadRef, -} from "@t3tools/contracts"; +import type { OrchestrationV2ThreadProjection, ScopedThreadRef } from "@t3tools/contracts"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/unstable/reactivity"; -import type { EnvironmentThread, EnvironmentThreadShell } from "./models.ts"; -import { scopeThread } from "./models.ts"; +import type { + EnvironmentThread, + EnvironmentThreadShell, + ThreadCheckpointSummary, + ThreadConversationMessage, + ThreadPendingApproval, + ThreadPendingUserInput, + ThreadProposedPlan, + ThreadRunSummary, + ThreadRuntimeSummary, + ScopedThreadProjection, + ThreadWorkEntry, +} from "./models.ts"; +import { presentThread } from "./models.ts"; import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts"; -const EMPTY_MESSAGES: ReadonlyArray = Object.freeze([]); -const EMPTY_ACTIVITIES: ReadonlyArray = Object.freeze([]); -const EMPTY_PROPOSED_PLANS: ReadonlyArray = Object.freeze([]); -const EMPTY_CHECKPOINTS: ReadonlyArray = Object.freeze([]); +const EMPTY_MESSAGES: ReadonlyArray = Object.freeze([]); +const EMPTY_WORK_ENTRIES: ReadonlyArray = Object.freeze([]); +const EMPTY_PROPOSED_PLANS: ReadonlyArray = Object.freeze([]); +const EMPTY_CHECKPOINTS: ReadonlyArray = Object.freeze([]); +const EMPTY_APPROVALS: ReadonlyArray = Object.freeze([]); +const EMPTY_USER_INPUTS: ReadonlyArray = Object.freeze([]); +const EMPTY_VISIBLE_TURN_ITEMS: OrchestrationV2ThreadProjection["visibleTurnItems"] = Object.freeze( + [], +); -/** - * Combine detail-only collections with the shell's authoritative thread metadata. - * - * Shell and detail subscriptions are intentionally independent. A cached detail can - * therefore briefly outlive a newer shell snapshot after reconnecting. Workspace - * consumers must use the shell branch/worktree/project fields so they do not target - * a stale checkout while retaining messages, activities, plans, and checkpoints - * from the detail subscription. - */ +/** Shell metadata wins over an independently cached detail projection. */ export function mergeEnvironmentThread( detail: EnvironmentThread | null, shell: EnvironmentThreadShell | null, ): EnvironmentThread | null { - if (detail === null || shell === null) { - return detail; - } - if (detail.environmentId !== shell.environmentId || detail.id !== shell.id) { - return detail; - } - + if (detail === null || shell === null) return detail; + if (detail.environmentId !== shell.environmentId || detail.id !== shell.id) return detail; return { ...detail, - environmentId: shell.environmentId, - id: shell.id, - projectId: shell.projectId, - title: shell.title, - modelSelection: shell.modelSelection, - runtimeMode: shell.runtimeMode, - interactionMode: shell.interactionMode, - branch: shell.branch, - worktreePath: shell.worktreePath, - latestTurn: shell.latestTurn, - createdAt: shell.createdAt, - updatedAt: shell.updatedAt, - archivedAt: shell.archivedAt, - session: shell.session, + ...shell, + latestRun: detail.latestRun, + runtime: detail.runtime, + source: shell.source, }; } @@ -82,15 +67,13 @@ export function createEnvironmentThreadDetailAtoms( const threadDetailAtomFamily = Atom.family((key: string) => { const ref = parseThreadKey(key); - let previousSource: OrchestrationThread | null = null; + let previousSource: OrchestrationV2ThreadProjection | null = null; let previousValue: EnvironmentThread | null = null; return Atom.make((get) => { const source = Option.getOrNull(get(threadStateValueAtomFamily(key)).data); - if (source === previousSource) { - return previousValue; - } + if (source === previousSource) return previousValue; previousSource = source; - previousValue = source === null ? null : scopeThread(ref.environmentId, source); + previousValue = source === null ? null : presentThread(ref.environmentId, source); return previousValue; }).pipe( Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), @@ -98,88 +81,96 @@ export function createEnvironmentThreadDetailAtoms( ); }); - const threadStatusAtomFamily = Atom.family((key: string) => + const scopedThreadProjectionAtomFamily = Atom.family((key: string) => { + const ref = parseThreadKey(key); + let previousProjection: OrchestrationV2ThreadProjection | null = null; + let previousValue: ScopedThreadProjection | null = null; + return Atom.make((get) => { + const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data); + if (projection === previousProjection) return previousValue; + previousProjection = projection; + previousValue = projection === null ? null : { environmentId: ref.environmentId, projection }; + return previousValue; + }).pipe( + Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), + Atom.withLabel(`scoped-thread-projection:${key}`), + ); + }); + + const visibleTurnItemsAtomFamily = Atom.family((key: string) => + Atom.make( + (get): OrchestrationV2ThreadProjection["visibleTurnItems"] => + Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.visibleTurnItems ?? + EMPTY_VISIBLE_TURN_ITEMS, + ).pipe( + Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), + Atom.withLabel(`environment-thread-visible-turn-items:${key}`), + ), + ); + + const family = (label: string, select: (thread: EnvironmentThread) => A, empty: A) => + Atom.family((key: string) => + Atom.make((get): A => { + const thread = get(threadDetailAtomFamily(key)); + return thread === null ? empty : select(thread); + }).pipe( + Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), + Atom.withLabel(`environment-thread-${label}:${key}`), + ), + ); + + const messages = family("messages", (thread) => thread.messages, EMPTY_MESSAGES); + const workEntries = family("work-entries", (thread) => thread.workEntries, EMPTY_WORK_ENTRIES); + const proposedPlans = family( + "proposed-plans", + (thread) => thread.proposedPlans, + EMPTY_PROPOSED_PLANS, + ); + const checkpoints = family("checkpoints", (thread) => thread.checkpoints, EMPTY_CHECKPOINTS); + const pendingApprovals = family( + "pending-approvals", + (thread) => thread.pendingApprovals, + EMPTY_APPROVALS, + ); + const pendingUserInputs = family( + "pending-user-inputs", + (thread) => thread.pendingUserInputs, + EMPTY_USER_INPUTS, + ); + const runtime = family("runtime", (thread) => thread.runtime, null); + const latestRun = family( + "latest-run", + (thread) => thread.latestRun, + null, + ); + + const status = Atom.family((key: string) => Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe( Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), Atom.withLabel(`environment-thread-status:${key}`), ), ); - - const threadErrorAtomFamily = Atom.family((key: string) => + const error = Atom.family((key: string) => Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe( Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), Atom.withLabel(`environment-thread-error:${key}`), ), ); - const threadMessagesAtomFamily = Atom.family((key: string) => - Atom.make( - (get): ReadonlyArray => - get(threadDetailAtomFamily(key))?.messages ?? EMPTY_MESSAGES, - ).pipe( - Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), - Atom.withLabel(`environment-thread-messages:${key}`), - ), - ); - - const threadActivitiesAtomFamily = Atom.family((key: string) => - Atom.make( - (get): ReadonlyArray => - get(threadDetailAtomFamily(key))?.activities ?? EMPTY_ACTIVITIES, - ).pipe( - Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), - Atom.withLabel(`environment-thread-activities:${key}`), - ), - ); - - const threadProposedPlansAtomFamily = Atom.family((key: string) => - Atom.make( - (get): ReadonlyArray => - get(threadDetailAtomFamily(key))?.proposedPlans ?? EMPTY_PROPOSED_PLANS, - ).pipe( - Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), - Atom.withLabel(`environment-thread-proposed-plans:${key}`), - ), - ); - - const threadCheckpointsAtomFamily = Atom.family((key: string) => - Atom.make( - (get): ReadonlyArray => - get(threadDetailAtomFamily(key))?.checkpoints ?? EMPTY_CHECKPOINTS, - ).pipe( - Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), - Atom.withLabel(`environment-thread-checkpoints:${key}`), - ), - ); - - const threadSessionAtomFamily = Atom.family((key: string) => - Atom.make( - (get): OrchestrationSession | null => get(threadDetailAtomFamily(key))?.session ?? null, - ).pipe( - Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), - Atom.withLabel(`environment-thread-session:${key}`), - ), - ); - - const threadLatestTurnAtomFamily = Atom.family((key: string) => - Atom.make( - (get): OrchestrationLatestTurn | null => get(threadDetailAtomFamily(key))?.latestTurn ?? null, - ).pipe( - Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS), - Atom.withLabel(`environment-thread-latest-turn:${key}`), - ), - ); - return { stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)), + threadAtom: (ref: ScopedThreadRef) => scopedThreadProjectionAtomFamily(threadKey(ref)), + visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)), detailAtom: (ref: ScopedThreadRef) => threadDetailAtomFamily(threadKey(ref)), - statusAtom: (ref: ScopedThreadRef) => threadStatusAtomFamily(threadKey(ref)), - errorAtom: (ref: ScopedThreadRef) => threadErrorAtomFamily(threadKey(ref)), - messagesAtom: (ref: ScopedThreadRef) => threadMessagesAtomFamily(threadKey(ref)), - activitiesAtom: (ref: ScopedThreadRef) => threadActivitiesAtomFamily(threadKey(ref)), - proposedPlansAtom: (ref: ScopedThreadRef) => threadProposedPlansAtomFamily(threadKey(ref)), - checkpointsAtom: (ref: ScopedThreadRef) => threadCheckpointsAtomFamily(threadKey(ref)), - sessionAtom: (ref: ScopedThreadRef) => threadSessionAtomFamily(threadKey(ref)), - latestTurnAtom: (ref: ScopedThreadRef) => threadLatestTurnAtomFamily(threadKey(ref)), + statusAtom: (ref: ScopedThreadRef) => status(threadKey(ref)), + errorAtom: (ref: ScopedThreadRef) => error(threadKey(ref)), + messagesAtom: (ref: ScopedThreadRef) => messages(threadKey(ref)), + workEntriesAtom: (ref: ScopedThreadRef) => workEntries(threadKey(ref)), + proposedPlansAtom: (ref: ScopedThreadRef) => proposedPlans(threadKey(ref)), + checkpointsAtom: (ref: ScopedThreadRef) => checkpoints(threadKey(ref)), + pendingApprovalsAtom: (ref: ScopedThreadRef) => pendingApprovals(threadKey(ref)), + pendingUserInputsAtom: (ref: ScopedThreadRef) => pendingUserInputs(threadKey(ref)), + runtimeAtom: (ref: ScopedThreadRef) => runtime(threadKey(ref)), + latestRunAtom: (ref: ScopedThreadRef) => latestRun(threadKey(ref)), }; } diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts deleted file mode 100644 index 94eb1c6537..0000000000 --- a/packages/client-runtime/src/state/threadReducer.test.ts +++ /dev/null @@ -1,700 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; - -import { - CheckpointRef, - EventId, - MessageId, - ProjectId, - ProviderInstanceId, - ThreadId, - TurnId, -} from "@t3tools/contracts"; -import type { OrchestrationThread } from "@t3tools/contracts"; - -import { applyThreadDetailEvent } from "./threadReducer.ts"; - -const baseEventFields = { - eventId: EventId.make("event-1"), - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, -} as const; - -const baseThread: OrchestrationThread = { - id: ThreadId.make("thread-1"), - projectId: ProjectId.make("project-1"), - title: "Test Thread", - 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, -}; - -describe("applyThreadDetailEvent", () => { - describe("project events", () => { - it("returns unchanged for project.created", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 1, - occurredAt: "2026-04-01T01:00:00.000Z", - aggregateKind: "project", - aggregateId: ProjectId.make("project-1"), - type: "project.created", - payload: { - projectId: ProjectId.make("project-1"), - title: "T3 Code", - workspaceRoot: "/repo", - repositoryIdentity: null, - defaultModelSelection: null, - scripts: [], - createdAt: "2026-04-01T01:00:00.000Z", - updatedAt: "2026-04-01T01:00:00.000Z", - deletedAt: null, - }, - } as any); - expect(result.kind).toBe("unchanged"); - }); - }); - - describe("thread.created", () => { - it("creates a fresh thread", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 1, - occurredAt: "2026-04-01T01:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-2"), - type: "thread.created", - payload: { - threadId: ThreadId.make("thread-2"), - projectId: ProjectId.make("project-1"), - title: "New Thread", - modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - worktreePath: null, - createdAt: "2026-04-01T01:00:00.000Z", - updatedAt: "2026-04-01T01:00:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.id).toBe("thread-2"); - expect(result.thread.title).toBe("New Thread"); - expect(result.thread.branch).toBe("main"); - expect(result.thread.messages).toEqual([]); - expect(result.thread.session).toBeNull(); - } - }); - }); - - describe("thread.deleted", () => { - it("returns deleted signal", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 2, - occurredAt: "2026-04-01T02:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.deleted", - payload: { - threadId: ThreadId.make("thread-1"), - deletedAt: "2026-04-01T02:00:00.000Z", - }, - }); - expect(result.kind).toBe("deleted"); - }); - }); - - describe("thread.archived / thread.unarchived", () => { - it("sets archivedAt", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 3, - occurredAt: "2026-04-01T03:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.archived", - payload: { - threadId: ThreadId.make("thread-1"), - archivedAt: "2026-04-01T03:00:00.000Z", - updatedAt: "2026-04-01T03:00:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.archivedAt).toBe("2026-04-01T03:00:00.000Z"); - } - }); - - it("clears archivedAt", () => { - const archivedThread = { ...baseThread, archivedAt: "2026-04-01T03:00:00.000Z" }; - const result = applyThreadDetailEvent(archivedThread, { - ...baseEventFields, - sequence: 4, - occurredAt: "2026-04-01T04:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.unarchived", - payload: { - threadId: ThreadId.make("thread-1"), - updatedAt: "2026-04-01T04:00:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.archivedAt).toBeNull(); - } - }); - }); - - describe("thread.meta-updated", () => { - it("patches title and branch", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 5, - occurredAt: "2026-04-01T05:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.meta-updated", - payload: { - threadId: ThreadId.make("thread-1"), - title: "Updated Title", - branch: "feature/demo", - updatedAt: "2026-04-01T05:00:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.title).toBe("Updated Title"); - expect(result.thread.branch).toBe("feature/demo"); - // Model selection should be unchanged since it wasn't in the payload - expect(result.thread.modelSelection).toEqual(baseThread.modelSelection); - } - }); - }); - - describe("thread.message-sent", () => { - it("appends a new message", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 6, - occurredAt: "2026-04-01T06:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.message-sent", - payload: { - threadId: ThreadId.make("thread-1"), - messageId: MessageId.make("msg-1"), - role: "user", - text: "Hello, world!", - turnId: null, - streaming: false, - createdAt: "2026-04-01T06:00:00.000Z", - updatedAt: "2026-04-01T06:00:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.messages).toHaveLength(1); - expect(result.thread.messages[0]?.text).toBe("Hello, world!"); - } - }); - - it("appends text for streaming messages", () => { - const threadWithMessage: OrchestrationThread = { - ...baseThread, - messages: [ - { - id: MessageId.make("msg-2"), - role: "assistant", - text: "Hello", - turnId: TurnId.make("turn-1"), - streaming: true, - createdAt: "2026-04-01T06:00:00.000Z", - updatedAt: "2026-04-01T06:00:00.000Z", - }, - ], - }; - - const result = applyThreadDetailEvent(threadWithMessage, { - ...baseEventFields, - sequence: 7, - occurredAt: "2026-04-01T06:01:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.message-sent", - payload: { - threadId: ThreadId.make("thread-1"), - messageId: MessageId.make("msg-2"), - role: "assistant", - text: ", world!", - turnId: TurnId.make("turn-1"), - streaming: true, - createdAt: "2026-04-01T06:00:00.000Z", - updatedAt: "2026-04-01T06:01:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.messages).toHaveLength(1); - expect(result.thread.messages[0]?.text).toBe("Hello, world!"); - } - }); - - it("updates latestTurn for assistant messages with a turn", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 8, - occurredAt: "2026-04-01T07:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.message-sent", - payload: { - threadId: ThreadId.make("thread-1"), - messageId: MessageId.make("msg-3"), - role: "assistant", - text: "Done.", - turnId: TurnId.make("turn-1"), - streaming: false, - createdAt: "2026-04-01T07:00:00.000Z", - updatedAt: "2026-04-01T07:00:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.latestTurn?.turnId).toBe("turn-1"); - expect(result.thread.latestTurn?.state).toBe("completed"); - expect(result.thread.latestTurn?.assistantMessageId).toBe("msg-3"); - } - }); - - it("keeps latestTurn running for interim assistant messages while the session runs the turn", () => { - const threadWithRunningSession: OrchestrationThread = { - ...baseThread, - session: { - threadId: ThreadId.make("thread-1"), - status: "running", - providerName: "claude", - runtimeMode: "full-access", - activeTurnId: TurnId.make("turn-1"), - lastError: null, - updatedAt: "2026-04-01T06:59:00.000Z", - }, - latestTurn: { - turnId: TurnId.make("turn-1"), - state: "running", - requestedAt: "2026-04-01T06:59:00.000Z", - startedAt: "2026-04-01T06:59:00.000Z", - completedAt: null, - assistantMessageId: null, - }, - }; - - const result = applyThreadDetailEvent(threadWithRunningSession, { - ...baseEventFields, - sequence: 8, - occurredAt: "2026-04-01T07:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.message-sent", - payload: { - threadId: ThreadId.make("thread-1"), - messageId: MessageId.make("msg-3"), - role: "assistant", - text: "Interim commentary between tool calls.", - turnId: TurnId.make("turn-1"), - streaming: false, - createdAt: "2026-04-01T07:00:00.000Z", - updatedAt: "2026-04-01T07:00:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.latestTurn?.state).toBe("running"); - expect(result.thread.latestTurn?.completedAt).toBeNull(); - } - }); - }); - - describe("thread.session-set", () => { - it("settles a running latestTurn when the session leaves the running status", () => { - const threadWithRunningTurn: OrchestrationThread = { - ...baseThread, - latestTurn: { - turnId: TurnId.make("turn-1"), - state: "running", - requestedAt: "2026-04-01T07:00:00.000Z", - startedAt: "2026-04-01T07:00:00.000Z", - completedAt: null, - assistantMessageId: MessageId.make("msg-3"), - }, - }; - - const result = applyThreadDetailEvent(threadWithRunningTurn, { - ...baseEventFields, - sequence: 9, - occurredAt: "2026-04-01T08:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.session-set", - payload: { - threadId: ThreadId.make("thread-1"), - session: { - threadId: ThreadId.make("thread-1"), - status: "ready", - providerName: "claude", - runtimeMode: "full-access", - activeTurnId: null, - lastError: null, - updatedAt: "2026-04-01T08:00:00.000Z", - }, - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.latestTurn?.state).toBe("completed"); - expect(result.thread.latestTurn?.completedAt).toBe("2026-04-01T08:00:00.000Z"); - } - }); - - it("updates session and latestTurn for a running session", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 9, - occurredAt: "2026-04-01T08:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.session-set", - payload: { - threadId: ThreadId.make("thread-1"), - session: { - threadId: ThreadId.make("thread-1"), - status: "running", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: TurnId.make("turn-1"), - lastError: null, - updatedAt: "2026-04-01T08:00:00.000Z", - }, - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.session?.status).toBe("running"); - expect(result.thread.latestTurn?.turnId).toBe("turn-1"); - expect(result.thread.latestTurn?.state).toBe("running"); - } - }); - }); - - describe("thread.session-stop-requested", () => { - it("marks session as stopped", () => { - const threadWithSession: OrchestrationThread = { - ...baseThread, - session: { - threadId: ThreadId.make("thread-1"), - status: "running", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: TurnId.make("turn-1"), - lastError: null, - updatedAt: "2026-04-01T08:00:00.000Z", - }, - }; - - const result = applyThreadDetailEvent(threadWithSession, { - ...baseEventFields, - sequence: 10, - occurredAt: "2026-04-01T09:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.session-stop-requested", - payload: { - threadId: ThreadId.make("thread-1"), - createdAt: "2026-04-01T09:00:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.session?.status).toBe("stopped"); - expect(result.thread.session?.activeTurnId).toBeNull(); - } - }); - - it("returns unchanged when no session exists", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 10, - occurredAt: "2026-04-01T09:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.session-stop-requested", - payload: { - threadId: ThreadId.make("thread-1"), - createdAt: "2026-04-01T09:00:00.000Z", - }, - }); - expect(result.kind).toBe("unchanged"); - }); - }); - - describe("thread.proposed-plan-upserted", () => { - it("adds a proposed plan", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 11, - occurredAt: "2026-04-01T10:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.proposed-plan-upserted", - payload: { - threadId: ThreadId.make("thread-1"), - proposedPlan: { - id: "plan-1", - turnId: TurnId.make("turn-1"), - planMarkdown: "## Plan\n- Do stuff", - implementedAt: null, - implementationThreadId: null, - createdAt: "2026-04-01T10:00:00.000Z", - updatedAt: "2026-04-01T10:00:00.000Z", - }, - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.proposedPlans).toHaveLength(1); - expect(result.thread.proposedPlans[0]?.id).toBe("plan-1"); - } - }); - }); - - describe("thread.activity-appended", () => { - it("adds an activity", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 12, - occurredAt: "2026-04-01T11:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.activity-appended", - payload: { - threadId: ThreadId.make("thread-1"), - activity: { - id: EventId.make("activity-1"), - tone: "tool", - kind: "file-edit", - summary: "Edited src/index.ts", - payload: {}, - turnId: TurnId.make("turn-1"), - createdAt: "2026-04-01T11:00:00.000Z", - }, - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.activities).toHaveLength(1); - expect(result.thread.activities[0]?.kind).toBe("file-edit"); - } - }); - - it("preserves the complete activity history when live events arrive", () => { - const existingActivities = Array.from({ length: 129 }, (_, index) => ({ - id: EventId.make(`activity-${index}`), - tone: "tool" as const, - kind: "command", - summary: `Ran command ${index}`, - payload: {}, - turnId: TurnId.make("turn-1"), - sequence: index, - createdAt: "2026-04-01T11:00:00.000Z", - })); - const result = applyThreadDetailEvent( - { ...baseThread, activities: existingActivities }, - { - ...baseEventFields, - sequence: 130, - occurredAt: "2026-04-01T11:01:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.activity-appended", - payload: { - threadId: ThreadId.make("thread-1"), - activity: { - id: EventId.make("activity-129"), - tone: "tool", - kind: "command", - summary: "Ran command 129", - payload: {}, - turnId: TurnId.make("turn-1"), - sequence: 129, - createdAt: "2026-04-01T11:01:00.000Z", - }, - }, - }, - ); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.activities).toHaveLength(130); - expect(result.thread.activities[0]?.id).toBe("activity-0"); - } - }); - }); - - describe("thread.turn-diff-completed", () => { - it("adds a checkpoint and updates latestTurn", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 13, - occurredAt: "2026-04-01T12:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.turn-diff-completed", - payload: { - threadId: ThreadId.make("thread-1"), - turnId: TurnId.make("turn-1"), - checkpointTurnCount: 1, - checkpointRef: CheckpointRef.make("ref-1"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("msg-3"), - completedAt: "2026-04-01T12:00:00.000Z", - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.checkpoints).toHaveLength(1); - expect(result.thread.latestTurn?.turnId).toBe("turn-1"); - expect(result.thread.latestTurn?.state).toBe("completed"); - } - }); - }); - - describe("thread.reverted", () => { - it("filters entities to retained turns", () => { - const threadWithData: OrchestrationThread = { - ...baseThread, - messages: [ - { - id: MessageId.make("msg-1"), - role: "user", - text: "First", - turnId: null, - streaming: false, - createdAt: "2026-04-01T01:00:00.000Z", - updatedAt: "2026-04-01T01:00:00.000Z", - }, - { - id: MessageId.make("msg-2"), - role: "assistant", - text: "Response 1", - turnId: TurnId.make("turn-1"), - streaming: false, - createdAt: "2026-04-01T02:00:00.000Z", - updatedAt: "2026-04-01T02:00:00.000Z", - }, - { - id: MessageId.make("msg-3"), - role: "assistant", - text: "Response 2", - turnId: TurnId.make("turn-2"), - streaming: false, - createdAt: "2026-04-01T03:00:00.000Z", - updatedAt: "2026-04-01T03:00:00.000Z", - }, - ], - checkpoints: [ - { - turnId: TurnId.make("turn-1"), - checkpointTurnCount: 1, - checkpointRef: CheckpointRef.make("ref-1"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("msg-2"), - completedAt: "2026-04-01T02:00:00.000Z", - }, - { - turnId: TurnId.make("turn-2"), - checkpointTurnCount: 2, - checkpointRef: CheckpointRef.make("ref-2"), - status: "ready", - files: [], - assistantMessageId: MessageId.make("msg-3"), - completedAt: "2026-04-01T03:00:00.000Z", - }, - ], - }; - - const result = applyThreadDetailEvent(threadWithData, { - ...baseEventFields, - sequence: 14, - occurredAt: "2026-04-01T04:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.reverted", - payload: { - threadId: ThreadId.make("thread-1"), - turnCount: 1, - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - // turn-2 checkpoint is filtered out (turnCount 2 > revert target 1) - expect(result.thread.checkpoints).toHaveLength(1); - expect(result.thread.checkpoints[0]?.turnId).toBe("turn-1"); - // msg-3 (turn-2) is filtered, msg-1 (no turn) and msg-2 (turn-1) remain - expect(result.thread.messages).toHaveLength(2); - expect(result.thread.latestTurn?.turnId).toBe("turn-1"); - } - }); - }); - - describe("no-op events", () => { - it("returns unchanged for approval-response-requested", () => { - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 15, - occurredAt: "2026-04-01T13:00:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.approval-response-requested", - payload: { - threadId: ThreadId.make("thread-1"), - requestId: "req-1", - decision: "approve", - createdAt: "2026-04-01T13:00:00.000Z", - }, - } as any); - expect(result.kind).toBe("unchanged"); - }); - }); -}); diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts deleted file mode 100644 index 670540fee7..0000000000 --- a/packages/client-runtime/src/state/threadReducer.ts +++ /dev/null @@ -1,547 +0,0 @@ -import { pipe } from "effect/Function"; -import * as Arr from "effect/Array"; -import * as O from "effect/Order"; -import type { - MessageId, - OrchestrationCheckpointSummary, - OrchestrationEvent, - OrchestrationLatestTurn, - OrchestrationMessage, - OrchestrationSession, - OrchestrationThread, - OrchestrationThreadActivity, - TurnId, -} from "@t3tools/contracts"; - -export type ThreadDetailReducerResult = - | { readonly kind: "updated"; readonly thread: OrchestrationThread } - | { readonly kind: "deleted" } - | { readonly kind: "unchanged" }; - -const proposedPlanOrder = O.combine( - O.mapInput(O.String, (p) => p.createdAt), - O.mapInput(O.String, (p) => p.id), -); - -const checkpointOrder = O.mapInput( - O.Number, - (cp: OrchestrationThread["checkpoints"][number]) => - cp.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER, -); - -const activityOrder = O.combineAll([ - O.mapInput(O.Number, (a) => a.sequence ?? Number.MAX_SAFE_INTEGER), - O.mapInput(O.String, (a) => a.createdAt), - O.mapInput(O.String, (a) => a.id), -]); - -/** - * Apply a single orchestration event to an `OrchestrationThread`, returning - * the updated thread, a deletion signal, or an "unchanged" marker when the - * event doesn't affect this thread. - * - * This is a pure reducer operating on contract types. UI-specific mapping - * (e.g. resolving attachment preview URLs, normalising model slugs, adding - * scoped fields like `environmentId`) is the caller's responsibility. - */ -export function applyThreadDetailEvent( - thread: OrchestrationThread, - event: OrchestrationEvent, -): ThreadDetailReducerResult { - switch (event.type) { - // ── Project events (irrelevant to thread detail) ──────────────── - case "project.created": - case "project.meta-updated": - case "project.deleted": - return { kind: "unchanged" }; - - // ── Thread lifecycle ──────────────────────────────────────────── - case "thread.created": - return { - kind: "updated", - thread: { - id: event.payload.threadId, - projectId: event.payload.projectId, - title: event.payload.title, - modelSelection: event.payload.modelSelection, - runtimeMode: event.payload.runtimeMode, - interactionMode: event.payload.interactionMode, - branch: event.payload.branch, - worktreePath: event.payload.worktreePath, - latestTurn: null, - createdAt: event.payload.createdAt, - updatedAt: event.payload.updatedAt, - archivedAt: null, - deletedAt: null, - messages: [], - proposedPlans: [], - activities: [], - checkpoints: [], - session: null, - }, - }; - - case "thread.deleted": - return { kind: "deleted" }; - - case "thread.archived": - return { - kind: "updated", - thread: { - ...thread, - archivedAt: event.payload.archivedAt, - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.unarchived": - return { - kind: "updated", - thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt }, - }; - - // ── Thread metadata ───────────────────────────────────────────── - case "thread.meta-updated": - return { - kind: "updated", - thread: { - ...thread, - ...(event.payload.title !== undefined ? { title: event.payload.title } : {}), - ...(event.payload.modelSelection !== undefined - ? { modelSelection: event.payload.modelSelection } - : {}), - ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}), - ...(event.payload.worktreePath !== undefined - ? { worktreePath: event.payload.worktreePath } - : {}), - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.runtime-mode-set": - return { - kind: "updated", - thread: { - ...thread, - runtimeMode: event.payload.runtimeMode, - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.interaction-mode-set": - return { - kind: "updated", - thread: { - ...thread, - interactionMode: event.payload.interactionMode, - updatedAt: event.payload.updatedAt, - }, - }; - - // ── Turn lifecycle ────────────────────────────────────────────── - case "thread.turn-start-requested": - return { - kind: "updated", - thread: { - ...thread, - ...(event.payload.modelSelection !== undefined - ? { modelSelection: event.payload.modelSelection } - : {}), - runtimeMode: event.payload.runtimeMode, - interactionMode: event.payload.interactionMode, - updatedAt: event.occurredAt, - }, - }; - - case "thread.turn-interrupt-requested": { - if (event.payload.turnId === undefined) { - return { kind: "unchanged" }; - } - const latestTurn = thread.latestTurn; - if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) { - return { kind: "unchanged" }; - } - return { - kind: "updated", - thread: { - ...thread, - latestTurn: { - ...latestTurn, - state: "interrupted", - startedAt: latestTurn.startedAt ?? event.payload.createdAt, - completedAt: latestTurn.completedAt ?? event.payload.createdAt, - }, - updatedAt: event.occurredAt, - }, - }; - } - - // ── Messages ──────────────────────────────────────────────────── - case "thread.message-sent": { - const message: OrchestrationMessage = { - id: event.payload.messageId, - role: event.payload.role, - text: event.payload.text, - ...(event.payload.attachments !== undefined - ? { attachments: event.payload.attachments } - : {}), - turnId: event.payload.turnId, - streaming: event.payload.streaming, - createdAt: event.payload.createdAt, - updatedAt: event.payload.updatedAt, - }; - - const existingMessage = thread.messages.find((entry) => entry.id === message.id); - const messages = existingMessage - ? Arr.map(thread.messages, (entry) => - entry.id !== message.id - ? entry - : { - ...entry, - text: message.streaming - ? `${entry.text}${message.text}` - : message.text.length > 0 - ? message.text - : entry.text, - streaming: message.streaming, - ...(message.turnId !== undefined ? { turnId: message.turnId } : {}), - ...(message.streaming ? {} : { updatedAt: message.updatedAt }), - ...(message.attachments !== undefined - ? { attachments: message.attachments } - : {}), - }, - ) - : Arr.append(thread.messages, message); - // Update latestTurn for assistant messages bound to a turn. A completed - // assistant message only settles the turn once the session is no longer - // running it — providers may emit several assistant messages per turn - // (commentary between tool calls), and the turn must stay unsettled - // until the provider reports turn end. - const turnStillRunning = - event.payload.turnId !== null && - thread.session?.status === "running" && - thread.session.activeTurnId === event.payload.turnId; - const settlesTurn = !event.payload.streaming && !turnStillRunning; - const latestTurn: OrchestrationThread["latestTurn"] = - event.payload.role === "assistant" && - event.payload.turnId !== null && - (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId) - ? { - turnId: event.payload.turnId, - state: settlesTurn - ? thread.latestTurn?.state === "interrupted" - ? "interrupted" - : thread.latestTurn?.state === "error" - ? "error" - : "completed" - : "running", - requestedAt: - thread.latestTurn?.turnId === event.payload.turnId - ? thread.latestTurn.requestedAt - : event.payload.createdAt, - startedAt: - thread.latestTurn?.turnId === event.payload.turnId - ? (thread.latestTurn.startedAt ?? event.payload.createdAt) - : event.payload.createdAt, - completedAt: settlesTurn - ? event.payload.updatedAt - : thread.latestTurn?.turnId === event.payload.turnId - ? (thread.latestTurn.completedAt ?? null) - : null, - assistantMessageId: event.payload.messageId, - } - : thread.latestTurn; - - // Rebind checkpoint assistant message IDs for assistant messages. - const checkpoints = - event.payload.role === "assistant" && event.payload.turnId !== null - ? rebindCheckpointAssistantMessage( - thread.checkpoints, - event.payload.turnId, - event.payload.messageId, - ) - : thread.checkpoints; - - return { - kind: "updated", - thread: { - ...thread, - messages, - checkpoints, - latestTurn, - updatedAt: event.occurredAt, - }, - }; - } - - // ── Session ───────────────────────────────────────────────────── - case "thread.session-set": { - // Leaving the "running" session status is the turn-end signal: settle a - // still-running latest turn so its duration reflects the whole turn. - const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status); - const latestTurn: OrchestrationLatestTurn | null = - event.payload.session.status === "running" && event.payload.session.activeTurnId !== null - ? { - turnId: event.payload.session.activeTurnId, - state: "running", - requestedAt: - thread.latestTurn?.turnId === event.payload.session.activeTurnId - ? thread.latestTurn.requestedAt - : event.payload.session.updatedAt, - startedAt: - thread.latestTurn?.turnId === event.payload.session.activeTurnId - ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt) - : event.payload.session.updatedAt, - completedAt: null, - assistantMessageId: - thread.latestTurn?.turnId === event.payload.session.activeTurnId - ? thread.latestTurn.assistantMessageId - : null, - } - : thread.latestTurn !== null && - thread.latestTurn.state === "running" && - settledTurnState !== null - ? { - ...thread.latestTurn, - state: settledTurnState, - // A running turn's completedAt can only hold a mid-turn - // placeholder checkpoint timestamp — the session leaving - // "running" is the authoritative turn end. - completedAt: event.payload.session.updatedAt, - } - : thread.latestTurn; - - return { - kind: "updated", - thread: { - ...thread, - session: event.payload.session, - latestTurn, - updatedAt: event.occurredAt, - }, - }; - } - - case "thread.session-stop-requested": - return thread.session === null - ? { kind: "unchanged" } - : { - kind: "updated", - thread: { - ...thread, - session: { - ...thread.session, - status: "stopped", - activeTurnId: null, - updatedAt: event.payload.createdAt, - }, - updatedAt: event.occurredAt, - }, - }; - - // ── Proposed plans ────────────────────────────────────────────── - case "thread.proposed-plan-upserted": { - const proposedPlan = event.payload.proposedPlan; - - const proposedPlans = pipe( - thread.proposedPlans, - Arr.filter((entry) => entry.id !== proposedPlan.id), - Arr.append(proposedPlan), - Arr.sort(proposedPlanOrder), - ); - - return { - kind: "updated", - thread: { ...thread, proposedPlans, updatedAt: event.occurredAt }, - }; - } - - // ── Checkpoints / turn diffs ──────────────────────────────────── - case "thread.turn-diff-completed": { - const checkpoint: OrchestrationCheckpointSummary = { - turnId: event.payload.turnId, - checkpointTurnCount: event.payload.checkpointTurnCount, - checkpointRef: event.payload.checkpointRef, - status: event.payload.status, - files: event.payload.files, - assistantMessageId: event.payload.assistantMessageId, - completedAt: event.payload.completedAt, - }; - - const existing = thread.checkpoints.find((entry) => entry.turnId === checkpoint.turnId); - // Don't overwrite a non-missing checkpoint with a missing one. - if (existing && existing.status !== "missing" && checkpoint.status === "missing") { - return { kind: "unchanged" }; - } - - const checkpoints = pipe( - thread.checkpoints, - Arr.filter((entry) => entry.turnId !== checkpoint.turnId), - Arr.append(checkpoint), - Arr.sort(checkpointOrder), - ); - - // Mid-turn diff updates produce placeholder checkpoints; record the - // checkpoint, but don't settle a turn its session is still running. - const diffTurnStillRunning = - thread.session?.status === "running" && - thread.session.activeTurnId === event.payload.turnId; - const latestTurn = - !diffTurnStillRunning && - (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId) - ? { - turnId: event.payload.turnId, - state: checkpointStatusToTurnState(event.payload.status), - requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt, - startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt, - completedAt: event.payload.completedAt, - assistantMessageId: event.payload.assistantMessageId, - } - : thread.latestTurn; - - return { - kind: "updated", - thread: { ...thread, checkpoints, latestTurn, updatedAt: event.occurredAt }, - }; - } - - // ── Revert ────────────────────────────────────────────────────── - case "thread.reverted": { - const checkpoints = pipe( - thread.checkpoints, - Arr.filter( - (entry) => - entry.checkpointTurnCount !== undefined && - entry.checkpointTurnCount <= event.payload.turnCount, - ), - Arr.sort(checkpointOrder), - ); - - const retainedTurnIds = new Set(Arr.map(checkpoints, (entry) => entry.turnId)); - const messages = retainMessagesAfterRevert(thread.messages, retainedTurnIds); - const proposedPlans = pipe( - thread.proposedPlans, - Arr.filter((plan) => plan.turnId === null || retainedTurnIds.has(plan.turnId)), - ); - const activities = pipe( - thread.activities, - Arr.filter((activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId)), - ); - const latestCheckpoint = checkpoints.at(-1) ?? null; - - return { - kind: "updated", - thread: { - ...thread, - checkpoints, - messages, - proposedPlans, - activities, - latestTurn: - latestCheckpoint === null - ? null - : { - turnId: latestCheckpoint.turnId, - state: checkpointStatusToTurnState( - latestCheckpoint.status as "ready" | "missing" | "error", - ), - requestedAt: latestCheckpoint.completedAt, - startedAt: latestCheckpoint.completedAt, - completedAt: latestCheckpoint.completedAt, - assistantMessageId: latestCheckpoint.assistantMessageId ?? null, - }, - updatedAt: event.occurredAt, - }, - }; - } - - // ── Activities ────────────────────────────────────────────────── - case "thread.activity-appended": { - const activities = pipe( - thread.activities, - Arr.filter((activity) => activity.id !== event.payload.activity.id), - Arr.append(event.payload.activity), - Arr.sort(activityOrder), - ); - - return { - kind: "updated", - thread: { ...thread, activities, updatedAt: event.occurredAt }, - }; - } - - // ── Events that don't mutate thread state directly ────────────── - case "thread.approval-response-requested": - case "thread.user-input-response-requested": - case "thread.checkpoint-revert-requested": - return { kind: "unchanged" }; - } - - // Forward-compatible: ignore unrecognized event types. - return { kind: "unchanged" }; -} - -// ── Helpers ────────────────────────────────────────────────────────── - -/** - * Turn state to settle a still-running latest turn with when its session - * leaves the "running" status, or null while the session is (re)starting or - * running and the turn must stay unsettled. - */ -function settledTurnStateForSessionStatus( - status: OrchestrationSession["status"], -): "completed" | "interrupted" | "error" | null { - switch (status) { - case "idle": - case "ready": - return "completed"; - case "error": - return "error"; - case "interrupted": - case "stopped": - return "interrupted"; - case "starting": - case "running": - return null; - } -} - -function checkpointStatusToTurnState( - status: "ready" | "missing" | "error", -): OrchestrationLatestTurn["state"] { - switch (status) { - case "ready": - return "completed"; - case "error": - return "error"; - case "missing": - return "completed"; - } -} - -function rebindCheckpointAssistantMessage( - checkpoints: ReadonlyArray, - turnId: TurnId, - messageId: MessageId, -): OrchestrationCheckpointSummary[] { - return Arr.map(checkpoints, (entry) => - entry.turnId === turnId ? { ...entry, assistantMessageId: messageId } : entry, - ); -} - -function retainMessagesAfterRevert( - messages: ReadonlyArray, - retainedTurnIds: ReadonlySet, -): OrchestrationMessage[] { - // Keep messages that belong to a retained turn, plus system messages and - // messages without a turn binding (pre-turn-0 user messages). - return Arr.filter(messages, (message) => { - if (message.role === "system") { - return true; - } - if (message.turnId === null) { - return true; - } - return retainedTurnIds.has(message.turnId); - }); -} diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 65cee0427e..3d96fd0ed4 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -1,7 +1,7 @@ import type { EnvironmentId, - OrchestrationShellSnapshot, - OrchestrationThreadShell, + OrchestrationV2ShellSnapshot, + OrchestrationV2ThreadShell, ProjectId, ScopedProjectRef, ScopedThreadRef, @@ -10,7 +10,7 @@ import type { import { Atom } from "effect/unstable/reactivity"; import type { EnvironmentThreadShell } from "./models.ts"; -import { scopeThreadShell } from "./models.ts"; +import { presentThreadShell } from "./models.ts"; import type { EnvironmentCatalogState } from "./connections.ts"; import { arrayElementsEqual, @@ -21,9 +21,9 @@ import { threadRefsEqual, } from "./entities.ts"; -const EMPTY_THREADS: ReadonlyArray = Object.freeze([]); +const EMPTY_THREADS: ReadonlyArray = Object.freeze([]); const EMPTY_SCOPED_THREAD_REFS: ReadonlyArray = Object.freeze([]); -const EMPTY_THREAD_INDEX: ReadonlyMap = new Map(); +const EMPTY_THREAD_INDEX: ReadonlyMap = new Map(); const EMPTY_THREAD_REFS_BY_PROJECT: ReadonlyMap< ProjectId, ReadonlyArray @@ -33,17 +33,17 @@ export function createEnvironmentThreadShellAtoms(input: { readonly catalogValueAtom: Atom.Atom; readonly snapshotAtom: ( environmentId: EnvironmentId, - ) => Atom.Atom; + ) => Atom.Atom; }) { const environmentThreadsAtom = Atom.family((environmentId: EnvironmentId) => Atom.make( - (get): ReadonlyArray => + (get): ReadonlyArray => get(input.snapshotAtom(environmentId))?.threads ?? EMPTY_THREADS, ).pipe(Atom.withLabel(`environment-threads:${environmentId}`)), ); const environmentThreadIndexAtom = Atom.family((environmentId: EnvironmentId) => - Atom.make((get): ReadonlyMap => { + Atom.make((get): ReadonlyMap => { const threads = get(environmentThreadsAtom(environmentId)); if (threads.length === 0) { return EMPTY_THREAD_INDEX; @@ -102,7 +102,7 @@ export function createEnvironmentThreadShellAtoms(input: { const threadShellAtomFamily = Atom.family((key: string) => { const ref = parseThreadKey(key); - let previousSource: OrchestrationThreadShell | null = null; + let previousSource: OrchestrationV2ThreadShell | null = null; let previousValue: EnvironmentThreadShell | null = null; return Atom.make((get) => { const source = get(environmentThreadIndexAtom(ref.environmentId)).get(ref.threadId) ?? null; @@ -110,7 +110,7 @@ export function createEnvironmentThreadShellAtoms(input: { return previousValue; } previousSource = source; - previousValue = source === null ? null : scopeThreadShell(ref.environmentId, source); + previousValue = source === null ? null : presentThreadShell(ref.environmentId, source); return previousValue; }).pipe(Atom.withLabel(`environment-thread-shell:${key}`)); }); diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 3a5a8b6963..ae073b1993 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -1,37 +1,28 @@ import { EnvironmentId, EventId, - ORCHESTRATION_WS_METHODS, - ProjectId, - ProviderInstanceId, - ThreadId, - type OrchestrationThread, - type OrchestrationThreadStreamItem, + ORCHESTRATION_V2_WS_METHODS, + type OrchestrationV2ThreadStreamItem, } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; -import * as Ref from "effect/Ref"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; -import * as TestClock from "effect/testing/TestClock"; -import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import { AVAILABLE_CONNECTION_STATE, PrimaryConnectionTarget, type PreparedConnection, - type SupervisorConnectionState, } from "../connection/model.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as Persistence from "../platform/persistence.ts"; import * as RpcSession from "../rpc/session.ts"; -import { - EMPTY_ENVIRONMENT_THREAD_STATE, - makeEnvironmentThreadState, - type EnvironmentThreadState, -} from "./threads.ts"; +import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; +import { v2Projection, v2ThreadId } from "./orchestrationV2TestFixtures.ts"; +import { makeEnvironmentThreadState } from "./threads.ts"; const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), @@ -39,365 +30,73 @@ const TARGET = new PrimaryConnectionTarget({ httpBaseUrl: "https://environment.example.test", wsBaseUrl: "wss://environment.example.test", }); -const THREAD_ID = ThreadId.make("thread-1"); -const BASE_THREAD: OrchestrationThread = { - id: THREAD_ID, - projectId: ProjectId.make("project-1"), - title: "Cached thread", - modelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: "gpt-5.4", - }, - runtimeMode: "full-access", - interactionMode: "default", - branch: "main", - 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, -}; -type TestThreadInput = OrchestrationThreadStreamItem | Error; - -function testSession(client: WsRpcProtocolClient): RpcSession.RpcSession { - return { - client, - initialConfig: Effect.never, - ready: Effect.void, - probe: Effect.void, - closed: Effect.never, - }; -} - -function awaitThreadState( - observed: Queue.Queue, - predicate: (state: EnvironmentThreadState) => boolean, -) { - return Queue.take(observed).pipe( - Effect.repeat({ - until: predicate, - }), - ); -} - -const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (options?: { - readonly cached?: OrchestrationThread; -}) { - const inputs = yield* Queue.unbounded(); - const observed = yield* Queue.unbounded(); - const latest = yield* Ref.make(EMPTY_ENVIRONMENT_THREAD_STATE); - const retryCount = yield* Ref.make(0); - const subscriptionCount = yield* Ref.make(0); - const savedThreads = yield* Ref.make>([]); - const removedThreads = yield* Ref.make>([]); - const supervisorState = yield* SubscriptionRef.make( - AVAILABLE_CONNECTION_STATE, - ); - const streamFrom = (queue: Queue.Queue) => - Stream.fromQueue(queue).pipe( - Stream.mapEffect((input) => - input instanceof Error ? Effect.fail(input) : Effect.succeed(input), - ), - ); - const client = { - [ORCHESTRATION_WS_METHODS.subscribeThread]: () => - Stream.unwrap( - Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe( - Effect.map(() => streamFrom(inputs)), - ), - ), - } as unknown as WsRpcProtocolClient; - const supervisorSession = yield* SubscriptionRef.make>( - Option.some(testSession(client)), - ); - const prepared = yield* SubscriptionRef.make>(Option.none()); - const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ - target: TARGET, - state: supervisorState, - session: supervisorSession, - prepared, - connect: Effect.void, - disconnect: Effect.void, - retryNow: Ref.update(retryCount, (count) => count + 1), - } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); - const cache = Persistence.EnvironmentCacheStore.of({ - loadShell: () => Effect.succeed(Option.none()), - saveShell: () => Effect.void, - loadThread: (_environmentId, threadId) => - Effect.succeed( - threadId === THREAD_ID && options?.cached !== undefined - ? Option.some(options.cached) - : Option.none(), - ), - saveThread: (_environmentId, thread) => - Ref.update(savedThreads, (current) => [...current, thread]), - removeThread: (_environmentId, threadId) => - Ref.update(removedThreads, (current) => [...current, threadId]), - clear: () => Effect.void, - }); - const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe( - Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), - Effect.provideService(Persistence.EnvironmentCacheStore, cache), - ); - yield* SubscriptionRef.changes(threadState).pipe( - Stream.runForEach((state) => - Ref.set(latest, state).pipe(Effect.andThen(Queue.offer(observed, state))), - ), - Effect.forkScoped, - ); - - return { - inputs, - observed, - latest, - retryCount, - subscriptionCount, - supervisorState, - supervisorSession, - savedThreads, - removedThreads, - replaceSession: SubscriptionRef.set(supervisorSession, Option.some(testSession(client))), - }; -}); - -const snapshot = (thread: OrchestrationThread): OrchestrationThreadStreamItem => ({ - kind: "snapshot", - snapshot: { - snapshotSequence: 1, - thread, - }, -}); - -const titleUpdated = (title: string, sequence = 2): OrchestrationThreadStreamItem => ({ - kind: "event", - event: { - eventId: EventId.make("event-title"), - sequence, - occurredAt: "2026-04-01T01:00:00.000Z", - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - aggregateKind: "thread", - aggregateId: THREAD_ID, - type: "thread.meta-updated", - payload: { - threadId: THREAD_ID, - title, - updatedAt: "2026-04-01T01:00:00.000Z", - }, - }, -}); - -const deleted = (): OrchestrationThreadStreamItem => ({ - kind: "event", - event: { - eventId: EventId.make("event-deleted"), - sequence: 3, - occurredAt: "2026-04-01T02:00:00.000Z", - commandId: null, - causationEventId: null, - correlationId: null, - metadata: {}, - aggregateKind: "thread", - aggregateId: THREAD_ID, - type: "thread.deleted", - payload: { - threadId: THREAD_ID, - deletedAt: "2026-04-01T02:00:00.000Z", - }, - }, -}); - -describe("EnvironmentThreads", () => { - it.effect("publishes cached data before a live snapshot arrives", () => +describe("V2 thread synchronization", () => { + it.effect("applies a snapshot followed by committed projection events", () => Effect.gen(function* () { - const harness = yield* makeHarness({ cached: BASE_THREAD }); - const state = yield* awaitThreadState( - harness.observed, - (value) => value.status === "cached" && Option.isSome(value.data), - ); - - expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD); - expect(Option.isNone(state.error)).toBe(true); - }), - ); - - it.effect("reduces live events and persists the latest thread", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ cached: BASE_THREAD }); - yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD)); - yield* Queue.offer(harness.inputs, titleUpdated("Live title")); - - const state = yield* awaitThreadState( - harness.observed, - (value) => - value.status === "live" && - Option.isSome(value.data) && - value.data.value.title === "Live title", - ); - yield* TestClock.adjust("500 millis"); - yield* Effect.yieldNow; - - expect(Option.getOrThrow(state.data).title).toBe("Live title"); - expect((yield* Ref.get(harness.savedThreads)).at(-1)?.title).toBe("Live title"); - }), - ); - - it.effect("ignores replayed thread events at or below the snapshot sequence", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ cached: BASE_THREAD }); - yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD)); - yield* Queue.offer(harness.inputs, titleUpdated("Replayed title", 1)); - yield* Queue.offer(harness.inputs, titleUpdated("Live title", 2)); - - const state = yield* awaitThreadState( - harness.observed, - (value) => - value.status === "live" && - Option.isSome(value.data) && - value.data.value.title === "Live title", - ); - - expect(Option.getOrThrow(state.data).title).toBe("Live title"); - }), - ); - - it.effect("removes cached data when the thread is deleted", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ cached: BASE_THREAD }); - yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD)); - yield* Queue.offer(harness.inputs, deleted()); - - const state = yield* awaitThreadState( - harness.observed, - (value) => value.status === "deleted", - ); - - expect(Option.isNone(state.data)).toBe(true); - expect(yield* Ref.get(harness.removedThreads)).toEqual([THREAD_ID]); - }), - ); - - it.effect("preserves data after a domain failure and resumes on a replacement session", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ cached: BASE_THREAD }); - yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD)); - yield* Queue.offer(harness.inputs, new Error("stream failed")); - - const state = yield* awaitThreadState(harness.observed, (value) => - Option.isSome(value.error), - ); - - expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD); - expect(Option.getOrThrow(state.error)).toBe("stream failed"); - expect(yield* Ref.get(harness.retryCount)).toBe(0); - - yield* harness.replaceSession; - for (let attempt = 0; attempt < 100; attempt += 1) { - if ((yield* Ref.get(harness.subscriptionCount)) >= 2) { - break; - } - yield* Effect.yieldNow; - } - yield* Queue.offer( - harness.inputs, - snapshot({ - ...BASE_THREAD, - title: "Recovered thread", - }), - ); - const recovered = yield* awaitThreadState( - harness.observed, - (value) => - value.status === "live" && - Option.isSome(value.data) && - value.data.value.title === "Recovered thread", - ); - - expect(Option.isNone(recovered.error)).toBe(true); - expect(yield* Ref.get(harness.subscriptionCount)).toBe(2); - }), - ); - - it.effect("recovers from a transient domain failure without replacing the session", () => - Effect.gen(function* () { - const harness = yield* makeHarness(); - yield* Queue.offer(harness.inputs, new Error("thread not found yet")); - - const failed = yield* awaitThreadState(harness.observed, (value) => - Option.isSome(value.error), - ); - expect(Option.getOrThrow(failed.error)).toBe("thread not found yet"); - expect(yield* Ref.get(harness.subscriptionCount)).toBe(1); - - yield* TestClock.adjust("250 millis"); - for (let attempt = 0; attempt < 100; attempt += 1) { - if ((yield* Ref.get(harness.subscriptionCount)) >= 2) { - break; - } - yield* Effect.yieldNow; - } - yield* Queue.offer( - harness.inputs, - snapshot({ - ...BASE_THREAD, - title: "Materialized thread", - }), - ); - - const recovered = yield* awaitThreadState( - harness.observed, - (value) => - value.status === "live" && - Option.isSome(value.data) && - value.data.value.title === "Materialized thread", - ); - - expect(Option.isNone(recovered.error)).toBe(true); - expect(yield* Ref.get(harness.subscriptionCount)).toBe(2); - expect(yield* Ref.get(harness.retryCount)).toBe(0); - }), - ); - - it.effect("does not overwrite a live snapshot when the supervisor becomes ready", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ cached: BASE_THREAD }); - yield* SubscriptionRef.set(harness.supervisorState, { - desired: true, - network: "online", - phase: "connecting", - stage: "synchronizing", - attempt: 1, - generation: 0, - lastFailure: null, - retryAt: null, + const events = yield* Queue.unbounded(); + const client = { + [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: () => Stream.fromQueue(events), + } as unknown as WsRpcProtocolClient; + const rpcSession: RpcSession.RpcSession = { + client, + initialConfig: Effect.never, + ready: Effect.void, + probe: Effect.void, + closed: Effect.never, + }; + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target: TARGET, + state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE), + session: yield* SubscriptionRef.make(Option.some(rpcSession)), + prepared: yield* SubscriptionRef.make(Option.none()), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, }); - yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD)); - yield* awaitThreadState(harness.observed, (value) => value.status === "live"); - - yield* SubscriptionRef.set(harness.supervisorState, { - desired: true, - network: "online", - phase: "connected", - stage: null, - attempt: 1, - generation: 1, - lastFailure: null, - retryAt: null, + const cache = Persistence.EnvironmentCacheStore.of({ + loadShell: () => Effect.succeed(Option.none()), + saveShell: () => Effect.void, + loadThread: () => Effect.succeed(Option.none()), + saveThread: () => Effect.void, + removeThread: () => Effect.void, + clear: () => Effect.void, }); - for (let index = 0; index < 10; index += 1) { - yield* Effect.yieldNow; - } + const state = yield* makeEnvironmentThreadState(v2ThreadId).pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.provideService(Persistence.EnvironmentCacheStore, cache), + ); - expect((yield* Ref.get(harness.latest)).status).toBe("live"); + yield* Queue.offer(events, { + kind: "snapshot", + snapshotSequence: 1, + projection: v2Projection, + }); + yield* SubscriptionRef.changes(state).pipe( + Stream.filter((current) => current.status === "live"), + Stream.runHead, + ); + + const occurredAt = DateTime.makeUnsafe("2026-06-20T02:00:00.000Z"); + yield* Queue.offer(events, { + kind: "event", + sequence: 2, + event: { + id: EventId.make("event-title"), + type: "thread.metadata-updated", + threadId: v2ThreadId, + occurredAt, + payload: { ...v2Projection.thread, title: "Updated", updatedAt: occurredAt }, + }, + }); + yield* SubscriptionRef.changes(state).pipe( + Stream.filter((current) => Option.getOrNull(current.data)?.thread.title === "Updated"), + Stream.runHead, + ); + + expect(Option.getOrThrow((yield* SubscriptionRef.get(state)).data).thread.title).toBe( + "Updated", + ); }), ); }); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index bbb38f8d4b..ec309dfe3d 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -1,8 +1,8 @@ import { - ORCHESTRATION_WS_METHODS, + ORCHESTRATION_V2_WS_METHODS, type EnvironmentId as EnvironmentIdType, - type OrchestrationThread, - type OrchestrationThreadStreamItem, + type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadStreamItem, type ThreadId as ThreadIdType, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -19,14 +19,14 @@ import { EnvironmentSupervisor } from "../connection/supervisor.ts"; import { EnvironmentCacheStore } from "../platform/persistence.ts"; import { subscribe } from "../rpc/client.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; -import { applyThreadDetailEvent } from "./threadReducer.ts"; +import { applyOrchestrationV2ProjectionEvent } from "./orchestrationV2Projection.ts"; import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts"; import { followStreamInEnvironment } from "./runtime.ts"; export type EnvironmentThreadStatus = "empty" | "cached" | "synchronizing" | "live" | "deleted"; export interface EnvironmentThreadState { - readonly data: Option.Option; + readonly data: Option.Option; readonly status: EnvironmentThreadStatus; readonly error: Option.Option; } @@ -37,7 +37,9 @@ export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = { error: Option.none(), }; -function statusWithoutLiveData(data: Option.Option): EnvironmentThreadStatus { +function statusWithoutLiveData( + data: Option.Option, +): EnvironmentThreadStatus { return Option.isSome(data) ? "cached" : "empty"; } @@ -62,7 +64,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make threadId, error: error.message, }), - Effect.as(Option.none()), + Effect.as(Option.none()), ), ), ); @@ -72,10 +74,10 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make error: Option.none(), }); const lastSequence = yield* SubscriptionRef.make(0); - const persistence = yield* Queue.sliding(1); + const persistence = yield* Queue.sliding(1); const persist = Effect.fn("EnvironmentThreadState.persist")(function* ( - thread: OrchestrationThread, + thread: OrchestrationV2ThreadProjection, ) { yield* cache.saveThread(environmentId, thread).pipe( Effect.catch((error) => @@ -122,7 +124,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make })); const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* ( - thread: OrchestrationThread, + thread: OrchestrationV2ThreadProjection, ) { yield* SubscriptionRef.set(state, { data: Option.some(thread), @@ -152,19 +154,19 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make }); const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* ( - item: OrchestrationThreadStreamItem, + item: OrchestrationV2ThreadStreamItem, ) { if (item.kind === "snapshot") { - yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence); - yield* setThread(item.snapshot.thread); + yield* SubscriptionRef.set(lastSequence, item.snapshotSequence); + yield* setThread(item.projection); return; } const sequence = yield* SubscriptionRef.get(lastSequence); - if (item.event.sequence <= sequence) { + if (item.sequence <= sequence) { return; } - yield* SubscriptionRef.set(lastSequence, item.event.sequence); + yield* SubscriptionRef.set(lastSequence, item.sequence); const current = yield* SubscriptionRef.get(state); if (Option.isNone(current.data)) { @@ -173,11 +175,13 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } return; } - const result = applyThreadDetailEvent(current.data.value, item.event); - if (result.kind === "updated") { - yield* setThread(result.thread); - } else if (result.kind === "deleted") { + if (item.event.type === "thread.deleted") { yield* setDeleted(); + return; + } + const next = applyOrchestrationV2ProjectionEvent(current.data.value, item.event); + if (next !== null) { + yield* setThread(next); } }); @@ -197,7 +201,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make yield* setSynchronizing; yield* subscribe( - ORCHESTRATION_WS_METHODS.subscribeThread, + ORCHESTRATION_V2_WS_METHODS.subscribeThread, { threadId }, { onExpectedFailure: setStreamError, @@ -252,5 +256,4 @@ export * from "./checkpointDiff.ts"; export * from "./composerPathSearch.ts"; export * from "./threadCommands.ts"; export * from "./threadDetail.ts"; -export * from "./threadReducer.ts"; export * from "./threadShell.ts"; diff --git a/packages/contracts/src/chatAttachment.ts b/packages/contracts/src/chatAttachment.ts index 5d1f28d583..bdefc8fe87 100644 --- a/packages/contracts/src/chatAttachment.ts +++ b/packages/contracts/src/chatAttachment.ts @@ -1,6 +1,6 @@ import * as Schema from "effect/Schema"; -import { NonNegativeInt, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { MessageId, NonNegativeInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; export const PROVIDER_SEND_TURN_MAX_INPUT_CHARS = 120_000; export const PROVIDER_SEND_TURN_MAX_ATTACHMENTS = 8; @@ -39,3 +39,23 @@ export type ChatAttachment = typeof ChatAttachment.Type; export const UploadChatAttachment = Schema.Union([UploadChatImageAttachment]); export type UploadChatAttachment = typeof UploadChatAttachment.Type; + +export const PersistChatAttachmentsInput = Schema.Struct({ + threadId: ThreadId, + messageId: MessageId, + attachments: Schema.Array(UploadChatAttachment), +}); +export type PersistChatAttachmentsInput = typeof PersistChatAttachmentsInput.Type; + +export const PersistChatAttachmentsResult = Schema.Struct({ + attachments: Schema.Array(ChatAttachment), +}); +export type PersistChatAttachmentsResult = typeof PersistChatAttachmentsResult.Type; + +export class PersistChatAttachmentsError extends Schema.TaggedErrorClass()( + "PersistChatAttachmentsError", + { + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 29e45397a8..aa3c03d691 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1096,6 +1096,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ status: OrchestrationV2ShellThreadStatus, pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummary), latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary), + latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtc), + hasActionableProposedPlan: Schema.Boolean, itemCount: NonNegativeInt, visibleItemCount: NonNegativeInt, createdAt: Schema.DateTimeUtc, @@ -1666,6 +1668,7 @@ export const OrchestrationV2Command = Schema.Union([ text: Schema.String, attachments: Schema.Array(ChatAttachment), modelSelection: Schema.optional(ModelSelection), + sourcePlanRef: Schema.optional(Schema.Struct({ threadId: ThreadId, planId: PlanId })), dispatchMode: Schema.Union([ Schema.Struct({ type: Schema.Literal("steer_active"), targetRunId: RunId }), Schema.Struct({ type: Schema.Literal("restart_active"), targetRunId: RunId }), @@ -1766,6 +1769,7 @@ export const ORCHESTRATION_V2_WS_METHODS = { export const OrchestrationV2ArchivedShellSnapshot = Schema.Struct({ schemaVersion: PositiveInt, snapshotSequence: NonNegativeInt, + projects: Schema.Array(OrchestrationProjectShell), threads: Schema.Array(OrchestrationV2ThreadShell), }); export type OrchestrationV2ArchivedShellSnapshot = typeof OrchestrationV2ArchivedShellSnapshot.Type; @@ -1790,11 +1794,20 @@ export type OrchestrationV2ArchivedShellStreamItem = typeof OrchestrationV2ArchivedShellStreamItem.Type; export const OrchestrationV2ThreadLaunchWorkspaceStrategy = Schema.Union([ - Schema.Struct({ type: Schema.Literal("root") }), + Schema.Struct({ + type: Schema.Literal("root"), + branch: Schema.optional(TrimmedNonEmptyString), + }), + Schema.Struct({ + type: Schema.Literal("existing_worktree"), + worktreePath: TrimmedNonEmptyString, + branch: Schema.optional(TrimmedNonEmptyString), + }), Schema.Struct({ type: Schema.Literal("worktree"), baseRef: TrimmedNonEmptyString, branch: Schema.optional(TrimmedNonEmptyString), + startFromOrigin: Schema.optional(Schema.Boolean), }), ]); export type OrchestrationV2ThreadLaunchWorkspaceStrategy = @@ -1802,6 +1815,9 @@ export type OrchestrationV2ThreadLaunchWorkspaceStrategy = export const OrchestrationV2ThreadLaunchInput = Schema.Struct({ commandId: CommandId, + creationSource: Schema.optional(OrchestrationV2CreationSource), + threadId: Schema.optional(ThreadId), + reuseExistingThread: Schema.optional(Schema.Boolean), projectId: ProjectId, title: TrimmedNonEmptyString, modelSelection: ModelSelection, @@ -1809,7 +1825,11 @@ export const OrchestrationV2ThreadLaunchInput = Schema.Struct({ interactionMode: ProviderInteractionMode, workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy, initialMessage: Schema.optional( - Schema.Struct({ text: Schema.String, attachments: Schema.Array(ChatAttachment) }), + Schema.Struct({ + messageId: Schema.optional(MessageId), + text: Schema.String, + attachments: Schema.Array(ChatAttachment), + }), ), }); export type OrchestrationV2ThreadLaunchInput = typeof OrchestrationV2ThreadLaunchInput.Type; diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts index a7e5e56433..83d51485b2 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -72,6 +72,7 @@ export const ProjectMutation = Schema.Union([ projectId: ProjectId, title: TrimmedNonEmptyString, workspaceRoot: TrimmedNonEmptyString, + createWorkspaceRootIfMissing: Schema.optional(Schema.Boolean), defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)), scripts: Schema.optional(Schema.Array(ProjectScript)), }), @@ -88,10 +89,20 @@ export const ProjectMutation = Schema.Union([ type: Schema.Literal("project.delete"), commandId: CommandId, projectId: ProjectId, + force: Schema.optional(Schema.Boolean), }), ]); export type ProjectMutation = typeof ProjectMutation.Type; +export class ProjectMutationError extends Schema.TaggedErrorClass()( + "ProjectMutationError", + { + commandId: CommandId, + message: Schema.String, + cause: Schema.optional(Schema.Defect()), + }, +) {} + export const ProjectSearchEntriesInput = Schema.Struct({ cwd: TrimmedNonEmptyString, query: TrimmedNonEmptyString.check(Schema.isMaxLength(256)), diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index c854904753..6ab96102dd 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -14,6 +14,11 @@ import { FilesystemBrowseError, } from "./filesystem.ts"; import { AssetAccessError, AssetCreateUrlInput, AssetCreateUrlResult } from "./assets.ts"; +import { + PersistChatAttachmentsError, + PersistChatAttachmentsInput, + PersistChatAttachmentsResult, +} from "./chatAttachment.ts"; import { OrchestrationGetFullThreadDiffError, OrchestrationGetFullThreadDiffInput, @@ -152,6 +157,7 @@ import { SourceControlRepositoryLookupInput, } from "./sourceControl.ts"; import { VcsError } from "./vcs.ts"; +import { Project, ProjectMutation, ProjectMutationError } from "./project.ts"; export const WS_METHODS = { // Project registry methods @@ -162,6 +168,7 @@ export const WS_METHODS = { projectsReadFile: "projects.readFile", projectsSearchEntries: "projects.searchEntries", projectsWriteFile: "projects.writeFile", + projectsMutate: "projects.mutate", // Shell methods shellOpenInEditor: "shell.openInEditor", @@ -169,6 +176,7 @@ export const WS_METHODS = { // Filesystem methods filesystemBrowse: "filesystem.browse", assetsCreateUrl: "assets.createUrl", + assetsPersistChatAttachments: "assets.persistChatAttachments", // VCS methods vcsPull: "vcs.pull", @@ -387,6 +395,12 @@ export const WsProjectsWriteFileRpc = Rpc.make(WS_METHODS.projectsWriteFile, { error: Schema.Union([ProjectWriteFileError, EnvironmentAuthorizationError]), }); +export const WsProjectsMutateRpc = Rpc.make(WS_METHODS.projectsMutate, { + payload: ProjectMutation, + success: Project, + error: Schema.Union([ProjectMutationError, EnvironmentAuthorizationError]), +}); + export const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, { payload: LaunchEditorInput, error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]), @@ -404,6 +418,12 @@ export const WsAssetsCreateUrlRpc = Rpc.make(WS_METHODS.assetsCreateUrl, { error: Schema.Union([AssetAccessError, EnvironmentAuthorizationError]), }); +export const WsAssetsPersistChatAttachmentsRpc = Rpc.make(WS_METHODS.assetsPersistChatAttachments, { + payload: PersistChatAttachmentsInput, + success: PersistChatAttachmentsResult, + error: Schema.Union([PersistChatAttachmentsError, EnvironmentAuthorizationError]), +}); + export const WsSubscribeVcsStatusRpc = Rpc.make(WS_METHODS.subscribeVcsStatus, { payload: VcsStatusInput, success: VcsStatusStreamEvent, @@ -789,9 +809,11 @@ export const WsRpcGroup = RpcGroup.make( WsProjectsReadFileRpc, WsProjectsSearchEntriesRpc, WsProjectsWriteFileRpc, + WsProjectsMutateRpc, WsShellOpenInEditorRpc, WsFilesystemBrowseRpc, WsAssetsCreateUrlRpc, + WsAssetsPersistChatAttachmentsRpc, WsSubscribeVcsStatusRpc, WsVcsPullRpc, WsVcsRefreshStatusRpc, diff --git a/packages/shared/src/orchestrationTiming.ts b/packages/shared/src/orchestrationTiming.ts index 6914e1320d..ec44464aaf 100644 --- a/packages/shared/src/orchestrationTiming.ts +++ b/packages/shared/src/orchestrationTiming.ts @@ -1,12 +1,12 @@ -type LatestTurnTiming = { - readonly turnId: string | null; +type LatestRunTiming = { + readonly runId: string | null; readonly startedAt: string | null; readonly completedAt: string | null; }; -type SessionActivityState = { +type RuntimeActivityState = { readonly orchestrationStatus: string; - readonly activeTurnId?: string | null; + readonly activeRunId?: string | null; }; export function formatDuration(durationMs: number): string { @@ -31,24 +31,24 @@ export function formatElapsed(startIso: string, endIso: string | undefined): str return formatDuration(endedAt - startedAt); } -export function isLatestTurnSettled( - latestTurn: LatestTurnTiming | null, - session: SessionActivityState | null, +export function isLatestRunSettled( + latestRun: LatestRunTiming | null, + runtime: RuntimeActivityState | null, ): boolean { - if (!latestTurn?.startedAt) return false; - if (!latestTurn.completedAt) return false; - if (!session) return true; - if (session.orchestrationStatus === "running") return false; + if (!latestRun?.startedAt) return false; + if (!latestRun.completedAt) return false; + if (!runtime) return true; + if (runtime.orchestrationStatus === "running") return false; return true; } export function deriveActiveWorkStartedAt( - latestTurn: LatestTurnTiming | null, - session: SessionActivityState | null, + latestRun: LatestRunTiming | null, + runtime: RuntimeActivityState | null, sendStartedAt: string | null, ): string | null { - if (!isLatestTurnSettled(latestTurn, session)) { - return latestTurn?.startedAt ?? sendStartedAt; + if (!isLatestRunSettled(latestRun, runtime)) { + return latestRun?.startedAt ?? sendStartedAt; } return sendStartedAt; }