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 e844181673..a6ccd4eadb 100644 --- a/apps/mobile/src/connection/storage.ts +++ b/apps/mobile/src/connection/storage.ts @@ -2,6 +2,11 @@ import { ConnectionPersistenceError, ConnectionRegistrationStore, ConnectionTargetStore, + EnvironmentCacheStore, + ORCHESTRATION_CACHE_SCHEMA_VERSION, + StoredOrchestrationShellSnapshot, + StoredOrchestrationThreadSnapshot, + decodeOrDiscardOrchestrationCache, registerConnectionInCatalog, removeConnectionFromCatalog, removeCatalogValue, @@ -13,11 +18,88 @@ import { CredentialStore, ProfileStore, } from "@t3tools/client-runtime/connection"; +import { EnvironmentId, ThreadId } 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 CatalogStore from "./catalog-store"; +import * as Schema from "effect/Schema"; +import * as SecureStore from "expo-secure-store"; + +import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store"; + +const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots"; +const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots"; +const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots"; + +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({ + reason: "remote-unavailable", + detail: `Could not ${operation} the local connection catalog: ${String(cause)}`, + }); +} + +function shellPersistenceError( + operation: + | "load-shell" + | "save-shell" + | "load-thread" + | "save-thread" + | "remove-thread" + | "clear-environment", + cause: unknown, +) { + return new ConnectionPersistenceError({ + operation, + message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`, + }); +} + +function threadSnapshotFileName(threadId: ThreadId): string { + return `${encodeURIComponent(threadId)}.json`; +} + +const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")( + function* ( + environmentId: EnvironmentId, + operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment", + ) { + return yield* Effect.tryPromise({ + try: async () => { + const { Directory, Paths } = await import("expo-file-system"); + const directory = new Directory( + Paths.document, + THREAD_SNAPSHOT_CACHE_DIRECTORY, + encodeURIComponent(environmentId), + ); + if (operation !== "clear-environment") { + directory.create({ idempotent: true, intermediates: true }); + } + return directory; + }, + catch: (cause) => shellPersistenceError(operation, cause), + }); + }, +); + +const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* ( + environmentId: EnvironmentId, + threadId: ThreadId, + operation: "load-thread" | "save-thread" | "remove-thread", +) { + const { File } = yield* Effect.promise(() => import("expo-file-system")); + return new File( + yield* threadSnapshotDirectory(environmentId, operation), + threadSnapshotFileName(threadId), + ); +}); function targetPersistenceError( operation: "list-targets" | "register-connection" | "remove-connection", @@ -128,6 +210,172 @@ export const connectionStorageLayer = Layer.effectContext( ), })), }); + const cacheStore = EnvironmentCacheStore.of({ + loadShell: (environmentId) => + Effect.gen(function* () { + const file = yield* shellSnapshotFile(environmentId, "load-shell"); + if (file.exists) { + const raw = yield* Effect.tryPromise({ + try: () => file.text(), + catch: (cause) => shellPersistenceError("load-shell", cause), + }); + const parsed = yield* Effect.try({ + try: () => JSON.parse(raw) as unknown, + catch: (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) { + yield* Effect.try({ + try: () => legacyFile.delete(), + catch: (cause) => shellPersistenceError("load-shell", cause), + }); + } + + 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: ORCHESTRATION_CACHE_SCHEMA_VERSION, + environmentId, + snapshot, + } as const; + const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe( + Effect.mapError((cause) => shellPersistenceError("save-shell", cause)), + ); + yield* Effect.try({ + try: () => { + if (!file.exists) { + file.create({ intermediates: true, overwrite: true }); + } + file.write(JSON.stringify(encoded)); + }, + catch: (cause) => shellPersistenceError("save-shell", cause), + }); + }), + loadThread: (environmentId, threadId) => + Effect.gen(function* () { + const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread"); + if (!file.exists) { + return Option.none(); + } + const raw = yield* Effect.tryPromise({ + try: () => file.text(), + catch: (cause) => shellPersistenceError("load-thread", cause), + }); + const parsed = yield* Effect.try({ + try: () => JSON.parse(raw) as unknown, + catch: (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.thread.id, "save-thread"); + const encoded = yield* Effect.fromResult( + encodeStoredThreadSnapshot({ + schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, + environmentId, + threadId: thread.thread.id, + thread, + }), + ).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause))); + yield* Effect.try({ + try: () => { + if (!file.exists) { + file.create({ intermediates: true, overwrite: true }); + } + file.write(JSON.stringify(encoded)); + }, + catch: (cause) => shellPersistenceError("save-thread", cause), + }); + }), + removeThread: (environmentId, threadId) => + Effect.gen(function* () { + const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread"); + if (file.exists) { + file.delete(); + } + }).pipe( + Effect.mapError((cause) => + cause._tag === "ConnectionPersistenceError" + ? cause + : shellPersistenceError("remove-thread", cause), + ), + ), + clear: (environmentId) => + Effect.gen(function* () { + const file = yield* shellSnapshotFile(environmentId, "clear-environment"); + if (file.exists) { + yield* Effect.try({ + try: () => file.delete(), + catch: (cause) => shellPersistenceError("clear-environment", cause), + }); + } + const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment"); + if (legacyFile.exists) { + yield* Effect.try({ + try: () => legacyFile.delete(), + catch: (cause) => shellPersistenceError("clear-environment", cause), + }); + } + const threadDirectory = yield* threadSnapshotDirectory( + environmentId, + "clear-environment", + ); + if (threadDirectory.exists) { + yield* Effect.try({ + try: () => threadDirectory.delete(), + catch: (cause) => shellPersistenceError("clear-environment", cause), + }); + } + }), + }); + return Context.make(ConnectionTargetStore, targetStore).pipe( Context.add(ConnectionRegistrationStore, registrationStore), Context.add(ProfileStore.ConnectionProfileStore, profileStore), diff --git a/apps/mobile/src/features/archive/archivedThreadList.test.ts b/apps/mobile/src/features/archive/archivedThreadList.test.ts index 697d13e7c4..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,42 +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, - settledOverride: input.settledOverride ?? null, - settledAt: input.settledAt ?? null, - }; + 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 60cb1b4755..74240cdf03 100644 --- a/apps/mobile/src/features/home/HomeScreen.tsx +++ b/apps/mobile/src/features/home/HomeScreen.tsx @@ -123,14 +123,51 @@ interface HomeScreenProps { /* ─── Layout constants ───────────────────────────────────────────────── */ -const ESTIMATED_THREAD_ROW_HEIGHT = 72; -const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44; -/** - * Top spacing between the list and the Android custom header. The Android - * header (AndroidHomeHeader) is rendered in-flow above this screen and - * already consumes the top safe-area inset, so the list only needs breathing - * room here. - */ +function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } { + switch (thread.runtime?.status) { + case "running": + case "waiting": + return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" }; + 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 "failed": + return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" }; + default: + return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" }; + } +} + +const COLLAPSED_THREAD_LIMIT = 6; +const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic)); + +function threadRowExit(values: ExitAnimationsValues) { + "worklet"; + + return { + initialValues: { + height: values.currentHeight, + opacity: 1, + originX: values.currentOriginX, + }, + animations: { + height: withDelay( + 90, + withTiming(0, { + duration: 170, + easing: Easing.inOut(Easing.cubic), + }), + ), + opacity: withDelay(80, withTiming(0, { duration: 100 })), + originX: withTiming(values.currentOriginX - values.windowWidth, { + duration: 190, + easing: Easing.out(Easing.cubic), + }), + }, + }; +} function deriveEmptyState(props: { readonly catalogState: WorkspaceState; @@ -190,7 +227,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, }; } @@ -1071,6 +1108,7 @@ export function HomeScreen(props: HomeScreenProps) { onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined} variant="plain" /> +<<<<<<< HEAD {emptyState.loading ? ( @@ -1080,6 +1118,19 @@ export function HomeScreen(props: HomeScreenProps) { ); } +======= + ) : !hasResults ? ( + + ) : ( + projectGroups.map((group) => { + const isExpanded = expandedProjects.has(group.key); + const visibleThreads = isExpanded + ? group.threads + : group.threads.slice(0, COLLAPSED_THREAD_LIMIT); +>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover) const listHeader = Platform.OS === "ios" ? null : ; diff --git a/apps/mobile/src/features/home/homeThreadList.test.ts b/apps/mobile/src/features/home/homeThreadList.test.ts index 60d3ab2c86..c5caa35a21 100644 --- a/apps/mobile/src/features/home/homeThreadList.test.ts +++ b/apps/mobile/src/features/home/homeThreadList.test.ts @@ -6,11 +6,8 @@ import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-searc import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { - buildHomeProjectScopes, - buildHomeThreadGroups, - sortHomeProjectScopes, -} from "./homeThreadList"; +import { buildHomeThreadGroups } from "./homeThreadList"; +import { makeThreadShellFixture } from "../../test-fixtures"; function makeProject( input: Partial & Pick, @@ -30,25 +27,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, - settledOverride: input.settledOverride ?? null, - settledAt: input.settledAt ?? null, - }; + }); } const NOW = Date.parse("2026-06-29T00:00:00.000Z"); 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 377ae82aba..8bd11b40a2 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,16 +6,21 @@ 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) { +<<<<<<< HEAD // Opaque for the same reason as PendingUserInputCard: nothing blurs the feed // behind this card, so a translucent surface bleeds messages through it. +======= + const canRespond = props.approval.responseCapability === "live"; + const disabled = !canRespond || props.respondingApprovalId === props.approval.requestId; +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) return ( @@ -29,17 +34,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")} > @@ -48,7 +59,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 ddb625f9b2..82ed65af02 100644 --- a/apps/mobile/src/features/threads/PendingUserInputCard.tsx +++ b/apps/mobile/src/features/threads/PendingUserInputCard.tsx @@ -1,342 +1,118 @@ -import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts"; -import { useCallback, useRef } from "react"; -import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native"; -import Animated, { - Easing, - FadeInUp, - FadeOutDown, - LinearTransition, - useAnimatedStyle, - useSharedValue, - withTiming, - type SharedValue, -} from "react-native-reanimated"; +import type { RuntimeRequestId } from "@t3tools/contracts"; +import { Pressable, View } from "react-native"; -import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout"; - -import { SymbolView } from "../../components/AppSymbol"; import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText"; -import { ControlPill } from "../../components/ControlPill"; import { cn } from "../../lib/cn"; -import { useThemeColor } from "../../lib/useThemeColor"; -import { - isPendingUserInputOptionSelected, - type PendingUserInput, - type PendingUserInputDraftAnswer, -} from "../../lib/threadActivity"; +import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity"; export interface PendingUserInputCardProps { readonly pendingUserInput: PendingUserInput; - /** - * Constant while a request is pending (it reserves keyboard space), so the - * keyboard transition is pure translation; changes only on rare discrete - * corrections, which the layout transition smooths. - */ - readonly maxHeight: number; - readonly collapsed: boolean; - readonly onToggleCollapsed: () => void; - /** Renders a stop control on the collapsed bar, which replaces the composer. */ - readonly onStopThread?: () => void; - /** - * 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the - * collapsed bar (inside a clipping window) on the UI thread; the host - * animates it directly from the tap handler so the card and the feed - * inset glide start the same frame. - */ - readonly cardProgress?: SharedValue; - /** - * Receives how far the expanded card extends above the bar footprint - * (written from onLayout with no re-render); the host adds it to the - * thread feed's end inset so the end of the chat stays visible above the - * card. - */ - readonly cardCoverage?: SharedValue; - /** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */ - readonly onInputFocusChange?: (focused: boolean) => void; readonly drafts: Record; - readonly answers: Record> | null; - readonly respondingUserInputId: ApprovalRequestId | null; - readonly onSelectOption: ( - requestId: ApprovalRequestId, - question: UserInputQuestion, - label: string, - ) => void; + readonly answers: Record | null; + readonly respondingUserInputId: RuntimeRequestId | null; + readonly onSelectOption: (requestId: RuntimeRequestId, questionId: string, label: string) => void; readonly onChangeCustomAnswer: ( - requestId: ApprovalRequestId, + requestId: RuntimeRequestId, questionId: string, customAnswer: string, ) => void; readonly onSubmit: () => Promise; } -/** - * On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded - * card is an absolutely-positioned overlay rising above it. The overlay's - * measured height (which drives the thread feed's bottom inset) therefore - * never changes on collapse/expand, so the transcript stays perfectly still - * while the card animates over it. - * - * Android cannot use the overlay: it does not hit-test touches outside a - * parent's bounds, which made everything above the bar-sized wrapper - * untouchable. There the expanded card renders in-flow instead (the wrapper - * grows with it, and the host skips the coverage inset since the measured - * overlay already includes the card). - */ -const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios"; - -const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200); - export function PendingUserInputCard(props: PendingUserInputCardProps) { - const iconSubtle = useThemeColor("--color-icon-subtle"); - const questionCount = props.pendingUserInput.questions.length; - - const cardCoverage = props.cardCoverage; - const barHeightRef = useRef(0); - const cardHeightRef = useRef(0); - // Measured card height, written straight from onLayout: the collapse slide - // distance. Not animated — it only changes on discrete relayouts. - const cardHeight = useSharedValue(0); - const notifyCoverage = useCallback(() => { - if (!cardCoverage) { - return; - } - const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current); - if (coverage === cardCoverage.value) { - return; - } - if (cardCoverage.value === 0) { - // First measurement lands while the list is doing its initial - // end-pin (thread opened onto a pending request); animating it from - // zero would move the end anchor out from under that scroll. - cardCoverage.value = coverage; - return; - } - // Animated so a coverage change at rest (discrete max-height - // corrections) glides the feed instead of stepping it; toggle timing is - // owned by the host's progress values. - cardCoverage.value = withTiming(coverage, { - duration: USER_INPUT_TOGGLE_DURATION_MS, - easing: Easing.out(Easing.cubic), - }); - }, [cardCoverage]); - const handleBarLayout = useCallback( - (event: LayoutChangeEvent) => { - barHeightRef.current = event.nativeEvent.layout.height; - notifyCoverage(); - }, - [notifyCoverage], - ); - const handleCardLayout = useCallback( - (event: LayoutChangeEvent) => { - cardHeightRef.current = event.nativeEvent.layout.height; - cardHeight.value = event.nativeEvent.layout.height; - notifyCoverage(); - }, - [cardHeight, notifyCoverage], - ); - const cardProgress = props.cardProgress; - // No opacity: fading an opaque card over the live transcript reads as a - // crossfade (card text, transcript, and bar all half-visible at once). - // Instead the card stays opaque and slides its full height down past the - // clipping window's bottom edge, so the transcript is only revealed where - // the card has physically left. - const cardAnimatedStyle = useAnimatedStyle(() => { - const progress = cardProgress === undefined ? 1 : cardProgress.value; - return { - transform: [{ translateY: (1 - progress) * cardHeight.value }], - }; - }); - - // On iOS the card stays MOUNTED while collapsed (hidden via the animated - // style): expanding animates existing views on the UI thread the same - // frame the host starts the progress timing, instead of paying a React - // mount + layout before anything moves. - const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed; - const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY; - // The bar renders UNDER the card (earlier in JSX), always opaque: while - // expanded the opaque card covers it, and during the collapse slide the - // card's top edge wipes past and reveals it — no opacity handoff, so no - // crossfade frames. - const bar = showBar ? ( - - - - User input needed +<<<<<<< HEAD + // The surface is opaque on purpose: the card floats over the thread feed + // with no blur behind it, so a translucent background renders the questions + // on top of whatever message happens to sit underneath. +======= + const canRespond = props.pendingUserInput.responseCapability === "live"; +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) + return ( + + + User input needed + + + Fill in the pending answers + + {!canRespond ? ( + + The provider process for this request is no longer available. Interrupt or restart the run + to continue. - - {questionCount} question{questionCount === 1 ? "" : "s"} - - - - - {props.onStopThread ? ( - ) : null} - - ) : null; - const card = renderCard ? ( - // The surface is opaque on purpose: the card floats over the thread - // feed with no blur behind it, so a translucent background renders - // the questions on top of whatever message happens to sit underneath. - - - - - User input needed - - - Fill in the pending answers - - - - - - - - {props.pendingUserInput.questions.map((question) => { - const draft = props.drafts[question.id]; - return ( - - - {question.header} - - - {question.question} - - - {question.options.map((option) => { - const selected = isPendingUserInputOptionSelected(draft, option.label); - return ( - { + const draft = props.drafts[question.id]; + return ( + + + {question.header} + + + {question.question} + + + {question.options.map((option) => { + const selected = + draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length; + return ( + + props.onSelectOption( + props.pendingUserInput.requestId, + question.id, + option.label, + ) + } + > + - props.onSelectOption( - props.pendingUserInput.requestId, - question, - option.label, - ) - } > - - {option.label} - - - ); - })} - - - props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value) - } - onFocus={() => props.onInputFocusChange?.(true)} - onBlur={() => props.onInputFocusChange?.(false)} - placeholder="Or type a custom answer" - className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50" - /> + {option.label} + + + ); + })} - ); - })} - + + props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value) + } + placeholder="Or type a custom answer" + className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50" + /> + + ); + })} void props.onSubmit()} > Submit answers - - ) : null; - return ( - - {bar} - {EXPANDED_CARD_IS_OVERLAY ? ( - // Clipping window for the collapse slide: same footprint as the - // expanded card, bottom edge on the bar's bottom edge. The sliding - // card exits through the bottom edge instead of drawing over the - // composer area, wiping the bar (and the transcript) into view. - - {card} - - ) : ( - card - )} ); } diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index 55a4eed568..ec7edbb2ca 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -1,8 +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, @@ -13,7 +17,6 @@ import { serializeComposerFileLink, type ComposerTrigger, } from "@t3tools/shared/composerTrigger"; -import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native"; import type { ReactNode } from "react"; import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react"; import { @@ -40,18 +43,17 @@ import { scopedThreadKey } from "../../lib/scopedEntities"; import { AppText as Text } from "../../components/AppText"; import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip"; -import { GlassSurface } from "../../components/GlassSurface"; import { ComposerEditor, type ComposerEditorHandle, type ComposerEditorSelection, } from "../../components/ComposerEditor"; import { - ComposerInlineControl, ComposerToolbarButton, ComposerToolbarRow, ComposerToolbarScroller, -} from "../../components/ComposerToolbar"; + ComposerToolbarTrigger, +} from "../../components/ComposerToolbarTrigger"; import { ControlPill } from "../../components/ControlPill"; import { ProviderIcon } from "../../components/ProviderIcon"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; @@ -66,14 +68,8 @@ import { import { resolveProviderOptionDescriptors } from "../../lib/providerOptions"; import { useComposerPathSearch } from "../../state/use-composer-path-search"; import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover"; -import { - type ExistingThreadSettingsRouteSession, - useExistingThreadSettingsRoutePresentation, -} from "./ThreadSettingsSheet"; -import { - useThreadSettingsSheetPresentation, - type NavigationWithFinishTransitioning, -} from "./use-thread-settings-sheet-presentation"; +import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet"; +import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation"; /** * Height of the collapsed composer (pill + vertical padding, excluding safe-area inset). @@ -85,7 +81,7 @@ export const COMPOSER_COLLAPSED_CHROME = 60; * Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset). * Used by the parent to compute the larger feed bottom inset when the composer is focused. */ -export const COMPOSER_EXPANDED_CHROME = 156; +export const COMPOSER_EXPANDED_CHROME = 174; export interface ThreadComposerProps { readonly draftMessage: string; @@ -96,13 +92,7 @@ export interface ThreadComposerProps { readonly connectionState: RemoteClientConnectionState; readonly connectionError: string | null; readonly environmentLabel: string | null; - /** - * Message sync phase for the selected thread (drives the status pill): - * "loading" = first fetch, nothing to show yet; "syncing" = cached messages - * are on screen while they reconcile with the server. - */ - readonly threadSyncPhase?: "loading" | "syncing" | null; - readonly selectedThread: OrchestrationThreadShell; + readonly selectedThread: EnvironmentThreadShell; readonly serverConfig: T3ServerConfig | null; readonly queueCount: number; readonly environmentId: EnvironmentId; @@ -119,13 +109,11 @@ export interface ThreadComposerProps { readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void; readonly onReconnectEnvironment: () => void; readonly onExpandedChange?: (expanded: boolean) => void; - /** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */ - readonly onEditorFocusChange?: (focused: boolean) => void; } /** - * The pill / card container — renders with Expo's native GlassView on supported - * iOS 26+ devices and keeps the existing opaque fallback elsewhere. + * The pill / card container — renders as LiquidGlassView on supported + * iOS 26+ devices (progressive blur, native morph), opaque View otherwise. * Exported so NewTaskDraftScreen can render the same composer chrome. */ // One timing for every piece of the expanded↔compact morph so the surface, @@ -141,8 +129,6 @@ export function ComposerSurface(props: { readonly children: ReactNode; readonly style: ViewStyle; readonly isDarkMode: boolean; - /** Existing thread composers morph between pill and card layouts. */ - readonly animateLayout?: boolean; }) { // Drop shadow lives on a wrapper: `overflow: "hidden"` on the surface itself // (needed to clip content to the pill shape) would clip the shadow on iOS. @@ -155,26 +141,35 @@ export function ComposerSurface(props: { elevation: 10, }; + if (isLiquidGlassSupported) { + return ( + + + {props.children} + + + ); + } + return ( - - + {props.children} - + ); } @@ -265,7 +260,6 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill( }); export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) { - const navigation = useNavigation(); const isDarkMode = useColorScheme() === "dark"; const foregroundColor = useThemeColor("--color-foreground"); const bodyText = useScaledTextRole("body"); @@ -276,16 +270,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer editorRef: inputRef, isEditorFocused: isFocused, }); - const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation(); - const settingsRoutePresentedRef = useRef(false); const wasExpandedBeforePreviewRef = useRef(false); const inFlightThreadIdsRef = useRef(new Set()); const { onExpandedChange } = props; const [previewImageUri, setPreviewImageUri] = useState(null); const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0; - // Opening and presentation count as active so the composer stays expanded - // while focus moves between its native editor and the settings picker. + // Opening and closing count as active so the composer stays expanded while + // focus moves between its native editor and the settings modal. const isExpanded = isFocused || settingsSheetPresentation.isActive; const canSend = hasContent; @@ -311,24 +303,28 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer } }, [inputRef]); - const onEditorFocusChange = props.onEditorFocusChange; const handleFocus = useCallback(() => { setIsFocused(true); - onEditorFocusChange?.(true); - }, [onEditorFocusChange]); + }, []); const handleBlur = useCallback(() => { setIsFocused(false); - onEditorFocusChange?.(false); - }, [onEditorFocusChange]); +<<<<<<< HEAD + }, []); const showStopAction = props.selectedThread.session?.status === "running" || props.selectedThread.session?.status === "starting"; +======= + onExpandedChange?.(false); + }, [onExpandedChange]); + const showStopAction = threadRuntimeIsActive(props.selectedThread.runtime); +>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover) const sendLabel = props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send"; const currentModelSelection = props.selectedThread.modelSelection; const currentRuntimeMode = props.selectedThread.runtimeMode; + const currentInteractionMode = props.selectedThread.interactionMode ?? "default"; const connectionStatus = composerConnectionStatus({ connectionError: props.connectionError, connectionState: props.connectionState, @@ -538,7 +534,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer // after the send so its preference read and native Activity start don't // contend with the queued-message feedback on the tap frame. armAgentAwarenessLiveActivityForLocalWork({ - environmentId: props.environmentId, threadTitle: props.selectedThread.title, projectTitle: props.environmentLabel ?? "T3 Code", }); @@ -621,71 +616,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer }), [currentModelOption?.capabilities, currentModelSelection.options], ); - const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id); - const settingsRouteSession = useMemo( - () => ({ - ownerId: settingsOwnerId, - providerGroups: threadProviderGroups, - selectedModel: currentModelSelection, - onSelectModel: (option) => props.onUpdateModelSelection(option.selection), - optionDescriptors: providerOptionDescriptors, - onUpdateOptionSelections: (options) => - props.onUpdateModelSelection({ ...currentModelSelection, options }), - runtimeMode: currentRuntimeMode, - onUpdateRuntimeMode: props.onUpdateRuntimeMode, - }), - [ - currentModelSelection, - currentRuntimeMode, - props.onUpdateModelSelection, - props.onUpdateRuntimeMode, - providerOptionDescriptors, - settingsOwnerId, - threadProviderGroups, - ], - ); - const openSettings = useCallback(() => { - settingsRoutePresentation.present(settingsRouteSession); - settingsSheetPresentation.open(); - }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]); - - useEffect(() => { - if (settingsSheetPresentation.isActive) { - settingsRoutePresentation.present(settingsRouteSession); - } - }, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]); - - useEffect(() => { - if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) { - return; - } - - settingsRoutePresentedRef.current = true; - navigation.dispatch(StackActions.push("ThreadSettingsSheet")); - }, [navigation, settingsSheetPresentation.isVisible]); - - useFocusEffect( - useCallback(() => { - if (!settingsRoutePresentedRef.current) { - return; - } - - settingsRoutePresentedRef.current = false; - settingsSheetPresentation.onDismissed(); - settingsRoutePresentation.clear(settingsOwnerId); - }, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]), - ); - - useEffect( - () => - // UIKit's completion callback for the sheet dismissal, surfaced by the - // native-stack patch. This is when the queued keyboard restore runs. - (navigation as unknown as NavigationWithFinishTransitioning).addListener( - "finishTransitioning", - settingsSheetPresentation.onStackTransitionsFinished, - ), - [navigation, settingsSheetPresentation.onStackTransitionsFinished], - ); + const settingsSummaryLabel = threadSettingsSummaryLabel({ + modelLabel: currentModelOption?.label ?? currentModelSelection.model, + optionDescriptors: providerOptionDescriptors, + runtimeMode: currentRuntimeMode, + interactionMode: currentInteractionMode, + }); return ( ) : null} - {isExpanded ? ( - + + + {isExpanded ? ( + // Toolbar row — matches draft page layout (expanded only) + + void props.onPickDraftImages()} showChevron={false} /> - } - label={currentModelOption?.label ?? currentModelSelection.model} - maxWidth={152} - onPress={openSettings} + label={settingsSummaryLabel} + maxWidth={320} + onPress={settingsSheetPresentation.open} /> {showStopAction ? ( - ) : null} - + + ) : null} {/* Queue count */} {props.queueCount > 0 ? ( @@ -898,6 +834,21 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer ) : null} + props.onUpdateModelSelection(option.selection)} + optionDescriptors={providerOptionDescriptors} + onUpdateOptionSelections={(options) => + props.onUpdateModelSelection({ ...currentModelSelection, options }) + } + runtimeMode={currentRuntimeMode} + onUpdateRuntimeMode={props.onUpdateRuntimeMode} + /> + ; 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 activePendingUserInputAnswers: Record | null; + readonly respondingUserInputId: RuntimeRequestId | null; readonly draftMessage: string; readonly draftAttachments: ReadonlyArray; readonly connectionStateLabel: EnvironmentConnectionPhase; @@ -101,6 +62,7 @@ export interface ThreadDetailScreenProps { readonly threadSyncStatus?: EnvironmentThreadStatus; /** Non-null when older turns exist beyond the loaded window. */ readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null; + readonly activeThreadBusy: boolean; readonly environmentId: EnvironmentId; readonly projectWorkspaceRoot: string | null; readonly threadCwd: string | null; @@ -121,16 +83,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, - question: UserInputQuestion, + requestId: RuntimeRequestId, + questionId: string, label: string, ) => void; readonly onChangeUserInputCustomAnswer: ( - requestId: ApprovalRequestId, + requestId: RuntimeRequestId, questionId: string, customAnswer: string, ) => void; @@ -208,48 +170,8 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray state.isVisible); - const liveKeyboardHeight = useKeyboardState((state) => state.height); - // Android can swallow the IME hide callbacks when the app is backgrounded - // mid keyboard-hide (the reported repro: send — which blurs and starts the - // hide — then Home within a second). The keyboard library's height AND - // visibility then stay frozen open, so gating the sticky translation on - // visibility alone still strands the composer after resume. Quarantine the - // translation on every Android resume instead; any sign of a live keyboard - // stream — an owned input gaining focus, or any visibility/height movement — - // lifts it. A healthy resume sees no visual difference (the translation is - // already zero while the keyboard is closed). - const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false); - useEffect(() => { - if (Platform.OS !== "android") { - return; - } - const subscription = AppState.addEventListener("change", (state) => { - if (state === "active") { - setKeyboardStateSuspect(true); - } - }); - return () => { - subscription.remove(); - }; - }, []); - useEffect(() => { - setKeyboardStateSuspect(false); - }, [isKeyboardVisible, liveKeyboardHeight]); - const handleOwnedInputFocusChange = useCallback((focused: boolean) => { - if (focused) { - setKeyboardStateSuspect(false); - } - }, []); - const windowHeight = useWindowDimensions().height; - const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + IOS_NAV_BAR_HEIGHT; const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`; const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id); const composerEditorRef = useRef(null); @@ -260,17 +182,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread const lastScrolledAnchorMessageIdRef = useRef(null); const [composerExpanded, setComposerExpanded] = useState(false); const [anchorMessageId, setAnchorMessageId] = useState(null); - const [endFollowEnabled, setEndFollowEnabled] = useState(true); - // Android keys the safe-area padding on keyboard visibility (#5988): the - // back gesture closes the keyboard while the editor stays focused, and a - // focus-keyed inset would leave the toolbar under the gesture bar. iOS must - // NOT use visibility — it only flips on keyboardDidHide, after the hide - // animation, so the composer would ride down flush to the screen edge and - // then snap up into the inset. On iOS blur precedes the hide, so the - // focus-keyed inset is already in place while the composer rides down. - const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded) - ? 0 - : Math.max(insets.bottom, 12); + const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12); const contentPresentationKind = props.contentPresentation.kind; // The raw sync status enters "synchronizing" on every full fetch, cached or // not. Whether messages are already on screen decides the pill label: no @@ -291,41 +203,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread const selectedThreadFeed = props.selectedThreadFeed; const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME; const composerOverlapHeight = composerChrome + composerBottomInset; - // While a user-input request is pending, the questionnaire owns the - // composer slot outright: expanded it is the full card, collapsed it is a - // composer-style bar in the same place (with its own stop control). The - // composer never mounts into the transition, which keeps the collapse and - // keyboard animations coherent. Collapse state is keyed by request id so a - // new request re-expands automatically. - const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] = - useState(null); - const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null; - const userInputCollapsed = - activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId; - // The card's height RESERVES keyboard space at all times instead of - // tracking the keyboard: transforms (the sticky translation) apply - // same-frame on the UI thread while layout props lag a Yoga pass behind, - // so any height that follows the keyboard flashes the card over the nav - // header on the way up. With a constant height the keyboard transition is - // pure translation — frame-perfect by construction — and the resting card - // stays compact over the transcript. Before the first open the reserve is - // an estimate; once a real height is known the card corrects once, - // discretely. - const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0); - useEffect(() => { - if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) { - setLastKnownKeyboardHeight(liveKeyboardHeight); - } - }, [lastKnownKeyboardHeight, liveKeyboardHeight]); - const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({ - windowHeight, - keyboardHeight: - lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT, - navigationHeaderHeight, - // The questionnaire owns the composer slot, so only the composer's - // bottom inset still overlaps. - composerOverlapHeight: composerBottomInset, - }); const estimatedOverlayHeight = composerOverlapHeight; // The overlay's measured height includes the home-indicator inset (the // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes @@ -342,103 +219,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread Math.max(0, estimatedOverlayHeight - nativeInsetOvercount), -nativeInsetOvercount, ); - // The expanded questionnaire is an absolute overlay on iOS, so it never - // changes the measured overlay height (that constancy is what keeps the - // feed from snapping on collapse/expand). The toggle choreography runs on - // SHARED VALUES set directly in the tap handler — one JS hop, then the - // card's rise/sink and the feed's end-inset glide animate in lockstep on - // the UI thread, keyboard-style, instead of waiting on React mount + - // onLayout + state round trips. Coverage (how far the card extends above - // the bar) is measured straight into a shared value by the card's - // onLayout, with no re-render. - const userInputCardProgress = useSharedValue(1); - const userInputInsetProgress = useSharedValue(1); - const userInputCardCoverage = useSharedValue(0); - // Android renders the expanded card in-flow (it cannot hit-test the iOS - // overlay outside the bar's bounds), so its measured overlay height already - // includes the card — the coverage extra is iOS-only. - const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null; - const combinedContentInsetEndAdjustment = useSharedValue( - Math.max(0, estimatedOverlayHeight - nativeInsetOvercount), - ); - useAnimatedReaction( - () => - contentInsetEndAdjustment.value + - (userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0), - (value) => { - combinedContentInsetEndAdjustment.value = value; - }, - [userInputCoverageApplies], - ); const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef }); - const endFollowEnabledRef = useRef(true); - endFollowEnabledRef.current = endFollowEnabled; - const userInputRepinTimerRef = useRef | null>(null); - // The list's own corrections for these inset changes drift on short - // content (and the error compounds across toggles), so deterministically - // re-pin the end once a toggle settles: a no-op when the resting position - // is already right, corrective when it is not. Follow state is re-checked - // inside the callback — the user may grab the list during the settle - // window, and yanking them back would override a live gesture. - const scheduleUserInputRepin = useCallback( - (delayMs: number) => { - if (userInputRepinTimerRef.current !== null) { - clearTimeout(userInputRepinTimerRef.current); - } - userInputRepinTimerRef.current = setTimeout(() => { - userInputRepinTimerRef.current = null; - if (!endFollowEnabledRef.current) { - return; - } - void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => { - freeze.set(false); - }); - }, delayMs); - }, - [freeze, scrollMessageToEnd], - ); - useEffect( - () => () => { - if (userInputRepinTimerRef.current !== null) { - clearTimeout(userInputRepinTimerRef.current); - } - }, - [], - ); - const handleToggleUserInputCollapsed = useCallback(() => { - if (activeUserInputRequestId === null) { - return; - } - if (userInputCollapsed) { - // Expanding: card and feed glide start NOW, on the UI thread. - userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING); - userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING); - setCollapsedUserInputRequestId(null); - scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50); - } else { - // Collapsing hides the custom-answer inputs; release the keyboard with - // them instead of leaving it up over a dead responder. - Keyboard.dismiss(); - userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING); - // Instant: the sinking card still covers the strip being revealed, and - // animating the inset downward is what drifted the short-content end - // anchor. - userInputInsetProgress.value = 0; - setCollapsedUserInputRequestId(activeUserInputRequestId); - scheduleUserInputRepin(60); - } - }, [ - activeUserInputRequestId, - scheduleUserInputRepin, - userInputCardProgress, - userInputCollapsed, - userInputInsetProgress, - ]); - useEffect(() => { - // A new request always arrives expanded. - userInputCardProgress.value = 1; - userInputInsetProgress.value = 1; - }, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]); const showContent = props.showContent ?? true; const layoutVariant = props.layoutVariant ?? "compact"; const isSplitLayout = layoutVariant === "split"; @@ -459,7 +240,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread useEffect(() => { setAnchorMessageId(null); lastScrolledAnchorMessageIdRef.current = null; - setEndFollowEnabled(true); freeze.set(false); }, [freeze, selectedThreadKey]); @@ -531,16 +311,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread composerEditorRef.current?.blur(); }, []); - const handleScrollToEnd = useCallback(() => { - void Haptics.selectionAsync(); - void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => { - freeze.set(false); - }); - }, [freeze, scrollMessageToEnd]); - - const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled; - const isDarkMode = useColorScheme() === "dark"; - const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => { feedTouchStartRef.current = { pageX: event.nativeEvent.pageX, @@ -572,6 +342,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread }, []); return ( +<<<<<<< HEAD {showContent ? ( @@ -609,14 +379,55 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread ) : ( )} +======= + + + {showContent ? ( + + + + ) : ( + + )} + + {/* Floating composer — sticks to keyboard via KeyboardStickyView */} + {showContent ? ( + + + {props.activeWorkStartedAt ? ( + + ) : null} +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) {/* Floating composer — sticks to keyboard via KeyboardStickyView */} {showContent ? ( @@ -624,60 +435,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread list's bottom inset, so any padding above the pill/composer pushes the resting content floor up by the same amount. */} - {showScrollToEndButton ? ( - - {isLiquidGlassSupported ? ( - - - - ) : ( - - )} - - ) : null} {props.activePendingApproval || props.activePendingUserInput ? ( @@ -691,13 +452,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread {props.activePendingUserInput ? ( - {/* Hidden (not unmounted) while a user-input request owns the - composer slot, so composer drafts and editor state survive. */} - - - + ) : null} diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx index c5edb822ae..ada1b63f1b 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 { formatElapsed } from "@t3tools/shared/orchestrationTiming"; import { SymbolView } from "../../components/AppSymbol"; @@ -48,7 +48,6 @@ import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reani import { useThemeColor } from "../../lib/useThemeColor"; import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics"; import { useFontFamily } from "../../lib/useFontFamily"; -import { scopedThreadKey } from "../../lib/scopedEntities"; import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic"; import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks"; @@ -88,13 +87,9 @@ 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 { - resolveThreadFeedLiveFollow, - type ThreadFeedLiveFollowEvent, -} from "./thread-feed-live-follow"; import { collapsedWorkLogHeight, ThreadWorkGroupToggle, @@ -147,8 +142,7 @@ export interface ThreadFeedProps { readonly feed: ReadonlyArray; readonly contentPresentation: ThreadContentPresentation; readonly agentLabel: string; - readonly latestTurn: ThreadFeedLatestTurn | null; - readonly activeWorkStartedAt: string | null; + readonly latestRun: ThreadFeedLatestRun | null; readonly listRef: RefObject; readonly freeze: SharedValue; readonly anchorMessageId: MessageId | null; @@ -159,7 +153,6 @@ export interface ThreadFeedProps { readonly layoutVariant?: LayoutVariant; readonly usesAutomaticContentInsets?: boolean; readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void; - readonly onEndFollowEnabledChange?: (enabled: boolean) => void; readonly skills?: ReadonlyArray; /** Non-null when older turns exist beyond the loaded window. */ readonly loadEarlier?: { @@ -825,11 +818,11 @@ function renderFeedEntry( readonly copiedRowId: string | null; 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; @@ -843,16 +836,12 @@ function renderFeedEntry( const entry = info.item; const { markdownStyles, iconSubtleColor, userBubbleColor } = props; - if (entry.type === "working") { - return ; - } - - 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]" > @@ -897,7 +886,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) && @@ -1332,10 +1321,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { const copyFeedbackTimeoutRef = useRef | null>(null); const foldSettleFrameRef = useRef(null); const foldSettleSecondFrameRef = useRef(null); +<<<<<<< HEAD const disclosureAnchorKeyRef = useRef(null); const headerMaterialVisibleRef = useRef(false); const previousLatestTurnRef = useRef(props.latestTurn); - const userScrollSettleTimerRef = useRef | null>(null); const { width: windowWidth } = useWindowDimensions(); const { appearance } = useAppearancePreferences(); const [viewportWidth, setViewportWidth] = useState(() => @@ -1354,28 +1343,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // momentum; only motion inside a session can break follow, so MVCP // compensations and programmatic scrolls never strand a follower. const userScrollSessionRef = useRef(false); - const setEndFollow = useCallback( - (enabled: boolean) => { - if (endFollowEnabledRef.current === enabled) { - return; - } - endFollowEnabledRef.current = enabled; - setEndFollowEnabled(enabled); - props.onEndFollowEnabledChange?.(enabled); - }, - [props.onEndFollowEnabledChange], - ); - const transitionEndFollow = useCallback( - (event: ThreadFeedLiveFollowEvent) => { - setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event)); - }, - [setEndFollow], - ); + const setEndFollow = useCallback((enabled: boolean) => { + if (endFollowEnabledRef.current === enabled) { + return; + } + endFollowEnabledRef.current = enabled; + setEndFollowEnabled(enabled); + }, []); +======= + const previousLatestTurnRef = useRef(props.latestRun); + const { width: viewportWidth } = useWindowDimensions(); + const [foldToggleSettling, setFoldToggleSettling] = useState(false); +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) const [interactionState, setInteractionState] = useState<{ readonly copiedRowId: string | null; readonly expandedWorkGroups: Record; readonly expandedWorkRows: Record; - readonly expandedTurnIds: ReadonlySet; + readonly expandedTurnIds: ReadonlySet; }>({ copiedRowId: null, expandedWorkGroups: {}, @@ -1465,15 +1449,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { viewportWidth, ], ); - const reportHeaderMaterialVisibility = useCallback( - (visible: boolean) => { - if (headerMaterialVisibleRef.current === visible) { - return; - } - headerMaterialVisibleRef.current = visible; - props.onHeaderMaterialVisibilityChange?.(visible); - }, - [props.onHeaderMaterialVisibilityChange], + const presentedFeed = useMemo( + () => deriveThreadFeedPresentation(props.feed, props.latestRun, expandedTurnIds), + [expandedTurnIds, props.feed, props.latestRun], ); const handleScroll = useCallback( (event: NativeSyntheticEvent) => { @@ -1482,72 +1460,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // UIKit's adjustedContentInset, so topContentInset is 0 here). Add the // header height back or the material toggles a full header too late. reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6); - // LegendList recomputes its inset-aware end distance before invoking - // this handler, so getState() is current. Only the actual end re-arms - // follow: its broader maintain-scroll threshold is large enough for a - // streaming chunk to pull a user back before their upward drag escapes. - // A live user-scroll session still wins even if the first scroll event - // remains inside LegendList's at-end tolerance. + // Latch bookkeeping. LegendList recomputes its inset-aware end distance + // before invoking this handler, so getState() is current. Returning to + // the end re-arms follow no matter who scrolled (the user, or our own + // scroll-to-end); moving away breaks it only during a user-initiated + // scroll session, so MVCP compensations and programmatic repositioning + // can never strand a follower. const listState = props.listRef.current?.getState(); if (listState) { - transitionEndFollow({ - type: "scroll", - isAtEnd: listState.isAtEnd, - userScrollSessionActive: userScrollSessionRef.current, - }); + if (listState.isWithinMaintainScrollAtEndThreshold) { + setEndFollow(true); + } else if (userScrollSessionRef.current) { + setEndFollow(false); + } } }, - [reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow], + [reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow], ); - const clearUserScrollSettle = useCallback(() => { - if (userScrollSettleTimerRef.current !== null) { - clearTimeout(userScrollSettleTimerRef.current); - userScrollSettleTimerRef.current = null; + const handleScrollBeginDrag = useCallback(() => { + userScrollSessionRef.current = true; + }, []); + // The session must survive past finger-lift so momentum that carries the + // user away from the end still breaks follow; a drag released with no + // momentum ends its session at the release itself, otherwise at momentum + // end. Leaving a session open would let a later animated maintain-scroll + // read as user motion and break follow spuriously. + const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent) => { + const velocity = event.nativeEvent.velocity?.y ?? 0; + if (Math.abs(velocity) < 0.05) { + userScrollSessionRef.current = false; } }, []); - const handleScrollBeginDrag = useCallback(() => { - clearUserScrollSettle(); - userScrollSessionRef.current = true; - // Pause before the first scroll event. Otherwise a stream update can run - // maintainScrollAtEnd between touch-down and the drag leaving its threshold. - transitionEndFollow({ type: "user-scroll-begin" }); - }, [clearUserScrollSettle, transitionEndFollow]); - const finishUserScroll = useCallback( - (releaseIsAtEnd?: boolean) => { - clearUserScrollSettle(); - const userScrollSessionActive = userScrollSessionRef.current; - userScrollSessionRef.current = false; - transitionEndFollow({ - type: "user-scroll-end", - // With no momentum, preserve the finger-release position. Streaming - // growth during the native momentum-detection window must not turn a - // release at the live edge into an opt-out from follow. - isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false, - userScrollSessionActive, - }); - }, - [clearUserScrollSettle, props.listRef, transitionEndFollow], - ); - // Finger-lift velocity is not a reliable momentum signal: a gentle fling - // can report zero and still decelerate. Give native momentum a short window - // to announce itself; if it does, onMomentumScrollBegin cancels this fallback - // and the session survives until the settled momentum-end position. This - // mirrors the native-event handoff used by the home thread list's scroll gate. - const handleScrollEndDrag = useCallback(() => { - clearUserScrollSettle(); - const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false; - userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160); - }, [clearUserScrollSettle, finishUserScroll, props.listRef]); - const handleMomentumScrollBegin = useCallback(() => { - if (userScrollSessionRef.current) { - clearUserScrollSettle(); - } - }, [clearUserScrollSettle]); const handleMomentumScrollEnd = useCallback(() => { - finishUserScroll(); - }, [finishUserScroll]); - - useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]); + userScrollSessionRef.current = false; + }, []); const handleViewportLayout = useCallback((event: LayoutChangeEvent) => { const nextWidth = Math.round(event.nativeEvent.layout.width); @@ -1556,30 +1502,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current)); }, []); - // Thread identity is env-scoped: two environments can hold the same - // ThreadId, and keying resets (or the list mount) on the bare id would - // carry stale scroll/follow state across an environment switch. - const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId); - useEffect(() => { reportHeaderMaterialVisibility(false); - }, [feedThreadKey, reportHeaderMaterialVisibility]); + }, [props.threadId, reportHeaderMaterialVisibility]); // A thread switch opens pinned to the end; a send explicitly returns to the // live edge (ThreadDetailScreen scrolls the new message into place). Both // re-arm follow regardless of where the user had scrolled before. useEffect(() => { - clearUserScrollSettle(); userScrollSessionRef.current = false; - transitionEndFollow({ type: "reset" }); - }, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]); + setEndFollow(true); + }, [props.threadId, setEndFollow]); useEffect(() => { if (props.anchorMessageId !== null) { - clearUserScrollSettle(); userScrollSessionRef.current = false; - transitionEndFollow({ type: "reset" }); + setEndFollow(true); } - }, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]); + }, [props.anchorMessageId, setEndFollow]); const expandedWorkGroupIds = useMemo(() => { const ids = new Set(); @@ -1615,7 +1554,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { // initial scroll-to-end computes with a zero end inset and rests one // composer-height short of the end. Layout effect: it must land before the // list's first positioning tick or the one-shot initial scroll misses it. - const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`; + const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`; useLayoutEffect(() => { const bottom = props.contentInsetEndAdjustment.value; if (bottom > 0) { @@ -1634,29 +1573,29 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { [presentedFeed, props.anchorMessageId, anchorTopInset], ); 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), @@ -1665,14 +1604,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 () => { @@ -1766,17 +1705,28 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { [suspendEndScrollMaintenanceForDisclosure], ); - const onToggleTurnFold = useCallback( - (turnId: TurnId) => { - suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`); - setInteractionState((current) => { - const next = new Set(current.expandedTurnIds); - if (next.has(turnId)) { - next.delete(turnId); - } else { - next.add(turnId); - } - return { ...current, expandedTurnIds: next }; + const onToggleTurnFold = useCallback((runId: RunId) => { + setFoldToggleSettling(true); + if (foldSettleFrameRef.current !== null) { + cancelAnimationFrame(foldSettleFrameRef.current); + } + if (foldSettleSecondFrameRef.current !== null) { + cancelAnimationFrame(foldSettleSecondFrameRef.current); + } + setInteractionState((current) => { + const next = new Set(current.expandedTurnIds); + if (next.has(runId)) { + next.delete(runId); + } else { + next.add(runId); + } + return { ...current, expandedTurnIds: next }; + }); + foldSettleFrameRef.current = requestAnimationFrame(() => { + foldSettleSecondFrameRef.current = requestAnimationFrame(() => { + setFoldToggleSettling(false); + foldSettleFrameRef.current = null; + foldSettleSecondFrameRef.current = null; }); }, [suspendEndScrollMaintenanceForDisclosure], @@ -1982,7 +1932,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { onScroll={handleScroll} onScrollBeginDrag={handleScrollBeginDrag} onScrollEndDrag={handleScrollEndDrag} - onMomentumScrollBegin={handleMomentumScrollBegin} onMomentumScrollEnd={handleMomentumScrollEnd} scrollEventThrottle={16} ListHeaderComponent={ diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index cad1cab8e6..2e2eeb264c 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -1,11 +1,6 @@ -import { NativeStackScreenOptions } from "../../native/StackHeader"; -import { - StackActions, - useFocusEffect, - useNavigation, - type StaticScreenProps, -} from "@react-navigation/native"; -import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react"; +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, ThreadId, type ProjectScript } from "@t3tools/contracts"; import { @@ -479,20 +474,15 @@ function ThreadRouteContent( void navigation.navigate("Connections"); }, [navigation]); const handleStopThread = useCallback(() => { - if ( - !selectedThread || - (selectedThread.session?.status !== "running" && - selectedThread.session?.status !== "starting") - ) { + const runtime = selectedThread?.runtime; + if (!selectedThread || !runtime || !threadRuntimeIsActive(runtime)) { return; } return interruptThreadTurn({ environmentId: selectedThread.environmentId, input: { threadId: selectedThread.id, - ...(selectedThread.session.activeTurnId - ? { turnId: selectedThread.session.activeTurnId } - : {}), + ...(runtime.activeRunId ? { runId: runtime.activeRunId } : {}), }, }); }, [interruptThreadTurn, selectedThread]); @@ -522,7 +512,7 @@ function ThreadRouteContent( 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) { @@ -530,7 +520,7 @@ function ThreadRouteContent( } const nextId = nextOpenTerminalId({ - listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId), + listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId), }); void navigation.navigate("ThreadTerminal", { environmentId: String(selectedThread.environmentId), @@ -557,9 +547,9 @@ function ThreadRouteContent( } 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 9de3d4d308..547e4f4930 100644 --- a/apps/mobile/src/features/threads/threadPresentation.ts +++ b/apps/mobile/src/features/threads/threadPresentation.ts @@ -7,49 +7,9 @@ export function threadSortValue(thread: EnvironmentThreadShell): number { return Number.isNaN(candidate) ? 0 : candidate; } -export type ThreadStatusKind = - | "pending-approval" - | "awaiting-input" - | "working" - | "connecting" - | "error" - | "plan-ready"; - -export interface ThreadStatusPresentation extends StatusTone { - readonly kind: ThreadStatusKind; - /** Foreground color for the leading status icon. */ - readonly iconColor: string; - /** Background color for the leading status icon circle. */ - readonly iconBackground: string; - /** Whether the indicator represents in-flight activity. */ - readonly pulse: boolean; -} - -/** Neutral icon colors for threads with no actionable status. */ -export const THREAD_STATUS_NEUTRAL_ICON = { - iconColor: "#8e8e93", - iconBackground: "rgba(142,142,147,0.22)", -} as const; - -function isLatestTurnSettled( - latestTurn: OrchestrationLatestTurn | null, - session: OrchestrationSession | null, -): boolean { - if (!latestTurn?.startedAt) return false; - if (!latestTurn.completedAt) return false; - if (!session) return true; - return session.status !== "running"; -} - -/** - * Resolves the user-facing status of a thread, in priority order. Returns - * `null` for quiescent threads so rows stay free of "Idle"-style noise. - * Mirrors `resolveThreadStatusPill` in apps/web/src/components/Sidebar.logic.ts. - */ -export function resolveThreadStatus( - thread: EnvironmentThreadShell, -): ThreadStatusPresentation | null { - if (thread.hasPendingApprovals) { +export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone { + const status = thread.runtime?.status; + if (status === "running" || status === "waiting") { return { kind: "pending-approval", label: "Needs Approval", @@ -60,8 +20,7 @@ export function resolveThreadStatus( pulse: false, }; } - - if (thread.hasPendingUserInput) { + if (status === "completed") { return { kind: "awaiting-input", label: "Awaiting Input", @@ -72,8 +31,7 @@ export function resolveThreadStatus( pulse: false, }; } - - if (thread.session?.status === "running") { + if (status === "queued" || status === "starting") { return { kind: "working", label: "Working", @@ -84,8 +42,7 @@ export function resolveThreadStatus( pulse: true, }; } - - if (thread.session?.status === "starting") { + if (status === "failed") { return { kind: "connecting", label: "Connecting", diff --git a/apps/mobile/src/features/threads/use-project-actions.ts b/apps/mobile/src/features/threads/use-project-actions.ts index 9d03dde59a..184ee3c4d7 100644 --- a/apps/mobile/src/features/threads/use-project-actions.ts +++ b/apps/mobile/src/features/threads/use-project-actions.ts @@ -58,15 +58,16 @@ export function useCreateProjectThread() { const result = await startTurn({ environmentId: input.project.environmentId, - input: buildProjectThreadStartTurnInput({ - projectId: input.project.id, - projectCwd: input.project.workspaceRoot, - threadId: metadata.threadId, - commandId: metadata.commandId, - messageId: metadata.messageId, - createdAt: metadata.createdAt, - text: initialMessageText, - attachments: input.initialAttachments, + input: { + commandId: CommandId.make(metadata.commandId), + creationSource: "mobile", + threadId, + message: { + messageId: MessageId.make(metadata.messageId), + role: "user", + text: initialMessageText, + attachments: input.initialAttachments, + }, modelSelection: input.modelSelection, runtimeMode: input.runtimeMode, interactionMode: input.interactionMode, 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 e1d46fd858..2169527c31 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -1,561 +1,112 @@ +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"; -import { - buildPendingUserInputAnswers, - buildThreadFeed, - deriveThreadFeedPresentation, - isPendingUserInputOptionSelected, - setPendingUserInputCustomAnswer, - togglePendingUserInputOptionSelection, - type ThreadFeedActivity, - type ThreadFeedEntry, -} from "./threadActivity"; +const runId = RunId.make("run-1"); -const singleSelectQuestion = { - id: "runtime", - header: "Runtime", - question: "Which runtime should be used?", - options: [ - { label: "Go", description: "One binary" }, - { label: "Node.js", description: "Reuse TypeScript" }, - ], - multiSelect: false, -} as const; - -const multiSelectQuestion = { - id: "scope", - header: "Scope", - question: "Which data should be collected?", - options: [ - { label: "Orders", description: "Receipts" }, - { label: "Listings", description: "Inventory" }, - ], - multiSelect: true, -} as const; - -describe("pending user input answers", () => { - it("replaces single-select options and toggles multi-select options", () => { - expect( - togglePendingUserInputOptionSelection( - singleSelectQuestion, - { selectedOptionLabels: ["Go"] }, - "Node.js", - ), - ).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] }); - - const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders"); - const ordersAndListings = togglePendingUserInputOptionSelection( - multiSelectQuestion, - orders, - "Listings", - ); - expect(ordersAndListings).toEqual({ - customAnswer: "", - selectedOptionLabels: ["Orders", "Listings"], - }); - expect( - togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"), - ).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] }); - - const paddedOrders = togglePendingUserInputOptionSelection( - multiSelectQuestion, - undefined, - " Orders ", - ); - expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] }); - expect( - togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "), - ).toEqual({ customAnswer: "" }); - }); - - it("builds array answers for multi-select questions", () => { - expect( - buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], { - runtime: { selectedOptionLabels: ["Go"] }, - scope: { selectedOptionLabels: ["Orders", "Listings"] }, - }), - ).toEqual({ - runtime: "Go", - scope: ["Orders", "Listings"], - }); - }); - - it("clears selected options while a custom answer is active", () => { - expect( - setPendingUserInputCustomAnswer( - { selectedOptionLabels: ["Orders", "Listings"] }, - "Orders first", - ), - ).toEqual({ customAnswer: "Orders first" }); - }); - - it("matches selected chips against normalized option labels", () => { - expect( - isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "), - ).toBe(true); - expect( - isPendingUserInputOptionSelected( - { selectedOptionLabels: ["Orders"], customAnswer: "Orders first" }, - " Orders ", - ), - ).toBe(false); - }); -}); - -function makeActivity( - input: Partial & - Pick, -): OrchestrationThreadActivity { +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, - settledOverride: input.settledOverride ?? null, - settledAt: input.settledAt ?? null, + 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", - }, - }), + it("orders V2 messages and work entries while retaining structured tool data", () => { + 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); - 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" }], - }, + 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"'); + }); + + 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("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'", - }, - }), - ], + 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 group = feed[0]; - - expect(group).toMatchObject({ - type: "activity-group", - }); - if (!group || group.type !== "activity-group") { - return; - } - - expect(group.activities).toHaveLength(1); - expect(group.activities[0]).toMatchObject({ - id: "tool-completed", - createdAt: "2026-04-01T00:00:02.000Z", - turnId: "turn-1", - summary: "Run tests", - detail: "bun run test", - canExpand: true, - icon: "command", - toolLike: true, - status: "success", - }); - expect(group.activities[0]?.getFullDetail()).toBe("/bin/zsh -lc 'bun run test'"); - expect(group.activities[0]?.getCopyText()).toBe( - "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'", - ); - }); - - it("keeps MCP inputs available to expanded mobile work rows", () => { - const turnId = TurnId.make("turn-mcp"); - const thread = makeThread({ - id: ThreadId.make("thread-mcp"), - projectId: ProjectId.make("project-1"), - title: "Expandable MCP call", - latestTurn: { - turnId, - state: "completed", - requestedAt: "2026-04-01T00:00:00.000Z", - startedAt: "2026-04-01T00:00:01.000Z", - completedAt: "2026-04-01T00:00:03.000Z", - assistantMessageId: null, - }, - activities: [ - makeActivity({ - id: EventId.make("mcp-completed"), - kind: "tool.completed", - tone: "tool", - summary: "Call repository tool", - createdAt: "2026-04-01T00:00:02.000Z", - turnId, - payload: { - title: "Call repository tool", - itemType: "mcp_tool_call", - detail: "repository.search", - status: "completed", - data: { - item: { - server: "repository", - tool: "search", - arguments: { query: "work log" }, - }, - }, - }, - }), - ], - }); - - const group = buildThreadFeed(thread)[0]; - expect(group).toMatchObject({ type: "activity-group" }); - if (!group || group.type !== "activity-group") { - return; - } - - expect(group.activities[0]?.icon).toBe("wrench"); - expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"'); - expect(group.activities[0]?.getFullDetail()).toContain("repository.search"); - }); - - it("defers large tool output expansion until a work row is opened or copied", () => { - let serializedToolOutputs = 0; - const activities = Array.from({ length: 5_000 }, (_, index) => - makeActivity({ - id: EventId.make(`large-tool-${index}`), - kind: "tool.completed", - tone: "tool", - summary: `Tool ${index}`, - createdAt: new Date(Date.UTC(2026, 3, 1, 0, 0, index)).toISOString(), - payload: { - title: `Tool ${index}`, - itemType: "mcp_tool_call", - status: "completed", - data: { - item: { - toJSON: () => { - serializedToolOutputs += 1; - return { output: "x".repeat(32_768) }; - }, - }, - }, - }, - }), - ); - const thread = makeThread({ - id: ThreadId.make("thread-large-tools"), - projectId: ProjectId.make("project-1"), - title: "Large tools", - activities, - }); - - const feed = buildThreadFeed(thread); - expect(serializedToolOutputs).toBe(0); - - const group = feed[0]; - expect(group).toMatchObject({ type: "activity-group" }); - if (!group || group.type !== "activity-group") { - return; - } - - expect(group.activities).toHaveLength(5_000); - expect(group.activities[0]?.getFullDetail()).toContain('"output"'); - expect(serializedToolOutputs).toBe(1); - expect(group.activities[0]?.getCopyText()).toContain('"output"'); - expect(serializedToolOutputs).toBe(1); - }); - - it("folds settled turn work while leaving the terminal answer visible", () => { - const turnId = TurnId.make("turn-1"); - const thread = makeThread({ - id: ThreadId.make("thread-3"), - projectId: ProjectId.make("project-1"), - title: "Folded work", - latestTurn: { - turnId, - state: "completed", - requestedAt: "2026-04-01T00:00:00.000Z", - startedAt: "2026-04-01T00:00:01.000Z", - completedAt: "2026-04-01T00:00:18.000Z", - assistantMessageId: MessageId.make("assistant-final"), - }, - messages: [ - { - id: MessageId.make("assistant-commentary"), - role: "assistant", - text: "I am checking.", - turnId, - streaming: false, - createdAt: "2026-04-01T00:00:02.000Z", - updatedAt: "2026-04-01T00:00:03.000Z", - }, - { - id: MessageId.make("assistant-final"), - role: "assistant", - text: "Done.", - turnId, - streaming: false, - createdAt: "2026-04-01T00:00:17.000Z", - updatedAt: "2026-04-01T00:00:18.000Z", - }, - ], - activities: [ - makeActivity({ - id: EventId.make("tool-completed"), - kind: "tool.completed", - tone: "tool", - summary: "Read files", - createdAt: "2026-04-01T00:00:05.000Z", - turnId, - payload: { - title: "Read files", - itemType: "file_read", - status: "completed", - }, - }), - ], - }); - - const feed = buildThreadFeed(thread); - const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set()); - expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]); - expect(collapsed[0]).toMatchObject({ - type: "turn-fold", - label: "Worked for 17s", - expanded: false, - }); - - const expanded = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set([turnId])); - expect(expanded.map((entry) => entry.id)).toEqual([ - "turn-fold:turn-1", - "assistant-commentary", - "tool-completed", - "assistant-final", - ]); - }); - - it("measures a steer-superseded turn from its user boundary through trailing work", () => { - const firstTurnId = TurnId.make("turn-1"); - const secondTurnId = TurnId.make("turn-2"); - const thread = makeThread({ - id: ThreadId.make("thread-steered"), - projectId: ProjectId.make("project-1"), - title: "Steered work", - latestTurn: { - turnId: secondTurnId, - state: "running", - requestedAt: "2026-04-01T00:00:14.000Z", - startedAt: "2026-04-01T00:00:14.000Z", + const presented = deriveThreadFeedPresentation( + feed, + { + runId, + status: "running", + startedAt: "2026-06-20T00:00:01.000Z", completedAt: null, - assistantMessageId: MessageId.make("assistant-next"), }, - messages: [ - { - id: MessageId.make("user-1"), - role: "user", - text: "Do it once more.", - turnId: null, - streaming: false, - createdAt: "2026-04-01T00:00:00.000Z", - updatedAt: "2026-04-01T00:00:00.000Z", - }, - { - id: MessageId.make("assistant-commentary"), - role: "assistant", - text: "Kicking off call 1.", - turnId: firstTurnId, - streaming: false, - createdAt: "2026-04-01T00:00:09.000Z", - updatedAt: "2026-04-01T00:00:09.000Z", - }, - { - id: MessageId.make("user-2"), - role: "user", - text: "Actually do 15.", - turnId: null, - streaming: false, - createdAt: "2026-04-01T00:00:14.000Z", - updatedAt: "2026-04-01T00:00:14.000Z", - }, - { - id: MessageId.make("assistant-next"), - role: "assistant", - text: "One down - adjusting.", - turnId: secondTurnId, - streaming: true, - createdAt: "2026-04-01T00:00:17.000Z", - updatedAt: "2026-04-01T00:00:17.000Z", - }, - ], - activities: [ - makeActivity({ - id: EventId.make("work-1"), - kind: "tool.completed", - tone: "tool", - summary: "Ran command", - createdAt: "2026-04-01T00:00:12.000Z", - turnId: firstTurnId, - payload: { - title: "Ran command", - itemType: "command_execution", - status: "completed", - }, - }), - ], - }); + new Set(), + ); - const feed = buildThreadFeed(thread); - const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set()); - expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({ - turnId: firstTurnId, - label: "Worked for 12s", - }); - }); - - it("keeps an active turn expanded and classifies error-shaped tool output", () => { - const turnId = TurnId.make("turn-running"); - const thread = makeThread({ - id: ThreadId.make("thread-4"), - projectId: ProjectId.make("project-1"), - title: "Running work", - latestTurn: { - turnId, - state: "running", - requestedAt: "2026-04-01T00:00:00.000Z", - startedAt: "2026-04-01T00:00:01.000Z", - completedAt: null, - assistantMessageId: null, - }, - activities: [ - makeActivity({ - id: EventId.make("tool-failed"), - kind: "tool.completed", - tone: "tool", - summary: "Run command", - createdAt: "2026-04-01T00:00:05.000Z", - turnId, - payload: { - title: "Run command", - itemType: "command_execution", - detail: "zsh: command not found: nope", - status: "completed", - }, - }), - ], - }); - - const feed = buildThreadFeed(thread); - expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed); - expect(feed[0]).toMatchObject({ - type: "activity-group", - activities: [{ status: "failure" }], - }); + expect(presented.some((entry) => entry.type === "run-fold")).toBe(false); + expect(presented.find((entry) => entry.type === "activity-group")?.activities[0]?.status).toBe( + "failure", + ); }); it("appends active work as a normal timeline row", () => { diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index fbcb2e1c7e..34f50ee6db 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -1,39 +1,27 @@ -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 selectedOptionLabels?: ReadonlyArray; + readonly selectedOptionLabel?: string; readonly customAnswer?: string; } 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 canExpand: boolean; @@ -56,6 +44,7 @@ export interface ThreadFeedActivity { readonly status: "success" | "failure" | "neutral" | null; } +<<<<<<< HEAD const MAX_VISIBLE_WORK_LOG_ENTRIES = 1; type WorkLogToolLifecycleStatus = "inProgress" | "completed" | "failed" | "declined" | "stopped"; @@ -84,18 +73,20 @@ interface DerivedWorkLogEntry extends WorkLogEntry { taskId?: string; } +======= +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) 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; }; @@ -110,149 +101,38 @@ 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: "work-toggle"; + readonly type: "run-fold"; readonly id: string; readonly createdAt: string; - readonly turnId: TurnId | null; - readonly groupId: string; - readonly hiddenCount: number; - readonly expanded: boolean; - readonly onlyToolActivities: boolean; - } - | { - readonly type: "turn-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; } -function normalizeSelectedOptionLabels( - value: ReadonlyArray | undefined, -): ReadonlyArray { - if (!Array.isArray(value)) { - return []; - } - - return Array.from( - new Set(value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)), - ); -} - function resolvePendingUserInputAnswer( - question: UserInputQuestion, draft: PendingUserInputDraftAnswer | undefined, -): string | ReadonlyArray | null { +): string | null { +<<<<<<< HEAD const customAnswer = normalizeDraftAnswer(draft?.customAnswer); if (customAnswer) { return customAnswer; } - - const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels); - if (question.multiSelect) { - return selectedOptionLabels.length > 0 ? selectedOptionLabels : null; - } - return selectedOptionLabels[0] ?? null; + return normalizeDraftAnswer(draft?.selectedOptionLabel); } /** Codex children settle via task.updated (idle/failed/interrupted), never @@ -562,7 +442,10 @@ function workLogEntryIsToolLike(entry: WorkLogEntry): boolean { function toolDetailTextLooksLikeFailure(text: string): boolean { const normalized = text.toLowerCase(); +======= +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) return ( +<<<<<<< HEAD normalized.includes("file not found") || normalized.includes("no files found") || normalized.includes("enoent") || @@ -577,645 +460,248 @@ function toolDetailTextLooksLikeFailure(text: string): boolean { //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) +>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover) ); } -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 workEntryHasExpandedBody(entry: WorkLogEntry): boolean { - return ( - (entry.itemType === "mcp_tool_call" && entry.toolData !== undefined) || - Boolean((entry.rawCommand ?? entry.command)?.trim()) || - Boolean(entry.detail?.trim()) || - (entry.changedFiles?.some((path) => path.trim().length > 0) ?? false) - ); -} - -function memoizeValue(build: () => T): () => T { - let value: T; - let initialized = false; - return () => { - if (!initialized) { - value = build(); - initialized = true; - } - return value; - }; -} - -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[] = []; - // Mutable backing array for the trailing group so appending an activity is - // O(1) instead of re-copying the group (which made this loop quadratic on - // long tool runs). The array is only mutated while it is the trailing group. - let openGroupActivities: ThreadFeedActivity[] | null = null; - let openGroupTurnId: TurnId | null = null; - 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); openGroupActivities = null; continue; } - - if (openGroupActivities !== null && openGroupTurnId === entry.turnId) { - openGroupActivities.push(entry.activity); + const previous = grouped.at(-1); + if (previous?.type === "activity-group" && previous.runId === entry.runId) { + grouped[grouped.length - 1] = { + ...previous, + activities: [...previous.activities, entry.activity], + }; continue; } - - openGroupActivities = [entry.activity]; - openGroupTurnId = entry.turnId; grouped.push({ type: "activity-group", id: entry.id, createdAt: entry.createdAt, - turnId: entry.turnId, - activities: openGroupActivities, + 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( @@ -1224,20 +710,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; @@ -1245,41 +730,31 @@ function deriveThreadFeedTurnFolds( export function deriveThreadFeedPresentation( feed: ReadonlyArray, - latestTurn: ThreadFeedLatestTurn | null, - expandedTurnIds: ReadonlySet, - expandedWorkGroupIds: ReadonlySet = new Set(), - activeWorkStartedAt: string | null = null, + latestRun: ThreadFeedLatestRun | null, + expandedRunIds: ReadonlySet, ): ThreadFeedEntry[] { - const sourceFeed = feed.filter( - (entry) => - entry.type !== "turn-fold" && entry.type !== "work-toggle" && entry.type !== "working", - ); - 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)) { - appendPresentedFeedEntry(result, entry, expandedWorkGroupIds); - } + if (!collapsedEntryIds.has(entry.id)) result.push(entry); } if (activeWorkStartedAt !== null) { result.push({ @@ -1291,288 +766,54 @@ export function deriveThreadFeedPresentation( return result; } -function appendPresentedFeedEntry( - result: ThreadFeedEntry[], - entry: Exclude, - expandedWorkGroupIds: ReadonlySet, -): void { - if (entry.type !== "activity-group") { - result.push(entry); - return; - } - - const activities = entry.activities.filter( - (activity) => !(activity.toolLike && activity.status === "neutral"), - ); - if (activities.length === 0) { - return; - } - if (activities.length <= MAX_VISIBLE_WORK_LOG_ENTRIES) { - result.push({ - ...entry, - activities, - }); - return; - } - - const groupId = entry.id; - const expanded = expandedWorkGroupIds.has(groupId); - const hiddenCount = activities.length - MAX_VISIBLE_WORK_LOG_ENTRIES; - const visibleActivities = expanded ? activities : activities.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES); - - for (const activity of visibleActivities) { - result.push({ - type: "activity-group", - id: activity.id, - createdAt: activity.createdAt, - turnId: activity.turnId, - activities: [activity], - }); - } - result.push({ - type: "work-toggle", - id: `work-toggle:${groupId}`, - createdAt: entry.createdAt, - turnId: entry.turnId, - groupId, - hiddenCount, - expanded, - onlyToolActivities: activities.every((activity) => activity.toolLike), - }); -} - -/** - * Sorts activities into lifecycle order. `derivePendingApprovals` and - * `derivePendingUserInputs` both expect this ordering; sorting once and - * passing the result to both avoids re-sorting the full activity history - * per derivation. - */ -export function sortThreadActivities( - activities: ReadonlyArray, -): ReadonlyArray { - return Arr.sort(activities, activityOrder); -} - -export function derivePendingApprovals( - sortedActivities: ReadonlyArray, -): PendingApproval[] { - const openByRequestId = new Map(); - - for (const activity of sortedActivities) { - 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( - sortedActivities: ReadonlyArray, -): PendingUserInput[] { - const openByRequestId = new Map(); - - for (const activity of sortedActivities) { - 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 selectedOptionLabels = - customAnswer.trim().length > 0 - ? undefined - : normalizeSelectedOptionLabels(draft?.selectedOptionLabels); - return { - customAnswer, - ...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}), - }; -} - -export function isPendingUserInputOptionSelected( - draft: PendingUserInputDraftAnswer | undefined, - optionLabel: string, -): boolean { - if (normalizeDraftAnswer(draft?.customAnswer)) { - return false; - } - - return normalizeSelectedOptionLabels(draft?.selectedOptionLabels).includes(optionLabel.trim()); -} - -export function togglePendingUserInputOptionSelection( - question: UserInputQuestion, - draft: PendingUserInputDraftAnswer | undefined, - optionLabel: string, -): PendingUserInputDraftAnswer { - const normalizedOptionLabel = optionLabel.trim(); - - if (question.multiSelect) { - const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels); - const nextSelectedOptionLabels = selectedOptionLabels.includes(normalizedOptionLabel) - ? selectedOptionLabels.filter((label) => label !== normalizedOptionLabel) - : [...selectedOptionLabels, normalizedOptionLabel]; - - return { - customAnswer: "", - ...(nextSelectedOptionLabels.length > 0 - ? { selectedOptionLabels: nextSelectedOptionLabels } - : {}), - }; - } - - return { - customAnswer: "", - selectedOptionLabels: [normalizedOptionLabel], - }; + const selectedOptionLabel = + customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel; + return { customAnswer, ...(selectedOptionLabel ? { selectedOptionLabel } : {}) }; } export function buildPendingUserInputAnswers( - questions: ReadonlyArray, + questions: ReadonlyArray, draftAnswers: Record, -): Record> | null { - const answers: Record> = {}; - +): Record | null { + const answers: Record = {}; for (const question of questions) { - const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]); - if (!answer) { - return null; - } + const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]); + 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 getFullDetail = memoizeValue(() => buildWorkEntryExpandedBody(entry)); - const getCopyText = memoizeValue(() => - [summary, detail, getFullDetail()] - .filter((value, index, values): value is string => { - return Boolean(value) && values.indexOf(value) === index; - }) - .join("\n"), - ); - return { - type: "activity", - id: entry.id, - createdAt: entry.createdAt, - turnId: entry.turnId, - activity: { - id: entry.id, - createdAt: entry.createdAt, - turnId: entry.turnId, - summary, - detail, - canExpand: workEntryHasExpandedBody(entry), - getFullDetail, - getCopyText, - icon: workEntryIcon(entry), - 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 0c0da1f847..47d93f98fb 100644 --- a/apps/mobile/src/state/queries.ts +++ b/apps/mobile/src/state/queries.ts @@ -1,23 +1,9 @@ -import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs"; -import type { - EnvironmentId, - OrchestrationThread, - ThreadId, - VcsListRefsResult, - VcsRef, -} from "@t3tools/contracts"; -import { - createThreadSearchResultsAtomFamily, - makeThreadSearchKey, - type EnvironmentThreadSearchMatch, -} from "@t3tools/client-runtime/state/thread-search"; -import { useAtomValue } from "@effect/atom-react"; -import * as Cause from "effect/Cause"; +import 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"; -import { useCallback, useEffect, useMemo, useState } from "react"; +import { Atom } from "effect/unstable/reactivity"; +import { useEffect, useMemo, useState } from "react"; -import { appAtomRegistry } from "./atom-registry"; import { orchestrationEnvironment } from "./orchestration"; import { projectEnvironment } from "./projects"; import { useEnvironmentQuery } from "./query"; @@ -33,8 +19,6 @@ const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200; const COMPOSER_PATH_SEARCH_LIMIT = 20; const THREAD_SEARCH_DEBOUNCE_MS = 200; const VCS_REF_LIST_LIMIT = 100; -const EMPTY_REFS: ReadonlyArray = []; -const INITIAL_BRANCH_CURSORS = [undefined] as const; const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray = Object.freeze([]); const EMPTY_THREAD_SEARCH_ATOM = Atom.make({ matches: EMPTY_THREAD_SEARCH_MATCHES, @@ -51,7 +35,7 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({ }); export interface ThreadDetailView { - readonly data: OrchestrationThread | null; + readonly data: EnvironmentThread | null; readonly error: string | null; readonly isPending: boolean; readonly isDeleted: boolean; @@ -63,7 +47,7 @@ export interface ComposerPathSearchTarget { readonly query: string | null; } -export function useDebouncedValue(value: A, delayMs: number): A { +function useDebouncedValue(value: A, delayMs: number): A { const [debounced, setDebounced] = useState(value); useEffect(() => { @@ -136,113 +120,6 @@ export function useBranches(input: { ); } -export function usePaginatedBranches(target: VcsRefTarget) { - const query = target.query?.trim() ?? ""; - const targetKey = - target.environmentId !== null && target.cwd !== null - ? JSON.stringify([target.environmentId, target.cwd, query]) - : null; - const [pagination, setPagination] = useState<{ - readonly targetKey: string | null; - readonly cursors: ReadonlyArray; - }>({ - targetKey, - cursors: INITIAL_BRANCH_CURSORS, - }); - const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS; - const pageAtoms = useMemo( - () => - target.environmentId !== null && target.cwd !== null - ? cursors.map((cursor) => - vcsEnvironment.listRefs({ - environmentId: target.environmentId!, - input: { - cwd: target.cwd!, - ...(query.length > 0 ? { query } : {}), - ...(cursor === undefined ? {} : { cursor }), - limit: VCS_REF_LIST_LIMIT, - }, - }), - ) - : [], - [cursors, query, target.cwd, target.environmentId], - ); - const pagesAtom = useMemo( - () => - Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe( - Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`), - ), - [pageAtoms, targetKey], - ); - const results = useAtomValue(pagesAtom); - const values = results.flatMap((result) => { - const value = Option.getOrNull(AsyncResult.value(result)); - return value === null ? [] : [value]; - }); - const refs = new Map(); - for (const value of values) { - for (const ref of value.refs) { - refs.set(ref.name, ref); - } - } - const first = values[0] ?? null; - const last = values.at(-1) ?? null; - const data: VcsListRefsResult | null = - first === null || last === null - ? null - : { - refs: [...refs.values()], - isRepo: first.isRepo, - hasPrimaryRemote: first.hasPrimaryRemote, - nextCursor: last.nextCursor, - totalCount: Math.max(...values.map((value) => value.totalCount)), - }; - const lastResult = results.at(-1); - const isFetchingNextPage = - results.length > 1 && - lastResult?.waiting === true && - Option.isNone(AsyncResult.value(lastResult)); - const failed = results.find((result) => result._tag === "Failure"); - const error = - failed?._tag === "Failure" - ? (() => { - const cause = Cause.squash(failed.cause); - return cause instanceof Error && cause.message.trim().length > 0 - ? cause.message - : "Failed to load refs."; - })() - : null; - const refresh = useCallback(() => { - const firstPage = pageAtoms[0]; - setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS }); - if (firstPage !== undefined) { - appAtomRegistry.refresh(firstPage); - } - }, [pageAtoms, targetKey]); - const loadNext = useCallback(() => { - if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) { - return; - } - setPagination((current) => { - const currentCursors = - current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS; - return currentCursors.includes(data.nextCursor!) - ? { targetKey, cursors: currentCursors } - : { targetKey, cursors: [...currentCursors, data.nextCursor!] }; - }); - }, [data?.nextCursor, targetKey]); - - return { - data, - refs: data?.refs ?? EMPTY_REFS, - error, - isPending: results.some((result) => result.waiting), - isFetchingNextPage, - refresh, - loadNext, - }; -} - export function useComposerPathSearch(target: ComposerPathSearchTarget) { const normalizedTarget = useMemo( () => ({ 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 30b3a0704f..fa3e336625 100644 --- a/apps/mobile/src/state/use-selected-thread-requests.ts +++ b/apps/mobile/src/state/use-selected-thread-requests.ts @@ -1,22 +1,15 @@ import { useAtomValue } from "@effect/atom-react"; import { useCallback, useMemo, useState } from "react"; -import { - ApprovalRequestId, - type ProviderApprovalDecision, - type UserInputQuestion, -} 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, sortThreadActivities, - togglePendingUserInputOptionSelection, type PendingUserInputDraftAnswer, } from "../lib/threadActivity"; import { appAtomRegistry } from "./atom-registry"; @@ -28,21 +21,15 @@ const userInputDraftsByRequestKeyAtom = Atom.make< Record> >({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts")); -function setUserInputDraftOption( - requestKey: string, - question: UserInputQuestion, - label: string, -): void { +function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void { const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom); appAtomRegistry.set(userInputDraftsByRequestKeyAtom, { ...current, [requestKey]: { ...current[requestKey], - [question.id]: togglePendingUserInputOptionSelection( - question, - current[requestKey]?.[question.id], - label, - ), + [questionId]: { + selectedOptionLabel: label, + }, }, }); } @@ -77,14 +64,11 @@ 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); - // Sort once; both derivations expect the same lifecycle ordering. - const sortedActivities = useMemo( - () => (selectedThread ? sortThreadActivities(selectedThread.activities) : []), + const activePendingApprovals = useMemo( + () => selectedThread?.pendingApprovals ?? [], [selectedThread], ); const activePendingApprovals = useMemo( @@ -93,8 +77,8 @@ export function useSelectedThreadRequests() { ); const activePendingApproval = activePendingApprovals[0] ?? null; const activePendingUserInputs = useMemo( - () => derivePendingUserInputs(sortedActivities), - [sortedActivities], + () => selectedThread?.pendingUserInputs ?? [], + [selectedThread], ); const activePendingUserInput = activePendingUserInputs[0] ?? null; const activePendingUserInputDrafts = @@ -108,19 +92,19 @@ export function useSelectedThreadRequests() { : null; const onSelectUserInputOption = useCallback( - (requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => { + (requestId: RuntimeRequestId, questionId: string, label: string) => { if (!selectedThreadShell) { return; } const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId); - setUserInputDraftOption(requestKey, question, label); + setUserInputDraftOption(requestKey, questionId, label); }, [selectedThreadShell], ); const onChangeUserInputCustomAnswer = useCallback( - (requestId: ApprovalRequestId, questionId: string, customAnswer: string) => { + (requestId: RuntimeRequestId, questionId: string, customAnswer: string) => { if (!selectedThreadShell) { return; } @@ -132,10 +116,16 @@ export function useSelectedThreadRequests() { ); const onRespondToApproval = useCallback( - async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => { + async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => { if (!selectedThreadShell) { return; } + if ( + activePendingApprovals.find((approval) => approval.requestId === requestId) + ?.responseCapability !== "live" + ) { + return; + } setRespondingApprovalId(requestId); const result = await respondToApproval({ @@ -149,11 +139,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 721c82a0e3..bf296007bb 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 { @@ -106,13 +107,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]); @@ -123,12 +124,14 @@ export function useThreadComposerState() { } return deriveActiveWorkStartedAt( - selectedThread.latestTurn, + selectedThread.latestRun, selectedThreadSessionActivity, null, ); }, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]); + const activeThreadBusy = !!selectedThread && threadRuntimeIsActive(selectedThread.runtime); + const onSendMessage = useCallback(async () => { if (!selectedThreadShell) { return null; @@ -304,6 +307,7 @@ export function useThreadComposerState() { modelSelection, runtimeMode, interactionMode, + activeThreadBusy, onChangeDraftMessage, onPickDraftImages, onPasteIntoDraft, diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.ts index 68c973ff97..5c045f7c9e 100644 --- a/apps/mobile/src/state/use-thread-outbox-drain.ts +++ b/apps/mobile/src/state/use-thread-outbox-drain.ts @@ -1,7 +1,7 @@ import { useAtomValue } from "@effect/atom-react"; -import type { - EnvironmentProject, - EnvironmentThreadShell, +import { + threadRuntimeIsActive, + type EnvironmentThreadShell, } from "@t3tools/client-runtime/state/shell"; import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime"; import { @@ -221,6 +221,7 @@ export function useThreadOutboxDrain(): void { environmentId: queuedMessage.environmentId, input: { commandId: queuedMessage.commandId, + creationSource: "mobile", threadId: queuedMessage.threadId, message: { messageId: queuedMessage.messageId, @@ -314,7 +315,7 @@ export function useThreadOutboxDrain(): void { threadExists: thread !== undefined, shellStatus, environmentConnected: environment?.connectionState === "connected", - threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting", + threadBusy: threadRuntimeIsActive(thread?.runtime), }); if (deliveryAction === "wait") { continue; 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 a0966c87c2..0f56f6d0ab 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), ); @@ -111,7 +118,7 @@ const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe( projectionStoreLayer, providerSessionManagerProvided, runExecutionServiceProvided, - runtimePolicyLayer, + runtimePolicyProvided, ), ), ); @@ -130,7 +137,7 @@ const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe( idAllocatorLayer, projectionStoreLayer, providerSessionManagerProvided, - runtimePolicyLayer, + runtimePolicyProvided, ), ), ); @@ -189,7 +196,7 @@ const orchestratorProvided = orchestratorLayer.pipe( idAllocatorLayer, providerAdapterRegistryProvided, providerEventIngestorProvided, - runtimePolicyLayer, + runtimePolicyProvided, providerSessionManagerProvided, providerSwitchServiceProvided, runExecutionServiceProvided, @@ -201,9 +208,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 ebfe951a40..895d4aeea0 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"; @@ -13,9 +16,11 @@ import { type AuthAccessStreamEvent, type AuthEnvironmentScope, AuthSessionId, + CommandId, type DiscoveredLocalServerList, type GitActionProgressEvent, type GitManagerServiceError, + type MessageId, OrchestrationGetFullThreadDiffError, OrchestrationGetTurnDiffError, ORCHESTRATION_V2_WS_METHODS, @@ -28,18 +33,21 @@ import { type ProjectEntriesFailure, type ProjectFileFailure, type ProjectFileOperation, + type ProjectMutation, ProjectListEntriesError, ProjectReadFileError, ProjectSearchContentsError, ProjectSearchEntriesError, ProjectWriteFileError, + ProjectMutationError, RelayClientInstallFailedError, type RelayClientInstallProgressEvent, type FilesystemBrowseFailure, FilesystemBrowseError, AssetWorkspaceContextNotFoundError, AssetWorkspaceContextResolutionError, - RpcClientId, + ChatAttachmentId, + PersistChatAttachmentsError, EnvironmentAuthorizationError, ThreadId, type TerminalAttachStreamEvent, @@ -81,6 +89,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"; @@ -121,6 +131,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; @@ -256,8 +333,11 @@ const RPC_REQUIRED_SCOPE = new Map([ [WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope], [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], @@ -627,20 +707,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", @@ -675,6 +763,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( @@ -684,7 +830,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) => threadManagement.dispatch( ThreadManagementService.withCreationProvenance(command, { createdBy: "user", - creationSource: "web", + creationSource: "creationSource" in command ? command.creationSource : "web", }), ), ) @@ -775,26 +921,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( @@ -1223,6 +1372,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", @@ -1305,6 +1470,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 5fcad2f741..b2bc90efcc 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -118,6 +118,8 @@ export function BranchToolbarBranchSelector({ () => scopeThreadRef(environmentId, threadId), [environmentId, threadId], ); + const serverThread = useThread(threadRef); + 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 5c026c94a1..11f935c290 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1,3 +1,4 @@ +<<<<<<< HEAD import { EnvironmentId, MessageId, @@ -7,8 +8,13 @@ import { TurnId, } from "@t3tools/contracts"; import { afterEach, describe, expect, it, vi } from "vite-plus/test"; +======= +import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, RunId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; +>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover) -import type { Thread, ThreadShell } from "../types"; +import type { Thread } from "../types"; +import { makeThreadFixture } from "../test-fixtures"; import { MAX_HIDDEN_MOUNTED_PREVIEW_THREADS, MAX_HIDDEN_MOUNTED_TERMINAL_THREADS, @@ -76,7 +82,7 @@ describe("environment reconnect warning grace", () => { }); function makeThread(overrides: Partial = {}): Thread { - return { + return makeThreadFixture({ id: threadId, environmentId, projectId, @@ -87,27 +93,25 @@ function makeThread(overrides: Partial = {}): Thread { }, runtimeMode: "full-access", interactionMode: "default", - session: null, + runtime: null, messages: [], proposedPlans: [], - activities: [], - checkpoints: [], createdAt: now, updatedAt: now, archivedAt: null, settledOverride: null, settledAt: 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", @@ -115,12 +119,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", }; @@ -566,16 +568,15 @@ describe("startNewThreadForProject", () => { 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, - latestUserMessageId: localDispatch.latestUserMessageId, - session: readySession, + latestRun: completedTurn, + runtime: readySession, hasPendingApproval: false, hasPendingUserInput: false, threadError: null, @@ -585,11 +586,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", @@ -599,9 +600,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => { hasServerAcknowledgedLocalDispatch({ localDispatch, phase: "ready", - latestTurn: newerTurn, - latestUserMessageId: localDispatch.latestUserMessageId, - session: { ...readySession, updatedAt: newerTurn.completedAt }, + latestRun: newerTurn, + runtime: { ...readySession, updatedAt: newerTurn.completedAt }, hasPendingApproval: false, hasPendingUserInput: false, threadError: null, @@ -611,12 +611,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, @@ -626,12 +626,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => { hasServerAcknowledgedLocalDispatch({ localDispatch, phase: "running", - latestTurn: runningTurn, - latestUserMessageId: localDispatch.latestUserMessageId, - session: { + latestRun: runningTurn, + runtime: { ...readySession, status: "running", - activeTurnId: TurnId.make("turn-other"), + activeRunId: RunId.make("turn-other"), }, hasPendingApproval: false, hasPendingUserInput: false, @@ -642,12 +641,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => { hasServerAcknowledgedLocalDispatch({ localDispatch, phase: "running", - latestTurn: runningTurn, - latestUserMessageId: localDispatch.latestUserMessageId, - session: { + latestRun: runningTurn, + runtime: { ...readySession, status: "running", - activeTurnId: runningTurn.turnId, + activeRunId: runningTurn.runId, }, hasPendingApproval: false, hasPendingUserInput: false, @@ -704,9 +702,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => { const common = { localDispatch, phase: "ready" as const, - latestTurn: null, - latestUserMessageId: localDispatch.latestUserMessageId, - 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 04561b507c..064a13dabd 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -8,9 +8,11 @@ import { type ScopedProjectRef, type ScopedThreadRef, type ThreadId, - type TurnId, + type RunId, } from "@t3tools/contracts"; -import { type ChatMessage, type SessionPhase, type Thread, type ThreadShell } from "../types"; +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"; import { appAtomRegistry } from "../rpc/atomRegistry"; @@ -83,29 +85,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, - settledOverride: null, - settledAt: null, - deletedAt: null, - latestTurn: null, - branch: draftThread.branch, - worktreePath: draftThread.worktreePath, + plans: [], + turnItems: [], + checkpointScopes: [], checkpoints: [], - activities: [], - proposedPlans: [], - }; + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [], + updatedAt: timestamp, + }); } export function buildLoadingThreadFromShell(shell: ThreadShell): Thread { @@ -366,7 +385,7 @@ export function isBranchMismatchDismissedForSession(key: string | null): boolean 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), ); } @@ -390,7 +409,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; } @@ -491,41 +510,37 @@ export async function waitForStartedServerThread( export interface LocalDispatchSnapshot { startedAt: string; preparingWorktree: boolean; - latestUserMessageId: ChatMessage["id"] | null; - 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 latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user"); + const latestRun = activeThread?.latestRun ?? null; + const runtime = activeThread?.runtime ?? null; return { startedAt: new Date().toISOString(), preparingWorktree: Boolean(options?.preparingWorktree), - latestUserMessageId: latestUserMessage?.id ?? null, - 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; - latestUserMessageId: ChatMessage["id"] | null; - session: Thread["session"] | null; + latestRun: Thread["latestRun"] | null; + runtime: Thread["runtime"] | null; hasPendingApproval: boolean; hasPendingUserInput: boolean; threadError: string | null | undefined; @@ -537,34 +552,25 @@ export function hasServerAcknowledgedLocalDispatch(input: { return true; } - const latestTurn = input.latestTurn ?? null; - const session = input.session ?? null; - const latestUserMessageChanged = - input.localDispatch.latestUserMessageId !== input.latestUserMessageId; - 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") { - // Steering adds a user message to the current running turn without - // necessarily changing any of the turn timestamps. Treat that projected - // message as the server acknowledgment so the composer does not remain - // stuck in its local "Sending" state until the turn settles. - if (latestUserMessageChanged) { - return true; - } - 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; } @@ -572,8 +578,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 feac2d5978..a5755b390f 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, @@ -14,20 +13,20 @@ 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 { connectionStatusTitle, type EnvironmentConnectionPresentation, } from "@t3tools/client-runtime/connection"; import { - changeRequestAutoSettles, effectiveSettled, effectiveSnoozed, threadWokeAt, @@ -84,13 +83,14 @@ import { derivePendingUserInputs, derivePhase, deriveTimelineEntries, + deriveTimelineEntriesFromVisibleTurnItems, deriveActiveWorkStartedAt, deriveActivePlanState, deriveTurnPlans, findLatestProposedPlan, deriveWorkLogEntries, hasActionableProposedPlan, - isLatestTurnSettled, + isLatestRunSettled, } from "../session-logic"; import { type LegendListRef } from "@legendapp/list/react"; import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring"; @@ -141,7 +141,6 @@ import { closePreviewSession } from "./preview/closePreviewSession"; import { ThreadPreviewMiniPlayer } from "./preview/ThreadPreviewMiniPlayer"; import { subscribePreviewAction } from "./preview/previewActionBus"; import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic"; -import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop"; import { selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore, @@ -165,7 +164,6 @@ import { CheckCircle2Icon, ChevronDownIcon, GitBranchIcon, - PaperclipIcon, WifiOffIcon, } from "lucide-react"; import { cn, randomHex } from "~/lib/utils"; @@ -181,7 +179,6 @@ import { } from "~/projectScripts"; import { newDraftId, newMessageId, newThreadId } from "~/lib/utils"; import { useBrowserHistoryStore } from "~/browserHistoryStore"; -import { registerFaviconProjectForThread } from "~/browserFaviconStore"; import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels"; import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances"; import { @@ -245,7 +242,7 @@ import { useProjects, useThread, useThreadRefs, - useThreadShell, + useThreadVisibleTurnItems, } from "../state/entities"; import { environmentShell } from "../state/shell"; import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer"; @@ -276,10 +273,7 @@ import { shouldShowThreadErrorBanner, ThreadErrorBanner, } from "./chat/ThreadErrorBanner"; -import { - resolveDisplayedThreadPr, - threadChangeRequestSnapshotsAtom, -} from "./ThreadStatusIndicators"; +import { resolveThreadPr } from "./ThreadStatusIndicators"; import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack"; import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill"; import { @@ -354,7 +348,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 = {}; @@ -545,10 +539,10 @@ type PersistentTerminalLaunchContext = Pick(null); @@ -564,18 +558,17 @@ function useLocalDispatchState(input: { hasServerAcknowledgedLocalDispatch({ localDispatch, phase: input.phase, - latestTurn: input.activeLatestTurn, - latestUserMessageId, - 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, latestUserMessageId, @@ -1253,13 +1246,11 @@ function ChatViewContent(props: ChatViewProps) { ); const composerDraftTarget: ScopedThreadRef | DraftId = routeKind === "server" ? routeThreadRef : props.draftId; - const draftThread = useComposerDraftStore((store) => - routeKind === "server" - ? store.getDraftSessionByRef(routeThreadRef) - : draftId - ? store.getDraftSession(draftId) - : null, + const serverThread = useThread(routeKind === "server" ? routeThreadRef : null); + const serverVisibleTurnItems = useThreadVisibleTurnItems( + routeKind === "server" ? routeThreadRef : null, ); +<<<<<<< HEAD const routeServerThreadShell = useThreadShell(routeKind === "server" ? routeThreadRef : null); const serverThread = useThread(routeThreadRef, { waitForShell: draftThread !== null }); const loadingServerThread = useMemo( @@ -1275,6 +1266,11 @@ function ChatViewContent(props: ChatViewProps) { const routeThreadState = useEnvironmentThread( routeKind === "server" ? routeThreadRef.environmentId : null, routeKind === "server" ? routeThreadRef.threadId : null, +======= + const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); + const activeThreadLastVisitedAt = useUiStateStore( + (store) => store.threadLastVisitedAtById[routeThreadKey], +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) ); const loadEarlierTurns = useMemo(() => { if (routeKind !== "server" || !threadHasOlderTurns(routeThreadState)) { @@ -1341,7 +1337,6 @@ function ChatViewContent(props: ChatViewProps) { const composerElementContextsRef = useRef([]); const localComposerRef = useRef(null); const composerRef = useComposerHandleContext() ?? localComposerRef; - const [isWorkspaceFileDragActive, setIsWorkspaceFileDragActive] = useState(false); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [expandedImage, setExpandedImage] = useState(null); const [optimisticUserMessages, setOptimisticUserMessages] = useState([]); @@ -1358,21 +1353,10 @@ function ChatViewContent(props: ChatViewProps) { const [maximizedRightPanelThreadKey, setMaximizedRightPanelThreadKey] = useState( null, ); - const [respondingRequestIds, setRespondingRequestIds] = useState([]); + const [respondingRequestIds, setRespondingRequestIds] = useState([]); const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState< - ApprovalRequestId[] + RuntimeRequestId[] >([]); - - useEffect(() => { - setIsWorkspaceFileDragActive(false); - }, [draftId, routeThreadKey]); - - useEffect(() => { - if (!isWorkspaceFileDragActive) return; - const clearWorkspaceFileDrag = () => setIsWorkspaceFileDragActive(false); - window.addEventListener("dragend", clearWorkspaceFileDrag); - return () => window.removeEventListener("dragend", clearWorkspaceFileDrag); - }, [isWorkspaceFileDragActive]); const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState< Record> >({}); @@ -1525,7 +1509,7 @@ function ChatViewContent(props: ChatViewProps) { const isServerThread = activeServerThread !== null; const activeThread = activeServerThread ?? localDraftThread; const threadError = isServerThread - ? (localServerError ?? activeServerThread?.session?.lastError ?? null) + ? (localServerError ?? serverThread?.runtime?.lastError ?? null) : localDraftError; // Dismissals can only mask the shown error, never clear it: a server thread // keeps its error in session.lastError, so clearing the local shadow would @@ -1599,7 +1583,6 @@ function ChatViewContent(props: ChatViewProps) { [activeThreadEnvironmentId, activeThreadId], ); const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null; - const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom); const [timelineAnchor, setTimelineAnchor] = useState<{ readonly threadKey: string | null; readonly messageId: MessageId | null; @@ -1688,6 +1671,7 @@ function ChatViewContent(props: ChatViewProps) { const existingThreadKeys = new Set([...serverThreadKeys, ...draftThreadKeys]); return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey)); }, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]); +<<<<<<< HEAD const activeLatestTurn = activeThread?.latestTurn ?? null; // Reading a finished thread clears the sidebar's Done badge. The visit is // stamped at the turn's completion time — not now/updatedAt — so it clears @@ -1707,6 +1691,32 @@ function ChatViewContent(props: ChatViewProps) { serverThread?.id, serverThread?.latestTurn?.completedAt, ]); +======= + const activeLatestRun = activeThread?.latestRun ?? null; + const sourcePlanThreadRef = useMemo(() => { + const sourceThreadId = activeLatestRun?.sourcePlanRef?.threadId; + if (!activeThread || !sourceThreadId || sourceThreadId === activeThread.id) { + return null; + } + return scopeThreadRef(activeThread.environmentId, sourceThreadId); + }, [activeLatestRun?.sourcePlanRef?.threadId, activeThread]); + const sourceThreadProposedPlans = useThreadProposedPlans(sourcePlanThreadRef); + const threadPlanCatalog = useMemo(() => { + if (!activeThread) { + return []; + } + const entries: ThreadPlanCatalogEntry[] = [ + { id: activeThread.id, proposedPlans: activeThread.proposedPlans }, + ]; + if (sourcePlanThreadRef) { + entries.push({ + id: sourcePlanThreadRef.threadId, + proposedPlans: sourceThreadProposedPlans, + }); + } + return entries; + }, [activeThread, sourcePlanThreadRef, sourceThreadProposedPlans]); +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) useEffect(() => { setMountedTerminalThreadKeys((currentThreadIds) => { const nextThreadIds = reconcileMountedTerminalThreadIds({ @@ -1722,12 +1732,10 @@ function ChatViewContent(props: ChatViewProps) { : nextThreadIds; }); }, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]); - const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null); - const activeProjectRef = useMemo( - () => - activeThread ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) : null, - [activeThread?.environmentId, activeThread?.projectId], - ); + const latestRunSettled = isLatestRunSettled(activeLatestRun, activeThread?.runtime ?? null); + const activeProjectRef = activeThread + ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) + : null; const activeProject = useProject(activeProjectRef); const handleNewThreadInActiveProject = useCallback(() => { startNewThreadForProject(activeProjectRef, handleNewThread); @@ -1779,10 +1787,6 @@ function ChatViewContent(props: ChatViewProps) { // drive the environment picker in BranchToolbar. const allProjects = useProjects(); const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null; - useEffect(() => { - if (!activeThreadRef || !activeProjectRef) return; - registerFaviconProjectForThread(activeThreadRef, activeProjectRef); - }, [activeProjectRef, activeThreadRef]); useEffect(() => { if (!clientSettingsHydrated || !activeThreadRef || !activeProject) return; // Reuse the sidebar's grouping so history follows the project rows the user @@ -2213,6 +2217,7 @@ function ChatViewContent(props: ChatViewProps) { selectedProviderByThreadId ?? threadProvider, ); const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; +<<<<<<< HEAD const phase = derivePhase(activeThread?.session ?? null); const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]); @@ -2228,14 +2233,21 @@ function ChatViewContent(props: ChatViewProps) { agents: foldSubagentActivities(threadActivities, { sessionLive: agentSessionLive }), }), [agentSessionLive, threadActivities], +======= + const phase = derivePhase(activeThread?.runtime ?? null); + const threadWorkEntries = activeThread?.workEntries ?? EMPTY_WORK_ENTRIES; + const workLogEntries = useMemo( + () => deriveWorkLogEntries(threadWorkEntries), + [threadWorkEntries], +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) ); 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( @@ -2268,20 +2280,35 @@ 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, ); +<<<<<<< HEAD }, [activeLatestTurn?.turnId, activeThread?.proposedPlans, latestTurnSettled]); +======= + }, [activeLatestRun?.runId, activeThread?.proposedPlans, latestRunSettled]); + const sidebarProposedPlan = useMemo( + () => + findSidebarProposedPlan({ + threads: threadPlanCatalog, + latestRun: activeLatestRun, + latestRunSettled, + threadId: activeThread?.id ?? null, + }), + [activeLatestRun, activeThread?.id, latestRunSettled, threadPlanCatalog], + ); +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) const activePlan = useMemo( - () => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined), - [activeLatestTurn?.turnId, threadActivities], + () => deriveActivePlanState(activeThread?.todoPlans ?? [], activeLatestRun?.runId ?? undefined), + [activeLatestRun?.runId, activeThread?.todoPlans], ); // Current step for the in-chat working row: only for the running turn's own // plan (deriveActivePlanState falls back to older turns' plans, which must @@ -2301,7 +2328,7 @@ function ChatViewContent(props: ChatViewProps) { const showPlanFollowUpPrompt = pendingUserInputs.length === 0 && interactionMode === "plan" && - latestTurnSettled && + latestRunSettled && hasActionableProposedPlan(activeProposedPlan); const activePendingApproval = pendingApprovals[0] ?? null; const { @@ -2312,7 +2339,7 @@ function ChatViewContent(props: ChatViewProps) { isSendBusy, } = useLocalDispatchState({ activeThread, - activeLatestTurn, + activeLatestRun, phase, activePendingApproval: activePendingApproval?.requestId ?? null, activePendingUserInput: activePendingUserInput?.requestId ?? null, @@ -2320,8 +2347,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(() => { @@ -2385,7 +2412,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 ?? []) { @@ -2394,6 +2431,7 @@ function ChatViewContent(props: ChatViewProps) { } return [...attachmentIds]; }, [serverMessages]); + const serverAttachmentIds = isServerThread ? committedServerAttachmentIds : draftAttachmentIds; const serverAttachmentResources = useMemo( () => serverAttachmentIds.map((attachmentId) => ({ @@ -2564,7 +2602,16 @@ 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, @@ -2574,17 +2621,8 @@ function ChatViewContent(props: ChatViewProps) { ), [activeThread?.proposedPlans, timelineMessages, turnPlans, workLogEntries], ); - const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState(null); - const draftHeroDockRequested = - activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey; - const isDraftHeroState = - isLocalDraftThread && timelineEntries.length === 0 && !isWorking && !draftHeroDockRequested; - const [ - attachDraftHeroTransitionGroupRef, - attachDraftHeroComposerAnchorRef, - captureDraftHeroComposerRect, - ] = useDraftHeroLayoutTransition(isDraftHeroState); - const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } = + const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries; + const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } = useTurnDiffSummaries(activeThread); const turnDiffSummaryByAssistantMessageId = useMemo(() => { const byMessageId = new Map(); @@ -2615,7 +2653,7 @@ function ChatViewContent(props: ChatViewProps) { continue; } const turnCount = - summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId]; + summary.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[summary.runId]; if (typeof turnCount !== "number") { break; } @@ -2625,7 +2663,7 @@ function ChatViewContent(props: ChatViewProps) { } return byUserMessageId; - }, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]); + }, [inferredCheckpointTurnCountByRunId, timelineEntries, turnDiffSummaryByAssistantMessageId]); const gitCwd = activeProject ? projectScriptCwd({ @@ -2653,7 +2691,7 @@ function ChatViewContent(props: ChatViewProps) { ?.instanceId ?? null; const activeProviderInstanceId = selectedProviderInstanceId ?? - activeThread?.session?.providerInstanceId ?? + activeThread?.runtime?.providerInstanceId ?? activeThread?.modelSelection.instanceId ?? activeProject?.defaultModelSelection?.instanceId ?? null; @@ -2736,9 +2774,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 @@ -3282,6 +3318,28 @@ function ChatViewContent(props: ChatViewProps) { const toggleInteractionMode = useCallback(() => { handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan"); }, [handleInteractionModeChange, interactionMode]); +<<<<<<< HEAD +======= + const dismissPlanSidebarForCurrentTurn = useCallback(() => { + planSidebarDismissedForTurnRef.current = + activePlan?.runId ?? sidebarProposedPlan?.runId ?? "__dismissed__"; + }, [activePlan?.runId, sidebarProposedPlan?.runId]); + const togglePlanSidebar = useCallback(() => { + if (!activeThreadRef) return; + if (planSidebarOpen) { + dismissPlanSidebarForCurrentTurn(); + } else { + planSidebarDismissedForTurnRef.current = null; + } + useRightPanelStore.getState().toggle(activeThreadRef, "plan"); + }, [activeThreadRef, dismissPlanSidebarForCurrentTurn, planSidebarOpen]); + const closePlanSidebar = useCallback(() => { + if (!activeThreadRef) return; + setMaximizedRightPanelThreadKey(null); + useRightPanelStore.getState().close(activeThreadRef); + dismissPlanSidebarForCurrentTurn(); + }, [activeThreadRef, dismissPlanSidebarForCurrentTurn]); +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) const createBrowserSurface = useCallback(() => { if (!activeThreadRef) return; void addBrowserSurface({ threadRef: activeThreadRef, openPreview }); @@ -4023,6 +4081,31 @@ function ChatViewContent(props: ChatViewProps) { // activeThreadRef resets transitively with the active thread. }, [activeThread?.id]); +<<<<<<< HEAD +======= + // Auto-open the plan sidebar when plan/todo steps arrive for the current turn. + // Don't auto-open for plans carried over from a previous turn (the user can open manually). + useEffect(() => { + if (!autoOpenPlanSidebar) return; + if (!activePlan) return; + if (planSidebarOpen) return; + 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, + activeLatestRun?.runId, + activeThreadRef, + autoOpenPlanSidebar, + planSidebarOpen, + sidebarProposedPlan?.runId, + ]); + +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) useEffect(() => { setIsRevertingCheckpoint(false); }, [activeThread?.id]); @@ -4127,12 +4210,9 @@ function ChatViewContent(props: ChatViewProps) { // so the banner and the sidebar row never disagree. const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null); const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays); - const autoSettleOnMerge = useClientSettings((settings) => settings.sidebarAutoSettleOnMerge); - const activeThreadPr = resolveDisplayedThreadPr({ + const activeThreadPr = resolveThreadPr({ threadBranch: activeThread?.branch ?? null, gitStatus: gitStatusQuery.data ?? null, - snapshot: activeThreadKey ? changeRequestSnapshotByKey.get(activeThreadKey) : undefined, - retainTerminalOnBranchMismatch: activeThread?.worktreePath === null, }); // The right panel offers the thread's own change request, so it can only offer it once the // branch has one; until then the picker says so rather than opening an empty panel. @@ -4170,14 +4250,15 @@ function ChatViewContent(props: ChatViewProps) { if (activeThreadRef === null || activeThreadWokeAt === null) return; markThreadVisited(scopedThreadKey(activeThreadRef), activeThreadWokeAt); }, [activeThreadRef, activeThreadWokeAt, markThreadVisited]); - // Mirror of the sidebar's Woke pill for the open thread. It uses the same - // visit comparison and change request settle rule. + // Mirror of the sidebar's Woke pill for the open thread: same visit + // comparison, same merged/closed-PR suppression (finished work needs no + // wake-up call). Drives the dismissible composer banner below. const activeThreadLastVisitedAt = useUiStateStore((store) => activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey], ); const activeThreadWokeVisible = useMemo(() => { if (activeThreadWokeAt === null) return false; - if (changeRequestAutoSettles(activeThreadPr?.state, autoSettleOnMerge)) return false; + if (activeThreadPr?.state === "merged" || activeThreadPr?.state === "closed") return false; const wokeAtMs = Date.parse(activeThreadWokeAt); if (Number.isNaN(wokeAtMs)) return false; // Having the thread open counts as a visit at completedAt (the effect @@ -4199,22 +4280,18 @@ function ChatViewContent(props: ChatViewProps) { activeThreadLastVisitedAt, activeThreadPr?.state, activeThreadWokeAt, - autoSettleOnMerge, ]); const activeThreadSettled = useMemo(() => { if (activeThreadShell === null || !supportsSettlement) return false; return effectiveSettled(activeThreadShell, { now: `${nowMinute}:00.000Z`, autoSettleAfterDays, - autoSettleOnMerge, changeRequestState: activeThreadPr?.state ?? null, }); }, [ activeThreadPr?.state, activeThreadShell, autoSettleAfterDays, - autoSettleOnMerge, - changeRequestSnapshotByKey, nowMinute, supportsSettlement, ]); @@ -4739,13 +4816,6 @@ function ChatViewContent(props: ChatViewProps) { return; } - if (command === "rightPanel.toggleMaximized") { - event.preventDefault(); - event.stopPropagation(); - toggleRightPanelMaximized(); - return; - } - if (command === "terminal.split") { event.preventDefault(); event.stopPropagation(); @@ -4841,7 +4911,6 @@ function ChatViewContent(props: ChatViewProps) { keybindings, onToggleDiff, toggleRightPanel, - toggleRightPanelMaximized, toggleTerminalVisibility, composerRef, ]); @@ -5009,16 +5078,6 @@ function ChatViewContent(props: ChatViewProps) { draftText: trimmed, planMarkdown: activeProposedPlan.planMarkdown, }); - const outgoingFollowUpText = formatOutgoingPrompt({ - provider: ctxSelectedProvider, - model: ctxSelectedModel, - models: ctxSelectedProviderModels, - effort: ctxSelectedPromptEffort, - text: followUp.text.trim(), - }); - if (composerRef.current?.validateProviderInput(outgoingFollowUpText) === false) { - return; - } promptRef.current = ""; clearComposerDraftContent(composerDraftTarget); composerRef.current?.resetCursorState(); @@ -5088,34 +5147,6 @@ function ChatViewContent(props: ChatViewProps) { return; } - const composerImagesSnapshot = [...composerImages]; - const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts]; - const composerElementContextsSnapshot = [...composerElementContexts]; - const composerPreviewAnnotationsSnapshot = [...composerPreviewAnnotations]; - const composerReviewCommentsSnapshot: ReviewCommentContext[] = [...composerReviewComments]; - const messageTextWithContexts = appendElementContextsToPrompt( - appendTerminalContextsToPrompt(promptForSend, composerTerminalContextsSnapshot), - composerElementContextsSnapshot, - ); - const messageTextWithPreviewAnnotations = composerPreviewAnnotationsSnapshot.reduce( - (text, annotation) => appendPreviewAnnotationPrompt(text, annotation), - messageTextWithContexts, - ); - const messageTextForSend = appendReviewCommentsToPrompt( - messageTextWithPreviewAnnotations, - composerReviewCommentsSnapshot, - ); - const outgoingMessageText = formatOutgoingPrompt({ - provider: ctxSelectedProvider, - model: ctxSelectedModel, - models: ctxSelectedProviderModels, - effort: ctxSelectedPromptEffort, - text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT, - }); - if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) { - return; - } - sendInFlightRef.current = true; if (isDraftHeroState && activeThreadKey) { let resolveDockStarted: (() => void) | undefined; @@ -5134,8 +5165,32 @@ function ChatViewContent(props: ChatViewProps) { } beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) }); + const composerImagesSnapshot = [...composerImages]; + const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts]; + const composerElementContextsSnapshot = [...composerElementContexts]; + const composerPreviewAnnotationsSnapshot = [...composerPreviewAnnotations]; + const composerReviewCommentsSnapshot: ReviewCommentContext[] = [...composerReviewComments]; + const messageTextWithContexts = appendElementContextsToPrompt( + appendTerminalContextsToPrompt(promptForSend, composerTerminalContextsSnapshot), + composerElementContextsSnapshot, + ); + const messageTextWithPreviewAnnotations = composerPreviewAnnotationsSnapshot.reduce( + (text, annotation) => appendPreviewAnnotationPrompt(text, annotation), + messageTextWithContexts, + ); + const messageTextForSend = appendReviewCommentsToPrompt( + messageTextWithPreviewAnnotations, + composerReviewCommentsSnapshot, + ); const messageIdForSend = newMessageId(); const messageCreatedAt = new Date().toISOString(); + const outgoingMessageText = formatOutgoingPrompt({ + provider: ctxSelectedProvider, + model: ctxSelectedModel, + models: ctxSelectedProviderModels, + effort: ctxSelectedPromptEffort, + text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT, + }); const turnAttachmentsPromise = Promise.all( composerImagesSnapshot.map(async (image) => ({ type: "image" as const, @@ -5175,7 +5230,7 @@ function ChatViewContent(props: ChatViewProps) { role: "user", text: outgoingMessageText, ...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}), - turnId: null, + runId: null, createdAt: messageCreatedAt, updatedAt: messageCreatedAt, streaming: false, @@ -5389,8 +5444,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], @@ -5413,12 +5473,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], @@ -5441,7 +5506,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( @@ -5525,7 +5590,11 @@ function ChatViewContent(props: ChatViewProps) { ); const onAdvanceActivePendingUserInput = useCallback(() => { - if (!activePendingUserInput || !activePendingProgress) { + if ( + !activePendingUserInput || + activePendingUserInput.responseCapability !== "live" || + !activePendingProgress + ) { return; } if (activePendingProgress.isLastQuestion) { @@ -5620,7 +5689,7 @@ function ChatViewContent(props: ChatViewProps) { id: messageIdForSend, role: "user", text: outgoingMessageText, - turnId: null, + runId: null, createdAt: messageCreatedAt, updatedAt: messageCreatedAt, streaming: false, @@ -5752,9 +5821,6 @@ function ChatViewContent(props: ChatViewProps) { effort: ctxSelectedPromptEffort, text: implementationPrompt, }); - if (composerRef.current?.validateProviderInput(outgoingImplementationPrompt) === false) { - return; - } const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown)); const nextThreadModelSelection: ModelSelection = ctxSelectedModelSelection; @@ -5882,9 +5948,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; @@ -5908,9 +5974,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 && @@ -5937,9 +6003,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) { @@ -6019,9 +6085,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?.(); }, @@ -6069,9 +6135,8 @@ function ChatViewContent(props: ChatViewProps) { // One inset in both states: the controls move between containers when // the right panel opens, and a different right offset made them jump // sideways on every toggle. - "absolute top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] z-50 mr-px flex h-[var(--workspace-topbar-height)] items-center gap-1 [-webkit-app-region:no-drag]", + "workspace-titlebar-controls z-50 mr-px gap-1 [-webkit-app-region:no-drag]", )} - data-workspace-titlebar-controls > {rightPanelOpen && !shouldUseRightPanelSheet ? ( composerRef.current?.addDroppedFiles(files), - }); - return (
{rightPanelOpen && !shouldUseRightPanelSheet ? panelLayoutControls : null} @@ -6217,12 +6277,12 @@ function ChatViewContent(props: ChatViewProps) { "bg-background transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none", isElectron ? cn( - "drag-region relative flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 sm:px-5", + "workspace-topbar drag-region relative px-3 sm:px-5", reserveTitleBarControlInset && !inlineRightPanelOwnsTitleBar && "wco:pr-[var(--workspace-native-controls-inset)]", ) - : "flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)]", + : "workspace-topbar pl-[calc(env(safe-area-inset-left)+0.75rem)] pr-[calc(env(safe-area-inset-right)+0.75rem)] sm:pl-[calc(env(safe-area-inset-left)+1.25rem)] sm:pr-[calc(env(safe-area-inset-right)+1.25rem)]", COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS, )} > @@ -6268,28 +6328,7 @@ function ChatViewContent(props: ChatViewProps) { {/* Main content area with optional plan sidebar */}
{/* Chat column */} -
- {isWorkspaceFileDragActive ? ( -
-
-
-
- ) : null} +
{/* Provider status overlays the timeline without changing its content height. */}
>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) activeTurnStartedAt={activeWorkStartedAt} listRef={legendListRef} timelineEntries={timelineEntries} - latestTurn={activeLatestTurn} - runningTurnId={ - activeThread.session?.status === "running" - ? activeThread.session.activeTurnId - : null - } + latestRun={activeLatestRun} turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId} activeThreadEnvironmentId={activeThread.environmentId} routeThreadKey={routeThreadKey} @@ -6346,17 +6384,16 @@ function ChatViewContent(props: ChatViewProps) { className="pointer-events-none absolute left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5" style={{ bottom: composerOverlayHeight + 4 }} > - +
)}
@@ -6373,8 +6410,9 @@ function ChatViewContent(props: ChatViewProps) { >
+<<<<<<< HEAD
{isDraftHeroState ? (
@@ -6533,6 +6571,88 @@ function ChatViewContent(props: ChatViewProps) {
+
+
+
+
+
+ +
+ >>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) />
@@ -6627,7 +6747,6 @@ function ChatViewContent(props: ChatViewProps) { activeSurfaceId={activeRightPanelSurface?.id ?? null} pendingSurfaceIds={pendingFileSurfaceIds} previewSessions={activePreviewState.sessions} - desktopByTabId={activePreviewState.desktopByTabId} terminalLabelsById={activeTerminalLabelsById} onActivate={activateRightPanelSurface} onCloseSurface={closeRightPanelSurface} @@ -6666,7 +6785,6 @@ function ChatViewContent(props: ChatViewProps) { activeSurfaceId={activeRightPanelSurface?.id ?? null} pendingSurfaceIds={pendingFileSurfaceIds} previewSessions={activePreviewState.sessions} - desktopByTabId={activePreviewState.desktopByTabId} terminalLabelsById={activeTerminalLabelsById} onActivate={activateRightPanelSurface} onCloseSurface={closeRightPanelSurface} diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index 9bae9c58a9..94b4318bc9 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -1,6 +1,7 @@ import { describe, expect, it, vi } from "vite-plus/test"; import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts"; import type { Thread } from "../types"; +import { makeThreadFixture } from "../test-fixtures"; import { browseInputEndPaddingClass, buildBrowseGroups, @@ -143,7 +144,7 @@ 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, @@ -151,7 +152,7 @@ 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", @@ -160,13 +161,11 @@ function makeThread(overrides: Partial = {}): Thread { settledAt: 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 66f0a4e111..9d545bf2dd 100644 --- a/apps/web/src/components/DiffPanel.tsx +++ b/apps/web/src/components/DiffPanel.tsx @@ -6,7 +6,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, @@ -161,55 +161,55 @@ export default function DiffPanel({ ), ); 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; @@ -240,12 +240,12 @@ export default function DiffPanel({ 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: { @@ -257,7 +257,7 @@ export default function DiffPanel({ : null, ); const shouldRetryBranchDiffAtEnvironmentCwd = - selectedTurnId === null && + selectedRunId === null && primaryBranchDiffPreview.error?.includes("configured workspace root") === true && serverConfig?.cwd !== undefined && serverConfig.cwd !== activeCwd; @@ -333,7 +333,7 @@ export default function DiffPanel({ selectedTurnId, ]); const localBranchRefs = useEnvironmentQuery( - selectedTurnId === null && + selectedRunId === null && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd @@ -350,7 +350,7 @@ export default function DiffPanel({ : null, ); const remoteBranchRefs = useEnvironmentQuery( - selectedTurnId === null && + selectedRunId === null && selectedGitScope === "branch" && activeThread && branchDiffPreview.data?.cwd @@ -393,9 +393,9 @@ export default function DiffPanel({ 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") { @@ -496,9 +496,9 @@ export default function DiffPanel({ }); }, [collapseScopeKey, diffFileKeys]); - 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; @@ -530,6 +530,15 @@ export default function DiffPanel({ onClick={() => selectGitScope("unstaged")} > Working tree + {selectedRunId === null && selectedGitScope === "unstaged" && ( + + )} + + selectGitScope("branch")}> + Branch changes + {selectedRunId === null && selectedGitScope === "branch" && ( + + )} { - if (latestTurn) selectTurn(latestTurn.turnId); + if (latestTurn) selectTurn(latestTurn.runId); }} > Latest turn + {selectedRunId !== null && selectedTurn?.runId === latestTurn?.runId && ( + + )} Turn @@ -559,20 +571,15 @@ export default function DiffPanel({ {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.runId === selectedTurn?.runId && } ); })} @@ -580,7 +587,7 @@ export default function DiffPanel({ - {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 c6e113a445..22706d6e0c 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -36,20 +36,14 @@ import { shouldCreateNewThreadInCurrentProject, 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"); @@ -244,13 +238,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: @@ -268,9 +262,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); }); @@ -282,9 +276,9 @@ describe("hasUnseenCompletion", () => { hasPendingApprovals: false, hasPendingUserInput: false, interactionMode: "default", - latestTurn: makeLatestTurn(), + latestRun: makeLatestRun(), lastVisitedAt: undefined, - session: null, + runtime: null, }), ).toBe(false); }); @@ -1052,15 +1046,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", }, @@ -1103,11 +1095,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, }, }, }), @@ -1119,11 +1111,11 @@ describe("resolveThreadStatusPill", () => { resolveThreadStatusPill({ thread: { ...baseThread, - latestTurn: makeLatestTurn(), - session: { - ...baseThread.session, - status: "ready", - activeTurnId: null, + latestRun: makeLatestRun(), + runtime: { + ...baseThread.runtime, + status: "completed", + activeRunId: null, }, }, }), @@ -1136,12 +1128,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, }, }, }), @@ -1293,7 +1285,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"), @@ -1305,7 +1297,7 @@ 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", @@ -1314,13 +1306,11 @@ function makeThread(overrides: Partial = {}): Thread { settledAt: null, deletedAt: null, updatedAt: "2026-03-09T10:00:00.000Z", - latestTurn: null, + latestRun: null, branch: null, worktreePath: null, - checkpoints: [], - activities: [], ...overrides, - }; + }); } describe("getFallbackThreadIdAfterDelete", () => { @@ -1404,7 +1394,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, @@ -1420,7 +1410,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 9cb09219df..b39efa6682 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -10,7 +10,7 @@ import { import type { SidebarThreadSummary, Thread } from "../types"; import type { ThreadRouteTarget } from "../threadRoutes"; 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]"; @@ -150,9 +150,14 @@ type ThreadStatusInput = Pick< | "hasPendingApprovals" | "hasPendingUserInput" | "interactionMode" +<<<<<<< HEAD | "latestTurn" | "session" | "backgroundLiveness" +======= + | "latestRun" + | "runtime" +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) > & { lastVisitedAt?: string | undefined; }; @@ -250,8 +255,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; @@ -658,7 +663,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", @@ -667,7 +672,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", @@ -681,7 +686,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 5ae583b66b..513c1be0a9 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -143,15 +143,10 @@ import { import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic"; import { ThreadWorktreeIndicator, - nextThreadChangeRequestSnapshot, prStatusIndicator, - resolveDisplayedThreadPr, - resolveDisplayedThreadPrProvider, - setThreadChangeRequestSnapshot, + resolveThreadPr, settledPrHoverColorClass, terminalStatusFromRunningIds, - threadChangeRequestSnapshotsAtom, - type ThreadChangeRequestSnapshot, type TerminalStatusIndicator, } from "./ThreadStatusIndicators"; import { @@ -163,11 +158,7 @@ import { import { ProjectFavicon } from "./ProjectFavicon"; import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon"; import { getTriggerDisplayModelLabel } from "./chat/providerIconUtils"; -import { - deriveProviderInstanceEntries, - shouldShowInstanceBadge, - type ProviderInstanceEntry, -} from "../providerInstances"; +import { deriveProviderInstanceEntries, type ProviderInstanceEntry } from "../providerInstances"; import { primaryServerProvidersAtom } from "../state/server"; import { useThreadRunningTerminalIds } from "../state/terminalSessions"; import { stackedThreadToast, toastManager } from "./ui/toast"; @@ -256,8 +247,7 @@ function SidebarThreadTooltip({ projectCwd, projectFaviconPath, environmentLabel, - providerEntry, - showInstanceBadge, + driverKind, modelInstanceId, modelLabel, branchMismatch, @@ -269,8 +259,7 @@ function SidebarThreadTooltip({ projectCwd: string | null; projectFaviconPath: string | null; environmentLabel: string | null; - providerEntry: ProviderInstanceEntry | null; - showInstanceBadge: boolean; + driverKind: ProviderInstanceEntry["driverKind"] | null; modelInstanceId: string; modelLabel: string; branchMismatch: { @@ -280,7 +269,6 @@ function SidebarThreadTooltip({ terminalStatus: TerminalStatusIndicator | null; terminalProcessCount: number; }) { - const driverKind = providerEntry?.driverKind ?? null; return ( -
- {showInstanceBadge && providerEntry - ? `${modelLabel} · ${providerEntry.displayName}` - : modelLabel} -
+
{modelLabel}
) : null} {terminalStatus ? ( @@ -389,26 +366,19 @@ function SnoozePopoverButton(props: { ); return ( - - event.stopPropagation()} - onDoubleClick={(event) => event.stopPropagation()} - className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" - /> - } - /> - } - > - - - Snooze thread - + event.stopPropagation()} + onDoubleClick={(event) => event.stopPropagation()} + className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground" + /> + } + > + + {presets.map((preset) => ( ) : ( ) : null} {props.settlementSupported ? ( - - - } - > - - Settle - - Settle thread - + ) : null} ) : null} @@ -1534,19 +1498,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: { ) : null} {driverKind ? ( - + ) : null} @@ -1603,9 +1559,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: { }); const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId; const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null; - const showInstanceBadge = - providerEntry !== null && - shouldShowInstanceBadge(providerEntry, props.providerEntryByInstanceId.values()); + const driverKind = providerEntry?.driverKind ?? null; const selectedModel = providerEntry?.models.find( (model) => model.slug === thread.modelSelection.model, ); @@ -1663,8 +1617,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: { projectCwd={props.projectCwd} projectFaviconPath={props.projectFaviconPath} environmentLabel={props.environmentLabel} - providerEntry={providerEntry} - showInstanceBadge={showInstanceBadge} + driverKind={driverKind} modelInstanceId={modelInstanceId} modelLabel={modelLabel} branchMismatch={branchMismatch} @@ -1686,7 +1639,6 @@ export default function Sidebar() { const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays); const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge); const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete); - const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive); const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder); const timestampFormat = useClientSettings((s) => s.timestampFormat); const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings); @@ -1698,7 +1650,6 @@ export default function Sidebar() { pinThread, unpinThread, reorderPinnedThread, - archiveThread, deleteThread, } = useThreadActions(); const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, { @@ -1889,7 +1840,26 @@ export default function Sidebar() { // fresh clock whenever it recomputes. const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0); - const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom); + // PR states stream in per-row. The next partition applies the configured + // merge rule and the always-on close rule. + const [changeRequestStateByKey, setChangeRequestStateByKey] = useState< + ReadonlyMap + >(() => new Map()); + const handleChangeRequestState = useCallback( + (threadKey: string, state: "open" | "closed" | "merged" | null) => { + setChangeRequestStateByKey((current) => { + if ((current.get(threadKey) ?? null) === state) return current; + const next = new Map(current); + if (state === null) { + next.delete(threadKey); + } else { + next.set(threadKey, state); + } + return next; + }); + }, + [], + ); // Project scope: one menu above the list. Scoping filters the list without // making the header width depend on the number or length of project names. @@ -2005,11 +1975,7 @@ export default function Sidebar() { const supportsSnooze = serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true; const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); - const snapshot = changeRequestSnapshotByKey.get(threadKey); - const changeRequestState = - snapshot != null && (thread.worktreePath === null || snapshot.branch === thread.branch) - ? snapshot.pr.state - : null; + const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null; // Snooze outranks everything, including a pin: "hide until Tuesday" // temporarily suspends "keep on top". The pin survives underneath — // and so does its pinOrderKey, so on wake the thread reappears at @@ -2067,7 +2033,7 @@ export default function Sidebar() { }, [ autoSettleAfterDays, autoSettleOnMerge, - changeRequestSnapshotByKey, + changeRequestStateByKey, nowMinute, scopedProjectKeys, serverConfigs, @@ -2447,6 +2413,7 @@ export default function Sidebar() { [navigateToThread, router], ); +<<<<<<< HEAD const attemptSettle = useCallback( (threadRef: ScopedThreadRef, opts: { coSettlingKeys?: ReadonlySet } = {}) => { void (async () => { @@ -2477,6 +2444,17 @@ export default function Sidebar() { } } finally { settlingThreadKeysRef.current.delete(threadKey); +======= + const clicked = await api.contextMenu.show( + buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }), + position, + ); + + if (clicked === "mark-unread") { + for (const threadKey of threadKeys) { + const thread = sidebarThreadByKeyRef.current.get(threadKey); + markThreadUnread(threadKey, thread?.latestRun?.completedAt); +>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover) } })(); }, @@ -2996,6 +2974,7 @@ export default function Sidebar() { ); const handleThreadContextMenu = useCallback( +<<<<<<< HEAD (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { void (async () => { const api = readLocalApi(); @@ -3004,6 +2983,75 @@ export default function Sidebar() { const selectionState = useThreadSelectionStore.getState(); if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) { await handleMultiSelectContextMenu(position); +======= + async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => { + const api = readLocalApi(); + if (!api) return; + const threadKey = scopedThreadKey(threadRef); + const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null; + if (!thread) return; + const threadProject = memberProjectByScopedKey.get( + scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)), + ); + const threadWorkspacePath = + thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null; + const clicked = await api.contextMenu.show( + [ + ...(thread.branch + ? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }] + : []), + { id: "rename", label: "Rename thread" }, + { id: "mark-unread", label: "Mark unread" }, + { id: "copy-path", label: "Copy Path" }, + { id: "copy-thread-id", label: "Copy Thread ID" }, + { id: "delete", label: "Delete", destructive: true, icon: "trash" }, + ], + position, + ); + + if (clicked === "new-thread-on-branch") { + // Explicit branch carry-over: reuse the thread's worktree when it + // has one, otherwise its branch on the local checkout. + const result = await settlePromise(() => + handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), { + branch: thread.branch, + worktreePath: thread.worktreePath, + envMode: thread.worktreePath ? "worktree" : "local", + startFromOrigin: false, + }), + ); + if (result._tag === "Failure") { + const error = squashAtomCommandFailure(result); + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Could not create thread", + description: error instanceof Error ? error.message : "An error occurred.", + }), + ); + } + return; + } + + if (clicked === "rename") { + startThreadRename(threadKey, thread.title); + return; + } + + if (clicked === "mark-unread") { + markThreadUnread(threadKey, thread.latestRun?.completedAt); + return; + } + if (clicked === "copy-path") { + if (!threadWorkspacePath) { + toastManager.add( + stackedThreadToast({ + type: "error", + title: "Path unavailable", + description: "This thread does not have a workspace path to copy.", + }), + ); +>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover) return; } const thread = threadByKeyRef.current.get(threadKey); @@ -3041,8 +3089,6 @@ export default function Sidebar() { isSnoozed, canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }), isRegeneratingTitle, - isRunning: - thread.session?.status === "running" && thread.session.activeTurnId != null, supports: { settlement: supportsSettlement, snooze: supportsSnooze, @@ -3146,34 +3192,6 @@ export default function Sidebar() { case "copy-thread-id": copyThreadIdToClipboard(thread.id, { threadId: thread.id }); return; - case "archive": { - if (confirmThreadArchive) { - const confirmed = await settlePromise(() => - api.dialogs.confirm(`Archive thread "${thread.title}"?`), - ); - if (confirmed._tag === "Failure" || !confirmed.value) return; - } - let didArchive = false; - const result = await archiveThread(threadRef, { - onArchived: () => { - didArchive = true; - }, - }); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - toastManager.add( - stackedThreadToast({ - type: "error", - title: didArchive - ? "Thread archived, but navigation failed" - : "Failed to archive thread", - description: error instanceof Error ? error.message : "An error occurred.", - }), - ); - return; - } - return; - } case "delete": { if (confirmThreadDelete) { const confirmed = await settlePromise(() => @@ -3207,14 +3225,12 @@ export default function Sidebar() { })(); }, [ - archiveThread, attemptPin, attemptSettle, attemptSnooze, attemptUnpin, attemptUnsettle, attemptUnsnooze, - confirmThreadArchive, confirmThreadDelete, copyBranchToClipboard, copyPathToClipboard, @@ -3381,9 +3397,9 @@ export default function Sidebar() { {isSearchingThreads ? ( + ); })} @@ -3702,8 +3717,7 @@ export default function Sidebar() { onUnsnooze={attemptUnsnooze} onUnpin={attemptUnpin} onAcknowledgeWoke={acknowledgeWoke} - changeRequestSnapshot={changeRequestSnapshotByKey.get(threadKey) ?? null} - onChangeRequestSnapshot={setThreadChangeRequestSnapshot} + onChangeRequestState={handleChangeRequestState} /> ); }; diff --git a/apps/web/src/components/chat/ChangedFilesTree.test.tsx b/apps/web/src/components/chat/ChangedFilesTree.test.tsx index accc6e0872..37e0e71507 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"; @@ -150,7 +150,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; expanded: boolean; showCompactPreview: boolean; @@ -36,10 +36,10 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: { resolvedTheme: "light" | "dark"; onExpandedChange: (expanded: boolean) => void; onToggleAllDirectories: () => void; - onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; + onOpenTurnDiff: (runId: RunId, filePath?: string) => void; }) { const { - turnId, + runId, files, expanded, showCompactPreview, @@ -152,8 +152,8 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
{expanded ? ( ; 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"), @@ -296,7 +296,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 ? (
@@ -3111,16 +3120,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
- - {/* Bottom toolbar */} {isComposerCollapsedMobile ? null : activePendingApproval ? ( -
+
@@ -3214,7 +3220,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) 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 - ); - })} -
-
- - + {shortcutKey} + + ) : null} + + ); + return ( + + ); + })} +
+ ); }); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 70a330d463..2ae27fcb3b 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -284,7 +284,7 @@ describe("deriveMessagesTimelineRows", () => { id: "user-1" as never, role: "user", text: "Write a poem", - turnId: null, + runId: null, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", streaming: false, @@ -298,7 +298,7 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-thought" as never, role: "assistant", text: "I should ground this first.", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:10Z", updatedAt: "2026-01-01T00:00:11Z", streaming: false, @@ -312,14 +312,14 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-final" as never, role: "assistant", text: "Here is the poem.", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:20Z", updatedAt: "2026-01-01T00:00:30Z", streaming: false, }, }, ], - expandedTurnIds: new Set(["turn-1" as never]), + expandedRunIds: new Set(["turn-1" as never]), isWorking: false, activeTurnStartedAt: null, turnDiffSummaryByAssistantMessageId: new Map(), @@ -347,7 +347,7 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-one" as never, role: "assistant", text: "Earlier response.", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:10Z", updatedAt: "2026-01-01T00:00:11Z", streaming: false, @@ -361,16 +361,16 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-two" as never, role: "assistant", text: "Active response.", - turnId: "turn-2" as never, + runId: "turn-2" as never, createdAt: "2026-01-01T00:00:20Z", updatedAt: "2026-01-01T00:00:30Z", streaming: false, }, }, ], - latestTurn: { - turnId: "turn-2" as never, - state: "running", + latestRun: { + runId: "turn-2" as never, + status: "running", startedAt: "2026-01-01T00:00:19Z", completedAt: null, }, @@ -391,7 +391,7 @@ describe("deriveMessagesTimelineRows", () => { it("projects assistant diff summaries and user revert counts onto the affected rows", () => { const assistantTurnDiffSummary = { - turnId: "turn-1" as never, + runId: "turn-1" as never, completedAt: "2026-01-01T00:00:30Z", assistantMessageId: "assistant-1" as never, checkpointTurnCount: 2, @@ -410,7 +410,7 @@ describe("deriveMessagesTimelineRows", () => { id: "user-1" as never, role: "user", text: "Do the thing", - turnId: null, + runId: null, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", streaming: false, @@ -424,7 +424,7 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-1" as never, role: "assistant", text: "Done", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:20Z", updatedAt: "2026-01-01T00:00:30Z", streaming: false, @@ -462,7 +462,7 @@ describe("deriveMessagesTimelineRows", () => { id: "user-1" as never, role: "user" as const, text: "Build it", - turnId: null, + runId: null, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", streaming: false, @@ -476,7 +476,7 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-thought" as never, role: "assistant" as const, text: "Looking around first.", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:05Z", updatedAt: "2026-01-01T00:00:06Z", streaming: false, @@ -489,7 +489,7 @@ describe("deriveMessagesTimelineRows", () => { entry: { id: "work-1", createdAt: "2026-01-01T00:00:08Z", - turnId: "turn-1" as never, + runId: "turn-1" as never, label: "Ran command", tone: "tool" as const, }, @@ -502,7 +502,7 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-final" as never, role: "assistant" as const, text: "Done", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:20Z", updatedAt: "2026-01-01T00:00:22Z", streaming: false, @@ -522,7 +522,7 @@ describe("deriveMessagesTimelineRows", () => { (row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> => row.kind === "turn-fold", ); - expect(foldRow?.turnId).toBe("turn-1"); + expect(foldRow?.runId).toBe("turn-1"); expect(foldRow?.expanded).toBe(false); // User message boundary (00:00:00) → terminal message updatedAt (00:00:22). expect(foldRow?.label).toBe("Worked for 22s"); @@ -534,7 +534,7 @@ describe("deriveMessagesTimelineRows", () => { const expandedRows = deriveMessagesTimelineRows({ timelineEntries, - expandedTurnIds: new Set(["turn-1" as never]), + expandedRunIds: new Set(["turn-1" as never]), isWorking: false, activeTurnStartedAt: null, turnDiffSummaryByAssistantMessageId: new Map(), @@ -568,7 +568,7 @@ describe("deriveMessagesTimelineRows", () => { id: "user-1" as never, role: "user" as const, text: "do it once more", - turnId: null, + runId: null, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", streaming: false, @@ -582,7 +582,7 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-commentary" as never, role: "assistant" as const, text: "Kicking off call 1.", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:09Z", updatedAt: "2026-01-01T00:00:09Z", streaming: false, @@ -595,7 +595,7 @@ describe("deriveMessagesTimelineRows", () => { entry: { id: "work-1", createdAt: "2026-01-01T00:00:12Z", - turnId: "turn-1" as never, + runId: "turn-1" as never, label: "Ran command", tone: "tool" as const, }, @@ -608,7 +608,7 @@ describe("deriveMessagesTimelineRows", () => { id: "user-2" as never, role: "user" as const, text: "actually do 15", - turnId: null, + runId: null, createdAt: "2026-01-01T00:00:14Z", updatedAt: "2026-01-01T00:00:14Z", streaming: false, @@ -622,16 +622,16 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-next" as never, role: "assistant" as const, text: "One down — adjusting.", - turnId: "turn-2" as never, + runId: "turn-2" as never, createdAt: "2026-01-01T00:00:17Z", updatedAt: "2026-01-01T00:00:17Z", streaming: true, }, }, ], - latestTurn: { - turnId: "turn-2" as never, - state: "running", + latestRun: { + runId: "turn-2" as never, + status: "running", startedAt: "2026-01-01T00:00:14Z", completedAt: null, }, @@ -646,7 +646,7 @@ describe("deriveMessagesTimelineRows", () => { row.kind === "turn-fold", ); // User message (00:00:00) → trailing work entry (00:00:12). - expect(foldRow?.turnId).toBe("turn-1"); + expect(foldRow?.runId).toBe("turn-1"); expect(foldRow?.label).toBe("Worked for 12s"); }); @@ -660,15 +660,15 @@ describe("deriveMessagesTimelineRows", () => { entry: { id: "work-1", createdAt: "2026-01-01T00:00:05Z", - turnId: "turn-1" as never, + runId: "turn-1" as never, label: "Ran command", tone: "tool" as const, }, }, ], - latestTurn: { - turnId: "turn-1" as never, - state: "interrupted", + latestRun: { + runId: "turn-1" as never, + status: "interrupted", startedAt: "2026-01-01T00:00:00Z", completedAt: "2026-01-01T00:00:47Z", }, @@ -681,15 +681,88 @@ describe("deriveMessagesTimelineRows", () => { expect(rows).toEqual([ expect.objectContaining({ kind: "turn-fold", - turnId: "turn-1", + runId: "turn-1", label: "You stopped after 47s", expanded: false, }), ]); }); + it("keeps interruption request, intervening work, and result visible in order", () => { + const runId = "turn-1" as never; + const interruptEvent = (type: "run_interrupt_request" | "run_interrupt_result") => ({ + position: type === "run_interrupt_request" ? 0 : 2, + visibility: "local" as const, + sourceThreadId: "thread-1" as never, + sourceItemId: `item-${type}` as never, + item: { + id: `item-${type}`, + threadId: "thread-1", + runId, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: type === "run_interrupt_request" ? 0 : 2, + status: "completed", + title: null, + startedAt: null, + completedAt: null, + updatedAt: {}, + type, + message: type === "run_interrupt_request" ? "Stopping" : "Stopped", + }, + }); + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + { + id: "interrupt-request", + kind: "event", + createdAt: "2026-01-01T00:00:01Z", + projectedItem: interruptEvent("run_interrupt_request") as never, + }, + { + id: "work-entry", + kind: "work", + createdAt: "2026-01-01T00:00:02Z", + entry: { + id: "work-1", + createdAt: "2026-01-01T00:00:02Z", + runId, + label: "Finishing tool output", + tone: "tool", + }, + }, + { + id: "interrupt-result", + kind: "event", + createdAt: "2026-01-01T00:00:03Z", + projectedItem: interruptEvent("run_interrupt_result") as never, + }, + ], + latestRun: { + runId, + status: "interrupted", + startedAt: "2026-01-01T00:00:00Z", + completedAt: "2026-01-01T00:00:03Z", + }, + isWorking: false, + activeTurnStartedAt: null, + turnDiffSummaryByAssistantMessageId: new Map(), + revertTurnCountByUserMessageId: new Map(), + }); + + expect(rows.map((row) => row.id)).toEqual([ + "interrupt-request", + "work-entry", + "interrupt-result", + ]); + expect(rows.some((row) => row.kind === "turn-fold")).toBe(false); + }); + it("keeps the previous turn folded while a newly sent message awaits its turn", () => { - // Right after send, isWorking is true but latestTurn still points at the + // Right after send, isWorking is true but latestRun still points at the // previous, settled turn — it must stay folded through that window. const rows = deriveMessagesTimelineRows({ timelineEntries: [ @@ -700,7 +773,7 @@ describe("deriveMessagesTimelineRows", () => { entry: { id: "work-1", createdAt: "2026-01-01T00:00:05Z", - turnId: "turn-1" as never, + runId: "turn-1" as never, label: "Ran command", tone: "tool" as const, }, @@ -713,7 +786,7 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-final" as never, role: "assistant", text: "Done", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:20Z", updatedAt: "2026-01-01T00:00:22Z", streaming: false, @@ -727,16 +800,16 @@ describe("deriveMessagesTimelineRows", () => { id: "user-followup" as never, role: "user", text: "yooo", - turnId: null, + runId: null, createdAt: "2026-01-01T00:01:00Z", updatedAt: "2026-01-01T00:01:00Z", streaming: false, }, }, ], - latestTurn: { - turnId: "turn-1" as never, - state: "completed", + latestRun: { + runId: "turn-1" as never, + status: "completed", startedAt: "2026-01-01T00:00:00Z", completedAt: "2026-01-01T00:00:22Z", }, @@ -767,7 +840,7 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-thought" as never, role: "assistant", text: "Working on it.", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:05Z", updatedAt: "2026-01-01T00:00:06Z", streaming: false, @@ -780,15 +853,15 @@ describe("deriveMessagesTimelineRows", () => { entry: { id: "work-1", createdAt: "2026-01-01T00:00:08Z", - turnId: "turn-1" as never, + runId: "turn-1" as never, label: "Ran command", tone: "tool" as const, }, }, ], - latestTurn: { - turnId: "turn-1" as never, - state: "running", + latestRun: { + runId: "turn-1" as never, + status: "running", startedAt: "2026-01-01T00:00:00Z", completedAt: null, }, @@ -878,7 +951,7 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-thought" as never, role: "assistant", text: "Checking first.", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:10Z", updatedAt: "2026-01-01T00:00:11Z", streaming: false, @@ -892,14 +965,14 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-final" as never, role: "assistant", text: "Done.", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:20Z", updatedAt: "2026-01-01T00:00:30Z", streaming: false, }, }, ], - expandedTurnIds: new Set(["turn-1" as never]), + expandedRunIds: new Set(["turn-1" as never]), isWorking: false, activeTurnStartedAt: null, turnDiffSummaryByAssistantMessageId: new Map(), @@ -925,16 +998,16 @@ describe("deriveMessagesTimelineRows", () => { id: "assistant-thought" as never, role: "assistant", text: "Working on it.", - turnId: "turn-1" as never, + runId: "turn-1" as never, createdAt: "2026-01-01T00:00:10Z", updatedAt: "2026-01-01T00:00:11Z", streaming: false, }, }, ], - latestTurn: { - turnId: "turn-1" as never, - state: "running", + latestRun: { + runId: "turn-1" as never, + status: "running", startedAt: "2026-01-01T00:00:00Z", completedAt: null, }, @@ -1031,7 +1104,7 @@ describe("computeStableMessagesTimelineRows", () => { id: "user-1" as never, role: "user" as const, text: "First", - turnId: null, + runId: null, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", streaming: false, @@ -1040,7 +1113,7 @@ describe("computeStableMessagesTimelineRows", () => { id: "user-2" as never, role: "user" as const, text: "Second", - turnId: null, + runId: null, createdAt: "2026-01-01T00:00:10Z", updatedAt: "2026-01-01T00:00:10Z", streaming: false, @@ -1136,7 +1209,7 @@ describe("computeStableMessagesTimelineRows", () => { id: "user-1" as never, role: "user" as const, text: "First", - turnId: null, + runId: null, createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", streaming: false, @@ -1145,7 +1218,7 @@ describe("computeStableMessagesTimelineRows", () => { id: "user-2" as never, role: "user" as const, text: "Second", - turnId: null, + runId: null, createdAt: "2026-01-01T00:00:10Z", updatedAt: "2026-01-01T00:00:10Z", streaming: false, diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index c89bbd0557..be33f9cb63 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -8,7 +8,12 @@ import { type WorkLogEntry, } from "../../session-logic"; import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types"; -import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts"; +import { + type MessageId, + type OrchestrationV2ProjectedTurnItem, + type RunId, +} from "@t3tools/contracts"; +import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell"; export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1; export const TIMELINE_MINIMAP_ITEM_SPACING = 8; @@ -159,9 +164,9 @@ export interface TimelineDurationMessage { streaming: boolean; } -export type TimelineLatestTurn = Pick< - OrchestrationLatestTurn, - "turnId" | "state" | "startedAt" | "completedAt" +export type TimelineLatestRun = Pick< + ThreadRunSummary, + "runId" | "status" | "startedAt" | "completedAt" >; export type MessagesTimelineRow = @@ -184,7 +189,7 @@ export type MessagesTimelineRow = kind: "turn-fold"; id: string; createdAt: string; - turnId: TurnId; + runId: RunId; label: string; expanded: boolean; } @@ -200,6 +205,12 @@ export type MessagesTimelineRow = assistantTurnDiffSummary?: TurnDiffSummary | undefined; revertTurnCount?: number | undefined; } + | { + kind: "event"; + id: string; + createdAt: string; + projectedItem: OrchestrationV2ProjectedTurnItem; + } | { kind: "proposed-plan"; id: string; @@ -275,8 +286,8 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray; @@ -300,18 +311,16 @@ interface TurnFold { * user sends a message, the previous turn is still the "active" one until the * server creates the new turn, and folding must not flicker through that window. */ -function deriveUnsettledTurnId( - latestTurn: TimelineLatestTurn | null, - runningTurnId: TurnId | null, -): TurnId | null { - if (runningTurnId !== null) { - return runningTurnId; - } - if (!latestTurn) { +function deriveUnsettledRunId(latestRun: TimelineLatestRun | null): RunId | null { + if (!latestRun) { return null; } - const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running"; - return isSettled ? null : latestTurn.turnId; + const isSettled = + latestRun.completedAt !== null && + latestRun.status !== "running" && + latestRun.status !== "starting" && + latestRun.status !== "waiting"; + return isSettled ? null : latestRun.runId; } /** @@ -322,9 +331,21 @@ function deriveUnsettledTurnId( function deriveTurnFolds(input: { timelineEntries: ReadonlyArray; terminalAssistantMessageIds: ReadonlySet; - latestTurn: TimelineLatestTurn | null; - unsettledTurnId: TurnId | null; + latestRun: TimelineLatestRun | null; + unsettledRunId: RunId | null; }): ReadonlyMap { + const interruptedRunIds = new Set(); + for (const entry of input.timelineEntries) { + if ( + entry.kind === "event" && + entry.projectedItem.item.runId !== null && + (entry.projectedItem.item.type === "run_interrupt_request" || + entry.projectedItem.item.type === "run_interrupt_result") + ) { + interruptedRunIds.add(entry.projectedItem.item.runId); + } + } + interface TurnGroup { entries: Array; terminalEntry: Extract | null; @@ -337,7 +358,7 @@ function deriveTurnFolds(input: { */ startBoundary: string | null; } - const groupsByTurnId = new Map(); + const groupsByRunId = new Map(); let pendingUserBoundary: string | null = null; for (const entry of input.timelineEntries) { @@ -345,16 +366,16 @@ function deriveTurnFolds(input: { pendingUserBoundary = entry.message.createdAt; continue; } - const turnId = + const runId = entry.kind === "message" && entry.message.role === "assistant" - ? (entry.message.turnId ?? null) + ? (entry.message.runId ?? null) : entry.kind === "work" - ? (entry.entry.turnId ?? null) + ? (entry.entry.runId ?? null) : null; - if (!turnId) { + if (!runId) { continue; } - let group = groupsByTurnId.get(turnId); + let group = groupsByRunId.get(runId); if (!group) { group = { entries: [], @@ -366,7 +387,7 @@ function deriveTurnFolds(input: { startBoundary: pendingUserBoundary, }; pendingUserBoundary = null; - groupsByTurnId.set(turnId, group); + groupsByRunId.set(runId, group); } group.entries.push(entry); if (entry.kind === "message") { @@ -380,8 +401,8 @@ function deriveTurnFolds(input: { } const foldsByAnchorEntryId = new Map(); - for (const [turnId, group] of groupsByTurnId) { - if (turnId === input.unsettledTurnId) { + for (const [runId, group] of groupsByRunId) { + if (runId === input.unsettledRunId || interruptedRunIds.has(runId)) { continue; } if (group.hasStreamingMessage) { @@ -411,16 +432,14 @@ function deriveTurnFolds(input: { } const isLatestInterruptedTurn = - input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted"; + input.latestRun?.runId === runId && input.latestRun.status === "interrupted"; // A turn cut short by a steer leaves trailing work entries behind its // terminal message — take whichever ended last. const lastEntryEnd = lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt; const elapsedMs = - input.latestTurn?.turnId === turnId && - input.latestTurn.startedAt && - input.latestTurn.completedAt - ? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt) + input.latestRun?.runId === runId && input.latestRun.startedAt && input.latestRun.completedAt + ? computeElapsedMs(input.latestRun.startedAt, input.latestRun.completedAt) : computeElapsedMs( group.startBoundary ?? firstEntry.createdAt, maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ?? @@ -436,7 +455,7 @@ function deriveTurnFolds(input: { : "Worked"; foldsByAnchorEntryId.set(firstEntry.id, { - turnId, + runId, anchorEntryId: firstEntry.id, createdAt: firstEntry.createdAt, hiddenEntryIds, @@ -448,10 +467,8 @@ function deriveTurnFolds(input: { export function deriveMessagesTimelineRows(input: { timelineEntries: ReadonlyArray; - latestTurn?: TimelineLatestTurn | null; - runningTurnId?: TurnId | null; - expandedTurnIds?: ReadonlySet; - expandedWorkGroupIds?: ReadonlySet; + latestRun?: TimelineLatestRun | null; + expandedRunIds?: ReadonlySet; isWorking: boolean; activeTurnStartedAt: string | null; turnDiffSummaryByAssistantMessageId: ReadonlyMap; @@ -462,19 +479,16 @@ export function deriveMessagesTimelineRows(input: { input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])), ); const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries); - const unsettledTurnId = deriveUnsettledTurnId( - input.latestTurn ?? null, - input.runningTurnId ?? null, - ); + const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null); const foldsByAnchorEntryId = deriveTurnFolds({ timelineEntries: input.timelineEntries, terminalAssistantMessageIds, - latestTurn: input.latestTurn ?? null, - unsettledTurnId, + latestRun: input.latestRun ?? null, + unsettledRunId, }); const collapsedEntryIds = new Set(); for (const fold of foldsByAnchorEntryId.values()) { - if (!input.expandedTurnIds?.has(fold.turnId)) { + if (!input.expandedRunIds?.has(fold.runId)) { for (const entryId of fold.hiddenEntryIds) { collapsedEntryIds.add(entryId); } @@ -491,11 +505,11 @@ export function deriveMessagesTimelineRows(input: { if (turnFold) { nextRows.push({ kind: "turn-fold", - id: `turn-fold:${turnFold.turnId}`, + id: `turn-fold:${turnFold.runId}`, createdAt: turnFold.createdAt, - turnId: turnFold.turnId, + runId: turnFold.runId, label: turnFold.label, - expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false, + expanded: input.expandedRunIds?.has(turnFold.runId) ?? false, }); } @@ -587,20 +601,29 @@ export function deriveMessagesTimelineRows(input: { continue; } +<<<<<<< HEAD if (timelineEntry.kind === "turn-plan") { nextRows.push({ kind: "turn-plan", id: timelineEntry.id, createdAt: timelineEntry.createdAt, turnPlan: timelineEntry.turnPlan, +======= + if (timelineEntry.kind === "event") { + nextRows.push({ + kind: "event", + id: timelineEntry.id, + createdAt: timelineEntry.createdAt, + projectedItem: timelineEntry.projectedItem, +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) }); continue; } const assistantTurnStillInProgress = timelineEntry.message.role === "assistant" && - unsettledTurnId !== null && - timelineEntry.message.turnId === unsettledTurnId; + unsettledRunId !== null && + timelineEntry.message.runId === unsettledRunId; const durationStart = durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt; @@ -680,12 +703,17 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean case "proposed-plan": return a.proposedPlan === (b as typeof a).proposedPlan; +<<<<<<< HEAD case "turn-plan": { const bp = b as typeof a; // Plans rewrite in place: compare the snapshot's identity fields so an // unchanged plan keeps its row reference (virtualization stability). return a.createdAt === bp.createdAt && a.turnPlan.plan === bp.turnPlan.plan; } +======= + case "event": + return a.projectedItem === (b as typeof a).projectedItem; +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) case "work": return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries); diff --git a/apps/web/src/components/chat/MessagesTimeline.test.tsx b/apps/web/src/components/chat/MessagesTimeline.test.tsx index e51095bb00..eb7b113886 100644 --- a/apps/web/src/components/chat/MessagesTimeline.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.test.tsx @@ -180,8 +180,7 @@ function buildProps() { activeTurnInProgress: false, activeTurnStartedAt: null, listRef: createRef(), - latestTurn: null, - runningTurnId: null, + latestRun: null, turnDiffSummaryByAssistantMessageId: new Map(), routeThreadKey: "environment-local:thread-1", onOpenTurnDiff: () => {}, @@ -218,7 +217,7 @@ function buildUserTimelineEntry(text: string) { id: MessageId.make("message-1"), role: "user" as const, text, - turnId: null, + runId: null, createdAt: MESSAGE_CREATED_AT, updatedAt: MESSAGE_CREATED_AT, streaming: false, @@ -706,7 +705,116 @@ describe("MessagesTimeline", () => { expect(markup).toContain("Work Log"); }); - it("formats changed file paths from the workspace root", () => { + it("renders V2 interruption lifecycle entries as standalone rows", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('data-v2-item-type="run_interrupt_request"'); + expect(markup).toContain("Interrupt requested"); + expect(markup).toContain("Waiting for the provider to stop."); + expect(markup).toContain('data-v2-structured-details="true"'); + expect(markup).toContain("Structured details"); + expect(markup).toContain(""type": "run_interrupt_request""); + }); + + it("keeps inherited V2 work provenance on the rendered row", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); + const item = { + id: "command-inherited", + threadId: "thread-source", + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed", + title: null, + startedAt: null, + completedAt: null, + updatedAt: {}, + type: "command_execution", + input: "pwd", + output: "/workspace", + exitCode: 0, + } as const; + const projectedItem = { + position: 0, + visibility: "inherited", + sourceThreadId: "thread-source", + sourceItemId: item.id, + item, + } as const; + const markup = renderToStaticMarkup( + , + ); + + expect(markup).toContain('data-v2-item-type="command_execution"'); + expect(markup).toContain('data-v2-item-visibility="inherited"'); + expect(markup).toContain("Inherited"); + }); + + it("formats changed file paths from the workspace root", async () => { + const { MessagesTimeline } = await import("./MessagesTimeline"); const markup = renderToStaticMarkup( { createdAt: "2026-03-17T19:12:28.000Z", label: "Updated files", tone: "tool", + itemType: "file_change", + toolLifecycleStatus: "completed", changedFiles: ["C:/Users/mike/dev-stuff/t3code/apps/web/src/session-logic.ts"], }, }, @@ -754,7 +864,7 @@ describe("MessagesTimeline", () => { "```", "", ].join("\n"), - turnId: null, + runId: null, createdAt: "2026-03-17T19:12:28.000Z", updatedAt: "2026-03-17T19:12:28.000Z", streaming: false, @@ -793,7 +903,7 @@ describe("MessagesTimeline", () => { "```", "", ].join("\n"), - turnId: null, + runId: null, createdAt: "2026-03-17T19:12:28.000Z", updatedAt: "2026-03-17T19:12:28.000Z", streaming: false, diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index b1b665ab7b..3a4d08dace 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1,9 +1,10 @@ import { type EnvironmentId, type MessageId, + type OrchestrationV2TurnItem, type ScopedThreadRef, type ServerProviderSkill, - type TurnId, + type RunId, } from "@t3tools/contracts"; import { parseScopedThreadKey } from "@t3tools/client-runtime/environment"; import type { AgentPanelModel } from "@t3tools/client-runtime/state/subagentRuntime"; @@ -86,8 +87,7 @@ import { shouldPreserveAssistantLineBreaks, type StableMessagesTimelineRowsState, type MessagesTimelineRow, - TIMELINE_MINIMAP_MIN_ITEMS, - type TimelineLatestTurn, + type TimelineLatestRun, } from "./MessagesTimeline.logic"; import { TerminalContextInlineChip } from "./TerminalContextInlineChip"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -140,11 +140,16 @@ interface TimelineRowSharedState { activeThreadEnvironmentId: EnvironmentId; onRevertUserMessage: (messageId: MessageId) => void; onImageExpand: (preview: ExpandedImagePreview) => void; +<<<<<<< HEAD onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; onToggleTurnFold: (turnId: TurnId) => void; onToggleWorkGroup: (groupId: string, anchorKey: string) => void; agentPanelModel: AgentPanelModel; onOpenAgents: () => void; +======= + onOpenTurnDiff: (runId: RunId, filePath?: string) => void; + onToggleTurnFold: (runId: RunId) => void; +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) } interface TimelineRowActivityState { @@ -211,11 +216,10 @@ interface MessagesTimelineProps { activeTurnStartedAt: string | null; listRef: React.RefObject; timelineEntries: ReturnType; - latestTurn: TimelineLatestTurn | null; - runningTurnId: TurnId | null; + latestRun: TimelineLatestRun | null; turnDiffSummaryByAssistantMessageId: Map; routeThreadKey: string; - onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; + onOpenTurnDiff: (runId: RunId, filePath?: string) => void; revertTurnCountByUserMessageId: Map; onRevertUserMessage: (messageId: MessageId) => void; isRevertingCheckpoint: boolean; @@ -257,8 +261,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ onOpenAgents = NOOP_OPEN_AGENTS, listRef, timelineEntries, - latestTurn, - runningTurnId, + latestRun, turnDiffSummaryByAssistantMessageId, routeThreadKey, onOpenTurnDiff, @@ -282,6 +285,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({ topFadeEnabled = false, loadEarlier = null, }: MessagesTimelineProps) { +<<<<<<< HEAD const [expandedTurnIds, setExpandedTurnIds] = useState>(new Set()); const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState>(new Set()); const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false); @@ -294,6 +298,25 @@ export const MessagesTimeline = memo(function MessagesTimeline({ return () => { if (disclosureSettleFrameRef.current !== null) { cancelAnimationFrame(disclosureSettleFrameRef.current); +======= + const [expandedRunIds, setExpandedRunIds] = useState>(new Set()); + + // Toggling a fold inserts/removes rows between the fold row and the final + // message — everything above the trigger is unchanged, so the trigger stays + // put as long as the list doesn't re-anchor. maintainScrollAtEnd would do + // exactly that (pin the bottom content when row data changes while scrolled + // to the end), yanking the trigger out of view. Suppress it for the frames + // in which the toggle's data change and item measurements settle. + const [foldToggleSettling, setFoldToggleSettling] = useState(false); + const onToggleTurnFold = useCallback((runId: RunId) => { + setFoldToggleSettling(true); + setExpandedRunIds((existing) => { + const next = new Set(existing); + if (next.has(runId)) { + next.delete(runId); + } else { + next.add(runId); +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) } if (disclosureSettleSecondFrameRef.current !== null) { cancelAnimationFrame(disclosureSettleSecondFrameRef.current); @@ -367,41 +390,39 @@ export const MessagesTimeline = memo(function MessagesTimeline({ // An in-session interrupt leaves its turn expanded so the user keeps their // place; the next turn (or a reload, since this is local state) folds it. - const previousLatestTurnRef = useRef(latestTurn); + const previousLatestRunRef = useRef(latestRun); useEffect(() => { - const previous = previousLatestTurnRef.current; - previousLatestTurnRef.current = latestTurn; - if (!latestTurn || previous?.turnId === undefined) { + const previous = previousLatestRunRef.current; + previousLatestRunRef.current = latestRun; + if (!latestRun || previous?.runId === undefined) { return; } - if (latestTurn.turnId === previous.turnId) { - if (previous.state === "running" && latestTurn.state === "interrupted") { - setExpandedTurnIds((existing) => { + if (latestRun.runId === previous.runId) { + if (previous.status === "running" && latestRun.status === "interrupted") { + setExpandedRunIds((existing) => { const next = new Set(existing); - next.add(latestTurn.turnId); + next.add(latestRun.runId); return next; }); } return; } - setExpandedTurnIds((existing) => { - if (!existing.has(previous.turnId)) { + setExpandedRunIds((existing) => { + if (!existing.has(previous.runId)) { return existing; } const next = new Set(existing); - next.delete(previous.turnId); + next.delete(previous.runId); return next; }); - }, [latestTurn]); + }, [latestRun]); const rawRows = useMemo( () => deriveMessagesTimelineRows({ timelineEntries, - latestTurn, - runningTurnId, - expandedTurnIds, - expandedWorkGroupIds, + latestRun, + expandedRunIds, isWorking, activeTurnStartedAt, turnDiffSummaryByAssistantMessageId, @@ -409,10 +430,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({ }), [ timelineEntries, - latestTurn, - runningTurnId, - expandedTurnIds, - expandedWorkGroupIds, + latestRun, + expandedRunIds, isWorking, activeTurnStartedAt, turnDiffSummaryByAssistantMessageId, @@ -928,8 +947,12 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time // they sit closer to the work that follows them. (row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta) || row.kind === "work" || +<<<<<<< HEAD row.kind === "work-toggle" || row.kind === "turn-plan" +======= + row.kind === "event" +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) ? "pb-2" : "pb-4", row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null, @@ -947,7 +970,11 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time ) : null} {row.kind === "proposed-plan" ? : null} +<<<<<<< HEAD {row.kind === "turn-plan" ? : null} +======= + {row.kind === "event" ? : null} +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) {row.kind === "working" ? : null} ); @@ -1092,7 +1119,7 @@ function TurnFoldTimelineRow({ row }: { row: Extract ctx.onToggleTurnFold(row.turnId)} + onClick={() => ctx.onToggleTurnFold(row.runId)} className="flex cursor-pointer select-none items-center gap-1 rounded-md px-1 text-xs text-muted-foreground tabular-nums transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70" > {row.label} @@ -1179,6 +1206,7 @@ function ProposedPlanTimelineRow({ ); } +<<<<<<< HEAD /** * Inline folded plan chip: one row per turn that produced plan/todo steps. * Collapsed by default — a segment bar plus the in-progress step label — @@ -1278,6 +1306,174 @@ const TurnPlanTimelineRow = memo(function TurnPlanTimelineRow({ ); }); +======= +type V2EventTone = "muted" | "warning" | "danger" | "success"; + +function v2EventPresentation(item: OrchestrationV2TurnItem): { + readonly label: string; + readonly detail: string | null; + readonly tone: V2EventTone; + readonly icon: typeof CircleAlertIcon; +} { + switch (item.type) { + case "run_interrupt_request": + return { + label: "Interrupt requested", + detail: item.message, + tone: "warning", + icon: CircleAlertIcon, + }; + case "run_interrupt_result": + return { + label: "Run interrupted", + detail: item.message, + tone: "danger", + icon: XIcon, + }; + case "handoff": + return { + label: "Context handoff", + detail: + item.summary ?? + `${item.fromProviderInstanceIds.join(", ")} → ${item.toProviderInstanceId}`, + tone: item.status === "failed" ? "danger" : "muted", + icon: ZapIcon, + }; + case "fork": + return { + label: "Conversation fork", + detail: `Continues in ${item.targetThreadId}`, + tone: "muted", + icon: HammerIcon, + }; + case "compaction": { + const tokenSummary = + item.beforeTokenCount === undefined && item.afterTokenCount === undefined + ? null + : `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"} tokens`; + return { + label: "Context compacted", + detail: item.summary ?? tokenSummary, + tone: item.status === "failed" ? "danger" : "muted", + icon: MinusIcon, + }; + } + case "subagent": + return { + label: item.title ?? "Subagent", + detail: item.result ?? item.prompt, + tone: + item.status === "failed" ? "danger" : item.status === "completed" ? "success" : "muted", + icon: HammerIcon, + }; + case "approval_request": + return { + label: "Approval requested", + detail: item.prompt ?? item.requestKind, + tone: item.status === "failed" ? "danger" : "warning", + icon: MessageCircleIcon, + }; + case "user_input_request": + return { + label: "Input requested", + detail: item.questions.map((question) => question.question).join("\n"), + tone: item.status === "failed" ? "danger" : "warning", + icon: MessageCircleIcon, + }; + case "todo_list": { + const steps = item.steps.map((step) => `${step.status}: ${step.text}`).join("\n"); + return { + label: "Plan updated", + detail: [item.explanation, steps].filter(Boolean).join("\n\n") || null, + tone: item.status === "failed" ? "danger" : "success", + icon: CheckIcon, + }; + } + default: + return { + label: item.title?.trim() || item.type.replaceAll("_", " "), + detail: null, + tone: item.status === "failed" ? "danger" : "muted", + icon: WrenchIcon, + }; + } +} + +function V2EventTimelineRow({ row }: { row: Extract }) { + const ctx = use(TimelineRowCtx); + const { item, visibility, sourceThreadId } = row.projectedItem; + const presentation = v2EventPresentation(item); + const Icon = presentation.icon; + return ( +
+
+ +
+
+ {presentation.label} + {item.status !== "completed" ? ( + + {item.status} + + ) : null} + {visibility !== "local" ? ( + + {visibility === "inherited" ? "Inherited" : "Synthetic"} + + ) : null} +
+ {presentation.detail ? ( +
+ +
+ ) : null} + {visibility === "inherited" ? ( +

+ From {sourceThreadId} +

+ ) : null} +
+ + + Structured details + +
+              {JSON.stringify(item, null, 2)}
+            
+
+
+
+
+ ); +} +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) function WorkingTimelineRow({ row }: { row: Extract }) { const { workingStepLabel } = use(TimelineRowActivityCtx); @@ -1430,7 +1626,7 @@ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection( turnSummary: TurnDiffSummary | undefined; routeThreadKey: string; resolvedTheme: "light" | "dark"; - onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; + onOpenTurnDiff: (runId: RunId, filePath?: string) => void; }) { if (!turnSummary) return null; const checkpointFiles = turnSummary.files; @@ -1460,12 +1656,10 @@ function AssistantChangedFilesSectionInner({ checkpointFiles: TurnDiffSummary["files"]; routeThreadKey: string; resolvedTheme: "light" | "dark"; - onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void; + onOpenTurnDiff: (runId: RunId, filePath?: string) => void; }) { - const activity = use(TimelineRowActivityCtx); - const isLatestTurn = activity.latestTurnId === turnSummary.turnId; - const persistedExpanded = useUiStateStore( - (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId], + const allDirectoriesExpanded = useUiStateStore( + (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId] ?? true, ); const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded); const [autoExpanded] = useState(() => @@ -1475,19 +1669,46 @@ function AssistantChangedFilesSectionInner({ const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded); return ( - - setExpanded(routeThreadKey, turnSummary.turnId, nextExpanded) - } - onToggleAllDirectories={() => setAllDirectoriesExpanded((current) => !current)} - onOpenTurnDiff={onOpenTurnDiff} - /> +
+
+

+ Changed files ({changedFileCountLabel}) + {hasNonZeroStat(summaryStat) && ( + <> + • + + + )} +

+
+ + +
+
+ +
); } @@ -2040,8 +2261,8 @@ function buildToolCallExpandedBody( workspaceRoot: string | undefined, ): string | null { const blocks: string[] = []; - if (workEntry.itemType === "mcp_tool_call" && workEntry.toolData !== undefined) { - blocks.push(`MCP call\n${JSON.stringify(workEntry.toolData, null, 2)}`); + if (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) { + blocks.push(`Tool call\n${JSON.stringify(workEntry.toolData, null, 2)}`); } const raw = workEntryRawCommand(workEntry); if (raw?.trim()) { @@ -2060,6 +2281,20 @@ function buildToolCallExpandedBody( .join("\n"), ); } + if (workEntry.structuredPayload !== undefined) { + const structured = JSON.stringify(workEntry.structuredPayload, null, 2); + if (structured && !blocks.includes(structured)) { + blocks.push(structured); + } + } + if (workEntry.projectedItem?.visibility !== undefined) { + const { visibility, sourceThreadId } = workEntry.projectedItem; + if (visibility !== "local") { + blocks.push( + `${visibility === "inherited" ? "Inherited" : "Synthetic"} from ${sourceThreadId}`, + ); + } + } return blocks.length > 0 ? blocks.join("\n\n") : null; } @@ -2067,10 +2302,7 @@ export const toolCallExpandedBodyClassName = "max-h-64 cursor-text overflow-auto whitespace-pre-wrap break-words font-mono text-secondary-label text-[length:var(--font-size-code,0.6875rem)] leading-relaxed select-text"; 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"; @@ -2084,12 +2316,16 @@ 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"; +<<<<<<< HEAD case "dynamic_tool_call": +======= + case "subagent": +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) return "hammer"; case "collab_agent_tool_call": return "bot"; @@ -2234,7 +2470,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(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); @@ -2248,9 +2484,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(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 @@ -2293,6 +2527,8 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(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} >
@@ -2306,6 +2542,12 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(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 7e155bffc0..f5e9beaaa0 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -11,6 +11,11 @@ import { type SidebarProjectGroupingMode, } from "@t3tools/contracts"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +<<<<<<< HEAD +======= +import { presentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors"; +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) import { isAtomCommandInterrupted, settlePromise, @@ -3018,10 +3023,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 4ae476c1d1..2b32e8af26 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,14 +21,7 @@ import { CredentialStore, ProfileStore, } from "@t3tools/client-runtime/connection"; -import { - EnvironmentId, - OrchestrationShellSnapshot, - OrchestrationThreadDetailSnapshot, - ServerConfig, - ThreadId, - VcsListRefsResult, -} 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"; @@ -41,14 +38,9 @@ const THREAD_STORE_NAME = "thread"; const SERVER_CONFIG_STORE_NAME = "server-config"; const VCS_REFS_STORE_NAME = "vcs-refs"; 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); +<<<<<<< HEAD // v2 stores the snapshot sequence alongside the thread so a warm cache can // resume via `afterSequence` instead of re-downloading the full thread body. // v3 adds windowed (paginated) snapshots carrying `page` metadata. The bump @@ -61,6 +53,9 @@ const StoredThreadSnapshot = Schema.Struct({ threadId: ThreadId, snapshot: OrchestrationThreadDetailSnapshot, }); +======= +const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot; +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot); const StoredServerConfig = Schema.Struct({ schemaVersion: Schema.Literal(1), @@ -472,25 +467,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))); @@ -546,33 +540,40 @@ 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.snapshot) - : 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, snapshot) => Effect.gen(function* () { const encoded = yield* encodeStoredThreadSnapshot({ +<<<<<<< HEAD schemaVersion: 3, +======= + schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION, +>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover) environmentId, - threadId: snapshot.thread.id, - snapshot, + threadId: thread.thread.id, + thread, }).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause))); yield* writeDatabaseValue( database, THREAD_STORE_NAME, - threadCacheKey(environmentId, snapshot.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 7e7c95921f..9f36fa56f2 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"; @@ -57,7 +57,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( @@ -71,7 +71,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"); @@ -91,8 +91,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 ebb560a238..da4231bd0e 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 }; export type DiffRenderMode = "stacked" | "split"; @@ -22,8 +22,8 @@ interface DiffPanelStoreState { setDiffRenderMode: (mode: DiffRenderMode) => void; 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; } @@ -125,7 +125,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 569b4be96e..2c6195e0d2 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -211,7 +211,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({ @@ -333,7 +333,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 ca9a5986c6..642e280ed7 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,7 +22,7 @@ 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", @@ -30,13 +31,11 @@ function makeThread(overrides: Partial = {}): Thread { settledAt: null, deletedAt: null, updatedAt: "2026-03-09T10:00:00.000Z", - latestTurn: null, + latestRun: null, branch: null, worktreePath: null, - checkpoints: [], - activities: [], ...overrides, - }; + }); } describe("sortThreads", () => { @@ -51,7 +50,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, @@ -67,7 +66,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, @@ -95,7 +94,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 3c6127e017..0395683c67 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -1,1720 +1,160 @@ import { - classifyTaskAgentKind, - 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, - deriveTurnPlans, - derivePendingApprovals, - derivePendingUserInputs, deriveTimelineEntries, - deriveWorkLogEntries, + deriveTimelineEntriesFromVisibleTurnItems, findLatestProposedPlan, - 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 { - // Fixtures model post-ingestion rows: ingestion stamps agentKind on every - // task.* payload. Pass an explicit agentKind to model legacy rows. - const rawPayload = overrides.payload ?? {}; - const payload = - overrides.kind?.startsWith("task.") && !("agentKind" in rawPayload) - ? { - ...rawPayload, - agentKind: classifyTaskAgentKind({ - taskType: typeof rawPayload.taskType === "string" ? rawPayload.taskType : undefined, - agentId: typeof rawPayload.agentId === "string" ? rawPayload.agentId : undefined, - }), - } - : rawPayload; - 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("derives dynamic tool requests as actionable generic approvals", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "approval-open-dynamic-tool", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "approval.requested", - summary: "Approval requested", - tone: "approval", - payload: { - requestId: "req-dynamic-tool", - requestType: "dynamic_tool_call", - detail: "Search the web", - }, - }), - ]; - - expect(derivePendingApprovals(activities)).toEqual([ - { - requestId: "req-dynamic-tool", - requestKind: "command", - createdAt: "2026-02-23T00:00:01.000Z", - detail: "Search the web", - }, - ]); - }); - - 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("deriveTurnPlans", () => { - it("keeps one entry per turn, anchored at the first snapshot with the latest steps", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "plan-1a", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "turn.plan.updated", - summary: "Plan updated", - tone: "info", - turnId: "turn-1", - payload: { - plan: [{ step: "Inspect code", status: "inProgress" }], - }, - }), - makeActivity({ - id: "plan-1b", - createdAt: "2026-02-23T00:00:05.000Z", - kind: "turn.plan.updated", - summary: "Plan updated", - tone: "info", - turnId: "turn-1", - payload: { - plan: [{ step: "Inspect code", status: "completed" }], - }, - }), - makeActivity({ - id: "plan-2a", - createdAt: "2026-02-23T00:01:00.000Z", - kind: "turn.plan.updated", - summary: "Plan updated", - tone: "info", - turnId: "turn-2", - payload: { - plan: [{ step: "Ship it", status: "pending" }], - }, - }), - ]; - - const turnPlans = deriveTurnPlans(activities); - expect(turnPlans).toHaveLength(2); - expect(turnPlans[0]).toMatchObject({ - id: "turn-plan:turn-1", - createdAt: "2026-02-23T00:00:01.000Z", - turnId: "turn-1", - }); - expect(turnPlans[0]?.plan.steps).toEqual([{ step: "Inspect code", status: "completed" }]); - expect(turnPlans[1]?.plan.steps).toEqual([{ step: "Ship it", status: "pending" }]); - }); - - it("skips activities without parseable steps", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "plan-bad", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "turn.plan.updated", - summary: "Plan updated", - tone: "info", - turnId: "turn-1", - payload: { plan: [] }, - }), - ]; - expect(deriveTurnPlans(activities)).toEqual([]); - }); - - it("drops a turn's chip when a later snapshot clears the plan", () => { - const activities: OrchestrationThreadActivity[] = [ - makeActivity({ - id: "plan-set", - createdAt: "2026-02-23T00:00:01.000Z", - kind: "turn.plan.updated", - summary: "Plan updated", - tone: "info", - turnId: "turn-1", - payload: { plan: [{ step: "Inspect code", status: "inProgress" }] }, - }), - makeActivity({ - id: "plan-clear", - createdAt: "2026-02-23T00:00:02.000Z", - kind: "turn.plan.updated", - summary: "Plan updated", - tone: "info", - turnId: "turn-1", - payload: { plan: [] }, - }), - ]; - expect(deriveTurnPlans(activities)).toEqual([]); - }); -}); - -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("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, undefined); - 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 cd5e2aa11d..77b4524fdf 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -1,27 +1,24 @@ -import * as Option from "effect/Option"; -import * as Arr from "effect/Array"; -import { isBackgroundTaskActivity } from "@t3tools/client-runtime/state/subagentRuntime"; 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; @@ -29,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 }, @@ -46,251 +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"]; - /** Grouping key for subagent lifecycle rows (one row per agent). */ - taskId?: string; - /** Agent role (subagent_type) for labeled timeline rows. */ - agentRole?: string; - /** - * Present on agent-spawn CTA rows: one per workflow run or per-turn batch - * of direct spawns. The row renders as a call-to-action ("Kicked off N - * subagents") whose live status is derived from the agent panel model at - * render time; clicking opens the Agents panel. - */ - agentSpawn?: { - /** Workflow coordinator taskId, or null for a direct-spawn batch. */ - workflowId: string | null; - agentTaskIds: ReadonlyArray; - }; +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; - isWorkflowCoordinator?: boolean; - /** Shell/monitor/plan tasks: ordinary work-log rows, never spawn CTAs. */ - isBackgroundTask?: boolean; -} - -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: "turn-plan"; - createdAt: string; - turnPlan: TurnPlanEntry; + readonly id: string; + readonly kind: "work"; + readonly createdAt: string; + readonly entry: WorkLogEntry; } | { - id: string; - kind: "work"; - createdAt: string; - 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 { - // Spawn CTA rows are never neutral-hidden: mid-run they derive from - // task.progress (tone "thinking") and the neutral filter was swallowing - // them exactly while the fleet ran — the one moment they matter most. - if (entry.agentSpawn !== undefined) { - return false; - } - 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 { @@ -298,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`; @@ -313,269 +158,78 @@ 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)); } -function planStateFromActivity(activity: OrchestrationThreadActivity): ActivePlanState | null { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.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; - } +export function deriveActivePlanState( + plans: ReadonlyArray, + latestRunId: RunId | undefined, +): ActivePlanState | 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: activity.createdAt, - turnId: activity.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, }; } @@ -646,1077 +300,309 @@ export function deriveTurnPlans( } 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 plan === undefined ? null : toLatestProposedPlanState(plan); +} - return toLatestProposedPlanState(latestPlan); +export function findSidebarProposedPlan(input: { + 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 { + 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); + } + 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; } -/** - * Quiet-timeline guarantee: the work log carries the parent's narrative plus - * at most one row per agent. Everything an agent does internally lives in the - * Agents surface: - * - timelineBypass rows (Codex children, workflow members) never render here; - * - tool rows attributed to an owning agent (payload.agentId) are re-homed; - * - task.progress ticks collapse into one row per taskId; - * - task.updated is fold input only (status patches are not narrative). - * Unattributed rows always stay: over-hiding loses the only terminal signal. - */ -/** Agent (non-background) task.started rows seed spawn CTA batches. */ -function isAgentTaskStartedActivity(activity: OrchestrationThreadActivity): boolean { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - if (!payload || typeof payload.taskId !== "string") { - return false; - } - return !isBackgroundTaskActivity(payload); -} - -function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean { - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - if (!payload) { - return false; - } - const isTaskRow = - activity.kind === "task.started" || - activity.kind === "task.progress" || - activity.kind === "task.updated" || - activity.kind === "task.completed"; - // Task rows classify by the server stamp: a subagent's own background - // shell (agentId + "background") is agent-internal, but a nested AGENT - // (agentId + "agent") stays visible so its rows can anchor a spawn CTA - // (review finding: hiding on agentId alone removed nested agents and - // their anchors). Bypassed agent lifecycle rows also pass — collapse - // folds every such row into its batch's single CTA row, which is how - // Codex children (whose rows are ALL bypassed) get an anchor at the - // spawn point. - if (isTaskRow) { - const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0; - if (ownedByAgent || payload.timelineBypass === true) { - const isAgentTaskRow = - activity.kind !== "task.updated" && - typeof payload.taskId === "string" && - !isBackgroundTaskActivity(payload); - return !isAgentTaskRow; - } - return false; - } - if (payload.timelineBypass === true) { - return true; - } - // Non-task rows (attributed tool activity) owned by an agent are internal. - return typeof payload.agentId === "string" && payload.agentId.trim().length > 0; -} - -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; - // Agent task.started rows are CTA seeds: they carry the true spawn turn, - // which is the batch key (completions of background subagents arrive - // under later synthetic turns and must not start new batches). They - // collapse into the batch's single CTA row, never render standalone. - if (activity.kind === "task.started" && !isAgentTaskStartedActivity(activity)) continue; - if (activity.kind === "task.updated") continue; - if (activity.kind === "tool.progress") continue; - if (activity.kind === "context-window.updated") continue; - if (activity.summary === "Checkpoint captured") continue; - if (isPlanBoundaryToolActivity(activity)) continue; - if (isAgentInternalActivity(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.started" || - 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; - } - if (isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0) { - entry.taskId = payload.taskId; - } - if (isTaskActivity && typeof payload?.role === "string" && payload.role.length > 0) { - entry.agentRole = payload.role; - } - if ( - isTaskActivity && - (payload?.taskType === "local_workflow" || - (typeof payload?.workflowName === "string" && payload.workflowName.length > 0)) - ) { - entry.isWorkflowCoordinator = true; - } - if (isTaskActivity && payload && isBackgroundTaskActivity(payload)) { - entry.isBackgroundTask = true; - } - const collapseKey = deriveToolLifecycleCollapseKey(entry); - if (collapseKey) { - entry.collapseKey = collapseKey; - } - return entry; -} - -/** - * Spawn-group key for a subagent lifecycle row. Workflow members and their - * coordinator share the coordinator's group; direct spawns batch per turn. - * One CTA row per group (A1 design): "Kicked off N subagents". - */ -function agentSpawnGroupKey(entry: DerivedWorkLogEntry): string { - const taskId = entry.taskId ?? ""; - const workflowSlot = taskId.indexOf(":wf:"); - if (workflowSlot !== -1) { - return `wf:${taskId.slice(0, workflowSlot)}`; - } - if (entry.agentSpawn?.workflowId) { - return `wf:${entry.agentSpawn.workflowId}`; - } - if (entry.isWorkflowCoordinator) { - return `wf:${taskId}`; - } - // No turn id means no batch signal at all: fall back to one group per - // task. Unrelated turn-less spawns (separate fleets whose rows lost their - // turn) must not collapse into one immortal "direct:no-turn" CTA - // accumulating every agent the thread ever ran (review finding). Adapters - // stamp spawn turns (Codex spawnTurnId; Claude rows ride real turns), so - // this path is defensive. - return entry.turnId ? `direct:${entry.turnId}` : `direct:task:${taskId}`; -} - -function collapseDerivedWorkLogEntries( - entries: ReadonlyArray, -): DerivedWorkLogEntry[] { - const collapsed: DerivedWorkLogEntry[] = []; - // Subagent rows collapse by spawn group, not adjacency: a workflow run (or - // a turn's batch of direct spawns) is ONE narrative event in the chat — a - // CTA row that opens the Agents panel — no matter how many agents it - // contains or how their progress rows interleave (quiet-timeline - // guarantee). - const spawnRowIndex = new Map(); - // Batch membership is decided once, at the FIRST row seen for a taskId. - // Claude background subagents settle between turns, so their completion - // rows carry fresh synthetic turn ids (or none) — keying each row by its - // own turn splintered one batch into a stream of "Kicked off N subagents" - // rows (live-test finding, thread 7ac7ef05). - const groupKeyByTaskId = new Map(); - for (const entry of entries) { - const isTaskRow = - entry.taskId !== undefined && - !entry.isBackgroundTask && - (entry.activityKind === "task.started" || - entry.activityKind === "task.progress" || - entry.activityKind === "task.completed"); - if (isTaskRow && entry.taskId !== undefined) { - const rememberedKey = groupKeyByTaskId.get(entry.taskId); - const groupKey = rememberedKey ?? agentSpawnGroupKey(entry); - if (rememberedKey === undefined) { - groupKeyByTaskId.set(entry.taskId, groupKey); - } - const workflowId = groupKey.startsWith("wf:") ? groupKey.slice(3) : null; - const existingIndex = spawnRowIndex.get(groupKey); - if (existingIndex !== undefined) { - const existing = collapsed[existingIndex]!; - const agentTaskIds = existing.agentSpawn?.agentTaskIds.includes(entry.taskId) - ? existing.agentSpawn.agentTaskIds - : [...(existing.agentSpawn?.agentTaskIds ?? []), entry.taskId]; - collapsed[existingIndex] = { - ...mergeDerivedWorkLogEntries(existing, entry), - // The CTA row keeps the group's ANCHOR identity, not the last - // agent's: id/createdAt/turnId stay pinned to the spawn point so - // the row renders where the run launched instead of drifting to - // the newest progress tick (mid-run it drifted below the whole - // conversation, reading as "no visualization"), and the stable id - // keeps React state/virtualization sane. - id: existing.id, - createdAt: existing.createdAt, - turnId: existing.turnId ?? null, - ...(existing.taskId !== undefined ? { taskId: existing.taskId } : {}), - label: existing.label, - agentSpawn: { workflowId, agentTaskIds }, - }; - continue; - } - spawnRowIndex.set(groupKey, collapsed.length); - collapsed.push({ - ...entry, - agentSpawn: { workflowId, agentTaskIds: [entry.taskId] }, - }); - continue; - } - 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 { - // Subagent lifecycle rows collapse by agent identity: one row per agent, - // progress ticks fold into it, the terminal row wins the label. - if ( - entry.taskId && - (entry.activityKind === "task.progress" || entry.activityKind === "task.completed") - ) { - return `task${entry.taskId}`; - } - 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 extractAcpTextContent(value: unknown): string | null { - if (!Array.isArray(value)) { - return null; - } - - const chunks: string[] = []; - for (const entryValue of value) { - const entry = asRecord(entryValue); - if (entry?.type !== "content") { - continue; - } - const content = asRecord(entry.content); - if (content?.type !== "text") { - continue; - } - const text = asTrimmedString(content.text); - if (text) { - chunks.push(text); - } - } - - return chunks.length > 0 ? chunks.join("\n") : null; -} - -function extractToolOutput(payload: Record | null): string | null { - const data = asRecord(payload?.data); - const item = asRecord(data?.item); - const itemResult = asRecord(item?.result); - const rawOutput = asRecord(data?.rawOutput); - - const outputStreams: string[] = []; - const stdout = asTrimmedString(rawOutput?.stdout); - const stderr = asTrimmedString(rawOutput?.stderr); - if (stdout) { - outputStreams.push(stdout); - } - if (stderr) { - outputStreams.push(stderr); - } - - const candidates: unknown[] = [ - item?.aggregatedOutput, - itemResult?.content, - data?.rawOutput, - rawOutput?.content, - outputStreams.length > 0 ? outputStreams.join("\n") : null, - rawOutput?.output, - extractAcpTextContent(data?.content), - ]; - - for (const candidate of candidates) { - const text = asTrimmedString(candidate); - if (!text) { - continue; - } - const output = stripTrailingExitCode(text).output; - if (output) { - return output; - } - } - - 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); - const commandTool = isCommandToolDetail(payload, heading); - const commandPreview = commandTool - ? extractToolCommand(payload) - : { command: null, rawCommand: null }; - const command = commandPreview.command; - const normalizedCommand = normalizePreviewForComparison(command); - const normalizedRawCommand = normalizePreviewForComparison(commandPreview.rawCommand); - - if ( - detail && - normalizedHeading !== normalizedDetail && - (!commandTool || - (normalizedCommand !== normalizedDetail && normalizedRawCommand !== normalizedDetail)) - ) { - return detail; - } - - if (commandTool) { - if (!command) { - return null; - } - - const output = extractToolOutput(payload); - const normalizedOutput = normalizePreviewForComparison(output); - if ( - output && - normalizedOutput !== normalizedHeading && - normalizedOutput !== normalizedCommand - ) { - return output; - } - 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, turnPlans: 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 turnPlanRows: TimelineEntry[] = turnPlans.map((turnPlan) => ({ - id: turnPlan.id, - kind: "turn-plan", - createdAt: turnPlan.createdAt, - turnPlan, - })); - const workRows: TimelineEntry[] = workEntries.map((entry) => ({ - id: entry.id, - kind: "work", - createdAt: entry.createdAt, - entry, - })); - return [...messageRows, ...proposedPlanRows, ...turnPlanRows, ...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 7bca311823..281cbd706e 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -3,21 +3,14 @@ import type { EnvironmentProject, EnvironmentThread, EnvironmentThreadShell, + ThreadConversationMessage, + ThreadProposedPlan, + ThreadRuntimeSummary, + ThreadWorkEntry, } from "@t3tools/client-runtime/state/shell"; -import { - type EnvironmentThreadStatus, - 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 { mergeEnvironmentThread } from "@t3tools/client-runtime/state/threads"; +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"; @@ -28,9 +21,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"), @@ -53,14 +47,17 @@ const EMPTY_THREAD_STATUS_ATOM = Atom.make("empty").pip 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( @@ -186,31 +183,39 @@ export function useThread( 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 094db94c4d..f23ba6eb03 100644 --- a/apps/web/src/state/queries.ts +++ b/apps/web/src/state/queries.ts @@ -9,15 +9,8 @@ import { type EnvironmentThreadSearchMatch, } from "@t3tools/client-runtime/state/thread-search"; import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs"; -import type { - EnvironmentId, - OrchestrationThread, - ProjectContentMatch, - ProjectEntryKind, - 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"; @@ -56,7 +49,7 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({ }); 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 8973435788..7e531db8c5 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,10 +19,8 @@ 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", @@ -29,11 +28,11 @@ function makeThread(overrides: Partial = {}): Thread { settledOverride: null, settledAt: 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 9354db9c99..5b71f4939f 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 0cb1650066..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,13 +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, - settleThread, - stopThreadSession, - unsettleThread, -} 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, @@ -44,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 = { @@ -72,103 +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("dispatches settle and unsettle commands without timestamps", () => + it.effect("preserves plan implementation provenance on V2 runs", () => Effect.gen(function* () { - const dispatched: ClientOrchestrationCommand[] = []; - const supervisor = yield* makeSupervisor(dispatched); + const commands: OrchestrationV2Command[] = []; + const supervisor = yield* makeSupervisor({ commands, projects: [] }); - yield* settleThread({ - commandId: CommandId.make("settle-command"), - threadId: ThreadId.make("thread-1"), - }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor)); - yield* unsettleThread({ - commandId: CommandId.make("unsettle-command"), - threadId: ThreadId.make("thread-1"), - reason: "user", + 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(dispatched).toEqual([ - { - type: "thread.settle", - commandId: "settle-command", - threadId: "thread-1", + 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: [], }, - { - type: "thread.unsettle", - commandId: "unsettle-command", - threadId: "thread-1", - reason: "user", + 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 cb74f117b7..e660ac44db 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -1,333 +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 SettleThreadInput = CommandInput<"thread.settle">; -export type UnsettleThreadInput = CommandInput<"thread.unsettle">; -export type SnoozeThreadInput = CommandInput<"thread.snooze">; -export type UnsnoozeThreadInput = CommandInput<"thread.unsnooze">; -export type PinThreadInput = CommandInput<"thread.pin">; -export type UnpinThreadInput = CommandInput<"thread.unpin">; -export type ReorderPinnedThreadInput = CommandInput<"thread.pin.reorder">; -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 settleThread: (input: SettleThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.settleThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.settle", - 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 unsettleThread: (input: UnsettleThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.unsettleThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.unsettle", - commandId: yield* commandId(input), - }); -}); - -export const snoozeThread: (input: SnoozeThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.snoozeThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.snooze", - commandId: yield* commandId(input), - }); -}); - -export const unsnoozeThread: (input: UnsnoozeThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.unsnoozeThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.unsnooze", - commandId: yield* commandId(input), - }); -}); - -export const pinThread: (input: PinThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.pinThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.pin", - commandId: yield* commandId(input), - }); -}); - -export const unpinThread: (input: UnpinThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.unpinThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.unpin", - commandId: yield* commandId(input), - }); -}); - -export const reorderPinnedThread: (input: ReorderPinnedThreadInput) => CommandEffect = Effect.fn( - "EnvironmentCommands.reorderPinnedThread", -)(function* (input) { - return yield* dispatch({ - ...input, - type: "thread.pin.reorder", - commandId: yield* commandId(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 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 14a322bcd3..99aa4f6ac3 100644 --- a/packages/client-runtime/src/platform/persistence.ts +++ b/packages/client-runtime/src/platform/persistence.ts @@ -1,8 +1,7 @@ import { type EnvironmentId, - type OrchestrationShellSnapshot, - type OrchestrationThreadDetailSnapshot, - type ServerConfig, + type OrchestrationV2ShellSnapshot, + type OrchestrationV2ThreadProjection, type ThreadId, type VcsListRefsResult, } from "@t3tools/contracts"; @@ -60,21 +59,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< - Option.Option, - ConnectionPersistenceError - >; + ) => Effect.Effect, ConnectionPersistenceError>; readonly saveThread: ( environmentId: EnvironmentId, - snapshot: OrchestrationThreadDetailSnapshot, + 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 a221122fa6..eb7aca7641 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"; @@ -44,8 +40,8 @@ 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 | typeof WS_METHODS.subscribeServerConfig | typeof WS_METHODS.subscribeServerLifecycle 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 d3bb668020..cbf3a3ef48 100644 --- a/packages/client-runtime/src/state/entities.test.ts +++ b/packages/client-runtime/src/state/entities.test.ts @@ -1,372 +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, - settledOverride: null, - settledAt: 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(), - page: 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(), - page: 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 ba80275bff..7a659b6214 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -1,4 +1,4 @@ -import { ORCHESTRATION_WS_METHODS } from "@t3tools/contracts"; +import { ORCHESTRATION_V2_WS_METHODS } from "@t3tools/contracts"; import { Atom } from "effect/unstable/reactivity"; import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; @@ -10,7 +10,7 @@ export function createOrchestrationEnvironmentAtoms( return { turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:turn-diff", - tag: ORCHESTRATION_WS_METHODS.getTurnDiff, + tag: ORCHESTRATION_V2_WS_METHODS.getTurnDiff, }), workflowScript: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:workflow-script", @@ -21,7 +21,7 @@ export function createOrchestrationEnvironmentAtoms( }), fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:full-thread-diff", - tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff, + tag: ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff, }), threadSearch: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration:thread-search", @@ -31,7 +31,7 @@ export function createOrchestrationEnvironmentAtoms( }), 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 40e9bd80dc..2416a3ccc1 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"; @@ -22,7 +22,8 @@ import * as ConnectionWakeups from "../connection/wakeups.ts"; import * as Persistence from "../platform/persistence.ts"; import * as RpcSession from "../rpc/session.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; -import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts"; +import { makeEnvironmentShellState } from "./shell.ts"; +import { v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts"; const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), @@ -31,20 +32,9 @@ const TARGET = new PrimaryConnectionTarget({ wsBaseUrl: "wss://environment.example.test", }); -const PREPARED: PreparedConnection = { - environmentId: TARGET.environmentId, - label: TARGET.label, - httpBaseUrl: TARGET.httpBaseUrl, - socketUrl: TARGET.wsBaseUrl, - httpAuthorization: null, - target: TARGET, -}; - -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 { @@ -60,9 +50,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 c150bbb75b..b71b1d6b41 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"; @@ -30,7 +31,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; } @@ -42,7 +43,7 @@ const EMPTY_SHELL_STATE: EnvironmentShellState = { }; function shellStatusForSnapshot( - snapshot: Option.Option, + snapshot: Option.Option, ): EnvironmentShellStatus { return Option.isSome(snapshot) ? "cached" : "empty"; } @@ -62,7 +63,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") environmentId, ...safeErrorLogAttributes(error), }), - Effect.as(Option.none()), + Effect.as(Option.none()), ), ), ); @@ -71,13 +72,10 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") status: shellStatusForSnapshot(cachedSnapshot), error: Option.none(), }); - const awaitingCompletion = yield* Ref.make(false); - const lastAuthoritativeSession = yield* Ref.make(null); - const activeSubscriptionSession = yield* Ref.make(null); - 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) => @@ -136,7 +134,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") ); const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* ( - item: OrchestrationShellStreamItem, + item: OrchestrationV2ShellStreamItem, ) { if (item.kind === "synchronized") { yield* Ref.set(awaitingCompletion, false); @@ -178,80 +176,13 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") yield* Queue.offer(persistence, nextSnapshot); }); - const foregroundResubscriptions = Option.match(wakeups, { - onNone: () => Stream.never, - onSome: (service) => - service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)), - }); - - yield* setSynchronizing; - yield* Effect.forkScoped( - subscribeDynamic( - ORCHESTRATION_WS_METHODS.subscribeShell, - Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) { - yield* Ref.set(activeSubscriptionSession, session); - const supportsCompletionMarker = yield* session.initialConfig.pipe( - Effect.map((config) => config.shellResumeCompletionMarker === true), - Effect.orElseSucceed(() => false), - ); - yield* Ref.set(awaitingCompletion, supportsCompletionMarker); - yield* setSynchronizing; - - // Foreground resubscriptions on the same live session can resume from - // the in-memory cursor. A new session reloads the authoritative HTTP - // snapshot so a valid cursor cannot preserve incomplete cached data. - const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session; - let canResume = hasAuthoritativeSnapshot; - let current = yield* SubscriptionRef.get(state); - if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) { - const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe( - Effect.flatMap( - Option.match({ - onSome: Effect.succeed, - onNone: () => - SubscriptionRef.changes(supervisor.prepared).pipe( - Stream.filter(Option.isSome), - Stream.map((value) => value.value), - Stream.runHead, - Effect.map(Option.getOrThrow), - ), - }), - ), - ); - const httpSnapshot = yield* snapshotLoader.load(prepared); - if (Option.isSome(httpSnapshot)) { - yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value }); - canResume = true; - current = yield* SubscriptionRef.get(state); - } - } - - // If the authoritative refresh failed, omit the cached cursor so the - // socket fallback sends a complete snapshot for this new session. - if (!canResume || Option.isNone(current.snapshot)) { - return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}; - } - if (!supportsCompletionMarker) { - // Without a completion marker there is no synchronized signal for a - // resumed subscription, so report live immediately, like threads. - yield* SubscriptionRef.update(state, (value) => ({ - ...value, - status: "live" as const, - error: Option.none(), - })); - } - return { - afterSequence: current.snapshot.value.snapshotSequence, - ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}), - }; - }), - { - onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)), - retryExpectedFailureAfter: "250 millis", - resubscribe: foregroundResubscriptions, - }, - ).pipe(Stream.runForEach(applyItem)), - ); + yield* subscribe( + ORCHESTRATION_V2_WS_METHODS.subscribeShell, + {}, + { + onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)), + }, + ).pipe(Stream.runForEach(applyItem), Effect.forkScoped); yield* SubscriptionRef.changes(supervisor.state).pipe( Stream.runForEach((connectionState) => { switch (connectionProjectionPhase(connectionState)) { @@ -347,8 +278,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 fdccc4c47d..80a68c21ad 100644 --- a/packages/client-runtime/src/state/shellReducer.test.ts +++ b/packages/client-runtime/src/state/shellReducer.test.ts @@ -1,185 +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, - settledOverride: null, - settledAt: 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 ed3537e4f8..a13c56e8dd 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -62,6 +62,7 @@ export type { SnoozeThreadInput, StartThreadTurnInput, StopThreadSessionInput, + ThreadCommandInput, UnarchiveThreadInput, UnpinThreadInput, UnsettleThreadInput, 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 5a2ffa442e..a54b4469c1 100644 --- a/packages/client-runtime/src/state/threadDetail.ts +++ b/packages/client-runtime/src/state/threadDetail.ts @@ -1,69 +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 { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threadState.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, - settledOverride: shell.settledOverride, - settledAt: shell.settledAt, - snoozedUntil: shell.snoozedUntil, - snoozedAt: shell.snoozedAt, - pinnedAt: shell.pinnedAt, - pinOrderKey: shell.pinOrderKey, - session: shell.session, + ...shell, + latestRun: detail.latestRun, + runtime: detail.runtime, + source: shell.source, }; } @@ -88,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), @@ -104,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 8b2479c7a3..0000000000 --- a/packages/client-runtime/src/state/threadReducer.test.ts +++ /dev/null @@ -1,904 +0,0 @@ -import { describe, expect, it } from "vite-plus/test"; - -import { - CheckpointRef, - CommandId, - 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, - settledOverride: null, - settledAt: 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 and clears title regeneration", () => { - const regeneratingThread: OrchestrationThread = { - ...baseThread, - titleRegeneration: { - requestId: CommandId.make("regenerate-title"), - startedAt: "2026-04-01T02:00:00.000Z", - }, - }; - const result = applyThreadDetailEvent(regeneratingThread, { - ...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"); - expect(result.thread.titleRegeneration).toBeNull(); - } - }); - - 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.settled / thread.unsettled", () => { - it("sets the settled override and timestamp", () => { - const settledAt = "2026-04-01T05:00:00.000Z"; - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 5, - occurredAt: settledAt, - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.settled", - payload: { - threadId: ThreadId.make("thread-1"), - settledAt, - updatedAt: settledAt, - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.settledOverride).toBe("settled"); - expect(result.thread.settledAt).toBe(settledAt); - } - }); - - it.each([ - ["user", "active"], - ["activity", null], - ] as const)("unsettles for %s with override %s", (reason, settledOverride) => { - const settledThread: OrchestrationThread = { - ...baseThread, - settledOverride: "settled", - settledAt: "2026-04-01T05:00:00.000Z", - }; - const updatedAt = "2026-04-01T06:00:00.000Z"; - const result = applyThreadDetailEvent(settledThread, { - ...baseEventFields, - sequence: 6, - occurredAt: updatedAt, - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.unsettled", - payload: { - threadId: ThreadId.make("thread-1"), - reason, - updatedAt, - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.settledOverride).toBe(settledOverride); - expect(result.thread.settledAt).toBeNull(); - } - }); - }); - - describe("thread.pinned / thread.unpinned", () => { - it("sets pinnedAt", () => { - const pinnedAt = "2026-04-01T05:00:00.000Z"; - const result = applyThreadDetailEvent(baseThread, { - ...baseEventFields, - sequence: 5, - occurredAt: pinnedAt, - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.pinned", - payload: { - threadId: ThreadId.make("thread-1"), - pinnedAt, - updatedAt: pinnedAt, - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.pinnedAt).toBe(pinnedAt); - } - }); - - it("clears pinnedAt", () => { - const pinnedThread: OrchestrationThread = { - ...baseThread, - pinnedAt: "2026-04-01T05:00:00.000Z", - }; - const updatedAt = "2026-04-01T06:00:00.000Z"; - const result = applyThreadDetailEvent(pinnedThread, { - ...baseEventFields, - sequence: 6, - occurredAt: updatedAt, - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.unpinned", - payload: { - threadId: ThreadId.make("thread-1"), - updatedAt, - }, - }); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - expect(result.thread.pinnedAt).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"); - } - }); - - it("replaces earlier resolvable context-window updates for the same turn", () => { - const contextWindowActivity = (id: string, sequence: number, usedTokens: unknown) => ({ - id: EventId.make(id), - tone: "info" as const, - kind: "context-window.updated", - summary: "Context window updated", - payload: { usedTokens }, - turnId: TurnId.make("turn-1"), - sequence, - createdAt: "2026-04-01T11:00:00.000Z", - }); - const otherTurnActivity = contextWindowActivity("activity-other-turn", 2, 500); - const existingActivities = [ - contextWindowActivity("activity-cw-1", 1, 1_000), - { ...otherTurnActivity, turnId: TurnId.make("turn-0") }, - // Malformed row (no usedTokens): must survive, and must not be - // treated as the latest value by consumers. - contextWindowActivity("activity-cw-malformed", 3, undefined), - contextWindowActivity("activity-cw-2", 4, 2_000), - ]; - - const result = applyThreadDetailEvent( - { ...baseThread, activities: existingActivities }, - { - ...baseEventFields, - sequence: 20, - occurredAt: "2026-04-01T11:02:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.activity-appended", - payload: { - threadId: ThreadId.make("thread-1"), - activity: contextWindowActivity("activity-cw-3", 5, 3_000), - }, - }, - ); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - const ids = result.thread.activities.map((activity) => activity.id); - // Same-turn resolvable rows collapse to the newest; the other turn's - // row and the malformed row are untouched. - expect(ids).toEqual(["activity-other-turn", "activity-cw-malformed", "activity-cw-3"]); - } - }); - - it("does not collapse context-window history for a malformed update", () => { - const resolvable = { - id: EventId.make("activity-cw-resolvable"), - tone: "info" as const, - kind: "context-window.updated", - summary: "Context window updated", - payload: { usedTokens: 1_000 }, - turnId: TurnId.make("turn-1"), - sequence: 1, - createdAt: "2026-04-01T11:00:00.000Z", - }; - - const result = applyThreadDetailEvent( - { ...baseThread, activities: [resolvable] }, - { - ...baseEventFields, - sequence: 21, - occurredAt: "2026-04-01T11:03:00.000Z", - aggregateKind: "thread", - aggregateId: ThreadId.make("thread-1"), - type: "thread.activity-appended", - payload: { - threadId: ThreadId.make("thread-1"), - activity: { - ...resolvable, - id: EventId.make("activity-cw-broken"), - payload: { usedTokens: Number.NaN }, - sequence: 2, - }, - }, - }, - ); - - expect(result.kind).toBe("updated"); - if (result.kind === "updated") { - // The resolvable row must survive so consumers can still derive a - // usage value by walking backwards past the malformed row. - const ids = result.thread.activities.map((activity) => activity.id); - expect(ids).toEqual(["activity-cw-resolvable", "activity-cw-broken"]); - } - }); - }); - - 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 970fd94b1a..0000000000 --- a/packages/client-runtime/src/state/threadReducer.ts +++ /dev/null @@ -1,669 +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), -]); - -/** - * Matches the validity rule in `deriveLatestContextWindowSnapshot` (and the - * server's snapshot-side `dropStaleContextWindowActivities`): rows without a - * finite, non-negative `usedTokens` are skipped during the consumer's backward - * walk, so they must not replace an earlier resolvable row here. - */ -function isResolvableContextWindowActivity(activity: OrchestrationThreadActivity): boolean { - if (activity.kind !== "context-window.updated") { - return false; - } - const payload = - activity.payload && typeof activity.payload === "object" - ? (activity.payload as Record) - : null; - const usedTokens = payload?.usedTokens; - return typeof usedTokens === "number" && Number.isFinite(usedTokens) && usedTokens >= 0; -} - -/** - * 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, - settledOverride: null, - settledAt: null, - snoozedUntil: null, - snoozedAt: 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, - titleRegeneration: null, - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.unarchived": - return { - kind: "updated", - thread: { ...thread, archivedAt: null, updatedAt: event.payload.updatedAt }, - }; - - case "thread.settled": - return { - kind: "updated", - thread: { - ...thread, - settledOverride: "settled", - settledAt: event.payload.settledAt, - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.unsettled": - return { - kind: "updated", - thread: { - ...thread, - settledOverride: event.payload.reason === "user" ? "active" : null, - settledAt: null, - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.snoozed": - return { - kind: "updated", - thread: { - ...thread, - snoozedUntil: event.payload.snoozedUntil, - snoozedAt: event.payload.snoozedAt, - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.unsnoozed": - return { - kind: "updated", - thread: { - ...thread, - snoozedUntil: null, - snoozedAt: null, - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.pinned": - return { - kind: "updated", - thread: { - ...thread, - pinnedAt: event.payload.pinnedAt, - ...(event.payload.pinOrderKey !== undefined - ? { pinOrderKey: event.payload.pinOrderKey } - : {}), - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.unpinned": - return { - kind: "updated", - thread: { - ...thread, - pinnedAt: null, - pinOrderKey: null, - updatedAt: event.payload.updatedAt, - }, - }; - - case "thread.pin-reordered": - return { - kind: "updated", - thread: { - ...thread, - pinOrderKey: event.payload.orderKey, - 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.titleRegeneration !== undefined - ? { titleRegeneration: event.payload.titleRegeneration } - : {}), - ...(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 activity = event.payload.activity; - // A resolvable context-window update supersedes earlier resolvable ones - // for the same turn: consumers only read the latest value (walking the - // array backwards), and providers stream these updates continuously, so - // retaining the history grows the thread by thousands of rows over a - // long session. Mirrors the server-side snapshot rule in - // dropStaleContextWindowActivities; retention stays per turn so a - // thread.reverted that discards turns can still resolve a value from - // the turns that survive. - const supersedesContextWindow = isResolvableContextWindowActivity(activity); - const activities = pipe( - thread.activities, - Arr.filter( - (entry) => - entry.id !== activity.id && - !( - supersedesContextWindow && - entry.turnId === activity.turnId && - isResolvableContextWindowActivity(entry) - ), - ), - Arr.append(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 c2df434e8e..2ff57406c9 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -1,41 +1,29 @@ import { EnvironmentId, EventId, - ORCHESTRATION_WS_METHODS, - ProjectId, - ProviderInstanceId, - ThreadId, - TurnId, - type OrchestrationThread, - type OrchestrationThreadDetailSnapshot, - 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 ConnectionWakeups from "../connection/wakeups.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, - ThreadSnapshotLoader, - 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"), @@ -43,559 +31,73 @@ const TARGET = new PrimaryConnectionTarget({ httpBaseUrl: "https://environment.example.test", wsBaseUrl: "wss://environment.example.test", }); -const THREAD_ID = ThreadId.make("thread-1"); -const CACHED_SNAPSHOT_SEQUENCE = 7; -const PREPARED: PreparedConnection = { - environmentId: TARGET.environmentId, - label: TARGET.label, - httpBaseUrl: TARGET.httpBaseUrl, - socketUrl: TARGET.wsBaseUrl, - httpAuthorization: null, - target: TARGET, -}; -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, - settledOverride: null, - settledAt: null, - deletedAt: null, - messages: [], - proposedPlans: [], - activities: [], - checkpoints: [], - session: null, -}; -const ACTIVE_THREAD: OrchestrationThread = { - ...BASE_THREAD, - latestTurn: { - turnId: TurnId.make("turn-1"), - state: "running", - requestedAt: "2026-04-01T00:01:00.000Z", - startedAt: "2026-04-01T00:01:00.000Z", - completedAt: null, - assistantMessageId: null, - }, - session: { - threadId: THREAD_ID, - status: "running", - providerName: "codex", - runtimeMode: "full-access", - activeTurnId: TurnId.make("turn-1"), - lastError: null, - updatedAt: "2026-04-01T00:01:00.000Z", - }, -}; -type TestThreadInput = OrchestrationThreadStreamItem | Error; - -function testSession( - client: WsRpcProtocolClient, - options?: { readonly completionMarker?: boolean }, -): RpcSession.RpcSession { - return { - client, - initialConfig: Effect.succeed( - options?.completionMarker === true - ? ({ threadResumeCompletionMarker: true } as never) - : ({} as 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; - readonly httpSnapshot?: Option.Option; - readonly completionMarker?: boolean; -}) { - 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 loaderCalls = yield* Ref.make(0); - const lastSubscribeAfterSequence = yield* Ref.make(undefined); - const lastRequestCompletionMarker = yield* Ref.make(undefined); - const savedThreads = yield* Ref.make>([]); - const removedThreads = yield* Ref.make>([]); - const wakeups = yield* Queue.unbounded(); - 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]: (input: { - readonly afterSequence?: number; - readonly requestCompletionMarker?: boolean; - }) => - Stream.unwrap( - Ref.updateAndGet(subscriptionCount, (count) => count + 1).pipe( - Effect.andThen(Ref.set(lastSubscribeAfterSequence, input.afterSequence)), - Effect.andThen(Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker)), - Effect.as(streamFrom(inputs)), - ), - ), - } as unknown as WsRpcProtocolClient; - const supervisorSession = yield* SubscriptionRef.make>( - Option.some( - testSession( +describe("V2 thread synchronization", () => { + it.effect("applies a snapshot followed by committed projection events", () => + Effect.gen(function* () { + const events = yield* Queue.unbounded(); + const client = { + [ORCHESTRATION_V2_WS_METHODS.subscribeThread]: () => Stream.fromQueue(events), + } as unknown as WsRpcProtocolClient; + const rpcSession: RpcSession.RpcSession = { client, - options?.completionMarker === true ? { completionMarker: true } : undefined, - ), - ), - ); - const prepared = yield* SubscriptionRef.make>( - Option.some(PREPARED), - ); - const snapshotLoader = ThreadSnapshotLoader.of({ - load: (_prepared, threadId) => - Ref.update(loaderCalls, (count) => count + 1).pipe( - Effect.as( - threadId === THREAD_ID - ? (options?.httpSnapshot ?? Option.none()) - : 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({ - snapshotSequence: CACHED_SNAPSHOT_SEQUENCE, - thread: options.cached, - }) - : Option.none(), - ), - saveThread: (_environmentId, thread) => - Ref.update(savedThreads, (current) => [...current, thread]), - removeThread: (_environmentId, threadId) => - Ref.update(removedThreads, (current) => [...current, threadId]), - loadServerConfig: () => Effect.succeed(Option.none()), - saveServerConfig: () => Effect.void, - loadVcsRefs: () => Effect.succeed(Option.none()), - saveVcsRefs: () => Effect.void, - removeVcsRefs: () => Effect.void, - clearVcsRefs: () => Effect.void, - clear: () => Effect.void, - }); - const threadState = yield* makeEnvironmentThreadState(THREAD_ID).pipe( - Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), - Effect.provideService(Persistence.EnvironmentCacheStore, cache), - Effect.provideService(ThreadSnapshotLoader, snapshotLoader), - Effect.provideService( - ConnectionWakeups.ConnectionWakeups, - ConnectionWakeups.ConnectionWakeups.of({ changes: Stream.fromQueue(wakeups) }), - ), - ); - 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, - loaderCalls, - lastSubscribeAfterSequence, - lastRequestCompletionMarker, - supervisorState, - supervisorSession, - savedThreads, - removedThreads, - wakeups, - replaceSession: SubscriptionRef.set( - supervisorSession, - Option.some( - testSession( - client, - options?.completionMarker === true ? { completionMarker: true } : undefined, - ), - ), - ), - }; -}); - -const snapshot = (thread: OrchestrationThread): OrchestrationThreadStreamItem => ({ - kind: "snapshot", - snapshot: { - snapshotSequence: 1, - thread, - }, -}); - -const synchronized = (): OrchestrationThreadStreamItem => ({ kind: "synchronized" }); - -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 immediately from a warm cache", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ cached: BASE_THREAD }); - const state = yield* awaitThreadState(harness.observed, (value) => Option.isSome(value.data)); - - expect(Option.getOrThrow(state.data)).toEqual(BASE_THREAD); - expect(Option.isNone(state.error)).toBe(true); - }), - ); - - it.effect("resumes a warm cache via afterSequence without an HTTP fetch", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ cached: BASE_THREAD }); - - // The warm cache reaches live from the cached data, and a live event - // applies on top of it. - yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 1)); - yield* awaitThreadState( - harness.observed, - (value) => - value.status === "live" && - Option.isSome(value.data) && - value.data.value.title === "Live title", - ); - - // The subscription resumed from the cached sequence and never fetched the - // full snapshot over HTTP. - expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE); - expect(yield* Ref.get(harness.loaderCalls)).toBe(0); - }), - ); - - 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)?.thread.title).toBe("Live title"); - expect((yield* Ref.get(harness.savedThreads)).at(-1)?.snapshotSequence).toBe(2); - }), - ); - - it.effect("does not persist active thread snapshots during streaming or teardown", () => - Effect.gen(function* () { - const savedThreads = yield* Effect.scoped( - Effect.gen(function* () { - const harness = yield* makeHarness({ cached: ACTIVE_THREAD }); - yield* awaitThreadState( - harness.observed, - (value) => - value.status === "live" && - Option.isSome(value.data) && - value.data.value.session?.status === "running", - ); - - yield* TestClock.adjust("500 millis"); - yield* Effect.yieldNow; - - expect(yield* Ref.get(harness.savedThreads)).toEqual([]); - return harness.savedThreads; - }), - ); - - expect(yield* Ref.get(savedThreads)).toEqual([]); - }), - ); - - it.effect("seeds the thread from the HTTP snapshot and resumes live events", () => - Effect.gen(function* () { - const httpThread: OrchestrationThread = { ...BASE_THREAD, title: "HTTP title" }; - const harness = yield* makeHarness({ - httpSnapshot: Option.some({ snapshotSequence: 1, thread: httpThread }), + 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, }); - // No socket snapshot is pushed; only a live event arrives over the socket. - // It can only be applied if the HTTP snapshot already seeded the thread. - 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"); - // Cold cache: the full snapshot was loaded over HTTP and the socket - // resumed from that snapshot's sequence. - expect(yield* Ref.get(harness.loaderCalls)).toBeGreaterThanOrEqual(1); - expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(1); - }), - ); - - 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("does not resurrect a deleted thread when the app returns to the foreground", () => - Effect.gen(function* () { - const harness = yield* makeHarness({ - cached: BASE_THREAD, - completionMarker: true, - httpSnapshot: Option.some({ - snapshotSequence: 4, - thread: { ...BASE_THREAD, title: "Stale HTTP thread" }, - }), + 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, }); - yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD)); - yield* Queue.offer(harness.inputs, deleted()); - yield* awaitThreadState(harness.observed, (value) => value.status === "deleted"); - - expect(yield* Ref.get(harness.loaderCalls)).toBe(0); - yield* Queue.offer(harness.wakeups, "application-active"); - for (let attempt = 0; attempt < 100; attempt += 1) { - if ((yield* Ref.get(harness.subscriptionCount)) >= 2) break; - yield* Effect.yieldNow; - } - - const latest = yield* Ref.get(harness.latest); - expect(yield* Ref.get(harness.subscriptionCount)).toBe(2); - expect(yield* Ref.get(harness.loaderCalls)).toBe(0); - expect(latest.status).toBe("deleted"); - expect(Option.isNone(latest.data)).toBe(true); - }), - ); - - 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), + const state = yield* makeEnvironmentThreadState(v2ThreadId).pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.provideService(Persistence.EnvironmentCacheStore, cache), ); - 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, + yield* Queue.offer(events, { + kind: "snapshot", + snapshotSequence: 1, + projection: v2Projection, }); - yield* Queue.offer(harness.inputs, snapshot(BASE_THREAD)); - yield* awaitThreadState(harness.observed, (value) => value.status === "live"); + yield* SubscriptionRef.changes(state).pipe( + Stream.filter((current) => current.status === "live"), + Stream.runHead, + ); - yield* SubscriptionRef.set(harness.supervisorState, { - desired: true, - network: "online", - phase: "connected", - stage: null, - attempt: 1, - generation: 1, - lastFailure: null, - retryAt: null, + 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 }, + }, }); - for (let index = 0; index < 10; index += 1) { - yield* Effect.yieldNow; - } + yield* SubscriptionRef.changes(state).pipe( + Stream.filter((current) => Option.getOrNull(current.data)?.thread.title === "Updated"), + Stream.runHead, + ); - expect((yield* Ref.get(harness.latest)).status).toBe("live"); + 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 4ba5a0e9df..c37f20d766 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -1,10 +1,8 @@ import { - ORCHESTRATION_WS_METHODS, + ORCHESTRATION_V2_WS_METHODS, type EnvironmentId as EnvironmentIdType, - type OrchestrationThread, - type OrchestrationThreadDetailPage, - type OrchestrationThreadDetailSnapshot, - type OrchestrationThreadStreamItem, + type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadStreamItem, type ThreadId as ThreadIdType, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; @@ -26,17 +24,27 @@ import { EnvironmentCacheStore } from "../platform/persistence.ts"; import { subscribeDynamic } from "../rpc/client.ts"; import { ThreadSnapshotLoader, type ThreadSnapshotWindow } from "./threadSnapshotHttp.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"; -import { - EMPTY_ENVIRONMENT_THREAD_STATE, - type EnvironmentThreadPageState, - type EnvironmentThreadState, - type EnvironmentThreadStatus, -} from "./threadState.ts"; -function statusWithoutLiveData(data: Option.Option): EnvironmentThreadStatus { +export type EnvironmentThreadStatus = "empty" | "cached" | "synchronizing" | "live" | "deleted"; + +export interface EnvironmentThreadState { + readonly data: Option.Option; + readonly status: EnvironmentThreadStatus; + readonly error: Option.Option; +} + +export const EMPTY_ENVIRONMENT_THREAD_STATE: EnvironmentThreadState = { + data: Option.none(), + status: "empty", + error: Option.none(), +}; + +function statusWithoutLiveData( + data: Option.Option, +): EnvironmentThreadStatus { return Option.isSome(data) ? "cached" : "empty"; } @@ -147,7 +155,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make threadId, error: error.message, }), - Effect.as(Option.none()), + Effect.as(Option.none()), ), ), ); @@ -160,35 +168,11 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make // works while rendering from cache; a cached full snapshot has no page. page: Option.flatMap(cached, (snapshot) => pageStateFromSnapshot(snapshot.page)), }); - // Seed the resume cursor from the cached snapshot so a warm cache can catch up - // via `afterSequence` instead of re-downloading the full thread body. - const lastSequence = yield* SubscriptionRef.make( - Option.match(cached, { onNone: () => 0, onSome: (snapshot) => snapshot.snapshotSequence }), - ); - const awaitingCompletion = yield* Ref.make(false); - // Bumped whenever loaded history may have been rewritten out from under an - // in-flight older-page fetch (snapshot replacement, revert, deletion). A - // page response captured under an older epoch is discarded, not merged. - const historyEpoch = yield* Ref.make(0); - // Serializes stream-item application against older-page staleness checks + - // merges. Without it, a revert or snapshot processed between loadOlderTurns' - // epoch check and its merge could still slip resurrected history in. - const applyLock = yield* Semaphore.make(1); - // Whether the connected server accepts windowed reads; set per subscription - // from the session config. Gates loadOlderTurns so a reconnect to a - // pre-pagination server never sends unsupported window parameters. - const paginationSupported = yield* Ref.make(false); - // An older page whose thread watermark is ahead of the live state, parked - // until the subscription catches up (see mergeOlderPage's caller). At most - // one can exist because loadOlderTurns no-ops while loadingOlder is true. - const pendingOlderPage = yield* Ref.make<{ - readonly snapshot: OrchestrationThreadDetailSnapshot; - readonly epoch: number; - } | null>(null); - const persistence = yield* Queue.sliding(1); + const lastSequence = yield* SubscriptionRef.make(0); + const persistence = yield* Queue.sliding(1); const persist = Effect.fn("EnvironmentThreadState.persist")(function* ( - snapshot: OrchestrationThreadDetailSnapshot, + thread: OrchestrationV2ThreadProjection, ) { yield* cache.saveThread(environmentId, snapshot).pipe( Effect.catch((error) => @@ -253,10 +237,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make ); const setThread = Effect.fn("EnvironmentThreadState.setThread")(function* ( - thread: OrchestrationThread, - // "keep" preserves the current page state (live events touch only loaded - // recent turns); a snapshot or merged page passes its own page state. - page: Option.Option | "keep", + thread: OrchestrationV2ThreadProjection, ) { const waiting = yield* Ref.get(awaitingCompletion); yield* SubscriptionRef.update(state, (current) => ({ @@ -313,9 +294,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make ); }); - // Body of applyItem, running under applyLock. - const applyItemLocked = Effect.fn("EnvironmentThreadState.applyItemLocked")(function* ( - item: OrchestrationThreadStreamItem, + const applyItem = Effect.fn("EnvironmentThreadState.applyItem")(function* ( + item: OrchestrationV2ThreadStreamItem, ) { if (item.kind === "synchronized") { yield* Ref.set(awaitingCompletion, false); @@ -328,21 +308,16 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } if (item.kind === "snapshot") { - // A fresh snapshot replaces all loaded history, including older - // pages: a turn reverted while disconnected would otherwise survive - // in the preserved history with no event left to remove it. The - // epoch bump discards any older-page fetch racing this snapshot. - yield* Ref.update(historyEpoch, (epoch) => epoch + 1); - yield* SubscriptionRef.set(lastSequence, item.snapshot.snapshotSequence); - yield* setThread(item.snapshot.thread, pageStateFromSnapshot(item.snapshot.page)); + 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)) { @@ -351,20 +326,13 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make } return; } - if (item.event.type === "thread.reverted") { - // A revert rewrites loaded history (whole turns disappear), so an - // older-page fetch in flight may straddle the removed range; the epoch - // bump discards it. The stored page cursor stays valid: cursors are an - // (anchor, turnId) keyset derived from event content, which survives - // the revert projector's row rewrite, so no refresh is needed — the - // revert reducer's turn filtering fully handles loaded history. - yield* Ref.update(historyEpoch, (epoch) => epoch + 1); - } - const result = applyThreadDetailEvent(current.data.value, item.event); - if (result.kind === "updated") { - yield* setThread(result.thread, "keep"); - } 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); } // The event may have advanced the live state past a parked page's // watermark; merge it as soon as that happens. @@ -552,97 +520,14 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make }); yield* setSynchronizing; - yield* Effect.forkScoped( - subscribeDynamic( - ORCHESTRATION_WS_METHODS.subscribeThread, - Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) { - const config = yield* session.initialConfig.pipe( - Effect.orElseSucceed( - () => - ({}) as { - threadResumeCompletionMarker?: boolean; - threadSnapshotPagination?: boolean; - }, - ), - ); - const supportsCompletionMarker = config.threadResumeCompletionMarker === true; - // Windowed loads are gated on the server capability: pre-pagination - // servers reject unknown query params, and a windowed WS fallback to - // such a server would silently hide history. - const supportsPagination = config.threadSnapshotPagination === true; - yield* Ref.set(paginationSupported, supportsPagination); - yield* Ref.set(awaitingCompletion, supportsCompletionMarker); - yield* setSynchronizing; - - let current = yield* SubscriptionRef.get(state); - // A windowed cache resuming against a server without pagination is a - // trap: afterSequence resume keeps only the window, and the missing - // older turns can never be loaded (the server has no cursor reads). - // Drop the window marker and treat the data as needing a full reload. - if (!supportsPagination && Option.isSome(current.page)) { - yield* Ref.update(historyEpoch, (epoch) => epoch + 1); - yield* SubscriptionRef.update(state, (value) => ({ - ...value, - data: Option.none(), - status: value.status === "deleted" ? value.status : ("empty" as const), - page: Option.none(), - })); - yield* SubscriptionRef.set(lastSequence, 0); - current = yield* SubscriptionRef.get(state); - } - if (Option.isNone(current.data) && current.status !== "deleted") { - const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe( - Effect.flatMap( - Option.match({ - onSome: Effect.succeed, - onNone: () => - SubscriptionRef.changes(supervisor.prepared).pipe( - Stream.filter(Option.isSome), - Stream.map((value) => value.value), - Stream.runHead, - Effect.map(Option.getOrThrow), - ), - }), - ), - ); - const httpSnapshot = yield* snapshotLoader.load( - prepared, - threadId, - supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : undefined, - ); - if (Option.isSome(httpSnapshot)) { - yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value }); - current = yield* SubscriptionRef.get(state); - } - } - - const sequence = yield* SubscriptionRef.get(lastSequence); - const canResume = Option.isSome(current.data); - if (!supportsCompletionMarker && canResume) { - yield* SubscriptionRef.update(state, (value) => ({ - ...value, - status: value.status === "deleted" ? value.status : ("live" as const), - error: Option.none(), - })); - } - - return { - threadId, - ...(canResume ? { afterSequence: sequence } : {}), - ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}), - // The WS fallback snapshot (sent when afterSequence is missing or - // the gap is too large) should be windowed the same as the HTTP - // path; without this a resume failure re-downloads the full thread. - ...(supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : {}), - }; - }), - { - onExpectedFailure: setStreamError, - retryExpectedFailureAfter: "250 millis", - resubscribe: foregroundResubscriptions, - }, - ).pipe(Stream.runForEach(applyItem)), - ); + yield* subscribe( + ORCHESTRATION_V2_WS_METHODS.subscribeThread, + { threadId }, + { + onExpectedFailure: setStreamError, + retryExpectedFailureAfter: "250 millis", + }, + ).pipe(Stream.runForEach(applyItem), Effect.forkScoped); // Expose loadOlderTurns to UI actions through the request registry. // Requests funnel through a sliding queue drained serially, so mashing @@ -730,6 +615,5 @@ export * from "./threadSnapshotHttp.ts"; export * from "./composerPathSearch.ts"; export * from "./threadCommands.ts"; export * from "./threadDetail.ts"; -export * from "./threadReducer.ts"; export * from "./threadShell.ts"; export * from "./threadState.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 6f413c9734..abbd120486 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1097,6 +1097,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, @@ -1667,6 +1669,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 }), @@ -1767,6 +1770,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; @@ -1791,11 +1795,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 = @@ -1803,6 +1816,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, @@ -1810,7 +1826,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 da9c7a71ba..cb5c112f0b 100644 --- a/packages/contracts/src/project.ts +++ b/packages/contracts/src/project.ts @@ -73,6 +73,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)), }), @@ -89,10 +90,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, // An empty query is a bounded browse: the index returns frecency-ordered diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index fad91453ab..16d2ff50af 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -19,6 +19,11 @@ import { FilesystemBrowseError, } from "./filesystem.ts"; import { AssetAccessError, AssetCreateUrlInput, AssetCreateUrlResult } from "./assets.ts"; +import { + PersistChatAttachmentsError, + PersistChatAttachmentsInput, + PersistChatAttachmentsResult, +} from "./chatAttachment.ts"; import { OrchestrationGetFullThreadDiffError, OrchestrationGetFullThreadDiffInput, @@ -190,6 +195,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 @@ -201,6 +207,7 @@ export const WS_METHODS = { projectsSearchContents: "projects.searchContents", projectsSearchEntries: "projects.searchEntries", projectsWriteFile: "projects.writeFile", + projectsMutate: "projects.mutate", // Shell methods shellOpenInEditor: "shell.openInEditor", @@ -208,6 +215,7 @@ export const WS_METHODS = { // Filesystem methods filesystemBrowse: "filesystem.browse", assetsCreateUrl: "assets.createUrl", + assetsPersistChatAttachments: "assets.persistChatAttachments", // VCS methods vcsPull: "vcs.pull", @@ -639,6 +647,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]), @@ -656,6 +670,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, @@ -1099,9 +1119,11 @@ export const WsRpcGroup = RpcGroup.make( WsProjectsSearchContentsRpc, 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; }