Complete orchestration V2 frontend cutover
- Migrate web and mobile state, commands, and persistence to V2 projections - Render conversations from authoritative visible turn items - Harden runtime policy, launch handling, attachments, and cache invalidation
This commit is contained in:
1 parent
353acd9a27
commit
323ad3614f
111 files changed
+5816
-8099
No files matched your search
@@ -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.
|
||||
|
||||
@@ -3,6 +3,10 @@ import {
|
||||
ConnectionRegistrationStore,
|
||||
ConnectionTargetStore,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
decodeOrDiscardOrchestrationCache,
|
||||
registerConnectionInCatalog,
|
||||
removeConnectionFromCatalog,
|
||||
removeCatalogValue,
|
||||
@@ -14,12 +18,7 @@ import {
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
OrchestrationShellSnapshot,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -29,31 +28,16 @@ import * as SecureStore from "expo-secure-store";
|
||||
|
||||
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
|
||||
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
|
||||
const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
thread: OrchestrationThread,
|
||||
});
|
||||
|
||||
const LegacyStoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
environmentId: EnvironmentId,
|
||||
snapshotReceivedAt: Schema.String,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
|
||||
const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot);
|
||||
const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot);
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot);
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
@@ -289,44 +273,50 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-shell", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
}
|
||||
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
|
||||
if (!legacyFile.exists) {
|
||||
return Option.none();
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
}
|
||||
const legacyRaw = yield* Effect.tryPromise({
|
||||
try: () => legacyFile.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyParsed = yield* Effect.try({
|
||||
try: () => JSON.parse(legacyRaw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const legacyStored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
|
||||
return legacyStored.environmentId === environmentId
|
||||
? Option.some(legacyStored.snapshot)
|
||||
: Option.none();
|
||||
}),
|
||||
|
||||
return Option.none();
|
||||
}).pipe((decode) =>
|
||||
decodeOrDiscardOrchestrationCache(
|
||||
decode,
|
||||
shellSnapshotFile(environmentId, "load-shell").pipe(
|
||||
Effect.flatMap((file) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (file.exists) file.delete();
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.void),
|
||||
),
|
||||
),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "save-shell");
|
||||
const stored = {
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
|
||||
const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("save-shell", cause)),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
@@ -351,21 +341,36 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(
|
||||
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
|
||||
const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-thread", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
}),
|
||||
}).pipe((decode) =>
|
||||
decodeOrDiscardOrchestrationCache(
|
||||
decode,
|
||||
threadSnapshotFile(environmentId, threadId, "load-thread").pipe(
|
||||
Effect.flatMap((file) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (file.exists) file.delete();
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.void),
|
||||
),
|
||||
),
|
||||
),
|
||||
saveThread: (environmentId, thread) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.thread.id, "save-thread");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
Schema.encodeUnknownResult(StoredThreadSnapshot)({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
encodeStoredThreadSnapshot({
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
threadId: thread.thread.id,
|
||||
thread,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { buildArchivedThreadGroups } from "./archivedThreadList";
|
||||
import { makeRawThreadShell } from "../../test-fixtures";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
@@ -22,40 +24,30 @@ function makeProject(
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThreadShell> &
|
||||
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: "2026-06-02T00:00:00.000Z",
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
input: Pick<OrchestrationV2ThreadShell, "id" | "projectId" | "title"> & {
|
||||
readonly branch?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
},
|
||||
): OrchestrationV2ThreadShell {
|
||||
const archivedAt = input.archivedAt === undefined ? "2026-06-02T00:00:00.000Z" : input.archivedAt;
|
||||
return makeRawThreadShell({
|
||||
...input,
|
||||
};
|
||||
archivedAt: archivedAt === null ? null : DateTime.makeUnsafe(archivedAt),
|
||||
});
|
||||
}
|
||||
|
||||
function makeSnapshot(
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
|
||||
targetEnvironmentId = environmentId,
|
||||
): ArchivedSnapshotEntry {
|
||||
return {
|
||||
environmentId: targetEnvironmentId,
|
||||
snapshot: {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 1,
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -60,14 +60,16 @@ interface HomeScreenProps {
|
||||
/* ─── Status indicator colors ────────────────────────────────────────── */
|
||||
|
||||
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
|
||||
switch (thread.session?.status) {
|
||||
switch (thread.runtime?.status) {
|
||||
case "running":
|
||||
case "waiting":
|
||||
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
|
||||
case "ready":
|
||||
case "completed":
|
||||
return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
|
||||
case "queued":
|
||||
case "starting":
|
||||
return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
|
||||
case "error":
|
||||
case "failed":
|
||||
return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
|
||||
default:
|
||||
return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
|
||||
@@ -161,7 +163,7 @@ function deriveEmptyState(props: {
|
||||
|
||||
return {
|
||||
title: "No threads yet",
|
||||
detail: "Create a task to start a new coding session in one of your connected projects.",
|
||||
detail: "Create a task to start a new coding runtime in one of your connected projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
@@ -544,7 +546,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
) : !hasResults ? (
|
||||
<EmptyState
|
||||
title="No threads yet"
|
||||
detail="Create a task to start a new coding session."
|
||||
detail="Create a task to start a new coding runtime."
|
||||
/>
|
||||
) : (
|
||||
projectGroups.map((group) => {
|
||||
|
||||
@@ -6,6 +6,7 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildHomeThreadGroups } from "./homeThreadList";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -25,23 +26,21 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildGroups(
|
||||
|
||||
@@ -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<OrchestrationCheckpointSummary> &
|
||||
Pick<OrchestrationCheckpointSummary, "turnId" | "checkpointTurnCount" | "completedAt">,
|
||||
): OrchestrationCheckpointSummary {
|
||||
input: Partial<ThreadCheckpointSummary> &
|
||||
Pick<ThreadCheckpointSummary, "runId" | "checkpointTurnCount" | "completedAt">,
|
||||
): ThreadCheckpointSummary {
|
||||
return {
|
||||
checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any,
|
||||
status: "ready",
|
||||
@@ -52,12 +48,12 @@ describe("buildReviewSectionItems", () => {
|
||||
it("keeps one chip per checkpoint and appends git sources", () => {
|
||||
const checkpoints = [
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-1"),
|
||||
runId: RunId.make("run-1"),
|
||||
checkpointTurnCount: 1,
|
||||
completedAt: "2026-04-01T00:00:00.000Z",
|
||||
}),
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-2"),
|
||||
runId: RunId.make("run-2"),
|
||||
checkpointTurnCount: 2,
|
||||
completedAt: "2026-04-02T00:00:00.000Z",
|
||||
}),
|
||||
|
||||
@@ -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<OrchestrationCheckpointSummary>(
|
||||
const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
|
||||
compareCheckpointTurnCountDescending,
|
||||
);
|
||||
|
||||
@@ -510,14 +511,14 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
|
||||
}
|
||||
|
||||
export function getReviewSectionIdForCheckpoint(
|
||||
checkpoint: Pick<OrchestrationCheckpointSummary, "checkpointTurnCount">,
|
||||
checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
|
||||
): string {
|
||||
return `turn:${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
export function getReadyReviewCheckpoints(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
): ReadonlyArray<OrchestrationCheckpointSummary> {
|
||||
checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
|
||||
): ReadonlyArray<ThreadCheckpointSummary> {
|
||||
return pipe(
|
||||
checkpoints,
|
||||
Arr.filter((checkpoint) => checkpoint.status === "ready"),
|
||||
@@ -526,7 +527,7 @@ export function getReadyReviewCheckpoints(
|
||||
}
|
||||
|
||||
export function buildReviewSectionItems(input: {
|
||||
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
|
||||
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
|
||||
|
||||
@@ -1,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<string, OrchestrationCheckpointSummary>,
|
||||
) as Record<string, ThreadCheckpointSummary>,
|
||||
[readyCheckpoints],
|
||||
);
|
||||
const reviewSections = useMemo(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import type { ProviderApprovalDecision, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -6,14 +6,16 @@ import type { PendingApproval } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingApprovalCardProps {
|
||||
readonly approval: PendingApproval;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly onRespond: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
const canRespond = props.approval.responseCapability === "live";
|
||||
const disabled = !canRespond || props.respondingApprovalId === props.approval.requestId;
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
@@ -27,17 +29,23 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
{props.approval.detail}
|
||||
</Text>
|
||||
) : null}
|
||||
{!canRespond ? (
|
||||
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
|
||||
The provider process for this request is no longer available. Interrupt or restart the run
|
||||
to continue.
|
||||
</Text>
|
||||
) : null}
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-blue-500 px-3.5 py-3"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "accept")}
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Allow once</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-neutral-200 px-3.5 py-3 dark:bg-neutral-800"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
|
||||
@@ -46,7 +54,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-rose-100 px-3.5 py-3 dark:bg-rose-500/18"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApprovalRequestId } from "@t3tools/contracts";
|
||||
import type { RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
@@ -9,14 +9,10 @@ export interface PendingUserInputCardProps {
|
||||
readonly pendingUserInput: PendingUserInput;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly onSelectOption: (requestId: RuntimeRequestId, questionId: string, label: string) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -24,6 +20,7 @@ export interface PendingUserInputCardProps {
|
||||
}
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
const canRespond = props.pendingUserInput.responseCapability === "live";
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
@@ -32,6 +29,12 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
Fill in the pending answers
|
||||
</Text>
|
||||
{!canRespond ? (
|
||||
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
|
||||
The provider process for this request is no longer available. Interrupt or restart the run
|
||||
to continue.
|
||||
</Text>
|
||||
) : null}
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
@@ -49,6 +52,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
disabled={!canRespond}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
@@ -78,6 +82,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
editable={canRespond}
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
@@ -94,7 +99,9 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
|
||||
)}
|
||||
disabled={
|
||||
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
!canRespond ||
|
||||
props.answers === null ||
|
||||
props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
}
|
||||
onPress={() => void props.onSubmit()}
|
||||
>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
@@ -80,7 +83,7 @@ export interface ThreadComposerProps {
|
||||
readonly connectionState: RemoteClientConnectionState;
|
||||
readonly connectionError: string | null;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly queueCount: number;
|
||||
readonly activeThreadBusy: boolean;
|
||||
@@ -239,9 +242,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
setIsFocused(false);
|
||||
onExpandedChange?.(false);
|
||||
}, [onExpandedChange]);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
const showStopAction = threadRuntimeIsActive(props.selectedThread.runtime);
|
||||
|
||||
const sendLabel =
|
||||
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
RuntimeRequestId,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -46,7 +46,7 @@ import { ThreadFeed } from "./ThreadFeed";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
|
||||
export interface ThreadDetailScreenProps {
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly screenTone: StatusTone;
|
||||
readonly connectionError: string | null;
|
||||
@@ -54,11 +54,11 @@ export interface ThreadDetailScreenProps {
|
||||
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly activePendingApproval: PendingApproval | null;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
@@ -82,16 +82,16 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -377,7 +377,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
latestRun={props.selectedThread.latestRun}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { useRouter } from "expo-router";
|
||||
@@ -71,7 +71,7 @@ import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/l
|
||||
import {
|
||||
deriveThreadFeedPresentation,
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
type ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import { ThreadWorkLog } from "./thread-work-log";
|
||||
@@ -98,7 +98,7 @@ export interface ThreadFeedProps {
|
||||
readonly feed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly latestRun: ThreadFeedLatestRun | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
@@ -658,11 +658,11 @@ function renderFeedEntry(
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
readonly unsettledTurnId: RunId | null;
|
||||
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleWorkGroup: (groupId: string) => void;
|
||||
readonly onToggleWorkRow: (rowId: string) => void;
|
||||
readonly onToggleTurnFold: (turnId: TurnId) => void;
|
||||
readonly onToggleTurnFold: (runId: RunId) => void;
|
||||
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
||||
readonly onMarkdownLinkPress: (href: string) => void;
|
||||
readonly iconSubtleColor: string | import("react-native").ColorValue;
|
||||
@@ -676,12 +676,12 @@ function renderFeedEntry(
|
||||
const entry = info.item;
|
||||
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
if (entry.type === "run-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: entry.expanded }}
|
||||
onPress={() => props.onToggleTurnFold(entry.turnId)}
|
||||
onPress={() => props.onToggleTurnFold(entry.runId)}
|
||||
hitSlop={4}
|
||||
className="mb-3 min-h-11 flex-row items-center gap-2 border-b border-neutral-200/80 px-2 dark:border-white/[0.08]"
|
||||
>
|
||||
@@ -708,7 +708,7 @@ function renderFeedEntry(
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
message.turnId === props.unsettledTurnId;
|
||||
message.runId === props.unsettledTurnId;
|
||||
const showAssistantMeta =
|
||||
message.role === "assistant" &&
|
||||
props.terminalAssistantMessageIds.has(message.id) &&
|
||||
@@ -1110,14 +1110,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const previousLatestTurnRef = useRef(props.latestRun);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly expandedTurnIds: ReadonlySet<TurnId>;
|
||||
readonly expandedTurnIds: ReadonlySet<RunId>;
|
||||
}>({
|
||||
copiedRowId: null,
|
||||
expandedWorkGroups: {},
|
||||
@@ -1191,8 +1191,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
],
|
||||
);
|
||||
const presentedFeed = useMemo(
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestTurn, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestTurn],
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestRun, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestRun],
|
||||
);
|
||||
const anchoredEndSpace = useMemo(
|
||||
() =>
|
||||
@@ -1205,29 +1205,29 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[presentedFeed, props.anchorMessageId, topContentInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
const terminalIdsByTurn = new Map<RunId, string>();
|
||||
for (const entry of props.feed) {
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
|
||||
terminalIdsByTurn.set(entry.message.turnId, entry.message.id);
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
|
||||
terminalIdsByTurn.set(entry.message.runId, entry.message.id);
|
||||
}
|
||||
}
|
||||
return new Set(terminalIdsByTurn.values());
|
||||
}, [props.feed]);
|
||||
const unsettledTurnId =
|
||||
props.latestTurn &&
|
||||
(props.latestTurn.completedAt === null || props.latestTurn.state === "running")
|
||||
? props.latestTurn.turnId
|
||||
props.latestRun &&
|
||||
(props.latestRun.completedAt === null || props.latestRun.status === "running")
|
||||
? props.latestRun.runId
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
if (!props.latestTurn || !previous) {
|
||||
previousLatestTurnRef.current = props.latestRun;
|
||||
if (!props.latestRun || !previous) {
|
||||
return;
|
||||
}
|
||||
if (props.latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && props.latestTurn.state === "interrupted") {
|
||||
const interruptedTurnId = props.latestTurn.turnId;
|
||||
if (props.latestRun.runId === previous.runId) {
|
||||
if (previous.status === "running" && props.latestRun.status === "interrupted") {
|
||||
const interruptedTurnId = props.latestRun.runId;
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
|
||||
@@ -1236,14 +1236,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
return;
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
if (!current.expandedTurnIds.has(previous.turnId)) {
|
||||
if (!current.expandedTurnIds.has(previous.runId)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
next.delete(previous.turnId);
|
||||
next.delete(previous.runId);
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
}, [props.latestTurn]);
|
||||
}, [props.latestRun]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1296,7 +1296,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const onToggleTurnFold = useCallback((turnId: TurnId) => {
|
||||
const onToggleTurnFold = useCallback((runId: RunId) => {
|
||||
setFoldToggleSettling(true);
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
@@ -1306,10 +1306,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
next.add(runId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, type ProjectScript } from "@t3tools/contracts";
|
||||
@@ -152,20 +153,15 @@ export function ThreadRouteScreen() {
|
||||
void router.push("/connections");
|
||||
}, [router]);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
(selectedThread.session?.status !== "running" &&
|
||||
selectedThread.session?.status !== "starting")
|
||||
) {
|
||||
const runtime = selectedThread?.runtime;
|
||||
if (!selectedThread || !runtime || !threadRuntimeIsActive(runtime)) {
|
||||
return;
|
||||
}
|
||||
return interruptThreadTurn({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
...(selectedThread.session.activeTurnId
|
||||
? { turnId: selectedThread.session.activeTurnId }
|
||||
: {}),
|
||||
...(runtime.activeRunId ? { runId: runtime.activeRunId } : {}),
|
||||
},
|
||||
});
|
||||
}, [interruptThreadTurn, selectedThread]);
|
||||
@@ -191,7 +187,7 @@ export function ThreadRouteScreen() {
|
||||
terminalDebugLog("terminal-menu:open-new", {
|
||||
hasThread: Boolean(selectedThread),
|
||||
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
|
||||
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
||||
});
|
||||
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
@@ -199,7 +195,7 @@ export function ThreadRouteScreen() {
|
||||
}
|
||||
|
||||
const nextId = nextOpenTerminalId({
|
||||
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
||||
});
|
||||
void router.push(buildThreadTerminalNavigation(selectedThread, nextId));
|
||||
}, [router, selectedThread, selectedThreadProject?.workspaceRoot, terminalMenuSessions]);
|
||||
@@ -222,9 +218,9 @@ export function ThreadRouteScreen() {
|
||||
}
|
||||
|
||||
const targetTerminalId = resolveProjectScriptTerminalId({
|
||||
existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
existingTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
||||
hasRunningTerminal: terminalMenuSessions.some(
|
||||
(session) => session.status === "running" || session.status === "starting",
|
||||
(runtime) => runtime.status === "running" || runtime.status === "starting",
|
||||
),
|
||||
});
|
||||
const preferredWorktreePath = resolvePreferredThreadWorktreePath({
|
||||
|
||||
@@ -7,29 +7,29 @@ export function threadSortValue(thread: EnvironmentThreadShell): number {
|
||||
}
|
||||
|
||||
export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
|
||||
const status = thread.session?.status;
|
||||
if (status === "running") {
|
||||
const status = thread.runtime?.status;
|
||||
if (status === "running" || status === "waiting") {
|
||||
return {
|
||||
label: "Running",
|
||||
pillClassName: "bg-orange-500/12 dark:bg-orange-500/16",
|
||||
textClassName: "text-orange-700 dark:text-orange-300",
|
||||
};
|
||||
}
|
||||
if (status === "ready") {
|
||||
if (status === "completed") {
|
||||
return {
|
||||
label: "Ready",
|
||||
pillClassName: "bg-emerald-500/12 dark:bg-emerald-500/16",
|
||||
textClassName: "text-emerald-700 dark:text-emerald-300",
|
||||
};
|
||||
}
|
||||
if (status === "starting") {
|
||||
if (status === "queued" || status === "starting") {
|
||||
return {
|
||||
label: "Starting",
|
||||
pillClassName: "bg-sky-500/12 dark:bg-sky-500/16",
|
||||
textClassName: "text-sky-700 dark:text-sky-300",
|
||||
};
|
||||
}
|
||||
if (status === "error") {
|
||||
if (status === "failed") {
|
||||
return {
|
||||
label: "Error",
|
||||
pillClassName: "bg-rose-500/12 dark:bg-rose-500/16",
|
||||
|
||||
@@ -70,6 +70,7 @@ export function useCreateProjectThread() {
|
||||
environmentId: input.project.environmentId,
|
||||
input: {
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
creationSource: "mobile",
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
|
||||
@@ -4,6 +4,7 @@ import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools
|
||||
|
||||
import { groupProjectsByRepository } from "./repositoryGroups";
|
||||
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { makeThreadShellFixture } from "../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -23,22 +24,20 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title" | "modelSelection">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("groupProjectsByRepository", () => {
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -1,409 +1,111 @@
|
||||
import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell";
|
||||
import { MessageId, RunId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
|
||||
): OrchestrationThreadActivity {
|
||||
const runId = RunId.make("run-1");
|
||||
|
||||
function message(role: "user" | "assistant", text: string, createdAt: string, id: string) {
|
||||
return {
|
||||
tone: "info",
|
||||
payload: {},
|
||||
turnId: null,
|
||||
...input,
|
||||
};
|
||||
id: MessageId.make(id),
|
||||
role,
|
||||
text,
|
||||
attachments: [],
|
||||
runId: role === "assistant" ? runId : null,
|
||||
streaming: false,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
} as const;
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThread> & Pick<OrchestrationThread, "id" | "projectId" | "title">,
|
||||
): OrchestrationThread {
|
||||
function commandEntry(overrides: Partial<ThreadWorkEntry> = {}): ThreadWorkEntry {
|
||||
const structuredPayload = {
|
||||
type: "command_execution",
|
||||
input: "vp check",
|
||||
output: "ok",
|
||||
} as ThreadWorkEntry["structuredPayload"];
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...input,
|
||||
id: "item-1",
|
||||
createdAt: "2026-06-20T00:00:02.000Z",
|
||||
runId,
|
||||
label: "Ran command",
|
||||
command: "vp check",
|
||||
detail: "ok",
|
||||
tone: "tool",
|
||||
itemType: "command_execution",
|
||||
toolLifecycleStatus: "completed",
|
||||
structuredPayload,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadFeed", () => {
|
||||
it("keeps historic work entries attributed to their turns", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Runtime warning thread",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("activity-old"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-old"),
|
||||
payload: {
|
||||
message: "Old warning",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("activity-latest"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:03.000Z",
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
payload: {
|
||||
message: "Latest warning",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-old",
|
||||
activities: [{ id: "activity-old", turnId: "turn-old" }],
|
||||
},
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-latest",
|
||||
activities: [{ id: "activity-latest", turnId: "turn-latest" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("collapses matching tool lifecycle rows like desktop", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Collapsed tools",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-updated"),
|
||||
kind: "tool.updated",
|
||||
tone: "tool",
|
||||
summary: "Run tests",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run tests completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
type: "activity-group",
|
||||
});
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities).toEqual([
|
||||
{
|
||||
id: "tool-completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: "turn-1",
|
||||
summary: "Run tests",
|
||||
detail: "bun run test",
|
||||
fullDetail: "/bin/zsh -lc 'bun run test'",
|
||||
copyText: "Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status: "success",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps MCP inputs available to expanded mobile work rows", () => {
|
||||
const turnId = TurnId.make("turn-mcp");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-mcp"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Expandable MCP call",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("mcp-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Call repository tool",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Call repository tool",
|
||||
itemType: "mcp_tool_call",
|
||||
detail: "repository.search",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
server: "repository",
|
||||
tool: "search",
|
||||
arguments: { query: "work log" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities[0]?.icon).toBe("wrench");
|
||||
expect(group.activities[0]?.fullDetail).toContain('"query": "work log"');
|
||||
expect(group.activities[0]?.fullDetail).toContain("repository.search");
|
||||
});
|
||||
|
||||
it("folds settled turn work while leaving the terminal answer visible", () => {
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-3"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Folded work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:18.000Z",
|
||||
assistantMessageId: MessageId.make("assistant-final"),
|
||||
},
|
||||
it("orders V2 messages and work entries while retaining structured tool data", () => {
|
||||
const thread = makeThreadFixture({
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "I am checking.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
updatedAt: "2026-04-01T00:00:03.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-final"),
|
||||
role: "assistant",
|
||||
text: "Done.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:18.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Read files",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Read files",
|
||||
itemType: "file_read",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"),
|
||||
message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"),
|
||||
],
|
||||
workEntries: [commandEntry()],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
type: "turn-fold",
|
||||
label: "Worked for 17s",
|
||||
expanded: false,
|
||||
});
|
||||
expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
|
||||
const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
|
||||
expect(activity?.runId).toBe(runId);
|
||||
expect(activity?.fullDetail).toContain('"input": "vp check"');
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set([turnId]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"turn-fold:turn-1",
|
||||
"assistant-commentary",
|
||||
"tool-completed",
|
||||
"assistant-final",
|
||||
it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
|
||||
const thread = makeThreadFixture({
|
||||
messages: [
|
||||
message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"),
|
||||
message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"),
|
||||
],
|
||||
workEntries: [commandEntry()],
|
||||
});
|
||||
const feed = buildThreadFeed(thread);
|
||||
const latestRun = {
|
||||
runId,
|
||||
status: "completed" as const,
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: "2026-06-20T00:00:03.000Z",
|
||||
};
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
|
||||
expect(collapsed.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
|
||||
expect(expanded.map((entry) => entry.type)).toEqual([
|
||||
"message",
|
||||
"run-fold",
|
||||
"activity-group",
|
||||
"message",
|
||||
]);
|
||||
});
|
||||
|
||||
it("measures a steer-superseded turn from its user boundary through trailing work", () => {
|
||||
const firstTurnId = TurnId.make("turn-1");
|
||||
const secondTurnId = TurnId.make("turn-2");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-steered"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Steered work",
|
||||
latestTurn: {
|
||||
turnId: secondTurnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:14.000Z",
|
||||
startedAt: "2026-04-01T00:00:14.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: MessageId.make("assistant-next"),
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("user-1"),
|
||||
role: "user",
|
||||
text: "Do it once more.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "Kicking off call 1.",
|
||||
turnId: firstTurnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:09.000Z",
|
||||
updatedAt: "2026-04-01T00:00:09.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("user-2"),
|
||||
role: "user",
|
||||
text: "Actually do 15.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:14.000Z",
|
||||
updatedAt: "2026-04-01T00:00:14.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-next"),
|
||||
role: "assistant",
|
||||
text: "One down - adjusting.",
|
||||
turnId: secondTurnId,
|
||||
streaming: true,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:17.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("work-1"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Ran command",
|
||||
createdAt: "2026-04-01T00:00:12.000Z",
|
||||
turnId: firstTurnId,
|
||||
payload: {
|
||||
title: "Ran command",
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
it("keeps an active run expanded and marks failed tools as failures", () => {
|
||||
const thread = makeThreadFixture({
|
||||
messages: [message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user")],
|
||||
workEntries: [commandEntry({ tone: "error", toolLifecycleStatus: "failed" })],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
label: "Worked for 12s",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an active turn expanded and classifies error-shaped tool output", () => {
|
||||
const turnId = TurnId.make("turn-running");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-4"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Running work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
const presented = deriveThreadFeedPresentation(
|
||||
feed,
|
||||
{
|
||||
runId,
|
||||
status: "running",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-failed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run command",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Run command",
|
||||
itemType: "command_execution",
|
||||
detail: "zsh: command not found: nope",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
new Set(),
|
||||
);
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
activities: [{ status: "failure" }],
|
||||
});
|
||||
expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
|
||||
expect(presented.find((entry) => entry.type === "activity-group")?.activities[0]?.status).toBe(
|
||||
"failure",
|
||||
);
|
||||
});
|
||||
});
|
||||
+212
-1079
File diff suppressed because it is too large.
Load diff
@@ -1,4 +1,5 @@
|
||||
import type { EnvironmentId, OrchestrationThread, ThreadId } from "@t3tools/contracts";
|
||||
import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
@@ -18,7 +19,7 @@ const COMPOSER_PATH_SEARCH_LIMIT = 20;
|
||||
const VCS_REF_LIST_LIMIT = 100;
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: OrchestrationThread | null;
|
||||
readonly data: EnvironmentThread | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly isDeleted: boolean;
|
||||
|
||||
@@ -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<EnvironmentThreadState, "data"> & { readonly data: Option.Option<EnvironmentThread> } {
|
||||
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)),
|
||||
};
|
||||
}
|
||||
@@ -1,15 +1,13 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
import { scopedRequestKey } from "../lib/scopedEntities";
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
@@ -65,18 +63,16 @@ export function useSelectedThreadRequests() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
|
||||
null,
|
||||
);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
|
||||
|
||||
const activePendingApprovals = useMemo(
|
||||
() => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
|
||||
() => selectedThread?.pendingApprovals ?? [],
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => (selectedThread ? derivePendingUserInputs(selectedThread.activities) : []),
|
||||
() => selectedThread?.pendingUserInputs ?? [],
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
@@ -91,7 +87,7 @@ export function useSelectedThreadRequests() {
|
||||
: null;
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, label: string) => {
|
||||
(requestId: RuntimeRequestId, questionId: string, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
@@ -103,7 +99,7 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
|
||||
const onChangeUserInputCustomAnswer = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
|
||||
(requestId: RuntimeRequestId, questionId: string, customAnswer: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
@@ -115,10 +111,16 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
activePendingApprovals.find((approval) => approval.requestId === requestId)
|
||||
?.responseCapability !== "live"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRespondingApprovalId(requestId);
|
||||
const result = await respondToApproval({
|
||||
@@ -132,11 +134,16 @@ export function useSelectedThreadRequests() {
|
||||
setRespondingApprovalId((current) => (current === requestId ? null : current));
|
||||
return result;
|
||||
},
|
||||
[respondToApproval, selectedThreadShell],
|
||||
[activePendingApprovals, respondToApproval, selectedThreadShell],
|
||||
);
|
||||
|
||||
const onSubmitUserInput = useCallback(async () => {
|
||||
if (!selectedThreadShell || !activePendingUserInput || !activePendingUserInputAnswers) {
|
||||
if (
|
||||
!selectedThreadShell ||
|
||||
!activePendingUserInput ||
|
||||
activePendingUserInput.responseCapability !== "live" ||
|
||||
!activePendingUserInputAnswers
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import {
|
||||
@@ -105,13 +106,13 @@ export function useThreadComposerState() {
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread?.session) {
|
||||
if (!selectedThread?.runtime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
orchestrationStatus: selectedThread.session.status,
|
||||
activeTurnId: selectedThread.session.activeTurnId ?? undefined,
|
||||
orchestrationStatus: selectedThread.runtime.status,
|
||||
activeRunId: selectedThread.runtime.activeRunId ?? undefined,
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
@@ -122,15 +123,13 @@ export function useThreadComposerState() {
|
||||
}
|
||||
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThread.latestRun,
|
||||
selectedThreadSessionActivity,
|
||||
null,
|
||||
);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
|
||||
const activeThreadBusy =
|
||||
!!selectedThread &&
|
||||
(selectedThread.session?.status === "running" || selectedThread.session?.status === "starting");
|
||||
const activeThreadBusy = !!selectedThread && threadRuntimeIsActive(selectedThread.runtime);
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import { CommandId, type MessageId } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
@@ -181,6 +184,7 @@ export function useThreadOutboxDrain(): void {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: queuedMessage.commandId,
|
||||
creationSource: "mobile",
|
||||
threadId: queuedMessage.threadId,
|
||||
message: {
|
||||
messageId: queuedMessage.messageId,
|
||||
@@ -225,7 +229,7 @@ export function useThreadOutboxDrain(): void {
|
||||
threadExists: thread !== undefined,
|
||||
shellStatus: shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty",
|
||||
environmentConnected: environment?.connectionState === "connected",
|
||||
threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting",
|
||||
threadBusy: threadRuntimeIsActive(thread?.runtime),
|
||||
});
|
||||
if (deliveryAction === "wait") {
|
||||
continue;
|
||||
|
||||
@@ -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> = {},
|
||||
): OrchestrationV2ThreadShell {
|
||||
const id = input.id ?? ThreadId.make("thread-test");
|
||||
const providerInstanceId = input.providerInstanceId ?? ProviderInstanceId.make("codex");
|
||||
const now = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
return {
|
||||
id,
|
||||
projectId: ProjectId.make("project-test"),
|
||||
title: "Thread",
|
||||
providerInstanceId,
|
||||
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: id, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
latestRunId: null,
|
||||
activeRunId: null,
|
||||
status: "idle",
|
||||
pendingRuntimeRequest: null,
|
||||
latestVisibleMessage: null,
|
||||
latestUserMessageAt: null,
|
||||
hasActionableProposedPlan: false,
|
||||
itemCount: 0,
|
||||
visibleItemCount: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
export function makeThreadShellFixture(
|
||||
overrides: Partial<EnvironmentThreadShell> = {},
|
||||
): EnvironmentThreadShell {
|
||||
const environmentId = overrides.environmentId ?? EnvironmentId.make("environment-test");
|
||||
const raw = makeRawThreadShell({
|
||||
id: overrides.id,
|
||||
projectId: overrides.projectId,
|
||||
title: overrides.title,
|
||||
providerInstanceId: overrides.providerInstanceId,
|
||||
modelSelection: overrides.modelSelection,
|
||||
runtimeMode: overrides.runtimeMode,
|
||||
interactionMode: overrides.interactionMode,
|
||||
branch: overrides.branch,
|
||||
worktreePath: overrides.worktreePath,
|
||||
});
|
||||
return { ...presentThreadShell(environmentId, raw), ...overrides };
|
||||
}
|
||||
|
||||
export function makeThreadFixture(overrides: Partial<EnvironmentThread> = {}): 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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Server
|
||||
|
||||
Node.js WebSocket server for the T3 Code app.
|
||||
@@ -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();
|
||||
|
||||
@@ -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(".")) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<RunId, number>;
|
||||
@@ -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<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
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<ProjectionStoreV2, never, SqlClient.SqlClient> =
|
||||
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:
|
||||
|
||||
@@ -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");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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>()(
|
||||
"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<RuntimePolicyV2> = 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<RuntimePolicyV2, never, RuntimePolicyV2> {
|
||||
|
||||
@@ -80,6 +80,20 @@ const makeLayer = (options?: { readonly failCreate?: boolean; readonly failSetup
|
||||
(
|
||||
command: Parameters<ThreadManagement.ThreadManagementService["Service"]["dispatch"]>[0],
|
||||
): Effect.Effect<OrchestratorV2DispatchResult, OrchestratorDispatchError> => {
|
||||
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<GitWorkflow.GitWorkflowService["Service"]["createWorktree"]>[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<GitWorkflow.GitWorkflowService["Service"]["fetchRemote"]>[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* () {
|
||||
|
||||
@@ -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<ChatAttachment>;
|
||||
}
|
||||
|
||||
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<ThreadLaunchError
|
||||
"provision-worktree",
|
||||
"run-setup-script",
|
||||
"create-thread",
|
||||
"update-thread",
|
||||
"dispatch-message",
|
||||
"compensate-worktree",
|
||||
]),
|
||||
@@ -185,11 +196,18 @@ export const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
const stored = yield* loadWorkflow(input);
|
||||
if (input.reuseExistingThread === true && input.threadId === undefined) {
|
||||
return yield* mapError(
|
||||
input,
|
||||
"update-thread",
|
||||
)("Reusing an existing thread requires a thread id.");
|
||||
}
|
||||
const threadId =
|
||||
stored === null
|
||||
? yield* ids.allocate
|
||||
? (input.threadId ??
|
||||
(yield* ids.allocate
|
||||
.thread({ projectId: input.projectId })
|
||||
.pipe(Effect.mapError(mapError(input, "persist-workflow")))
|
||||
.pipe(Effect.mapError(mapError(input, "persist-workflow")))))
|
||||
: ThreadId.make(stored.thread_id);
|
||||
if (stored?.status === "completed") {
|
||||
return {
|
||||
@@ -201,7 +219,38 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
}
|
||||
|
||||
let branch = stored?.branch ?? null;
|
||||
const validateReusableThread = Effect.fn("ThreadLaunchService.validateReusableThread")(
|
||||
function* () {
|
||||
const projection = yield* threads
|
||||
.getThreadProjection(threadId)
|
||||
.pipe(Effect.mapError(mapError(input, "update-thread", threadId)));
|
||||
if (
|
||||
projection.thread.projectId !== input.projectId ||
|
||||
projection.thread.archivedAt !== null ||
|
||||
projection.thread.deletedAt !== null ||
|
||||
projection.messages.length > 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,
|
||||
|
||||
@@ -32,7 +32,7 @@ import { layer as providerTurnControlServiceLayer } from "./ProviderTurnControlS
|
||||
import { layer as providerTurnStartServiceLayer } from "./ProviderTurnStartService.ts";
|
||||
import { layer as runExecutionServiceLayer } from "./RunExecutionService.ts";
|
||||
import { layer as runFinalizationServiceLayer } from "./RunFinalizationService.ts";
|
||||
import { layer as runtimePolicyLayer } from "./RuntimePolicy.ts";
|
||||
import { layerFromProjectRepository as runtimePolicyLayerFromProjectRepository } from "./RuntimePolicy.ts";
|
||||
import { layer as runtimeRequestServiceLayer } from "./RuntimeRequestService.ts";
|
||||
import { layer as threadManagementServiceLayer } from "./ThreadManagementService.ts";
|
||||
import { layer as threadLaunchServiceLayer } from "./ThreadLaunchService.ts";
|
||||
@@ -40,6 +40,13 @@ import { layer as threadLifecycleServiceLayer } from "./ThreadLifecycleService.t
|
||||
import { layer as threadForkServiceLayer } from "./ThreadForkService.ts";
|
||||
import { layer as turnItemPositionStoreLayer } from "./TurnItemPositionStore.ts";
|
||||
|
||||
export const ProjectServiceLayerLive = projectServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)),
|
||||
);
|
||||
const runtimePolicyProvided = runtimePolicyLayerFromProjectRepository.pipe(
|
||||
Layer.provide(ProjectionProjectRepositoryLive),
|
||||
);
|
||||
|
||||
const eventStoreProvided = eventStoreLayer.pipe(
|
||||
Layer.provide(OrchestrationEventInfrastructureLayerLive),
|
||||
);
|
||||
@@ -104,7 +111,7 @@ const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe(
|
||||
projectionStoreLayer,
|
||||
providerSessionManagerProvided,
|
||||
runExecutionServiceProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -123,7 +130,7 @@ const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe(
|
||||
idAllocatorLayer,
|
||||
projectionStoreLayer,
|
||||
providerSessionManagerProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -182,7 +189,7 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
idAllocatorLayer,
|
||||
providerAdapterRegistryProvided,
|
||||
providerEventIngestorProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
providerSessionManagerProvided,
|
||||
providerSwitchServiceProvided,
|
||||
runExecutionServiceProvided,
|
||||
@@ -194,9 +201,6 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
const threadManagementProvided = threadManagementServiceLayer.pipe(
|
||||
Layer.provide(orchestratorProvided),
|
||||
);
|
||||
export const ProjectServiceLayerLive = projectServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)),
|
||||
);
|
||||
export const ProjectSetupScriptRunnerLayerLive = projectSetupScriptRunnerLayer.pipe(
|
||||
Layer.provide(ProjectServiceLayerLive),
|
||||
);
|
||||
|
||||
+198
-27
@@ -1,8 +1,11 @@
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
@@ -19,9 +22,11 @@ import {
|
||||
type AuthAccessStreamEvent,
|
||||
type AuthEnvironmentScope,
|
||||
AuthSessionId,
|
||||
CommandId,
|
||||
type DiscoveredLocalServerList,
|
||||
type GitActionProgressEvent,
|
||||
type GitManagerServiceError,
|
||||
type MessageId,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
@@ -33,16 +38,20 @@ import {
|
||||
type ProjectEntriesFailure,
|
||||
type ProjectFileFailure,
|
||||
type ProjectFileOperation,
|
||||
type ProjectMutation,
|
||||
ProjectListEntriesError,
|
||||
ProjectReadFileError,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectWriteFileError,
|
||||
ProjectMutationError,
|
||||
RelayClientInstallFailedError,
|
||||
type RelayClientInstallProgressEvent,
|
||||
type FilesystemBrowseFailure,
|
||||
FilesystemBrowseError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
AssetWorkspaceContextResolutionError,
|
||||
ChatAttachmentId,
|
||||
PersistChatAttachmentsError,
|
||||
EnvironmentAuthorizationError,
|
||||
ThreadId,
|
||||
type TerminalAttachStreamEvent,
|
||||
@@ -83,6 +92,8 @@ import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import { issueAssetUrl } from "./assets/AssetAccess.ts";
|
||||
import { attachmentRelativePath, createDeterministicAttachmentId } from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
|
||||
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
|
||||
@@ -117,6 +128,73 @@ function unexpectedCompatibilityError(error: never): never {
|
||||
throw new Error(`Unhandled compatibility error: ${String(error)}`);
|
||||
}
|
||||
|
||||
const persistChatAttachments = Effect.fn("ws.assets.persistChatAttachments")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageId: MessageId;
|
||||
readonly attachments: ReadonlyArray<{
|
||||
readonly type: "image";
|
||||
readonly name: string;
|
||||
readonly mimeType: string;
|
||||
readonly sizeBytes: number;
|
||||
readonly dataUrl: string;
|
||||
}>;
|
||||
}) {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
return yield* Effect.forEach(
|
||||
input.attachments.map((attachment, index) => ({ attachment, index })),
|
||||
Effect.fn("ws.assets.persistChatAttachment")(function* ({ attachment, index }) {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (parsed === null || parsed.mimeType !== attachment.mimeType.toLowerCase()) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} has an invalid image payload.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* Effect.fromResult(Encoding.decodeBase64(parsed.base64)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} is not valid base64.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (bytes.byteLength !== attachment.sizeBytes) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} size does not match its payload.`,
|
||||
});
|
||||
}
|
||||
const rawId = createDeterministicAttachmentId(input.threadId, `${input.messageId}:${index}`);
|
||||
if (rawId === null) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: "Could not allocate an attachment identifier.",
|
||||
});
|
||||
}
|
||||
const persisted = {
|
||||
type: "image" as const,
|
||||
id: ChatAttachmentId.make(rawId),
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
};
|
||||
yield* fileSystem
|
||||
.writeFile(path.join(config.attachmentsDir, attachmentRelativePath(persisted)), bytes)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PersistChatAttachmentsError({
|
||||
message: `Could not persist attachment ${attachment.name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return persisted;
|
||||
}),
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
});
|
||||
|
||||
function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): {
|
||||
readonly failure: ProjectEntriesFailure;
|
||||
readonly normalizedCwd?: string;
|
||||
@@ -254,9 +332,11 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.projectsReadFile, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.projectsMutate, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.assetsCreateUrl, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.assetsPersistChatAttachments, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsRefreshStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsPull, AuthOrchestrationOperateScope],
|
||||
@@ -633,20 +713,28 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
},
|
||||
);
|
||||
|
||||
const getOrchestrationV2ArchivedShellSnapshot = threadManagement.getShellSnapshot().pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
schemaVersion: snapshot.schemaVersion,
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
threads: snapshot.archivedThreads,
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed to load archived thread snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const getOrchestrationV2ArchivedShellSnapshot = sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const projects = yield* projectionSnapshotQuery.getShellSnapshot();
|
||||
const threads = yield* threadManagement.getShellSnapshot();
|
||||
return {
|
||||
schemaVersion: threads.schemaVersion,
|
||||
snapshotSequence: yield* applicationEvents.latestApplicationSequence,
|
||||
projects: projects.projects,
|
||||
threads: threads.archivedThreads,
|
||||
} as const;
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed to load archived thread snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const subscribeOrchestrationV2ArchivedShell = Effect.fn(
|
||||
"ws.orchestrationV2.subscribeArchivedShell",
|
||||
@@ -681,6 +769,64 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
return Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live);
|
||||
});
|
||||
|
||||
const mutateProject = Effect.fn("ws.projects.mutate")(function* (mutation: ProjectMutation) {
|
||||
switch (mutation.type) {
|
||||
case "project.create":
|
||||
return yield* projectService.create({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
title: mutation.title,
|
||||
workspaceRoot: mutation.workspaceRoot,
|
||||
...(mutation.createWorkspaceRootIfMissing === undefined
|
||||
? {}
|
||||
: { createWorkspaceRootIfMissing: mutation.createWorkspaceRootIfMissing }),
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
});
|
||||
case "project.update":
|
||||
return yield* projectService.update({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
...(mutation.title === undefined ? {} : { title: mutation.title }),
|
||||
...(mutation.workspaceRoot === undefined
|
||||
? {}
|
||||
: { workspaceRoot: mutation.workspaceRoot }),
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
});
|
||||
case "project.delete": {
|
||||
const snapshot = yield* threadManagement.getShellSnapshot();
|
||||
const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].filter(
|
||||
(thread) => thread.projectId === mutation.projectId,
|
||||
);
|
||||
if (projectThreads.length > 0 && mutation.force !== true) {
|
||||
return yield* new ProjectMutationError({
|
||||
commandId: mutation.commandId,
|
||||
message: `Project ${mutation.projectId} is not empty.`,
|
||||
});
|
||||
}
|
||||
yield* Effect.forEach(
|
||||
projectThreads,
|
||||
(thread) =>
|
||||
threadManagement.dispatch({
|
||||
type: "thread.delete",
|
||||
commandId: CommandId.make(`${mutation.commandId}:delete-thread:${thread.id}`),
|
||||
threadId: thread.id,
|
||||
}),
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
return yield* projectService.delete({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const handlers = ServerWsRpcGroup.of({
|
||||
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
@@ -690,7 +836,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
threadManagement.dispatch(
|
||||
ThreadManagementService.withCreationProvenance(command, {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
creationSource: "creationSource" in command ? command.creationSource : "web",
|
||||
}),
|
||||
),
|
||||
)
|
||||
@@ -781,26 +927,29 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
.enqueueCommand(
|
||||
threadLaunch.launch({
|
||||
commandId: input.commandId,
|
||||
...(input.threadId === undefined ? {} : { threadId: input.threadId }),
|
||||
...(input.reuseExistingThread === undefined
|
||||
? {}
|
||||
: { reuseExistingThread: input.reuseExistingThread }),
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
workspaceStrategy:
|
||||
input.workspaceStrategy.type === "root"
|
||||
? { type: "root" }
|
||||
: {
|
||||
type: "worktree",
|
||||
baseRef: input.workspaceStrategy.baseRef,
|
||||
...(input.workspaceStrategy.branch === undefined
|
||||
? {}
|
||||
: { branch: input.workspaceStrategy.branch }),
|
||||
},
|
||||
workspaceStrategy: input.workspaceStrategy,
|
||||
...(input.initialMessage === undefined
|
||||
? {}
|
||||
: { initialMessage: input.initialMessage }),
|
||||
: {
|
||||
initialMessage: {
|
||||
...(input.initialMessage.messageId === undefined
|
||||
? {}
|
||||
: { messageId: input.initialMessage.messageId }),
|
||||
text: input.initialMessage.text,
|
||||
attachments: input.initialMessage.attachments,
|
||||
},
|
||||
}),
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
creationSource: input.creationSource ?? "web",
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
@@ -1059,6 +1208,22 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsMutate]: (mutation) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsMutate,
|
||||
startup.enqueueCommand(mutateProject(mutation)).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ProjectMutationError"
|
||||
? cause
|
||||
: new ProjectMutationError({
|
||||
commandId: mutation.commandId,
|
||||
message: "Failed to mutate project.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.shellOpenInEditor]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
@@ -1117,6 +1282,12 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
}),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.assetsPersistChatAttachments]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsPersistChatAttachments,
|
||||
persistChatAttachments(input).pipe(Effect.map((attachments) => ({ attachments }))),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.subscribeVcsStatus]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeVcsStatus,
|
||||
|
||||
@@ -126,7 +126,7 @@ export function BranchToolbarBranchSelector({
|
||||
[environmentId, threadId],
|
||||
);
|
||||
const serverThread = useThread(threadRef);
|
||||
const serverSession = serverThread?.session ?? null;
|
||||
const serverSession = serverThread?.runtime ?? null;
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, RunId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { Thread } from "../types";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
@@ -22,7 +23,7 @@ const threadId = ThreadId.make("thread-1");
|
||||
const now = "2026-03-29T00:00:00.000Z";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: threadId,
|
||||
environmentId,
|
||||
projectId,
|
||||
@@ -33,25 +34,23 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const completedTurn = {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed" as const,
|
||||
runId: RunId.make("turn-1"),
|
||||
status: "completed" as const,
|
||||
requestedAt: now,
|
||||
startedAt: "2026-03-29T00:00:01.000Z",
|
||||
completedAt: "2026-03-29T00:00:10.000Z",
|
||||
@@ -59,12 +58,10 @@ const completedTurn = {
|
||||
};
|
||||
|
||||
const readySession = {
|
||||
threadId,
|
||||
status: "ready" as const,
|
||||
status: "completed" as const,
|
||||
providerName: "codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access" as const,
|
||||
activeTurnId: null,
|
||||
activeRunId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
};
|
||||
@@ -326,15 +323,15 @@ describe("shouldWriteThreadErrorToCurrentServerThread", () => {
|
||||
describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
it("does not acknowledge unchanged server state", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: completedTurn, session: readySession }),
|
||||
makeThread({ latestRun: completedTurn, runtime: readySession }),
|
||||
);
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: completedTurn,
|
||||
session: readySession,
|
||||
latestRun: completedTurn,
|
||||
runtime: readySession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
@@ -344,11 +341,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
|
||||
it("acknowledges a settled newer turn", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: completedTurn, session: readySession }),
|
||||
makeThread({ latestRun: completedTurn, runtime: readySession }),
|
||||
);
|
||||
const newerTurn = {
|
||||
...completedTurn,
|
||||
turnId: TurnId.make("turn-2"),
|
||||
runId: RunId.make("turn-2"),
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: "2026-03-29T00:01:30.000Z",
|
||||
@@ -358,8 +355,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: newerTurn,
|
||||
session: { ...readySession, updatedAt: newerTurn.completedAt },
|
||||
latestRun: newerTurn,
|
||||
runtime: { ...readySession, updatedAt: newerTurn.completedAt },
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
@@ -369,12 +366,12 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
|
||||
it("waits for the matching running turn before acknowledging", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: completedTurn, session: readySession }),
|
||||
makeThread({ latestRun: completedTurn, runtime: readySession }),
|
||||
);
|
||||
const runningTurn = {
|
||||
...completedTurn,
|
||||
turnId: TurnId.make("turn-2"),
|
||||
state: "running" as const,
|
||||
runId: RunId.make("turn-2"),
|
||||
status: "running" as const,
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: null,
|
||||
@@ -384,11 +381,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
session: {
|
||||
latestRun: runningTurn,
|
||||
runtime: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
activeTurnId: TurnId.make("turn-other"),
|
||||
activeRunId: RunId.make("turn-other"),
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -399,11 +396,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
session: {
|
||||
latestRun: runningTurn,
|
||||
runtime: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
activeTurnId: runningTurn.turnId,
|
||||
activeRunId: runningTurn.runId,
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -417,8 +414,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
const common = {
|
||||
localDispatch,
|
||||
phase: "ready" as const,
|
||||
latestTurn: null,
|
||||
session: null,
|
||||
latestRun: null,
|
||||
runtime: null,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
|
||||
@@ -7,8 +7,10 @@ import {
|
||||
type ServerProvider,
|
||||
type ScopedThreadRef,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { presentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import { type ChatMessage, type SessionPhase, type Thread } from "../types";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -32,27 +34,46 @@ export function buildLocalDraftThread(
|
||||
draftThread: DraftThreadState,
|
||||
fallbackModelSelection: ModelSelection,
|
||||
): Thread {
|
||||
return {
|
||||
id: threadId,
|
||||
environmentId: draftThread.environmentId,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
modelSelection: fallbackModelSelection,
|
||||
runtimeMode: draftThread.runtimeMode,
|
||||
interactionMode: draftThread.interactionMode,
|
||||
session: null,
|
||||
const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
|
||||
return presentThread(draftThread.environmentId, {
|
||||
thread: {
|
||||
id: threadId,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
providerInstanceId: fallbackModelSelection.instanceId,
|
||||
modelSelection: fallbackModelSelection,
|
||||
runtimeMode: draftThread.runtimeMode,
|
||||
interactionMode: draftThread.interactionMode,
|
||||
branch: draftThread.branch,
|
||||
worktreePath: draftThread.worktreePath,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
runs: [],
|
||||
attempts: [],
|
||||
nodes: [],
|
||||
subagents: [],
|
||||
providerSessions: [],
|
||||
providerThreads: [],
|
||||
providerTurns: [],
|
||||
runtimeRequests: [],
|
||||
messages: [],
|
||||
createdAt: draftThread.createdAt,
|
||||
updatedAt: draftThread.createdAt,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: draftThread.branch,
|
||||
worktreePath: draftThread.worktreePath,
|
||||
plans: [],
|
||||
turnItems: [],
|
||||
checkpointScopes: [],
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
};
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt: timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
export function shouldWriteThreadErrorToCurrentServerThread(input: {
|
||||
@@ -251,7 +272,7 @@ export function buildExpiredTerminalContextToastCopy(
|
||||
|
||||
export function threadHasStarted(thread: Thread | null | undefined): boolean {
|
||||
return Boolean(
|
||||
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
|
||||
thread && (thread.latestRun !== null || thread.messages.length > 0 || thread.runtime !== null),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -275,7 +296,7 @@ export function deriveLockedProvider(input: {
|
||||
if (!threadHasStarted(input.thread)) {
|
||||
return null;
|
||||
}
|
||||
const sessionProvider = input.thread?.session?.providerName ?? null;
|
||||
const sessionProvider = input.thread?.runtime?.providerName ?? null;
|
||||
if (sessionProvider && isProviderDriverKind(sessionProvider)) {
|
||||
return sessionProvider;
|
||||
}
|
||||
@@ -376,37 +397,37 @@ export async function waitForStartedServerThread(
|
||||
export interface LocalDispatchSnapshot {
|
||||
startedAt: string;
|
||||
preparingWorktree: boolean;
|
||||
latestTurnTurnId: TurnId | null;
|
||||
latestTurnRequestedAt: string | null;
|
||||
latestTurnStartedAt: string | null;
|
||||
latestTurnCompletedAt: string | null;
|
||||
sessionStatus: NonNullable<Thread["session"]>["status"] | null;
|
||||
sessionUpdatedAt: string | null;
|
||||
latestRunId: RunId | null;
|
||||
latestRunRequestedAt: string | null;
|
||||
latestRunStartedAt: string | null;
|
||||
latestRunCompletedAt: string | null;
|
||||
runtimeStatus: NonNullable<Thread["runtime"]>["status"] | null;
|
||||
runtimeUpdatedAt: string | null;
|
||||
}
|
||||
|
||||
export function createLocalDispatchSnapshot(
|
||||
activeThread: Thread | undefined,
|
||||
options?: { preparingWorktree?: boolean },
|
||||
): LocalDispatchSnapshot {
|
||||
const latestTurn = activeThread?.latestTurn ?? null;
|
||||
const session = activeThread?.session ?? null;
|
||||
const latestRun = activeThread?.latestRun ?? null;
|
||||
const runtime = activeThread?.runtime ?? null;
|
||||
return {
|
||||
startedAt: new Date().toISOString(),
|
||||
preparingWorktree: Boolean(options?.preparingWorktree),
|
||||
latestTurnTurnId: latestTurn?.turnId ?? null,
|
||||
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
|
||||
latestTurnStartedAt: latestTurn?.startedAt ?? null,
|
||||
latestTurnCompletedAt: latestTurn?.completedAt ?? null,
|
||||
sessionStatus: session?.status ?? null,
|
||||
sessionUpdatedAt: session?.updatedAt ?? null,
|
||||
latestRunId: latestRun?.runId ?? null,
|
||||
latestRunRequestedAt: latestRun?.requestedAt ?? null,
|
||||
latestRunStartedAt: latestRun?.startedAt ?? null,
|
||||
latestRunCompletedAt: latestRun?.completedAt ?? null,
|
||||
runtimeStatus: runtime?.status ?? null,
|
||||
runtimeUpdatedAt: runtime?.updatedAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
localDispatch: LocalDispatchSnapshot | null;
|
||||
phase: SessionPhase;
|
||||
latestTurn: Thread["latestTurn"] | null;
|
||||
session: Thread["session"] | null;
|
||||
latestRun: Thread["latestRun"] | null;
|
||||
runtime: Thread["runtime"] | null;
|
||||
hasPendingApproval: boolean;
|
||||
hasPendingUserInput: boolean;
|
||||
threadError: string | null | undefined;
|
||||
@@ -418,25 +439,25 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
return true;
|
||||
}
|
||||
|
||||
const latestTurn = input.latestTurn ?? null;
|
||||
const session = input.session ?? null;
|
||||
const latestTurnChanged =
|
||||
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
|
||||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
|
||||
const latestRun = input.latestRun ?? null;
|
||||
const runtime = input.runtime ?? null;
|
||||
const latestRunChanged =
|
||||
input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
|
||||
input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
|
||||
input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
|
||||
|
||||
if (input.phase === "running") {
|
||||
if (!latestTurnChanged) {
|
||||
if (!latestRunChanged) {
|
||||
return false;
|
||||
}
|
||||
if (latestTurn?.startedAt === null || latestTurn === null) {
|
||||
if (latestRun?.startedAt === null || latestRun === null) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
session?.activeTurnId !== null &&
|
||||
session?.activeTurnId !== undefined &&
|
||||
latestTurn?.turnId !== session.activeTurnId
|
||||
runtime?.activeRunId !== null &&
|
||||
runtime?.activeRunId !== undefined &&
|
||||
latestRun?.runId !== runtime.activeRunId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -444,8 +465,8 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
}
|
||||
|
||||
return (
|
||||
latestTurnChanged ||
|
||||
input.localDispatch.sessionStatus !== (session?.status ?? null) ||
|
||||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
|
||||
latestRunChanged ||
|
||||
input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
|
||||
input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
type ApprovalRequestId,
|
||||
DEFAULT_MODEL,
|
||||
defaultInstanceIdForDriver,
|
||||
type EnvironmentId,
|
||||
@@ -13,14 +12,15 @@ import {
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ScopedThreadRef,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type RunId,
|
||||
type RuntimeRequestId,
|
||||
type KeybindingCommand,
|
||||
OrchestrationThreadActivity,
|
||||
ProviderInteractionMode,
|
||||
ProviderDriverKind,
|
||||
RuntimeMode,
|
||||
TerminalOpenInput,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
connectionStatusText,
|
||||
type EnvironmentConnectionPresentation,
|
||||
@@ -75,13 +75,14 @@ import {
|
||||
derivePendingUserInputs,
|
||||
derivePhase,
|
||||
deriveTimelineEntries,
|
||||
deriveTimelineEntriesFromVisibleTurnItems,
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
findSidebarProposedPlan,
|
||||
findLatestProposedPlan,
|
||||
deriveWorkLogEntries,
|
||||
hasActionableProposedPlan,
|
||||
isLatestTurnSettled,
|
||||
isLatestRunSettled,
|
||||
} from "../session-logic";
|
||||
import { type LegendListRef } from "@legendapp/list/react";
|
||||
import {
|
||||
@@ -197,6 +198,7 @@ import {
|
||||
useThread,
|
||||
useThreadProposedPlans,
|
||||
useThreadRefs,
|
||||
useThreadVisibleTurnItems,
|
||||
} from "../state/entities";
|
||||
import { environmentShell } from "../state/shell";
|
||||
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
|
||||
@@ -250,7 +252,7 @@ import { useAssetUrls } from "../assets/assetUrls";
|
||||
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_WORK_ENTRIES: ThreadWorkEntry[] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
|
||||
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
|
||||
@@ -359,10 +361,10 @@ type PersistentTerminalLaunchContext = Pick<TerminalLaunchContext, "cwd" | "work
|
||||
|
||||
function useLocalDispatchState(input: {
|
||||
activeThread: Thread | undefined;
|
||||
activeLatestTurn: Thread["latestTurn"] | null;
|
||||
activeLatestRun: Thread["latestRun"] | null;
|
||||
phase: SessionPhase;
|
||||
activePendingApproval: ApprovalRequestId | null;
|
||||
activePendingUserInput: ApprovalRequestId | null;
|
||||
activePendingApproval: RuntimeRequestId | null;
|
||||
activePendingUserInput: RuntimeRequestId | null;
|
||||
threadError: string | null | undefined;
|
||||
}) {
|
||||
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
|
||||
@@ -376,17 +378,17 @@ function useLocalDispatchState(input: {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: input.phase,
|
||||
latestTurn: input.activeLatestTurn,
|
||||
session: input.activeThread?.session ?? null,
|
||||
latestRun: input.activeLatestRun,
|
||||
runtime: input.activeThread?.runtime ?? null,
|
||||
hasPendingApproval: input.activePendingApproval !== null,
|
||||
hasPendingUserInput: input.activePendingUserInput !== null,
|
||||
threadError: input.threadError,
|
||||
}),
|
||||
[
|
||||
input.activeLatestTurn,
|
||||
input.activeLatestRun,
|
||||
input.activePendingApproval,
|
||||
input.activePendingUserInput,
|
||||
input.activeThread?.session,
|
||||
input.activeThread?.runtime,
|
||||
input.phase,
|
||||
input.threadError,
|
||||
localDispatch,
|
||||
@@ -1034,6 +1036,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const composerDraftTarget: ScopedThreadRef | DraftId =
|
||||
routeKind === "server" ? routeThreadRef : props.draftId;
|
||||
const serverThread = useThread(routeKind === "server" ? routeThreadRef : null);
|
||||
const serverVisibleTurnItems = useThreadVisibleTurnItems(
|
||||
routeKind === "server" ? routeThreadRef : null,
|
||||
);
|
||||
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
|
||||
const activeThreadLastVisitedAt = useUiStateStore((store) =>
|
||||
routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined,
|
||||
@@ -1111,9 +1116,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const [maximizedRightPanelThreadKey, setMaximizedRightPanelThreadKey] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<RuntimeRequestId[]>([]);
|
||||
const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
|
||||
ApprovalRequestId[]
|
||||
RuntimeRequestId[]
|
||||
>([]);
|
||||
const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState<
|
||||
Record<string, Record<string, PendingUserInputDraftAnswer>>
|
||||
@@ -1237,7 +1242,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const isServerThread = routeKind === "server" && serverThread !== null;
|
||||
const activeThread = isServerThread ? serverThread : localDraftThread;
|
||||
const threadError = isServerThread
|
||||
? (localServerError ?? serverThread?.session?.lastError ?? null)
|
||||
? (localServerError ?? serverThread?.runtime?.lastError ?? null)
|
||||
: localDraftError;
|
||||
const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode =
|
||||
@@ -1334,14 +1339,14 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const existingThreadKeys = new Set<string>([...serverThreadKeys, ...draftThreadKeys]);
|
||||
return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));
|
||||
}, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);
|
||||
const activeLatestTurn = activeThread?.latestTurn ?? null;
|
||||
const activeLatestRun = activeThread?.latestRun ?? null;
|
||||
const sourcePlanThreadRef = useMemo(() => {
|
||||
const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId;
|
||||
const sourceThreadId = activeLatestRun?.sourcePlanRef?.threadId;
|
||||
if (!activeThread || !sourceThreadId || sourceThreadId === activeThread.id) {
|
||||
return null;
|
||||
}
|
||||
return scopeThreadRef(activeThread.environmentId, sourceThreadId);
|
||||
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread]);
|
||||
}, [activeLatestRun?.sourcePlanRef?.threadId, activeThread]);
|
||||
const sourceThreadProposedPlans = useThreadProposedPlans(sourcePlanThreadRef);
|
||||
const threadPlanCatalog = useMemo<ThreadPlanCatalogEntry[]>(() => {
|
||||
if (!activeThread) {
|
||||
@@ -1373,7 +1378,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
: nextThreadIds;
|
||||
});
|
||||
}, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]);
|
||||
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
|
||||
const latestRunSettled = isLatestRunSettled(activeLatestRun, activeThread?.runtime ?? null);
|
||||
const activeProjectRef = activeThread
|
||||
? scopeProjectRef(activeThread.environmentId, activeThread.projectId)
|
||||
: null;
|
||||
@@ -1721,16 +1726,19 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
selectedProviderByThreadId ?? threadProvider ?? ProviderDriverKind.make("codex"),
|
||||
);
|
||||
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
|
||||
const phase = derivePhase(activeThread?.runtime ?? null);
|
||||
const threadWorkEntries = activeThread?.workEntries ?? EMPTY_WORK_ENTRIES;
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(threadWorkEntries),
|
||||
[threadWorkEntries],
|
||||
);
|
||||
const pendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(threadActivities),
|
||||
[threadActivities],
|
||||
() => derivePendingApprovals(activeThread?.pendingApprovals ?? []),
|
||||
[activeThread?.pendingApprovals],
|
||||
);
|
||||
const pendingUserInputs = useMemo(
|
||||
() => derivePendingUserInputs(threadActivities),
|
||||
[threadActivities],
|
||||
() => derivePendingUserInputs(activeThread?.pendingUserInputs ?? []),
|
||||
[activeThread?.pendingUserInputs],
|
||||
);
|
||||
const activePendingUserInput = pendingUserInputs[0] ?? null;
|
||||
const activePendingDraftAnswers = useMemo(
|
||||
@@ -1763,36 +1771,37 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
[activePendingDraftAnswers, activePendingUserInput],
|
||||
);
|
||||
const activePendingIsResponding = activePendingUserInput
|
||||
? respondingUserInputRequestIds.includes(activePendingUserInput.requestId)
|
||||
? activePendingUserInput.responseCapability !== "live" ||
|
||||
respondingUserInputRequestIds.includes(activePendingUserInput.requestId)
|
||||
: false;
|
||||
const activeProposedPlan = useMemo(() => {
|
||||
if (!latestTurnSettled) {
|
||||
if (!latestRunSettled) {
|
||||
return null;
|
||||
}
|
||||
return findLatestProposedPlan(
|
||||
activeThread?.proposedPlans ?? [],
|
||||
activeLatestTurn?.turnId ?? null,
|
||||
activeLatestRun?.runId ?? null,
|
||||
);
|
||||
}, [activeLatestTurn?.turnId, activeThread?.proposedPlans, latestTurnSettled]);
|
||||
}, [activeLatestRun?.runId, activeThread?.proposedPlans, latestRunSettled]);
|
||||
const sidebarProposedPlan = useMemo(
|
||||
() =>
|
||||
findSidebarProposedPlan({
|
||||
threads: threadPlanCatalog,
|
||||
latestTurn: activeLatestTurn,
|
||||
latestTurnSettled,
|
||||
latestRun: activeLatestRun,
|
||||
latestRunSettled,
|
||||
threadId: activeThread?.id ?? null,
|
||||
}),
|
||||
[activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog],
|
||||
[activeLatestRun, activeThread?.id, latestRunSettled, threadPlanCatalog],
|
||||
);
|
||||
const activePlan = useMemo(
|
||||
() => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
||||
[activeLatestTurn?.turnId, threadActivities],
|
||||
() => deriveActivePlanState(activeThread?.todoPlans ?? [], activeLatestRun?.runId ?? undefined),
|
||||
[activeLatestRun?.runId, activeThread?.todoPlans],
|
||||
);
|
||||
const planSidebarLabel = sidebarProposedPlan || interactionMode === "plan" ? "Plan" : "Tasks";
|
||||
const showPlanFollowUpPrompt =
|
||||
pendingUserInputs.length === 0 &&
|
||||
interactionMode === "plan" &&
|
||||
latestTurnSettled &&
|
||||
latestRunSettled &&
|
||||
hasActionableProposedPlan(activeProposedPlan);
|
||||
const activePendingApproval = pendingApprovals[0] ?? null;
|
||||
const {
|
||||
@@ -1803,7 +1812,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
isSendBusy,
|
||||
} = useLocalDispatchState({
|
||||
activeThread,
|
||||
activeLatestTurn,
|
||||
activeLatestRun,
|
||||
phase,
|
||||
activePendingApproval: activePendingApproval?.requestId ?? null,
|
||||
activePendingUserInput: activePendingUserInput?.requestId ?? null,
|
||||
@@ -1811,8 +1820,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
|
||||
const activeWorkStartedAt = deriveActiveWorkStartedAt(
|
||||
activeLatestTurn,
|
||||
activeThread?.session ?? null,
|
||||
activeLatestRun,
|
||||
activeThread?.runtime ?? null,
|
||||
localDispatchStartedAt,
|
||||
);
|
||||
useEffect(() => {
|
||||
@@ -1876,7 +1885,17 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
});
|
||||
}, []);
|
||||
const serverMessages = activeThread?.messages;
|
||||
const serverAttachmentIds = useMemo(() => {
|
||||
const committedServerAttachmentIds = useMemo(() => {
|
||||
const attachmentIds = new Set<string>();
|
||||
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<string>();
|
||||
for (const message of serverMessages ?? []) {
|
||||
for (const attachment of message.attachments ?? []) {
|
||||
@@ -1885,6 +1904,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
return [...attachmentIds];
|
||||
}, [serverMessages]);
|
||||
const serverAttachmentIds = isServerThread ? committedServerAttachmentIds : draftAttachmentIds;
|
||||
const serverAttachmentResources = useMemo(
|
||||
() =>
|
||||
serverAttachmentIds.map((attachmentId) => ({
|
||||
@@ -2056,12 +2076,22 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
return [...serverMessagesWithPreviewHandoff, ...pendingMessages];
|
||||
}, [attachmentPreviewHandoffByMessageId, displayServerMessages, optimisticUserMessages]);
|
||||
const timelineEntries = useMemo(
|
||||
const serverTimelineEntries = useMemo(
|
||||
() =>
|
||||
deriveTimelineEntriesFromVisibleTurnItems({
|
||||
visibleTurnItems: serverVisibleTurnItems,
|
||||
optimisticMessages: optimisticUserMessages,
|
||||
attachmentUrlById: serverAttachmentUrlById,
|
||||
}),
|
||||
[optimisticUserMessages, serverVisibleTurnItems, serverAttachmentUrlById],
|
||||
);
|
||||
const draftTimelineEntries = useMemo(
|
||||
() =>
|
||||
deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),
|
||||
[activeThread?.proposedPlans, timelineMessages, workLogEntries],
|
||||
);
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
const timelineEntries = isServerThread ? serverTimelineEntries : draftTimelineEntries;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const turnDiffSummaryByAssistantMessageId = useMemo(() => {
|
||||
const byMessageId = new Map<MessageId, TurnDiffSummary>();
|
||||
@@ -2092,7 +2122,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
continue;
|
||||
}
|
||||
const turnCount =
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[summary.runId];
|
||||
if (typeof turnCount !== "number") {
|
||||
break;
|
||||
}
|
||||
@@ -2102,7 +2132,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
|
||||
return byUserMessageId;
|
||||
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
|
||||
}, [inferredCheckpointTurnCountByRunId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
|
||||
|
||||
const gitCwd = activeProject
|
||||
? projectScriptCwd({
|
||||
@@ -2129,7 +2159,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
?.instanceId ?? null;
|
||||
const activeProviderInstanceId =
|
||||
selectedProviderInstanceId ??
|
||||
activeThread?.session?.providerInstanceId ??
|
||||
activeThread?.runtime?.providerInstanceId ??
|
||||
activeThread?.modelSelection.instanceId ??
|
||||
activeProject?.defaultModelSelection?.instanceId ??
|
||||
null;
|
||||
@@ -2188,9 +2218,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}, [activeThreadRef, diffOpen, isServerThread, onDiffPanelOpen]);
|
||||
|
||||
const envLocked = Boolean(
|
||||
activeThread &&
|
||||
(activeThread.messages.length > 0 ||
|
||||
(activeThread.session !== null && activeThread.session.status !== "stopped")),
|
||||
activeThread && (activeThread.messages.length > 0 || activeThread.runtime !== null),
|
||||
);
|
||||
|
||||
// Handle environment change for draft threads. When the user picks a
|
||||
@@ -2746,8 +2774,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}, [handleInteractionModeChange, interactionMode]);
|
||||
const dismissPlanSidebarForCurrentTurn = useCallback(() => {
|
||||
planSidebarDismissedForTurnRef.current =
|
||||
activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
|
||||
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
|
||||
activePlan?.runId ?? sidebarProposedPlan?.runId ?? "__dismissed__";
|
||||
}, [activePlan?.runId, sidebarProposedPlan?.runId]);
|
||||
const togglePlanSidebar = useCallback(() => {
|
||||
if (!activeThreadRef) return;
|
||||
if (planSidebarOpen) {
|
||||
@@ -3191,20 +3219,20 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
if (!autoOpenPlanSidebar) return;
|
||||
if (!activePlan) return;
|
||||
if (planSidebarOpen) return;
|
||||
const latestTurnId = activeLatestTurn?.turnId ?? null;
|
||||
if (latestTurnId && activePlan.turnId !== latestTurnId) return;
|
||||
const turnKey = activePlan.turnId ?? sidebarProposedPlan?.turnId ?? "__dismissed__";
|
||||
const latestRunId = activeLatestRun?.runId ?? null;
|
||||
if (latestRunId && activePlan.runId !== latestRunId) return;
|
||||
const turnKey = activePlan.runId ?? sidebarProposedPlan?.runId ?? "__dismissed__";
|
||||
if (planSidebarDismissedForTurnRef.current === turnKey) return;
|
||||
if (activeThreadRef) {
|
||||
useRightPanelStore.getState().open(activeThreadRef, "plan");
|
||||
}
|
||||
}, [
|
||||
activePlan,
|
||||
activeLatestTurn?.turnId,
|
||||
activeLatestRun?.runId,
|
||||
activeThreadRef,
|
||||
autoOpenPlanSidebar,
|
||||
planSidebarOpen,
|
||||
sidebarProposedPlan?.turnId,
|
||||
sidebarProposedPlan?.runId,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -3745,7 +3773,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
role: "user",
|
||||
text: outgoingMessageText,
|
||||
...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: messageCreatedAt,
|
||||
updatedAt: messageCreatedAt,
|
||||
streaming: false,
|
||||
@@ -3956,8 +3984,13 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
};
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!activeThreadId) return;
|
||||
if (
|
||||
pendingApprovals.find((approval) => approval.requestId === requestId)
|
||||
?.responseCapability !== "live"
|
||||
)
|
||||
return;
|
||||
|
||||
setRespondingRequestIds((existing) =>
|
||||
existing.includes(requestId) ? existing : [...existing, requestId],
|
||||
@@ -3980,12 +4013,17 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));
|
||||
return result;
|
||||
},
|
||||
[activeThreadId, environmentId, respondToThreadApproval, setThreadError],
|
||||
[activeThreadId, environmentId, pendingApprovals, respondToThreadApproval, setThreadError],
|
||||
);
|
||||
|
||||
const onRespondToUserInput = useCallback(
|
||||
async (requestId: ApprovalRequestId, answers: Record<string, unknown>) => {
|
||||
async (requestId: RuntimeRequestId, answers: Record<string, unknown>) => {
|
||||
if (!activeThreadId) return;
|
||||
if (
|
||||
pendingUserInputs.find((input) => input.requestId === requestId)?.responseCapability !==
|
||||
"live"
|
||||
)
|
||||
return;
|
||||
|
||||
setRespondingUserInputRequestIds((existing) =>
|
||||
existing.includes(requestId) ? existing : [...existing, requestId],
|
||||
@@ -4008,7 +4046,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));
|
||||
return result;
|
||||
},
|
||||
[activeThreadId, environmentId, respondToThreadUserInput, setThreadError],
|
||||
[activeThreadId, environmentId, pendingUserInputs, respondToThreadUserInput, setThreadError],
|
||||
);
|
||||
|
||||
const setActivePendingUserInputQuestionIndex = useCallback(
|
||||
@@ -4092,7 +4130,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
);
|
||||
|
||||
const onAdvanceActivePendingUserInput = useCallback(() => {
|
||||
if (!activePendingUserInput || !activePendingProgress) {
|
||||
if (
|
||||
!activePendingUserInput ||
|
||||
activePendingUserInput.responseCapability !== "live" ||
|
||||
!activePendingProgress
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (activePendingProgress.isLastQuestion) {
|
||||
@@ -4179,7 +4221,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
id: messageIdForSend,
|
||||
role: "user",
|
||||
text: outgoingMessageText,
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: messageCreatedAt,
|
||||
updatedAt: messageCreatedAt,
|
||||
streaming: false,
|
||||
@@ -4445,9 +4487,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
}
|
||||
const reason = getStartedThreadModelChangeBlockReason({
|
||||
providers: providerStatuses,
|
||||
hasStartedSession: activeThread.session !== null,
|
||||
hasStartedSession: activeThread.runtime !== null,
|
||||
currentModelSelection: activeThread.modelSelection,
|
||||
currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null,
|
||||
currentProviderInstanceId: activeThread.runtime?.providerInstanceId ?? null,
|
||||
nextModelSelection: { instanceId, model },
|
||||
});
|
||||
return reason ? `${reason.description} Start a new thread to use this model.` : null;
|
||||
@@ -4471,9 +4513,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
if (lockedProvider !== null && activeThread.session?.providerInstanceId) {
|
||||
if (lockedProvider !== null && activeThread.runtime?.providerInstanceId) {
|
||||
const currentEntry = providerStatuses.find(
|
||||
(snapshot) => snapshot.instanceId === activeThread.session?.providerInstanceId,
|
||||
(snapshot) => snapshot.instanceId === activeThread.runtime?.providerInstanceId,
|
||||
);
|
||||
if (
|
||||
currentEntry?.continuation?.groupKey &&
|
||||
@@ -4500,9 +4542,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
};
|
||||
const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({
|
||||
providers: providerStatuses,
|
||||
hasStartedSession: activeThread.session !== null,
|
||||
hasStartedSession: activeThread.runtime !== null,
|
||||
currentModelSelection: activeThread.modelSelection,
|
||||
currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null,
|
||||
currentProviderInstanceId: activeThread.runtime?.providerInstanceId ?? null,
|
||||
nextModelSelection,
|
||||
});
|
||||
if (modelChangeBlockReason) {
|
||||
@@ -4582,9 +4624,9 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
setExpandedImage(preview);
|
||||
}, []);
|
||||
const onOpenTurnDiff = useCallback(
|
||||
(turnId: TurnId, filePath?: string) => {
|
||||
(runId: RunId, filePath?: string) => {
|
||||
if (!isServerThread || !activeThreadRef) return;
|
||||
useDiffPanelStore.getState().selectTurn(activeThreadRef, turnId, filePath);
|
||||
useDiffPanelStore.getState().selectTurn(activeThreadRef, runId, filePath);
|
||||
useRightPanelStore.getState().open(activeThreadRef, "diff");
|
||||
onDiffPanelOpen?.();
|
||||
},
|
||||
@@ -4770,11 +4812,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
<MessagesTimeline
|
||||
key={activeThread.id}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnInProgress={isWorking || !latestRunSettled}
|
||||
activeTurnStartedAt={activeWorkStartedAt}
|
||||
listRef={legendListRef}
|
||||
timelineEntries={timelineEntries}
|
||||
latestTurn={activeLatestTurn}
|
||||
latestRun={activeLatestRun}
|
||||
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
|
||||
activeThreadEnvironmentId={activeThread.environmentId}
|
||||
routeThreadKey={routeThreadKey}
|
||||
@@ -4857,8 +4899,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
respondingRequestIds={respondingRequestIds}
|
||||
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activePlan={activePlan as { turnId?: TurnId } | null}
|
||||
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
|
||||
activePlan={activePlan}
|
||||
sidebarProposedPlan={sidebarProposedPlan}
|
||||
planSidebarLabel={planSidebarLabel}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
@@ -4867,7 +4909,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
providerStatuses={providerStatuses as ServerProvider[]}
|
||||
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
|
||||
activeThreadModelSelection={activeThread?.modelSelection}
|
||||
activeThreadActivities={activeThread?.activities}
|
||||
activeThreadWorkEntries={activeThread?.workEntries}
|
||||
resolvedTheme={resolvedTheme}
|
||||
settings={settings}
|
||||
keybindings={keybindings}
|
||||
@@ -4877,6 +4919,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
composerImagesRef={composerImagesRef}
|
||||
composerTerminalContextsRef={composerTerminalContextsRef}
|
||||
composerElementContextsRef={composerElementContextsRef}
|
||||
shouldAutoScrollRef={isAtEndRef}
|
||||
scheduleStickToBottom={scrollToEnd}
|
||||
onSend={onSend}
|
||||
onInterrupt={onInterrupt}
|
||||
onImplementPlanInNewThread={onImplementPlanInNewThread}
|
||||
|
||||
@@ -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 {
|
||||
buildThreadActionItems,
|
||||
filterCommandPaletteGroups,
|
||||
@@ -11,7 +12,7 @@ const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
@@ -19,20 +20,18 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("buildThreadActionItems", () => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
|
||||
import type { ScopedThreadRef, RunId } from "@t3tools/contracts";
|
||||
import {
|
||||
ArrowRightIcon,
|
||||
CheckIcon,
|
||||
@@ -230,55 +230,55 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
: null,
|
||||
);
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
() =>
|
||||
[...turnDiffSummaries].toSorted((left, right) => {
|
||||
const leftTurnCount =
|
||||
left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0;
|
||||
left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0;
|
||||
const rightTurnCount =
|
||||
right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0;
|
||||
right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0;
|
||||
if (leftTurnCount !== rightTurnCount) {
|
||||
return rightTurnCount - leftTurnCount;
|
||||
}
|
||||
return right.completedAt.localeCompare(left.completedAt);
|
||||
}),
|
||||
[inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
|
||||
[inferredCheckpointTurnCountByRunId, turnDiffSummaries],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!routeThreadRef || diffSelection.kind !== "turn") return;
|
||||
useDiffPanelStore.getState().reconcileTurnSelection(
|
||||
routeThreadRef,
|
||||
orderedTurnDiffSummaries.map((summary) => summary.turnId),
|
||||
orderedTurnDiffSummaries.map((summary) => summary.runId),
|
||||
);
|
||||
}, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
|
||||
|
||||
const selectedTurnId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
|
||||
const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
|
||||
const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch";
|
||||
const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null;
|
||||
const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
|
||||
const selectedFileRevealRequestId =
|
||||
diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
|
||||
const selectedTurn =
|
||||
selectedTurnId === null
|
||||
selectedRunId === null
|
||||
? undefined
|
||||
: (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
|
||||
: (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ??
|
||||
orderedTurnDiffSummaries[0]);
|
||||
const selectedCheckpointTurnCount =
|
||||
selectedTurn &&
|
||||
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
|
||||
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[selectedTurn.runId]);
|
||||
const latestTurn = orderedTurnDiffSummaries[0];
|
||||
const selectedScopeLabel =
|
||||
selectedTurnId === null
|
||||
selectedRunId === null
|
||||
? selectedGitScope === "unstaged"
|
||||
? "Working tree"
|
||||
: "Branch changes"
|
||||
: selectedTurn?.turnId === latestTurn?.turnId
|
||||
: selectedTurn?.runId === latestTurn?.runId
|
||||
? "Latest turn"
|
||||
: `Turn ${selectedCheckpointTurnCount ?? "?"}`;
|
||||
const reviewSectionId = selectedTurn ? `turn:${selectedTurn.turnId}` : selectedGitScope;
|
||||
const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope;
|
||||
const collapseScopeKey = routeThreadRef
|
||||
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
|
||||
: null;
|
||||
@@ -308,12 +308,12 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
|
||||
ignoreWhitespace: diffIgnoreWhitespace,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : null,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null,
|
||||
},
|
||||
{ enabled: isGitRepo && selectedTurn !== undefined },
|
||||
);
|
||||
const primaryBranchDiffPreview = useEnvironmentQuery(
|
||||
selectedTurnId === null && activeThread && activeCwd
|
||||
selectedRunId === null && activeThread && activeCwd
|
||||
? reviewEnvironment.diffPreview({
|
||||
environmentId: activeThread.environmentId,
|
||||
input: {
|
||||
@@ -325,7 +325,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
: null,
|
||||
);
|
||||
const shouldRetryBranchDiffAtEnvironmentCwd =
|
||||
selectedTurnId === null &&
|
||||
selectedRunId === null &&
|
||||
primaryBranchDiffPreview.error?.includes("configured workspace root") === true &&
|
||||
serverConfig?.cwd !== undefined &&
|
||||
serverConfig.cwd !== activeCwd;
|
||||
@@ -348,7 +348,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
(source) => source.kind === (selectedGitScope === "unstaged" ? "working-tree" : "branch-range"),
|
||||
);
|
||||
const localBranchRefs = useEnvironmentQuery(
|
||||
selectedTurnId === null &&
|
||||
selectedRunId === null &&
|
||||
selectedGitScope === "branch" &&
|
||||
activeThread &&
|
||||
branchDiffPreview.data?.cwd
|
||||
@@ -365,7 +365,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
: null,
|
||||
);
|
||||
const remoteBranchRefs = useEnvironmentQuery(
|
||||
selectedTurnId === null &&
|
||||
selectedRunId === null &&
|
||||
selectedGitScope === "branch" &&
|
||||
activeThread &&
|
||||
branchDiffPreview.data?.cwd
|
||||
@@ -408,9 +408,9 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
const renderablePatch = useMemo(
|
||||
() =>
|
||||
getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, {
|
||||
compactPartialHunkOffsets: selectedTurnId === null,
|
||||
compactPartialHunkOffsets: selectedRunId === null,
|
||||
}),
|
||||
[resolvedTheme, selectedPatch, selectedTurnId],
|
||||
[resolvedTheme, selectedPatch, selectedRunId],
|
||||
);
|
||||
const renderableFiles = useMemo(() => {
|
||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||
@@ -486,9 +486,9 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
[collapseScopeKey],
|
||||
);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
const selectTurn = (runId: RunId) => {
|
||||
if (!routeThreadRef) return;
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
|
||||
};
|
||||
const selectGitScope = (scope: "branch" | "unstaged") => {
|
||||
if (!routeThreadRef) return;
|
||||
@@ -513,23 +513,23 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
<DropdownMenuContent align="start" className="w-60">
|
||||
<DropdownMenuItem onClick={() => selectGitScope("unstaged")}>
|
||||
<span>Working tree</span>
|
||||
{selectedTurnId === null && selectedGitScope === "unstaged" && (
|
||||
{selectedRunId === null && selectedGitScope === "unstaged" && (
|
||||
<CheckIcon className="ml-auto" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => selectGitScope("branch")}>
|
||||
<span>Branch changes</span>
|
||||
{selectedTurnId === null && selectedGitScope === "branch" && (
|
||||
{selectedRunId === null && selectedGitScope === "branch" && (
|
||||
<CheckIcon className="ml-auto" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (latestTurn) selectTurn(latestTurn.turnId);
|
||||
if (latestTurn) selectTurn(latestTurn.runId);
|
||||
}}
|
||||
>
|
||||
<span>Latest turn</span>
|
||||
{selectedTurnId !== null && selectedTurn?.turnId === latestTurn?.turnId && (
|
||||
{selectedRunId !== null && selectedTurn?.runId === latestTurn?.runId && (
|
||||
<CheckIcon className="ml-auto" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
@@ -539,18 +539,15 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
{orderedTurnDiffSummaries.map((summary) => {
|
||||
const turnCount =
|
||||
summary.checkpointTurnCount ??
|
||||
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
|
||||
inferredCheckpointTurnCountByRunId[summary.runId] ??
|
||||
"?";
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={summary.turnId}
|
||||
onClick={() => selectTurn(summary.turnId)}
|
||||
>
|
||||
<DropdownMenuItem key={summary.runId} onClick={() => selectTurn(summary.runId)}>
|
||||
<span>Turn {turnCount}</span>
|
||||
<span className="ml-auto text-xs tabular-nums text-muted-foreground">
|
||||
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
|
||||
</span>
|
||||
{summary.turnId === selectedTurn?.turnId && <CheckIcon className="ml-1" />}
|
||||
{summary.runId === selectedTurn?.runId && <CheckIcon className="ml-1" />}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
@@ -558,7 +555,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
</DropdownMenuSub>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{selectedTurnId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
|
||||
{selectedRunId === null && selectedGitScope === "branch" && selectedGitSource?.baseRef && (
|
||||
<div
|
||||
className="flex min-w-0 max-w-full items-center gap-2 overflow-hidden text-xs text-muted-foreground"
|
||||
title={`${selectedGitSource.headRef ?? "HEAD"} → ${selectedGitSource.baseRef}`}
|
||||
@@ -748,7 +745,7 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Turn diffs are unavailable because this project is not a git repository.
|
||||
</div>
|
||||
) : selectedTurnId !== null && orderedTurnDiffSummaries.length === 0 ? (
|
||||
) : selectedRunId !== null && orderedTurnDiffSummaries.length === 0 ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
No completed turns yet.
|
||||
</div>
|
||||
|
||||
@@ -21,19 +21,14 @@ import {
|
||||
sortProjectsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationLatestTurn,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type Thread,
|
||||
} from "../types";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
|
||||
@@ -75,13 +70,13 @@ describe("resolveSidebarStageBadgeLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
function makeLatestTurn(overrides?: {
|
||||
function makeLatestRun(overrides?: {
|
||||
completedAt?: string | null;
|
||||
startedAt?: string | null;
|
||||
}): OrchestrationLatestTurn {
|
||||
}): NonNullable<Thread["latestRun"]> {
|
||||
return {
|
||||
turnId: "turn-1" as never,
|
||||
state: "completed",
|
||||
runId: "turn-1" as never,
|
||||
status: "completed",
|
||||
assistantMessageId: null,
|
||||
requestedAt: "2026-03-09T10:00:00.000Z",
|
||||
startedAt: overrides?.startedAt ?? "2026-03-09T10:00:00.000Z",
|
||||
@@ -97,9 +92,9 @@ describe("hasUnseenCompletion", () => {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "default",
|
||||
latestTurn: makeLatestTurn(),
|
||||
latestRun: makeLatestRun(),
|
||||
lastVisitedAt: "2026-03-09T10:04:00.000Z",
|
||||
session: null,
|
||||
runtime: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -111,9 +106,9 @@ describe("hasUnseenCompletion", () => {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "default",
|
||||
latestTurn: makeLatestTurn(),
|
||||
latestRun: makeLatestRun(),
|
||||
lastVisitedAt: undefined,
|
||||
session: null,
|
||||
runtime: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -570,15 +565,13 @@ describe("resolveThreadStatusPill", () => {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "plan" as const,
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
lastVisitedAt: undefined,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtime: {
|
||||
status: "running" as const,
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
activeTurnId: "turn-1" as never,
|
||||
activeRunId: "turn-1" as never,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
},
|
||||
@@ -621,11 +614,11 @@ describe("resolveThreadStatusPill", () => {
|
||||
thread: {
|
||||
...baseThread,
|
||||
hasActionableProposedPlan: true,
|
||||
latestTurn: makeLatestTurn(),
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
latestRun: makeLatestRun(),
|
||||
runtime: {
|
||||
...baseThread.runtime,
|
||||
status: "completed",
|
||||
activeRunId: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -637,11 +630,11 @@ describe("resolveThreadStatusPill", () => {
|
||||
resolveThreadStatusPill({
|
||||
thread: {
|
||||
...baseThread,
|
||||
latestTurn: makeLatestTurn(),
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
latestRun: makeLatestRun(),
|
||||
runtime: {
|
||||
...baseThread.runtime,
|
||||
status: "completed",
|
||||
activeRunId: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -654,12 +647,12 @@ describe("resolveThreadStatusPill", () => {
|
||||
thread: {
|
||||
...baseThread,
|
||||
interactionMode: "default",
|
||||
latestTurn: makeLatestTurn(),
|
||||
latestRun: makeLatestRun(),
|
||||
lastVisitedAt: "2026-03-09T10:04:00.000Z",
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
runtime: {
|
||||
...baseThread.runtime,
|
||||
status: "completed",
|
||||
activeRunId: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -813,7 +806,7 @@ function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
}
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
@@ -825,20 +818,18 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("getFallbackThreadIdAfterDelete", () => {
|
||||
@@ -922,7 +913,7 @@ describe("sortProjectsForSidebar", () => {
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older project user message",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
@@ -938,7 +929,7 @@ describe("sortProjectsForSidebar", () => {
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer project user message",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
streaming: false,
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from "../lib/threadSort";
|
||||
import type { SidebarThreadSummary, Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
import { isLatestTurnSettled } from "../session-logic";
|
||||
import { isLatestRunSettled } from "../session-logic";
|
||||
import { resolveServerBackedAppStageLabel } from "../branding.logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
@@ -54,8 +54,8 @@ type ThreadStatusInput = Pick<
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingUserInput"
|
||||
| "interactionMode"
|
||||
| "latestTurn"
|
||||
| "session"
|
||||
| "latestRun"
|
||||
| "runtime"
|
||||
> & {
|
||||
lastVisitedAt?: string | undefined;
|
||||
};
|
||||
@@ -153,8 +153,8 @@ export function useThreadJumpHintVisibility(): {
|
||||
}
|
||||
|
||||
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
if (!thread.latestRun?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestRun.completedAt);
|
||||
if (Number.isNaN(completedAt)) return false;
|
||||
if (!thread.lastVisitedAt) return false;
|
||||
|
||||
@@ -380,7 +380,7 @@ export function resolveThreadStatusPill(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "running") {
|
||||
if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
|
||||
return {
|
||||
label: "Working",
|
||||
colorClass: "text-sky-600 dark:text-sky-300/80",
|
||||
@@ -389,7 +389,7 @@ export function resolveThreadStatusPill(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "starting") {
|
||||
if (thread.runtime?.status === "starting" || thread.runtime?.status === "queued") {
|
||||
return {
|
||||
label: "Connecting",
|
||||
colorClass: "text-sky-600 dark:text-sky-300/80",
|
||||
@@ -401,7 +401,7 @@ export function resolveThreadStatusPill(input: {
|
||||
const hasPlanReadyPrompt =
|
||||
!thread.hasPendingUserInput &&
|
||||
thread.interactionMode === "plan" &&
|
||||
isLatestTurnSettled(thread.latestTurn, thread.session) &&
|
||||
isLatestRunSettled(thread.latestRun, thread.runtime) &&
|
||||
thread.hasActionableProposedPlan;
|
||||
if (hasPlanReadyPrompt) {
|
||||
return {
|
||||
|
||||
@@ -445,7 +445,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
[discoveredPorts, navigateToThread, openPreview, threadRef],
|
||||
);
|
||||
const isThreadRunning =
|
||||
thread.session?.status === "running" && thread.session.activeTurnId != null;
|
||||
thread.runtime?.status === "running" && thread.runtime.activeRunId != null;
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread: {
|
||||
...thread,
|
||||
@@ -1771,7 +1771,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
if (clicked === "mark-unread") {
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey);
|
||||
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
|
||||
markThreadUnread(threadKey, thread?.latestRun?.completedAt);
|
||||
}
|
||||
clearSelection();
|
||||
return;
|
||||
@@ -2127,7 +2127,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
}
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
|
||||
markThreadUnread(threadKey, thread.latestRun?.completedAt);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-path") {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TurnId } from "@t3tools/contracts";
|
||||
import { RunId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
@@ -54,7 +54,7 @@ describe("ChangedFilesTree", () => {
|
||||
({ files, visibleLabels, hiddenLabels }) => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesTree
|
||||
turnId={TurnId.make("turn-1")}
|
||||
runId={RunId.make("turn-1")}
|
||||
files={files}
|
||||
allDirectoriesExpanded={false}
|
||||
resolvedTheme="light"
|
||||
@@ -130,7 +130,7 @@ describe("ChangedFilesTree", () => {
|
||||
({ files, visibleLabels }) => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesTree
|
||||
turnId={TurnId.make("turn-1")}
|
||||
runId={RunId.make("turn-1")}
|
||||
files={files}
|
||||
allDirectoriesExpanded
|
||||
resolvedTheme="light"
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type TurnId } from "@t3tools/contracts";
|
||||
import { type RunId } from "@t3tools/contracts";
|
||||
import { memo, useCallback, useMemo, useState } from "react";
|
||||
import { type TurnDiffFileChange } from "../../types";
|
||||
import {
|
||||
@@ -15,15 +15,15 @@ import { Button } from "../ui/button";
|
||||
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
|
||||
|
||||
export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onToggleAllDirectories: () => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
const {
|
||||
turnId,
|
||||
runId,
|
||||
files,
|
||||
allDirectoriesExpanded,
|
||||
resolvedTheme,
|
||||
@@ -60,7 +60,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onOpenTurnDiff(turnId, files[0]?.path)}
|
||||
onClick={() => onOpenTurnDiff(runId, files[0]?.path)}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
@@ -68,8 +68,8 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
</div>
|
||||
<div className="px-2 pb-2">
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
key={`changed-files-tree:${runId}`}
|
||||
runId={runId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
@@ -81,13 +81,13 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
});
|
||||
|
||||
export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
|
||||
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, runId } = props;
|
||||
const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
|
||||
const directoryPathsKey = useMemo(
|
||||
() => collectDirectoryPaths(treeNodes).join("\u0000"),
|
||||
@@ -172,7 +172,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
type="button"
|
||||
className="group flex w-full items-center gap-1.5 rounded-xl py-1 pr-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => onOpenTurnDiff(turnId, node.path)}
|
||||
onClick={() => onOpenTurnDiff(runId, node.path)}
|
||||
>
|
||||
{hasDirectoryNodes || depth > 0 ? (
|
||||
<span aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
ModelSelection,
|
||||
PreviewAnnotationPayload,
|
||||
@@ -10,7 +9,8 @@ import type {
|
||||
ScopedThreadRef,
|
||||
ServerProvider,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
RunId,
|
||||
RuntimeRequestId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ProviderDriverKind,
|
||||
@@ -467,13 +467,13 @@ export interface ChatComposerProps {
|
||||
activePendingIsResponding: boolean;
|
||||
activePendingDraftAnswers: Record<string, PendingUserInputDraftAnswer>;
|
||||
activePendingQuestionIndex: number;
|
||||
respondingRequestIds: ApprovalRequestId[];
|
||||
respondingRequestIds: RuntimeRequestId[];
|
||||
|
||||
// Plan
|
||||
showPlanFollowUpPrompt: boolean;
|
||||
activeProposedPlan: Thread["proposedPlans"][number] | null;
|
||||
activePlan: { turnId?: TurnId } | null;
|
||||
sidebarProposedPlan: { turnId?: TurnId } | null;
|
||||
activePlan: { runId?: RunId | null } | null;
|
||||
sidebarProposedPlan: { runId?: RunId | null } | null;
|
||||
planSidebarLabel: string;
|
||||
planSidebarOpen: boolean;
|
||||
|
||||
@@ -488,7 +488,7 @@ export interface ChatComposerProps {
|
||||
activeThreadModelSelection: ModelSelection | null | undefined;
|
||||
|
||||
// Context window
|
||||
activeThreadActivities: Thread["activities"] | undefined;
|
||||
activeThreadWorkEntries: Thread["workEntries"] | undefined;
|
||||
|
||||
// Misc
|
||||
resolvedTheme: "light" | "dark";
|
||||
@@ -504,12 +504,16 @@ export interface ChatComposerProps {
|
||||
composerElementContextsRef: React.RefObject<ElementContextDraft[]>;
|
||||
composerRef: React.RefObject<ChatComposerHandle | null>;
|
||||
|
||||
// Scroll
|
||||
shouldAutoScrollRef: React.RefObject<boolean>;
|
||||
scheduleStickToBottom: () => void;
|
||||
|
||||
// Callbacks
|
||||
onSend: (e?: { preventDefault: () => void }) => void;
|
||||
onInterrupt: () => void;
|
||||
onImplementPlanInNewThread: () => void;
|
||||
onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
onSelectActivePendingUserInputOption: (questionId: string, optionLabel: string) => void;
|
||||
@@ -578,7 +582,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
providerStatuses,
|
||||
activeProjectDefaultModelSelection,
|
||||
activeThreadModelSelection,
|
||||
activeThreadActivities,
|
||||
activeThreadWorkEntries,
|
||||
resolvedTheme,
|
||||
settings,
|
||||
keybindings,
|
||||
@@ -589,6 +593,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerImagesRef,
|
||||
composerTerminalContextsRef,
|
||||
composerElementContextsRef,
|
||||
shouldAutoScrollRef,
|
||||
scheduleStickToBottom,
|
||||
onSend,
|
||||
onInterrupt,
|
||||
onImplementPlanInNewThread,
|
||||
@@ -666,7 +672,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
|
||||
const threadProvider =
|
||||
activeThread?.session?.providerInstanceId ??
|
||||
activeThread?.runtime?.providerInstanceId ??
|
||||
activeThreadModelSelection?.instanceId ??
|
||||
activeProjectDefaultModelSelection?.instanceId ??
|
||||
null;
|
||||
@@ -682,7 +688,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const lockedContinuationGroupKey = useMemo((): string | null => {
|
||||
if (!lockedProvider || !activeThread) return null;
|
||||
const lockedInstanceId =
|
||||
activeThread.session?.providerInstanceId ?? activeThreadModelSelection?.instanceId;
|
||||
activeThread.runtime?.providerInstanceId ?? activeThreadModelSelection?.instanceId;
|
||||
if (!lockedInstanceId) return null;
|
||||
return (
|
||||
providerInstanceEntries.find((entry) => entry.instanceId === lockedInstanceId)
|
||||
@@ -708,7 +714,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const selectedInstanceId = useMemo<ProviderInstanceId>(() => {
|
||||
const candidates: Array<string | null | undefined> = [
|
||||
composerDraft.activeProvider,
|
||||
activeThread?.session?.providerInstanceId,
|
||||
activeThread?.runtime?.providerInstanceId,
|
||||
activeThreadModelSelection?.instanceId,
|
||||
activeProjectDefaultModelSelection?.instanceId,
|
||||
];
|
||||
@@ -750,7 +756,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
}, [
|
||||
activeProjectDefaultModelSelection?.instanceId,
|
||||
activeThread?.session?.providerInstanceId,
|
||||
activeThread?.runtime?.providerInstanceId,
|
||||
activeThreadModelSelection?.instanceId,
|
||||
composerDraft.activeProvider,
|
||||
explicitSelectedInstanceId,
|
||||
@@ -849,8 +855,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// Context window
|
||||
// ------------------------------------------------------------------
|
||||
const activeContextWindow = useMemo(
|
||||
() => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []),
|
||||
[activeThreadActivities],
|
||||
() => deriveLatestContextWindowSnapshot(activeThreadWorkEntries ?? []),
|
||||
[activeThreadWorkEntries],
|
||||
);
|
||||
const activeThreadProviderDisplayName = useMemo(() => {
|
||||
if (!activeThreadModelSelection) return null;
|
||||
@@ -890,6 +896,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
|
||||
const composerFormRef = useRef<HTMLFormElement>(null);
|
||||
const composerSurfaceRef = useRef<HTMLDivElement>(null);
|
||||
const composerFormHeightRef = useRef(0);
|
||||
const composerSelectLockRef = useRef(false);
|
||||
const composerMenuOpenRef = useRef(false);
|
||||
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
|
||||
@@ -1322,12 +1329,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
};
|
||||
};
|
||||
|
||||
composerFormHeightRef.current = composerForm.getBoundingClientRect().height;
|
||||
const initialCompactness = measureFooterCompactness();
|
||||
setIsComposerPrimaryActionsCompact(initialCompactness.primaryActionsCompact);
|
||||
setIsComposerFooterCompact(initialCompactness.footerCompact);
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
|
||||
const observer = new ResizeObserver(() => {
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const [entry] = entries;
|
||||
if (!entry) return;
|
||||
const nextCompactness = measureFooterCompactness();
|
||||
setIsComposerPrimaryActionsCompact((previous) =>
|
||||
previous === nextCompactness.primaryActionsCompact
|
||||
@@ -1337,13 +1347,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
setIsComposerFooterCompact((previous) =>
|
||||
previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact,
|
||||
);
|
||||
const nextHeight = entry.contentRect.height;
|
||||
const previousHeight = composerFormHeightRef.current;
|
||||
composerFormHeightRef.current = nextHeight;
|
||||
if (previousHeight > 0 && Math.abs(nextHeight - previousHeight) < 0.5) return;
|
||||
if (!shouldAutoScrollRef.current) return;
|
||||
scheduleStickToBottom();
|
||||
});
|
||||
|
||||
observer.observe(composerForm);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [activeThreadId, composerFooterActionLayoutKey, composerFooterHasWideActions]);
|
||||
}, [
|
||||
activeThreadId,
|
||||
composerFooterActionLayoutKey,
|
||||
composerFooterHasWideActions,
|
||||
scheduleStickToBottom,
|
||||
shouldAutoScrollRef,
|
||||
]);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Image persist effect
|
||||
@@ -2126,6 +2148,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
<ComposerPendingApprovalActions
|
||||
requestId={activePendingApproval.requestId}
|
||||
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
|
||||
canRespond={activePendingApproval.responseCapability === "live"}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
/>
|
||||
</div>
|
||||
@@ -2455,6 +2478,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
<ComposerPendingApprovalActions
|
||||
requestId={activePendingApproval.requestId}
|
||||
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
|
||||
canRespond={activePendingApproval.responseCapability === "live"}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { type ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { type RuntimeRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
interface ComposerPendingApprovalActionsProps {
|
||||
requestId: ApprovalRequestId;
|
||||
requestId: RuntimeRequestId;
|
||||
isResponding: boolean;
|
||||
canRespond: boolean;
|
||||
onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
@@ -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
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={isResponding}
|
||||
disabled={isResponding || !canRespond}
|
||||
onClick={() => void onRespondToApproval(requestId, "cancel")}
|
||||
>
|
||||
Cancel turn
|
||||
@@ -29,7 +31,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive-outline"
|
||||
disabled={isResponding}
|
||||
disabled={isResponding || !canRespond}
|
||||
onClick={() => void onRespondToApproval(requestId, "decline")}
|
||||
>
|
||||
Decline
|
||||
@@ -37,7 +39,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={isResponding}
|
||||
disabled={isResponding || !canRespond}
|
||||
onClick={() => void onRespondToApproval(requestId, "acceptForSession")}
|
||||
>
|
||||
Always allow this session
|
||||
@@ -45,7 +47,7 @@ export const ComposerPendingApprovalActions = memo(function ComposerPendingAppro
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
disabled={isResponding}
|
||||
disabled={isResponding || !canRespond}
|
||||
onClick={() => void onRespondToApproval(requestId, "accept")}
|
||||
>
|
||||
Approve once
|
||||
|
||||
@@ -26,6 +26,12 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
|
||||
<span className="text-xs text-muted-foreground">1/{pendingCount}</span>
|
||||
) : null}
|
||||
</div>
|
||||
{approval.responseCapability === "not_resumable" ? (
|
||||
<p className="mt-2 text-xs text-muted-foreground">
|
||||
This request belonged to a provider process that is no longer available. Interrupt or
|
||||
restart the run to continue.
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { type RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { memo, useEffect, useEffectEvent, useRef, useState } from "react";
|
||||
import { type PendingUserInput } from "../../session-logic";
|
||||
import {
|
||||
@@ -10,7 +10,7 @@ import { cn } from "~/lib/utils";
|
||||
|
||||
interface PendingUserInputPanelProps {
|
||||
pendingUserInputs: PendingUserInput[];
|
||||
respondingRequestIds: ApprovalRequestId[];
|
||||
respondingRequestIds: RuntimeRequestId[];
|
||||
answers: Record<string, PendingUserInputDraftAnswer>;
|
||||
questionIndex: number;
|
||||
onToggleOption: (questionId: string, optionLabel: string) => void;
|
||||
@@ -59,6 +59,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
}) {
|
||||
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
|
||||
const activeQuestion = progress.activeQuestion;
|
||||
const canRespond = prompt.responseCapability === "live";
|
||||
const responseDisabled = isResponding || !canRespond;
|
||||
const autoAdvanceTimerRef = useRef<number | null>(null);
|
||||
const onAdvanceRef = useRef(onAdvance);
|
||||
const [optimisticSingleSelect, setOptimisticSingleSelect] = useState<{
|
||||
@@ -120,7 +122,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
// outside editable fields. Multi-select prompts toggle options in place; single-
|
||||
// select prompts keep the existing auto-advance behavior.
|
||||
useEffect(() => {
|
||||
if (!activeQuestion || isResponding) return;
|
||||
if (!activeQuestion || responseDisabled) return;
|
||||
const handler = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
const target = event.target;
|
||||
@@ -144,7 +146,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
};
|
||||
document.addEventListener("keydown", handler);
|
||||
return () => document.removeEventListener("keydown", handler);
|
||||
}, [activeQuestion, isResponding]);
|
||||
}, [activeQuestion, responseDisabled]);
|
||||
|
||||
if (!activeQuestion) {
|
||||
return null;
|
||||
@@ -165,6 +167,12 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
) : null}
|
||||
</div>
|
||||
<p className="text-sm text-foreground/90">{activeQuestion.question}</p>
|
||||
{!canRespond ? (
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
This request belonged to a provider process that is no longer available. Interrupt or
|
||||
restart the run to continue.
|
||||
</p>
|
||||
) : null}
|
||||
{activeQuestion.multiSelect ? (
|
||||
<p className="mt-1 text-xs text-muted-foreground/65">Select one or more options.</p>
|
||||
) : null}
|
||||
@@ -182,8 +190,8 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
isSelected
|
||||
? "border-primary/30 bg-primary/8 text-foreground"
|
||||
: "border-transparent bg-muted/22 text-foreground/85 hover:border-border/45 hover:bg-muted/34",
|
||||
isResponding && "opacity-50 cursor-not-allowed",
|
||||
!isResponding && "cursor-pointer",
|
||||
responseDisabled && "opacity-50 cursor-not-allowed",
|
||||
!responseDisabled && "cursor-pointer",
|
||||
);
|
||||
const content = (
|
||||
<>
|
||||
@@ -211,8 +219,10 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
<button
|
||||
key={`${activeQuestion.id}:${option.label}`}
|
||||
type="button"
|
||||
disabled={isResponding}
|
||||
disabled={responseDisabled}
|
||||
aria-disabled={responseDisabled}
|
||||
onClick={() => {
|
||||
if (responseDisabled) return;
|
||||
handleOptionSelection(activeQuestion.id, option.label);
|
||||
}}
|
||||
className={className}
|
||||
|
||||
@@ -272,7 +272,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,
|
||||
@@ -286,7 +286,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,
|
||||
@@ -300,14 +300,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(),
|
||||
@@ -335,7 +335,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,
|
||||
@@ -349,16 +349,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,
|
||||
},
|
||||
@@ -379,7 +379,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,
|
||||
@@ -398,7 +398,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,
|
||||
@@ -412,7 +412,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,
|
||||
@@ -450,7 +450,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,
|
||||
@@ -464,7 +464,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,
|
||||
@@ -477,7 +477,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,
|
||||
},
|
||||
@@ -490,7 +490,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,
|
||||
@@ -510,7 +510,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");
|
||||
@@ -522,7 +522,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(),
|
||||
@@ -556,7 +556,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,
|
||||
@@ -570,7 +570,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,
|
||||
@@ -583,7 +583,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,
|
||||
},
|
||||
@@ -596,7 +596,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,
|
||||
@@ -610,16 +610,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,
|
||||
},
|
||||
@@ -634,7 +634,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");
|
||||
});
|
||||
|
||||
@@ -648,15 +648,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",
|
||||
},
|
||||
@@ -669,15 +669,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: [
|
||||
@@ -688,7 +761,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,
|
||||
},
|
||||
@@ -701,7 +774,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,
|
||||
@@ -715,16 +788,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",
|
||||
},
|
||||
@@ -755,7 +828,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,
|
||||
@@ -768,15 +841,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,
|
||||
},
|
||||
@@ -805,7 +878,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,
|
||||
@@ -819,14 +892,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(),
|
||||
@@ -852,16 +925,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,
|
||||
},
|
||||
@@ -887,7 +960,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,
|
||||
@@ -896,7 +969,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,
|
||||
@@ -992,7 +1065,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,
|
||||
@@ -1001,7 +1074,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,
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import * as Equal from "effect/Equal";
|
||||
import { formatDuration, type TimelineEntry, 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;
|
||||
|
||||
@@ -30,9 +35,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 =
|
||||
@@ -46,7 +51,7 @@ export type MessagesTimelineRow =
|
||||
kind: "turn-fold";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
label: string;
|
||||
expanded: boolean;
|
||||
}
|
||||
@@ -62,6 +67,12 @@ export type MessagesTimelineRow =
|
||||
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
|
||||
revertTurnCount?: number | undefined;
|
||||
}
|
||||
| {
|
||||
kind: "event";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
projectedItem: OrchestrationV2ProjectedTurnItem;
|
||||
}
|
||||
| {
|
||||
kind: "proposed-plan";
|
||||
id: string;
|
||||
@@ -131,8 +142,8 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
continue;
|
||||
}
|
||||
|
||||
const responseKey = message.turnId
|
||||
? `turn:${message.turnId}`
|
||||
const responseKey = message.runId
|
||||
? `turn:${message.runId}`
|
||||
: `unkeyed:${nullTurnResponseIndex}`;
|
||||
lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
|
||||
}
|
||||
@@ -141,7 +152,7 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
}
|
||||
|
||||
interface TurnFold {
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
anchorEntryId: string;
|
||||
createdAt: string;
|
||||
hiddenEntryIds: ReadonlySet<string>;
|
||||
@@ -155,12 +166,16 @@ interface TurnFold {
|
||||
* 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): TurnId | null {
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,9 +186,21 @@ function deriveUnsettledTurnId(latestTurn: TimelineLatestTurn | null): TurnId |
|
||||
function deriveTurnFolds(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
latestTurn: TimelineLatestTurn | null;
|
||||
unsettledTurnId: TurnId | null;
|
||||
latestRun: TimelineLatestRun | null;
|
||||
unsettledRunId: RunId | null;
|
||||
}): ReadonlyMap<string, TurnFold> {
|
||||
const interruptedRunIds = new Set<RunId>();
|
||||
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<TimelineEntry>;
|
||||
terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
|
||||
@@ -186,7 +213,7 @@ function deriveTurnFolds(input: {
|
||||
*/
|
||||
startBoundary: string | null;
|
||||
}
|
||||
const groupsByTurnId = new Map<TurnId, TurnGroup>();
|
||||
const groupsByRunId = new Map<RunId, TurnGroup>();
|
||||
|
||||
let pendingUserBoundary: string | null = null;
|
||||
for (const entry of input.timelineEntries) {
|
||||
@@ -194,16 +221,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: [],
|
||||
@@ -215,7 +242,7 @@ function deriveTurnFolds(input: {
|
||||
startBoundary: pendingUserBoundary,
|
||||
};
|
||||
pendingUserBoundary = null;
|
||||
groupsByTurnId.set(turnId, group);
|
||||
groupsByRunId.set(runId, group);
|
||||
}
|
||||
group.entries.push(entry);
|
||||
if (entry.kind === "message") {
|
||||
@@ -229,8 +256,8 @@ function deriveTurnFolds(input: {
|
||||
}
|
||||
|
||||
const foldsByAnchorEntryId = new Map<string, TurnFold>();
|
||||
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) {
|
||||
@@ -253,16 +280,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) ??
|
||||
@@ -278,7 +303,7 @@ function deriveTurnFolds(input: {
|
||||
: "Worked";
|
||||
|
||||
foldsByAnchorEntryId.set(firstEntry.id, {
|
||||
turnId,
|
||||
runId,
|
||||
anchorEntryId: firstEntry.id,
|
||||
createdAt: firstEntry.createdAt,
|
||||
hiddenEntryIds,
|
||||
@@ -290,8 +315,8 @@ function deriveTurnFolds(input: {
|
||||
|
||||
export function deriveMessagesTimelineRows(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
latestTurn?: TimelineLatestTurn | null;
|
||||
expandedTurnIds?: ReadonlySet<TurnId>;
|
||||
latestRun?: TimelineLatestRun | null;
|
||||
expandedRunIds?: ReadonlySet<RunId>;
|
||||
isWorking: boolean;
|
||||
activeTurnStartedAt: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
@@ -302,16 +327,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);
|
||||
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<string>();
|
||||
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);
|
||||
}
|
||||
@@ -328,11 +353,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,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -376,10 +401,20 @@ export function deriveMessagesTimelineRows(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (timelineEntry.kind === "event") {
|
||||
nextRows.push({
|
||||
kind: "event",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
projectedItem: timelineEntry.projectedItem,
|
||||
});
|
||||
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;
|
||||
@@ -459,6 +494,9 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
case "proposed-plan":
|
||||
return a.proposedPlan === (b as typeof a).proposedPlan;
|
||||
|
||||
case "event":
|
||||
return a.projectedItem === (b as typeof a).projectedItem;
|
||||
|
||||
case "work":
|
||||
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
|
||||
|
||||
|
||||
@@ -108,7 +108,7 @@ function buildProps() {
|
||||
activeTurnInProgress: false,
|
||||
activeTurnStartedAt: null,
|
||||
listRef: createRef<LegendListRef | null>(),
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
routeThreadKey: "environment-local:thread-1",
|
||||
onOpenTurnDiff: () => {},
|
||||
@@ -142,7 +142,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,
|
||||
@@ -309,6 +309,114 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("Work Log");
|
||||
});
|
||||
|
||||
it("renders V2 interruption lifecycle entries as standalone rows", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "interrupt-request",
|
||||
kind: "event",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
projectedItem: {
|
||||
position: 0,
|
||||
visibility: "local",
|
||||
sourceThreadId: "thread-1",
|
||||
sourceItemId: "interrupt-request",
|
||||
item: {
|
||||
id: "interrupt-request",
|
||||
threadId: "thread-1",
|
||||
runId: "run-1",
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
updatedAt: {},
|
||||
type: "run_interrupt_request",
|
||||
message: "Waiting for the provider to stop.",
|
||||
},
|
||||
} as never,
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
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(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={
|
||||
[
|
||||
{
|
||||
id: item.id,
|
||||
kind: "work",
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
entry: {
|
||||
id: item.id,
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
runId: null,
|
||||
label: "Ran command",
|
||||
command: item.input,
|
||||
tone: "tool",
|
||||
itemType: item.type,
|
||||
toolLifecycleStatus: "completed",
|
||||
structuredPayload: item,
|
||||
projectedItem,
|
||||
},
|
||||
},
|
||||
] as never
|
||||
}
|
||||
/>,
|
||||
);
|
||||
|
||||
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(
|
||||
@@ -324,6 +432,8 @@ describe("MessagesTimeline", () => {
|
||||
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"],
|
||||
},
|
||||
},
|
||||
@@ -359,7 +469,7 @@ describe("MessagesTimeline", () => {
|
||||
"```",
|
||||
"</review_comment>",
|
||||
].join("\n"),
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
updatedAt: "2026-03-17T19:12:28.000Z",
|
||||
streaming: false,
|
||||
@@ -399,7 +509,7 @@ describe("MessagesTimeline", () => {
|
||||
"```",
|
||||
"</review_comment>",
|
||||
].join("\n"),
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
updatedAt: "2026-03-17T19:12:28.000Z",
|
||||
streaming: false,
|
||||
|
||||
@@ -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 { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
@@ -73,7 +74,7 @@ import {
|
||||
resolveAssistantMessageCopyState,
|
||||
type StableMessagesTimelineRowsState,
|
||||
type MessagesTimelineRow,
|
||||
type TimelineLatestTurn,
|
||||
type TimelineLatestRun,
|
||||
} from "./MessagesTimeline.logic";
|
||||
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
@@ -126,8 +127,8 @@ interface TimelineRowSharedState {
|
||||
activeThreadEnvironmentId: EnvironmentId;
|
||||
onRevertUserMessage: (messageId: MessageId) => void;
|
||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onToggleTurnFold: (turnId: TurnId) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
onToggleTurnFold: (runId: RunId) => void;
|
||||
}
|
||||
|
||||
interface TimelineRowActivityState {
|
||||
@@ -152,10 +153,10 @@ interface MessagesTimelineProps {
|
||||
activeTurnStartedAt: string | null;
|
||||
listRef: React.RefObject<LegendListRef | null>;
|
||||
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
|
||||
latestTurn: TimelineLatestTurn | null;
|
||||
latestRun: TimelineLatestRun | null;
|
||||
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
|
||||
routeThreadKey: string;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
revertTurnCountByUserMessageId: Map<MessageId, number>;
|
||||
onRevertUserMessage: (messageId: MessageId) => void;
|
||||
isRevertingCheckpoint: boolean;
|
||||
@@ -181,7 +182,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
activeTurnStartedAt,
|
||||
listRef,
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
latestRun,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
routeThreadKey,
|
||||
onOpenTurnDiff,
|
||||
@@ -199,7 +200,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
contentInsetEndAdjustment,
|
||||
onIsAtEndChange,
|
||||
}: MessagesTimelineProps) {
|
||||
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
|
||||
const [expandedRunIds, setExpandedRunIds] = useState<ReadonlySet<RunId>>(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
|
||||
@@ -208,14 +209,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
// 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((turnId: TurnId) => {
|
||||
const onToggleTurnFold = useCallback((runId: RunId) => {
|
||||
setFoldToggleSettling(true);
|
||||
setExpandedTurnIds((existing) => {
|
||||
setExpandedRunIds((existing) => {
|
||||
const next = new Set(existing);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
next.add(runId);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
@@ -240,39 +241,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,
|
||||
expandedTurnIds,
|
||||
latestRun,
|
||||
expandedRunIds,
|
||||
isWorking,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
@@ -280,8 +281,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}),
|
||||
[
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
expandedTurnIds,
|
||||
latestRun,
|
||||
expandedRunIds,
|
||||
isWorking,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
@@ -413,7 +414,8 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
// Commentary (non-terminal assistant) rows carry no metadata row, so
|
||||
// they sit closer to the work that follows them.
|
||||
(row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta) ||
|
||||
row.kind === "work"
|
||||
row.kind === "work" ||
|
||||
row.kind === "event"
|
||||
? "pb-2"
|
||||
: "pb-4",
|
||||
row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null,
|
||||
@@ -430,6 +432,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
<AssistantTimelineRow row={row} />
|
||||
) : null}
|
||||
{row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
|
||||
{row.kind === "event" ? <V2EventTimelineRow row={row} /> : null}
|
||||
{row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
|
||||
</div>
|
||||
);
|
||||
@@ -574,7 +577,7 @@ function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-
|
||||
type="button"
|
||||
aria-expanded={row.expanded}
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() => 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"
|
||||
>
|
||||
<span>{row.label}</span>
|
||||
@@ -660,6 +663,173 @@ function ProposedPlanTimelineRow({
|
||||
);
|
||||
}
|
||||
|
||||
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<TimelineRow, { kind: "event" }> }) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const { item, visibility, sourceThreadId } = row.projectedItem;
|
||||
const presentation = v2EventPresentation(item);
|
||||
const Icon = presentation.icon;
|
||||
return (
|
||||
<section
|
||||
className={cn(
|
||||
"rounded-lg border px-3 py-2",
|
||||
presentation.tone === "warning" && "border-amber-500/25 bg-amber-500/5",
|
||||
presentation.tone === "danger" && "border-destructive/25 bg-destructive/5",
|
||||
presentation.tone === "success" && "border-emerald-500/20 bg-emerald-500/5",
|
||||
presentation.tone === "muted" && "border-border/60 bg-card/30",
|
||||
)}
|
||||
data-v2-item-type={item.type}
|
||||
data-v2-item-visibility={visibility}
|
||||
>
|
||||
<div className="flex items-start gap-2.5">
|
||||
<Icon
|
||||
className={cn(
|
||||
"mt-0.5 size-3.5 shrink-0",
|
||||
presentation.tone === "warning" && "text-amber-600 dark:text-amber-400",
|
||||
presentation.tone === "danger" && "text-destructive",
|
||||
presentation.tone === "success" && "text-emerald-600 dark:text-emerald-400",
|
||||
presentation.tone === "muted" && "text-muted-foreground",
|
||||
)}
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1">
|
||||
<span className="text-xs font-medium text-foreground/90">{presentation.label}</span>
|
||||
{item.status !== "completed" ? (
|
||||
<span className="rounded-full border border-border/70 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground">
|
||||
{item.status}
|
||||
</span>
|
||||
) : null}
|
||||
{visibility !== "local" ? (
|
||||
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
|
||||
{visibility === "inherited" ? "Inherited" : "Synthetic"}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{presentation.detail ? (
|
||||
<div className="mt-1 text-xs leading-relaxed text-muted-foreground">
|
||||
<ChatMarkdown
|
||||
text={presentation.detail}
|
||||
cwd={ctx.markdownCwd}
|
||||
threadRef={ctx.threadRef ?? undefined}
|
||||
skills={ctx.skills}
|
||||
lineBreaks
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{visibility === "inherited" ? (
|
||||
<p className="mt-1 font-mono text-[10px] text-muted-foreground/65">
|
||||
From {sourceThreadId}
|
||||
</p>
|
||||
) : null}
|
||||
<details
|
||||
className="group/v2-details mt-2 rounded-md border border-border/50 bg-background/45"
|
||||
data-v2-structured-details="true"
|
||||
>
|
||||
<summary className="flex cursor-pointer list-none items-center gap-1.5 px-2 py-1.5 text-[11px] font-medium text-muted-foreground select-none hover:text-foreground [&::-webkit-details-marker]:hidden">
|
||||
<ChevronRightIcon className="size-3 transition-transform group-open/v2-details:rotate-90" />
|
||||
Structured details
|
||||
</summary>
|
||||
<pre className="max-h-80 overflow-auto border-t border-border/50 px-2 py-2 font-mono text-[10px] leading-relaxed whitespace-pre-wrap text-muted-foreground">
|
||||
{JSON.stringify(item, null, 2)}
|
||||
</pre>
|
||||
</details>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
|
||||
return (
|
||||
<div className="py-0.5 pl-1.5">
|
||||
@@ -845,7 +1015,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;
|
||||
@@ -875,10 +1045,10 @@ function AssistantChangedFilesSectionInner({
|
||||
checkpointFiles: TurnDiffSummary["files"];
|
||||
routeThreadKey: string;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
const allDirectoriesExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId] ?? true,
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId] ?? true,
|
||||
);
|
||||
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
@@ -902,7 +1072,7 @@ function AssistantChangedFilesSectionInner({
|
||||
size="xs"
|
||||
variant="outline"
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() => setExpanded(routeThreadKey, turnSummary.turnId, !allDirectoriesExpanded)}
|
||||
onClick={() => setExpanded(routeThreadKey, turnSummary.runId, !allDirectoriesExpanded)}
|
||||
>
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</Button>
|
||||
@@ -910,15 +1080,15 @@ function AssistantChangedFilesSectionInner({
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)}
|
||||
onClick={() => onOpenTurnDiff(turnSummary.runId, checkpointFiles[0]?.path)}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.turnId}`}
|
||||
turnId={turnSummary.turnId}
|
||||
key={`changed-files-tree:${turnSummary.runId}`}
|
||||
runId={turnSummary.runId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
@@ -1473,8 +1643,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()) {
|
||||
@@ -1493,14 +1663,25 @@ 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;
|
||||
}
|
||||
|
||||
function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
|
||||
if (
|
||||
workEntry.sourceActivityKind === "user-input.requested" ||
|
||||
workEntry.sourceActivityKind === "user-input.resolved"
|
||||
) {
|
||||
if (workEntry.itemType === "user_input_request") {
|
||||
return "message-circle";
|
||||
}
|
||||
if (workEntry.requestKind === "command") return "terminal";
|
||||
@@ -1514,13 +1695,12 @@ function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
|
||||
return "square-pen";
|
||||
}
|
||||
if (workEntry.itemType === "web_search") return "globe";
|
||||
if (workEntry.itemType === "image_view") return "eye";
|
||||
if (workEntry.itemType === "file_search") return "eye";
|
||||
|
||||
switch (workEntry.itemType) {
|
||||
case "mcp_tool_call":
|
||||
case "dynamic_tool":
|
||||
return "wrench";
|
||||
case "dynamic_tool_call":
|
||||
case "collab_agent_tool_call":
|
||||
case "subagent":
|
||||
return "hammer";
|
||||
}
|
||||
|
||||
@@ -1552,7 +1732,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const iconConfig = workToneIcon(workEntry.tone);
|
||||
const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
|
||||
const showWarningIndicator = false;
|
||||
const entryIconName = showWarningIndicator ? "x" : workEntryIconName(workEntry);
|
||||
const heading = toolWorkEntryHeading(workEntry);
|
||||
const rawPreview = workEntryPreview(workEntry, workspaceRoot);
|
||||
@@ -1566,9 +1746,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
const expandedBody = buildToolCallExpandedBody(workEntry, workspaceRoot);
|
||||
const canExpand = expandedBody !== null;
|
||||
const showFailedIndicator = workEntryIndicatesToolFailure(workEntry);
|
||||
const showDestructiveRowStyle =
|
||||
showFailedIndicator &&
|
||||
(workEntry.sourceActivityKind === "runtime.error" || !workLogEntryIsToolLike(workEntry));
|
||||
const showDestructiveRowStyle = showFailedIndicator && !workLogEntryIsToolLike(workEntry);
|
||||
const iconWrapperClass = cn(
|
||||
"flex size-5 shrink-0 items-center justify-center",
|
||||
showWarningIndicator
|
||||
@@ -1611,6 +1789,8 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
canExpand &&
|
||||
"cursor-pointer hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70",
|
||||
)}
|
||||
data-v2-item-type={workEntry.projectedItem?.item.type}
|
||||
data-v2-item-visibility={workEntry.projectedItem?.visibility}
|
||||
{...rowToggleProps}
|
||||
>
|
||||
<div className="flex select-none items-center gap-1.5 transition-[opacity,translate] duration-200">
|
||||
@@ -1624,6 +1804,12 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<p className="flex min-w-0 w-full items-baseline gap-1.5 text-[12px] leading-5">
|
||||
<span className={cn("min-w-0 shrink truncate", headingClass)}>{heading}</span>
|
||||
{workEntry.projectedItem?.visibility !== undefined &&
|
||||
workEntry.projectedItem.visibility !== "local" ? (
|
||||
<span className="shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[9px] leading-none text-muted-foreground">
|
||||
{workEntry.projectedItem.visibility === "inherited" ? "Inherited" : "Synthetic"}
|
||||
</span>
|
||||
) : null}
|
||||
{preview && (
|
||||
<span className="min-w-0 flex-1 truncate text-muted-foreground/55">{preview}</span>
|
||||
)}
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
type ScopedThreadRef,
|
||||
} from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
@@ -1459,10 +1460,7 @@ export function ArchivedThreadsPanel() {
|
||||
),
|
||||
);
|
||||
const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
|
||||
snapshot.threads.map((thread) => ({
|
||||
...thread,
|
||||
environmentId,
|
||||
})),
|
||||
snapshot.threads.map((thread) => presentThreadShell(environmentId, thread)),
|
||||
);
|
||||
|
||||
const archivedProjects = Array.from(projectsByEnvironmentAndId.values());
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
ConnectionTargetStore,
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
decodeOrDiscardOrchestrationCache,
|
||||
registerConnectionInCatalog,
|
||||
removeCatalogValue,
|
||||
removeConnectionFromCatalog,
|
||||
@@ -17,12 +21,7 @@ import {
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThread,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -37,20 +36,9 @@ const CATALOG_STORE_NAME = "catalog";
|
||||
const SHELL_STORE_NAME = "shell";
|
||||
const THREAD_STORE_NAME = "thread";
|
||||
const CATALOG_KEY = "document";
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
|
||||
const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
|
||||
const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
thread: OrchestrationThread,
|
||||
});
|
||||
const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
|
||||
const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot);
|
||||
const ConnectionCatalogDocumentJson = Schema.fromJsonString(ConnectionCatalogDocument);
|
||||
const decodeConnectionCatalogDocument = Schema.decodeUnknownEffect(ConnectionCatalogDocumentJson);
|
||||
@@ -429,25 +417,24 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (typeof raw !== "string") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredShellSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none(),
|
||||
return decodeOrDiscardOrchestrationCache(
|
||||
decodeStoredShellSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none(),
|
||||
),
|
||||
),
|
||||
removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("load-shell", cause),
|
||||
),
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeStoredShellSnapshot({
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
|
||||
@@ -469,33 +456,36 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (typeof raw !== "string") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredThreadSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none(),
|
||||
return decodeOrDiscardOrchestrationCache(
|
||||
decodeStoredThreadSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none(),
|
||||
),
|
||||
),
|
||||
removeDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, threadId),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("load-thread", cause),
|
||||
),
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
),
|
||||
saveThread: (environmentId, thread) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: 1,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.id,
|
||||
threadId: thread.thread.id,
|
||||
thread,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
yield* writeDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, thread.id),
|
||||
threadCacheKey(environmentId, thread.thread.id),
|
||||
encoded,
|
||||
);
|
||||
}).pipe(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId, RunId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { selectThreadDiffPanelSelection, useDiffPanelStore } from "./diffPanelStore";
|
||||
@@ -17,7 +17,7 @@ describe("diffPanelStore", () => {
|
||||
|
||||
it("clears incompatible selection fields when changing scopes", () => {
|
||||
const store = useDiffPanelStore.getState();
|
||||
store.selectTurn(THREAD_REF, TurnId.make("turn-1"), "src/app.ts");
|
||||
store.selectTurn(THREAD_REF, RunId.make("turn-1"), "src/app.ts");
|
||||
store.selectGitScope(THREAD_REF, "unstaged");
|
||||
|
||||
expect(
|
||||
@@ -31,7 +31,7 @@ describe("diffPanelStore", () => {
|
||||
});
|
||||
|
||||
it("increments the reveal request when opening the same turn file again", () => {
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const turnId = RunId.make("turn-1");
|
||||
useDiffPanelStore.getState().selectTurn(THREAD_REF, turnId, "src/app.ts");
|
||||
useDiffPanelStore.getState().selectTurn(THREAD_REF, turnId, "src/app.ts");
|
||||
|
||||
@@ -51,8 +51,8 @@ describe("diffPanelStore", () => {
|
||||
});
|
||||
|
||||
it("reconciles a missing turn selection to the latest available turn", () => {
|
||||
const missingTurnId = TurnId.make("turn-missing");
|
||||
const latestTurnId = TurnId.make("turn-latest");
|
||||
const missingTurnId = RunId.make("turn-missing");
|
||||
const latestTurnId = RunId.make("turn-latest");
|
||||
useDiffPanelStore.getState().selectTurn(THREAD_REF, missingTurnId, "src/app.ts");
|
||||
useDiffPanelStore.getState().reconcileTurnSelection(THREAD_REF, [latestTurnId]);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
|
||||
import type { RunId, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
|
||||
@@ -8,7 +8,7 @@ import { resolveStorage } from "./lib/storage";
|
||||
export type DiffPanelSelection =
|
||||
| { kind: "branch"; baseRef: string | null }
|
||||
| { kind: "unstaged" }
|
||||
| { kind: "turn"; turnId: TurnId; filePath: string | null; revealRequestId: number };
|
||||
| { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number };
|
||||
|
||||
const DEFAULT_SELECTION: DiffPanelSelection = { kind: "branch", baseRef: null };
|
||||
|
||||
@@ -17,8 +17,8 @@ interface DiffPanelStoreState {
|
||||
branchBaseRefByThreadKey: Record<string, string | null>;
|
||||
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<TurnId>) => void;
|
||||
selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void;
|
||||
reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray<RunId>) => void;
|
||||
removeThread: (ref: ScopedThreadRef) => void;
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ export const useDiffPanelStore = create<DiffPanelStoreState>()(
|
||||
}),
|
||||
{
|
||||
name: "t3code:diff-panel-state:v1",
|
||||
version: 1,
|
||||
version: 2,
|
||||
storage: createJSONStorage(() =>
|
||||
resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
|
||||
),
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -93,7 +93,7 @@ export function useThreadActions() {
|
||||
const resolved = resolveThreadTarget(target);
|
||||
if (!resolved) return AsyncResult.success(undefined);
|
||||
const { thread, threadRef } = resolved;
|
||||
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
|
||||
if (thread.runtime?.status === "running" && thread.runtime.activeRunId != null) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadArchiveBlockedError({
|
||||
@@ -210,7 +210,7 @@ export function useThreadActions() {
|
||||
shouldDeleteWorktree = confirmationResult.value;
|
||||
}
|
||||
|
||||
if (thread.session && thread.session.status !== "stopped") {
|
||||
if (thread.runtime !== null) {
|
||||
await stopThreadSession({
|
||||
environmentId: threadRef.environmentId,
|
||||
input: { threadId: threadRef.threadId },
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -1,17 +1,10 @@
|
||||
import type { OrchestrationThreadActivity, ThreadTokenUsageSnapshot } from "@t3tools/contracts";
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value && typeof value === "object" ? (value as Record<string, unknown>) : 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<ThreadTokenUsageSnapshot[Key], undefined> | null
|
||||
@@ -48,21 +41,20 @@ export function formatProviderDisplayName(provider: string | null | undefined):
|
||||
}
|
||||
|
||||
export function deriveLatestContextWindowSnapshot(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
entries: ReadonlyArray<ThreadWorkEntry>,
|
||||
): 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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
@@ -21,20 +22,18 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("sortThreads", () => {
|
||||
@@ -49,7 +48,7 @@ describe("sortThreads", () => {
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
@@ -65,7 +64,7 @@ describe("sortThreads", () => {
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:06:00.000Z",
|
||||
updatedAt: "2026-03-09T10:06:00.000Z",
|
||||
streaming: false,
|
||||
@@ -93,7 +92,7 @@ describe("sortThreads", () => {
|
||||
id: "message-1" as never,
|
||||
role: "assistant",
|
||||
text: "assistant only",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:02:00.000Z",
|
||||
updatedAt: "2026-03-09T10:02:00.000Z",
|
||||
streaming: false,
|
||||
|
||||
+123
-1652
File diff suppressed because it is too large.
Load diff
+405
-1257
File diff suppressed because it is too large.
Load diff
@@ -3,18 +3,14 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThread,
|
||||
EnvironmentThreadShell,
|
||||
ThreadConversationMessage,
|
||||
ThreadProposedPlan,
|
||||
ThreadRuntimeSummary,
|
||||
ThreadWorkEntry,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { mergeEnvironmentThread } from "@t3tools/client-runtime/state/threads";
|
||||
import type {
|
||||
OrchestrationMessage,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationSession,
|
||||
OrchestrationThreadActivity,
|
||||
ScopedProjectRef,
|
||||
ScopedThreadRef,
|
||||
ServerConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, ThreadId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { useMemo } from "react";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
@@ -24,9 +20,10 @@ import { environmentThreadDetails, environmentThreadShells } from "./threads";
|
||||
|
||||
const EMPTY_PROJECT_REFS: ReadonlyArray<ScopedProjectRef> = Object.freeze([]);
|
||||
const EMPTY_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);
|
||||
const EMPTY_MESSAGES: ReadonlyArray<OrchestrationMessage> = Object.freeze([]);
|
||||
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = Object.freeze([]);
|
||||
const EMPTY_PROPOSED_PLANS: ReadonlyArray<OrchestrationProposedPlan> = Object.freeze([]);
|
||||
const EMPTY_MESSAGES: ReadonlyArray<ThreadConversationMessage> = Object.freeze([]);
|
||||
const EMPTY_WORK_ENTRIES: ReadonlyArray<ThreadWorkEntry> = Object.freeze([]);
|
||||
const EMPTY_PROPOSED_PLANS: ReadonlyArray<ThreadProposedPlan> = Object.freeze([]);
|
||||
const EMPTY_VISIBLE_TURN_ITEMS: ReadonlyArray<OrchestrationV2ProjectedTurnItem> = Object.freeze([]);
|
||||
|
||||
const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(
|
||||
Atom.withLabel("web-project:empty"),
|
||||
@@ -46,14 +43,17 @@ const EMPTY_THREAD_DETAIL_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
|
||||
const EMPTY_MESSAGES_ATOM = Atom.make(EMPTY_MESSAGES).pipe(
|
||||
Atom.withLabel("web-thread-messages:empty"),
|
||||
);
|
||||
const EMPTY_ACTIVITIES_ATOM = Atom.make(EMPTY_ACTIVITIES).pipe(
|
||||
Atom.withLabel("web-thread-activities:empty"),
|
||||
const EMPTY_WORK_ENTRIES_ATOM = Atom.make(EMPTY_WORK_ENTRIES).pipe(
|
||||
Atom.withLabel("web-thread-work-entries:empty"),
|
||||
);
|
||||
const EMPTY_PROPOSED_PLANS_ATOM = Atom.make(EMPTY_PROPOSED_PLANS).pipe(
|
||||
Atom.withLabel("web-thread-proposed-plans:empty"),
|
||||
);
|
||||
const EMPTY_SESSION_ATOM = Atom.make<OrchestrationSession | null>(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<ThreadRuntimeSummary | null>(null).pipe(
|
||||
Atom.withLabel("web-thread-runtime:empty"),
|
||||
);
|
||||
|
||||
export const activeEnvironmentIdAtom = Atom.make<EnvironmentId | null>(null).pipe(
|
||||
@@ -144,31 +144,39 @@ export function useThread(ref: ScopedThreadRef | null): EnvironmentThread | null
|
||||
|
||||
export function useThreadMessages(
|
||||
ref: ScopedThreadRef | null,
|
||||
): ReadonlyArray<OrchestrationMessage> {
|
||||
): ReadonlyArray<ThreadConversationMessage> {
|
||||
return useAtomValue(
|
||||
ref === null ? EMPTY_MESSAGES_ATOM : environmentThreadDetails.messagesAtom(ref),
|
||||
);
|
||||
}
|
||||
|
||||
export function useThreadActivities(
|
||||
ref: ScopedThreadRef | null,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
export function useThreadWorkEntries(ref: ScopedThreadRef | null): ReadonlyArray<ThreadWorkEntry> {
|
||||
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<OrchestrationProposedPlan> {
|
||||
): ReadonlyArray<ThreadProposedPlan> {
|
||||
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<OrchestrationV2ProjectedTurnItem> {
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,13 +4,8 @@ import {
|
||||
type ComposerPathSearchTarget,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
ThreadId,
|
||||
VcsListRefsResult,
|
||||
VcsRef,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ThreadId, VcsListRefsResult, VcsRef } from "@t3tools/contracts";
|
||||
import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
@@ -30,7 +25,7 @@ const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
|
||||
const INITIAL_BRANCH_CURSORS = [undefined] as const;
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: OrchestrationThread | null;
|
||||
readonly data: EnvironmentThread | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly isDeleted: boolean;
|
||||
|
||||
@@ -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<EnvironmentThreadState, "data"> & { readonly data: Option.Option<EnvironmentThread> } {
|
||||
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)),
|
||||
};
|
||||
}
|
||||
@@ -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> = {}): 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,
|
||||
};
|
||||
}
|
||||
+11
-12
@@ -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<OrchestrationMessage, "attachments"> {
|
||||
export interface ChatMessage extends Omit<ThreadConversationMessage, "attachments"> {
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | 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;
|
||||
@@ -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> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
@@ -18,20 +19,18 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-02-13T00:00:00.000Z",
|
||||
updatedAt: "2026-02-13T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("getOrphanedWorktreePathForThread", () => {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,13 +1,22 @@
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
MessageId,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
PlanId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
type ClientOrchestrationCommand,
|
||||
WS_METHODS,
|
||||
type OrchestrationV2Command,
|
||||
type OrchestrationV2ThreadLaunchInput,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type ProjectMutation,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -21,7 +30,8 @@ import {
|
||||
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
|
||||
import * as RpcSession from "../rpc/session.ts";
|
||||
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
|
||||
import { archiveThread, createProject, stopThreadSession } from "./commands.ts";
|
||||
import { v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts";
|
||||
import { archiveThread, createProject, startThreadTurn } from "./commands.ts";
|
||||
|
||||
const TEST_CRYPTO_LAYER = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
@@ -38,14 +48,45 @@ const TARGET = new PrimaryConnectionTarget({
|
||||
wsBaseUrl: "wss://environment.example.test",
|
||||
});
|
||||
|
||||
const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (
|
||||
dispatched: ClientOrchestrationCommand[],
|
||||
) {
|
||||
const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (input: {
|
||||
readonly commands: OrchestrationV2Command[];
|
||||
readonly projects: ProjectMutation[];
|
||||
readonly launches?: OrchestrationV2ThreadLaunchInput[];
|
||||
readonly projection?: OrchestrationV2ThreadProjection;
|
||||
}) {
|
||||
const client = {
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command: ClientOrchestrationCommand) =>
|
||||
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
|
||||
Effect.sync(() => {
|
||||
dispatched.push(command);
|
||||
return { sequence: dispatched.length };
|
||||
input.commands.push(command);
|
||||
return { sequence: input.commands.length };
|
||||
}),
|
||||
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: () =>
|
||||
Effect.succeed(input.projection ?? v2Projection),
|
||||
[ORCHESTRATION_V2_WS_METHODS.launchThread]: (launchInput: OrchestrationV2ThreadLaunchInput) =>
|
||||
Effect.sync(() => {
|
||||
input.launches?.push(launchInput);
|
||||
return {
|
||||
threadId: launchInput.threadId ?? v2ThreadId,
|
||||
projection: input.projection ?? v2Projection,
|
||||
resumed: false,
|
||||
};
|
||||
}),
|
||||
[WS_METHODS.projectsMutate]: (mutation: ProjectMutation) =>
|
||||
Effect.sync(() => {
|
||||
input.projects.push(mutation);
|
||||
return {
|
||||
id: mutation.projectId,
|
||||
title: mutation.type === "project.create" ? mutation.title : "Project",
|
||||
workspaceRoot:
|
||||
mutation.type === "project.create" ? mutation.workspaceRoot : "/workspace/project",
|
||||
repositoryIdentity: null,
|
||||
faviconPath: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-06T00:00:00.000Z",
|
||||
updatedAt: "2026-06-06T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
};
|
||||
}),
|
||||
} as unknown as WsRpcProtocolClient;
|
||||
const session: RpcSession.RpcSession = {
|
||||
@@ -66,72 +107,222 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
|
||||
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
|
||||
});
|
||||
|
||||
describe("environment commands", () => {
|
||||
it.effect("adds generated command metadata", () =>
|
||||
describe("V2 environment commands", () => {
|
||||
it.effect("routes projects through the event-sourced project transport", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatched: ClientOrchestrationCommand[] = [];
|
||||
const supervisor = yield* makeSupervisor(dispatched);
|
||||
const projects: ProjectMutation[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands: [], projects });
|
||||
|
||||
const result = yield* createProject({
|
||||
yield* createProject({
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/workspace/project",
|
||||
createdAt: "2026-06-06T00:00:00.000Z",
|
||||
createWorkspaceRootIfMissing: true,
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(result).toEqual({ sequence: 1 });
|
||||
expect(dispatched).toEqual([
|
||||
expect(projects).toEqual([
|
||||
{
|
||||
type: "project.create",
|
||||
commandId: "00000000-0000-4000-8000-000000000000",
|
||||
projectId: "project-1",
|
||||
title: "Project",
|
||||
workspaceRoot: "/workspace/project",
|
||||
createdAt: "2026-06-06T00:00:00.000Z",
|
||||
createWorkspaceRootIfMissing: true,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("preserves caller metadata for idempotent queued commands", () =>
|
||||
it.effect("preserves caller command ids for idempotent V2 commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatched: ClientOrchestrationCommand[] = [];
|
||||
const supervisor = yield* makeSupervisor(dispatched);
|
||||
|
||||
yield* stopThreadSession({
|
||||
commandId: CommandId.make("queued-command"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-06-06T00:01:00.000Z",
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(dispatched).toEqual([
|
||||
{
|
||||
type: "thread.session.stop",
|
||||
commandId: "queued-command",
|
||||
threadId: "thread-1",
|
||||
createdAt: "2026-06-06T00:01:00.000Z",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("does not add timestamps to commands without createdAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatched: ClientOrchestrationCommand[] = [];
|
||||
const supervisor = yield* makeSupervisor(dispatched);
|
||||
const commands: OrchestrationV2Command[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands, projects: [] });
|
||||
|
||||
yield* archiveThread({
|
||||
commandId: CommandId.make("archive-command"),
|
||||
commandId: CommandId.make("queued-command"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(dispatched).toEqual([
|
||||
{
|
||||
type: "thread.archive",
|
||||
commandId: "archive-command",
|
||||
threadId: "thread-1",
|
||||
},
|
||||
expect(commands).toEqual([
|
||||
{ type: "thread.archive", commandId: "queued-command", threadId: "thread-1" },
|
||||
]);
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("preserves plan implementation provenance on V2 runs", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: OrchestrationV2Command[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands, projects: [] });
|
||||
|
||||
yield* startThreadTurn({
|
||||
commandId: CommandId.make("implement-plan"),
|
||||
threadId: v2ThreadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-implementation"),
|
||||
role: "user",
|
||||
text: "Implement the plan",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.make("thread-plan"),
|
||||
planId: PlanId.make("plan-1"),
|
||||
},
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]).toMatchObject({
|
||||
type: "message.dispatch",
|
||||
commandId: "implement-plan",
|
||||
threadId: v2ThreadId,
|
||||
sourcePlanRef: { threadId: "thread-plan", planId: "plan-1" },
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
});
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("preserves an existing worktree and branch during first-message launch", () =>
|
||||
Effect.gen(function* () {
|
||||
const launches: OrchestrationV2ThreadLaunchInput[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
|
||||
|
||||
yield* startThreadTurn({
|
||||
commandId: CommandId.make("launch-existing-worktree"),
|
||||
threadId: v2ThreadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-existing-worktree"),
|
||||
role: "user",
|
||||
text: "Continue here",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
createThread: {
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: v2Projection.thread.modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature",
|
||||
worktreePath: "/workspace/project-worktrees/feature",
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
},
|
||||
},
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(launches[0]).toMatchObject({
|
||||
threadId: v2ThreadId,
|
||||
workspaceStrategy: {
|
||||
type: "existing_worktree",
|
||||
worktreePath: "/workspace/project-worktrees/feature",
|
||||
branch: "feature",
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("provisions an origin-based worktree for an existing empty thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const launches: OrchestrationV2ThreadLaunchInput[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
|
||||
|
||||
yield* startThreadTurn({
|
||||
commandId: CommandId.make("launch-existing-thread-worktree"),
|
||||
threadId: v2ThreadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-existing-thread-worktree"),
|
||||
role: "user",
|
||||
text: "Move to a worktree",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/workspace/project",
|
||||
baseBranch: "main",
|
||||
branch: "feature",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
},
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(launches[0]).toMatchObject({
|
||||
threadId: v2ThreadId,
|
||||
reuseExistingThread: true,
|
||||
projectId: v2Projection.thread.projectId,
|
||||
workspaceStrategy: {
|
||||
type: "worktree",
|
||||
baseRef: "main",
|
||||
branch: "feature",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("maps explicit active-run delivery modes to V2 dispatch semantics", () =>
|
||||
Effect.gen(function* () {
|
||||
const activeRunId = RunId.make("run-active");
|
||||
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
|
||||
const projection: OrchestrationV2ThreadProjection = {
|
||||
...v2Projection,
|
||||
runs: [
|
||||
{
|
||||
id: activeRunId,
|
||||
threadId: v2ThreadId,
|
||||
ordinal: 1,
|
||||
providerInstanceId: v2Projection.thread.providerInstanceId,
|
||||
modelSelection: v2Projection.thread.modelSelection,
|
||||
providerThreadId: null,
|
||||
userMessageId: MessageId.make("message-active"),
|
||||
rootNodeId: null,
|
||||
activeAttemptId: null,
|
||||
status: "running",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
const commands: OrchestrationV2Command[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
|
||||
|
||||
for (const [mode, expectedType] of [
|
||||
["queue", "queue_after_active"],
|
||||
["steer", "steer_active"],
|
||||
["restart", "restart_active"],
|
||||
] as const) {
|
||||
yield* startThreadTurn({
|
||||
commandId: CommandId.make(`command-${mode}`),
|
||||
threadId: v2ThreadId,
|
||||
message: {
|
||||
messageId: MessageId.make(`message-${mode}`),
|
||||
role: "user",
|
||||
text: mode,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
dispatchMode: mode,
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(commands.at(-1)).toMatchObject({
|
||||
type: "message.dispatch",
|
||||
dispatchMode: {
|
||||
type: expectedType,
|
||||
...(mode === "queue" ? {} : { targetRunId: activeRunId }),
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
});
|
||||
@@ -1,256 +1,548 @@
|
||||
import {
|
||||
CommandId,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ClientOrchestrationCommand,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
WS_METHODS,
|
||||
type ChatAttachment,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type OrchestrationV2Command,
|
||||
type OrchestrationV2CreationSource,
|
||||
type PlanId,
|
||||
type ProjectId,
|
||||
type ProjectScript,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderInteractionMode,
|
||||
type ProviderUserInputAnswers,
|
||||
type RunId,
|
||||
type RuntimeMode,
|
||||
type RuntimeRequestId,
|
||||
type ThreadId,
|
||||
type UploadChatAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import type { EnvironmentSupervisor } from "../connection/supervisor.ts";
|
||||
import {
|
||||
type EnvironmentRpcFailure,
|
||||
type EnvironmentRpcSuccess,
|
||||
type EnvironmentRpcUnavailableError,
|
||||
request,
|
||||
} from "../rpc/client.ts";
|
||||
import { request } from "../rpc/client.ts";
|
||||
|
||||
type CommandType = ClientOrchestrationCommand["type"];
|
||||
type CommandOf<T extends CommandType> = Extract<ClientOrchestrationCommand, { readonly type: T }>;
|
||||
type CommandInput<T extends CommandType> = Omit<
|
||||
CommandOf<T>,
|
||||
"type" | "commandId" | "createdAt"
|
||||
> & {
|
||||
readonly commandId?: CommandId;
|
||||
} & ("createdAt" extends keyof CommandOf<T>
|
||||
? {
|
||||
readonly createdAt?: CommandOf<T>["createdAt"];
|
||||
}
|
||||
: {});
|
||||
|
||||
export type CreateProjectInput = CommandInput<"project.create">;
|
||||
export type UpdateProjectInput = CommandInput<"project.meta.update">;
|
||||
export type DeleteProjectInput = CommandInput<"project.delete">;
|
||||
export type CreateThreadInput = CommandInput<"thread.create">;
|
||||
export type DeleteThreadInput = CommandInput<"thread.delete">;
|
||||
export type ArchiveThreadInput = CommandInput<"thread.archive">;
|
||||
export type UnarchiveThreadInput = CommandInput<"thread.unarchive">;
|
||||
export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;
|
||||
export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;
|
||||
export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;
|
||||
export type StartThreadTurnInput = CommandInput<"thread.turn.start">;
|
||||
export type InterruptThreadTurnInput = CommandInput<"thread.turn.interrupt">;
|
||||
export type RespondToThreadApprovalInput = CommandInput<"thread.approval.respond">;
|
||||
export type RespondToThreadUserInputInput = CommandInput<"thread.user-input.respond">;
|
||||
export type RevertThreadCheckpointInput = CommandInput<"thread.checkpoint.revert">;
|
||||
export type StopThreadSessionInput = CommandInput<"thread.session.stop">;
|
||||
|
||||
type DispatchTag = typeof ORCHESTRATION_WS_METHODS.dispatchCommand;
|
||||
type CommandEffect = Effect.Effect<
|
||||
EnvironmentRpcSuccess<DispatchTag>,
|
||||
EnvironmentRpcFailure<DispatchTag> | 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<ProjectScript>;
|
||||
}
|
||||
|
||||
export interface UpdateProjectInput extends CommandMetadata {
|
||||
readonly projectId: ProjectId;
|
||||
readonly title?: string;
|
||||
readonly workspaceRoot?: string;
|
||||
readonly defaultModelSelection?: ModelSelection | null;
|
||||
readonly scripts?: ReadonlyArray<ProjectScript>;
|
||||
}
|
||||
|
||||
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<ChatAttachment | UploadChatAttachment>;
|
||||
};
|
||||
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<ChatAttachment | UploadChatAttachment>,
|
||||
) {
|
||||
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<ProjectScript>;
|
||||
}
|
||||
| {
|
||||
readonly type: "project.update";
|
||||
readonly commandId: CommandId;
|
||||
readonly projectId: ProjectId;
|
||||
readonly title?: string;
|
||||
readonly workspaceRoot?: string;
|
||||
readonly defaultModelSelection?: ModelSelection | null;
|
||||
readonly scripts?: ReadonlyArray<ProjectScript>;
|
||||
}
|
||||
| {
|
||||
readonly type: "project.delete";
|
||||
readonly commandId: CommandId;
|
||||
readonly projectId: ProjectId;
|
||||
readonly force?: boolean;
|
||||
},
|
||||
) {
|
||||
return yield* request(WS_METHODS.projectsMutate, mutation);
|
||||
});
|
||||
|
||||
export const createProject: (input: CreateProjectInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.createProject",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
export const createProject = Effect.fn("EnvironmentCommands.createProject")(function* (
|
||||
input: CreateProjectInput,
|
||||
) {
|
||||
return yield* mutateProject({
|
||||
type: "project.create",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
commandId: yield* allocateCommandId(input),
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
...(input.createWorkspaceRootIfMissing === undefined
|
||||
? {}
|
||||
: { createWorkspaceRootIfMissing: input.createWorkspaceRootIfMissing }),
|
||||
...(input.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: input.defaultModelSelection }),
|
||||
...(input.scripts === undefined ? {} : { scripts: input.scripts }),
|
||||
});
|
||||
});
|
||||
|
||||
export const updateProject: (input: UpdateProjectInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.updateProject",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "project.meta.update",
|
||||
commandId: yield* commandId(input),
|
||||
export const updateProject = Effect.fn("EnvironmentCommands.updateProject")(function* (
|
||||
input: UpdateProjectInput,
|
||||
) {
|
||||
return yield* mutateProject({
|
||||
type: "project.update",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
projectId: input.projectId,
|
||||
...(input.title === undefined ? {} : { title: input.title }),
|
||||
...(input.workspaceRoot === undefined ? {} : { workspaceRoot: input.workspaceRoot }),
|
||||
...(input.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: input.defaultModelSelection }),
|
||||
...(input.scripts === undefined ? {} : { scripts: input.scripts }),
|
||||
});
|
||||
});
|
||||
|
||||
export const deleteProject: (input: DeleteProjectInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.deleteProject",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
export const deleteProject = Effect.fn("EnvironmentCommands.deleteProject")(function* (
|
||||
input: DeleteProjectInput,
|
||||
) {
|
||||
return yield* mutateProject({
|
||||
type: "project.delete",
|
||||
commandId: yield* commandId(input),
|
||||
commandId: yield* allocateCommandId(input),
|
||||
projectId: input.projectId,
|
||||
...(input.force === undefined ? {} : { force: input.force }),
|
||||
});
|
||||
});
|
||||
|
||||
export const createThread: (input: CreateThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.createThread",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const createThread = Effect.fn("EnvironmentCommands.createThread")(function* (
|
||||
input: CreateThreadInput,
|
||||
) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.create",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
commandId: yield* allocateCommandId(input),
|
||||
createdBy: "user",
|
||||
creationSource: input.creationSource ?? "web",
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
});
|
||||
});
|
||||
|
||||
export const deleteThread: (input: DeleteThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.deleteThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.delete",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
function simpleThreadCommand(
|
||||
type: "thread.delete" | "thread.archive" | "thread.unarchive",
|
||||
input: ThreadCommandInput,
|
||||
) {
|
||||
return allocateCommandId(input).pipe(
|
||||
Effect.flatMap((commandId) => dispatch({ type, commandId, threadId: input.threadId })),
|
||||
);
|
||||
}
|
||||
|
||||
export const deleteThread = Effect.fn("EnvironmentCommands.deleteThread")(function* (
|
||||
input: DeleteThreadInput,
|
||||
) {
|
||||
return yield* simpleThreadCommand("thread.delete", input);
|
||||
});
|
||||
|
||||
export const archiveThread: (input: ArchiveThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.archiveThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.archive",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
export const archiveThread = Effect.fn("EnvironmentCommands.archiveThread")(function* (
|
||||
input: ArchiveThreadInput,
|
||||
) {
|
||||
return yield* simpleThreadCommand("thread.archive", input);
|
||||
});
|
||||
|
||||
export const unarchiveThread: (input: UnarchiveThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.unarchiveThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.unarchive",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(function* (
|
||||
input: UnarchiveThreadInput,
|
||||
) {
|
||||
return yield* simpleThreadCommand("thread.unarchive", input);
|
||||
});
|
||||
|
||||
export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.updateThreadMetadata",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.meta.update",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
|
||||
function* (input: UpdateThreadMetadataInput) {
|
||||
const commandId = yield* allocateCommandId(input);
|
||||
let result = null;
|
||||
if (
|
||||
input.title !== undefined ||
|
||||
input.branch !== undefined ||
|
||||
input.worktreePath !== undefined
|
||||
) {
|
||||
result = yield* dispatch({
|
||||
type: "thread.metadata.update",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
...(input.title === undefined ? {} : { title: input.title }),
|
||||
...(input.branch === undefined ? {} : { branch: input.branch }),
|
||||
...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
|
||||
});
|
||||
}
|
||||
if (input.modelSelection !== undefined) {
|
||||
result = yield* dispatch({
|
||||
type: "thread.model-selection.set",
|
||||
commandId: result === null ? commandId : CommandId.make(`${commandId}:model-selection`),
|
||||
threadId: input.threadId,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
}
|
||||
return result ?? { sequence: 0 };
|
||||
},
|
||||
);
|
||||
|
||||
export const setThreadRuntimeMode: (input: SetThreadRuntimeModeInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.setThreadRuntimeMode",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
export const setThreadInteractionMode: (input: SetThreadInteractionModeInput) => CommandEffect =
|
||||
Effect.fn("EnvironmentCommands.setThreadInteractionMode")(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const setThreadRuntimeMode = Effect.fn("EnvironmentCommands.setThreadRuntimeMode")(
|
||||
function* (input: SetThreadRuntimeModeInput) {
|
||||
return yield* dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
runtimeMode: input.runtimeMode,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const setThreadInteractionMode = Effect.fn("EnvironmentCommands.setThreadInteractionMode")(
|
||||
function* (input: SetThreadInteractionModeInput) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
interactionMode: input.interactionMode,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const startThreadTurn: (input: StartThreadTurnInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.startThreadTurn",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(function* (
|
||||
input: StartThreadTurnInput,
|
||||
) {
|
||||
const commandId = yield* allocateCommandId(input);
|
||||
const attachments = yield* persistAttachments(
|
||||
input.threadId,
|
||||
input.message.messageId,
|
||||
input.message.attachments,
|
||||
);
|
||||
const bootstrap = input.bootstrap?.createThread;
|
||||
const prepareWorktree = input.bootstrap?.prepareWorktree;
|
||||
if (bootstrap !== undefined || prepareWorktree !== undefined) {
|
||||
const existingProjection =
|
||||
bootstrap === undefined ? yield* getProjection(input.threadId) : null;
|
||||
const thread = bootstrap ?? existingProjection!.thread;
|
||||
const workspaceStrategy =
|
||||
prepareWorktree !== undefined
|
||||
? {
|
||||
type: "worktree" as const,
|
||||
baseRef: prepareWorktree.baseBranch,
|
||||
...(prepareWorktree.branch === undefined ? {} : { branch: prepareWorktree.branch }),
|
||||
...(prepareWorktree.startFromOrigin === undefined
|
||||
? {}
|
||||
: { startFromOrigin: prepareWorktree.startFromOrigin }),
|
||||
}
|
||||
: bootstrap?.worktreePath
|
||||
? {
|
||||
type: "existing_worktree" as const,
|
||||
worktreePath: bootstrap.worktreePath,
|
||||
...(bootstrap.branch === null ? {} : { branch: bootstrap.branch }),
|
||||
}
|
||||
: {
|
||||
type: "root" as const,
|
||||
...(bootstrap?.branch === null || bootstrap?.branch === undefined
|
||||
? {}
|
||||
: { branch: bootstrap.branch }),
|
||||
};
|
||||
return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
|
||||
commandId,
|
||||
creationSource: input.creationSource ?? "web",
|
||||
threadId: input.threadId,
|
||||
...(bootstrap === undefined ? { reuseExistingThread: true } : {}),
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: input.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
workspaceStrategy,
|
||||
initialMessage: {
|
||||
messageId: input.message.messageId,
|
||||
text: input.message.text,
|
||||
attachments,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const projection = yield* getProjection(input.threadId);
|
||||
const activeRun = projection.runs.findLast(
|
||||
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
|
||||
);
|
||||
const requestedMode = input.dispatchMode ?? "auto";
|
||||
const activeProviderThread =
|
||||
activeRun === undefined
|
||||
? undefined
|
||||
: projection.providerThreads.find((thread) => thread.id === activeRun.providerThreadId);
|
||||
const activeProviderSession =
|
||||
activeProviderThread?.providerSessionId === null ||
|
||||
activeProviderThread?.providerSessionId === undefined
|
||||
? undefined
|
||||
: projection.providerSessions.find(
|
||||
(session) => session.id === activeProviderThread.providerSessionId,
|
||||
);
|
||||
const turnCapabilities = activeProviderSession?.capabilities.turns;
|
||||
const dispatchMode =
|
||||
activeRun === undefined
|
||||
? ({ type: "start_immediately" } as const)
|
||||
: requestedMode === "steer"
|
||||
? ({ type: "steer_active", targetRunId: activeRun.id } as const)
|
||||
: requestedMode === "restart"
|
||||
? ({ type: "restart_active", targetRunId: activeRun.id } as const)
|
||||
: requestedMode === "queue"
|
||||
? ({ type: "queue_after_active" } as const)
|
||||
: turnCapabilities?.supportsActiveSteering === true
|
||||
? ({ type: "steer_active", targetRunId: activeRun.id } as const)
|
||||
: turnCapabilities?.supportsQueuedMessages === true
|
||||
? ({ type: "queue_after_active" } as const)
|
||||
: turnCapabilities?.supportsSteeringByInterruptRestart === true
|
||||
? ({ type: "restart_active", targetRunId: activeRun.id } as const)
|
||||
: ({ type: "queue_after_active" } as const);
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.turn.start",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "message.dispatch",
|
||||
commandId,
|
||||
createdBy: "user",
|
||||
creationSource: input.creationSource ?? "web",
|
||||
threadId: input.threadId,
|
||||
messageId: input.message.messageId,
|
||||
text: input.message.text,
|
||||
attachments,
|
||||
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
|
||||
...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
|
||||
dispatchMode,
|
||||
});
|
||||
});
|
||||
|
||||
export const interruptThreadTurn: (input: InterruptThreadTurnInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.interruptThreadTurn",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
|
||||
input: InterruptThreadTurnInput,
|
||||
) {
|
||||
const projection = yield* getProjection(input.threadId);
|
||||
const runId =
|
||||
input.runId ??
|
||||
(input.turnId as RunId | undefined) ??
|
||||
projection.runs.findLast(
|
||||
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
|
||||
)?.id;
|
||||
if (runId === undefined) return { sequence: 0 };
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "run.interrupt",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
runId,
|
||||
});
|
||||
});
|
||||
|
||||
export const respondToThreadApproval: (input: RespondToThreadApprovalInput) => CommandEffect =
|
||||
Effect.fn("EnvironmentCommands.respondToThreadApproval")(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")(
|
||||
function* (input: RespondToThreadApprovalInput) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.approval.respond",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "runtime-request.respond",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
requestId: input.requestId,
|
||||
decision: input.decision,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const respondToThreadUserInput: (input: RespondToThreadUserInputInput) => CommandEffect =
|
||||
Effect.fn("EnvironmentCommands.respondToThreadUserInput")(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")(
|
||||
function* (input: RespondToThreadUserInputInput) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.user-input.respond",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "runtime-request.respond",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
requestId: input.requestId,
|
||||
answers: input.answers,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const revertThreadCheckpoint: (input: RevertThreadCheckpointInput) => CommandEffect =
|
||||
Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(
|
||||
function* (input: RevertThreadCheckpointInput) {
|
||||
const projection = yield* getProjection(input.threadId);
|
||||
const checkpoint =
|
||||
projection.checkpoints.find(
|
||||
(candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId,
|
||||
) ??
|
||||
projection.checkpoints.findLast((candidate) => candidate.appRunOrdinal === input.turnCount);
|
||||
if (checkpoint === undefined) return { sequence: 0 };
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "checkpoint.rollback",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
scopeId: checkpoint.scopeId,
|
||||
checkpointId: checkpoint.id,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const stopThreadSession: (input: StopThreadSessionInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.stopThreadSession",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.session.stop",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* (
|
||||
input: StopThreadSessionInput,
|
||||
) {
|
||||
const projection = yield* getProjection(input.threadId);
|
||||
const commandId = yield* allocateCommandId(input);
|
||||
let result = { sequence: 0 };
|
||||
for (const session of projection.providerSessions) {
|
||||
result = yield* dispatch({
|
||||
type: "provider-session.detach",
|
||||
commandId: CommandId.make(`${commandId}:detach:${session.id}`),
|
||||
threadId: input.threadId,
|
||||
providerSessionId: session.id,
|
||||
reason: "client-requested",
|
||||
});
|
||||
}
|
||||
return result;
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
export * from "./capabilities.ts";
|
||||
export * from "./persistence.ts";
|
||||
export * from "./orchestrationCache.ts";
|
||||
export * from "./source.ts";
|
||||
export * from "./storageDocument.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);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -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<A, E, R, E2, R2>(
|
||||
decode: Effect.Effect<Option.Option<A>, E, R>,
|
||||
discard: Effect.Effect<void, E2, R2>,
|
||||
) {
|
||||
return decode.pipe(Effect.catch(() => discard.pipe(Effect.as(Option.none<A>()))));
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
type EnvironmentId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
@@ -52,18 +52,18 @@ export class EnvironmentCacheStore extends Context.Service<
|
||||
{
|
||||
readonly loadShell: (
|
||||
environmentId: EnvironmentId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationShellSnapshot>, ConnectionPersistenceError>;
|
||||
) => Effect.Effect<Option.Option<OrchestrationV2ShellSnapshot>, ConnectionPersistenceError>;
|
||||
readonly saveShell: (
|
||||
environmentId: EnvironmentId,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
snapshot: OrchestrationV2ShellSnapshot,
|
||||
) => Effect.Effect<void, ConnectionPersistenceError>;
|
||||
readonly loadThread: (
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThread>, ConnectionPersistenceError>;
|
||||
) => Effect.Effect<Option.Option<OrchestrationV2ThreadProjection>, ConnectionPersistenceError>;
|
||||
readonly saveThread: (
|
||||
environmentId: EnvironmentId,
|
||||
thread: OrchestrationThread,
|
||||
thread: OrchestrationV2ThreadProjection,
|
||||
) => Effect.Effect<void, ConnectionPersistenceError>;
|
||||
readonly removeThread: (
|
||||
environmentId: EnvironmentId,
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { ORCHESTRATION_V2_WS_METHODS, WS_METHODS } from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import type * as Duration from "effect/Duration";
|
||||
@@ -43,8 +39,6 @@ export type EnvironmentRpcTag = keyof WsRpcProtocolClient & string;
|
||||
type RpcMethod<TTag extends EnvironmentRpcTag> = 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
|
||||
|
||||
@@ -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<Error>({
|
||||
getSnapshotAtom: () =>
|
||||
Atom.make(
|
||||
AsyncResult.failure<OrchestrationShellSnapshot, Error>(
|
||||
AsyncResult.failure<OrchestrationV2ArchivedShellSnapshot, Error>(
|
||||
Cause.fail(new Error("credential=secret-value")),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -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<E
|
||||
export function createArchivedThreadSnapshotsAtomFamily<E>(options: {
|
||||
readonly getSnapshotAtom: (
|
||||
environmentId: EnvironmentId,
|
||||
) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationShellSnapshot, E>>;
|
||||
) => Atom.Atom<AsyncResult.AsyncResult<OrchestrationV2ArchivedShellSnapshot, E>>;
|
||||
readonly labelPrefix: string;
|
||||
}) {
|
||||
return Atom.family((environmentKey: string) =>
|
||||
|
||||
@@ -1,368 +1,115 @@
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { EnvironmentId, MessageId, RunId, TurnItemId } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { PrimaryConnectionTarget } from "../connection/model.ts";
|
||||
import {
|
||||
InvalidScopedProjectKeyError,
|
||||
InvalidScopedProjectRefCollectionKeyError,
|
||||
InvalidScopedThreadKeyError,
|
||||
parseProjectKey,
|
||||
parseProjectRefCollectionKey,
|
||||
parseThreadKey,
|
||||
} from "./entities.ts";
|
||||
import type { EnvironmentShellState } from "./shell.ts";
|
||||
import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts";
|
||||
import { createEnvironmentProjectAtoms } from "./projectEntities.ts";
|
||||
import { createEnvironmentSnapshotAtom } from "./snapshots.ts";
|
||||
import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts";
|
||||
import { mergeEnvironmentThread } from "./threadDetail.ts";
|
||||
import { createEnvironmentThreadShellAtoms } from "./threadShell.ts";
|
||||
import { presentThread, presentThreadShell } from "./models.ts";
|
||||
import { v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
|
||||
|
||||
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
const OTHER_PROJECT_ID = ProjectId.make("project-2");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const OTHER_THREAD_ID = ThreadId.make("thread-2");
|
||||
const environmentId = EnvironmentId.make("environment-v2");
|
||||
|
||||
describe("scoped entity keys", () => {
|
||||
it("preserves an invalid project key as structured error data", () => {
|
||||
const key = "missing-project-key-separator";
|
||||
let error: unknown;
|
||||
|
||||
try {
|
||||
parseProjectKey(key);
|
||||
} catch (cause) {
|
||||
error = cause;
|
||||
}
|
||||
|
||||
expect(error).toEqual(new InvalidScopedProjectKeyError({ key }));
|
||||
describe("V2 client presentation", () => {
|
||||
it("presents shell timestamps and status without constructing V1 state", () => {
|
||||
const shell = presentThreadShell(environmentId, v2ThreadShell);
|
||||
expect(shell.environmentId).toBe(environmentId);
|
||||
expect(shell.createdAt).toBe("2026-06-20T00:00:00.000Z");
|
||||
expect(shell.runtime).toBeNull();
|
||||
expect(shell.source).toBe(v2ThreadShell);
|
||||
});
|
||||
|
||||
it("preserves an invalid thread key as structured error data", () => {
|
||||
const key = "missing-thread-key-separator";
|
||||
let error: unknown;
|
||||
|
||||
try {
|
||||
parseThreadKey(key);
|
||||
} catch (cause) {
|
||||
error = cause;
|
||||
}
|
||||
|
||||
expect(error).toEqual(new InvalidScopedThreadKeyError({ key }));
|
||||
});
|
||||
|
||||
it("preserves malformed project reference collection input and its cause", () => {
|
||||
const key = "not-json";
|
||||
let error: unknown;
|
||||
|
||||
try {
|
||||
parseProjectRefCollectionKey(key);
|
||||
} catch (cause) {
|
||||
error = cause;
|
||||
}
|
||||
|
||||
expect(error).toBeInstanceOf(InvalidScopedProjectRefCollectionKeyError);
|
||||
expect(error).toMatchObject({ key, cause: expect.anything() });
|
||||
});
|
||||
|
||||
it("rejects invalid project reference collection shapes", () => {
|
||||
const key = JSON.stringify([["environment-1"]]);
|
||||
|
||||
expect(() => parseProjectRefCollectionKey(key)).toThrowError(
|
||||
InvalidScopedProjectRefCollectionKeyError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const THREAD_SHELL = {
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
} as const;
|
||||
|
||||
const SNAPSHOT: OrchestrationShellSnapshot = {
|
||||
snapshotSequence: 1,
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
projects: [
|
||||
{
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: OTHER_PROJECT_ID,
|
||||
title: "Other project",
|
||||
workspaceRoot: "/other-repo",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
THREAD_SHELL,
|
||||
{
|
||||
...THREAD_SHELL,
|
||||
id: OTHER_THREAD_ID,
|
||||
projectId: OTHER_PROJECT_ID,
|
||||
title: "Other thread",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function shellState(snapshot: OrchestrationShellSnapshot): EnvironmentShellState {
|
||||
return {
|
||||
snapshot: Option.some(snapshot),
|
||||
status: "live",
|
||||
error: Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
function makeHarness() {
|
||||
const shellStateAtoms = Atom.family((_environmentId: EnvironmentId) =>
|
||||
Atom.make(AsyncResult.success(shellState(SNAPSHOT))),
|
||||
);
|
||||
const threadStateAtoms = Atom.family((_key: string) =>
|
||||
Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)),
|
||||
);
|
||||
const catalogValueAtom = Atom.make({
|
||||
isReady: true,
|
||||
entries: new Map([
|
||||
[
|
||||
ENVIRONMENT_ID,
|
||||
it("retains the complete projection while deriving conversation parity", () => {
|
||||
const runId = RunId.make("run-1");
|
||||
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
|
||||
const projection = {
|
||||
...v2Projection,
|
||||
runs: [
|
||||
{
|
||||
target: new PrimaryConnectionTarget({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
label: "Environment",
|
||||
httpBaseUrl: "https://example.test",
|
||||
wsBaseUrl: "wss://example.test",
|
||||
}),
|
||||
profile: Option.none(),
|
||||
id: runId,
|
||||
threadId: v2Projection.thread.id,
|
||||
ordinal: 1,
|
||||
providerInstanceId: v2Projection.thread.providerInstanceId,
|
||||
modelSelection: v2Projection.thread.modelSelection,
|
||||
providerThreadId: null,
|
||||
userMessageId: MessageId.make("message-user"),
|
||||
rootNodeId: null,
|
||||
activeAttemptId: null,
|
||||
status: "running" as const,
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
},
|
||||
],
|
||||
]),
|
||||
});
|
||||
const snapshotAtom = createEnvironmentSnapshotAtom(shellStateAtoms);
|
||||
const projects = createEnvironmentProjectAtoms({
|
||||
catalogValueAtom,
|
||||
snapshotAtom,
|
||||
});
|
||||
const threadShells = createEnvironmentThreadShellAtoms({
|
||||
catalogValueAtom,
|
||||
snapshotAtom,
|
||||
});
|
||||
const threadDetails = createEnvironmentThreadDetailAtoms((environmentId, threadId) =>
|
||||
threadStateAtoms(`${environmentId}\u0000${threadId}`),
|
||||
);
|
||||
|
||||
return {
|
||||
registry: AtomRegistry.make(),
|
||||
shellStateAtom: shellStateAtoms(ENVIRONMENT_ID),
|
||||
threadStateAtom: (threadId: ThreadId) => threadStateAtoms(`${ENVIRONMENT_ID}\u0000${threadId}`),
|
||||
projects,
|
||||
threadShells,
|
||||
threadDetails,
|
||||
};
|
||||
}
|
||||
|
||||
describe("environment entity projections", () => {
|
||||
it("composes detail collections with authoritative shell workspace metadata", () => {
|
||||
const messages: OrchestrationThread["messages"] = [];
|
||||
const detail = {
|
||||
...THREAD_SHELL,
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
title: "Cached thread",
|
||||
branch: "stale-branch",
|
||||
worktreePath: "/repo/stale-worktree",
|
||||
deletedAt: null,
|
||||
messages,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
} satisfies OrchestrationThread & { readonly environmentId: EnvironmentId };
|
||||
const shell = {
|
||||
...THREAD_SHELL,
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
title: "Current thread",
|
||||
branch: "current-branch",
|
||||
worktreePath: "/repo/current-worktree",
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("message-user"),
|
||||
threadId: v2Projection.thread.id,
|
||||
runId,
|
||||
nodeId: null,
|
||||
role: "user" as const,
|
||||
text: "Hello",
|
||||
attachments: [],
|
||||
streaming: false,
|
||||
createdBy: "user" as const,
|
||||
creationSource: "web" as const,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const merged = mergeEnvironmentThread(detail, shell);
|
||||
const thread = presentThread(environmentId, projection);
|
||||
expect(thread.projection).toBe(projection);
|
||||
expect(thread.latestRun?.runId).toBe(runId);
|
||||
expect(thread.runtime?.status).toBe("running");
|
||||
expect(thread.runs).toHaveLength(1);
|
||||
expect(thread.availableActions.canInterrupt).toBe(true);
|
||||
expect(thread.messages[0]).toMatchObject({ text: "Hello", runId });
|
||||
});
|
||||
|
||||
expect(merged).toMatchObject({
|
||||
title: "Current thread",
|
||||
branch: "current-branch",
|
||||
worktreePath: "/repo/current-worktree",
|
||||
it("keeps the complete payload for generic V2 work-item rendering", () => {
|
||||
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
|
||||
const item = {
|
||||
id: TurnItemId.make("item-dynamic"),
|
||||
threadId: v2Projection.thread.id,
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed" as const,
|
||||
title: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "dynamic_tool" as const,
|
||||
toolName: "custom_tool",
|
||||
input: { nested: { value: 1 } },
|
||||
output: { ok: true },
|
||||
};
|
||||
const projection = {
|
||||
...v2Projection,
|
||||
turnItems: [item],
|
||||
visibleTurnItems: [
|
||||
{
|
||||
position: 0,
|
||||
visibility: "local" as const,
|
||||
sourceThreadId: v2Projection.thread.id,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
},
|
||||
],
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const thread = presentThread(environmentId, projection);
|
||||
expect(thread.workEntries[0]).toMatchObject({
|
||||
itemType: "dynamic_tool",
|
||||
label: "custom_tool",
|
||||
structuredPayload: item,
|
||||
});
|
||||
expect(merged?.messages).toBe(messages);
|
||||
});
|
||||
|
||||
it("preserves untouched project and thread identities across unrelated shell updates", () => {
|
||||
const harness = makeHarness();
|
||||
const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID);
|
||||
const threadRefsAtom = harness.threadShells.environmentThreadRefsAtom(ENVIRONMENT_ID);
|
||||
const projectsAtom = harness.projects.projectsAtom;
|
||||
const projectAtom = harness.projects.projectAtom({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
});
|
||||
const threadAtom = harness.threadShells.threadShellAtom({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
threadId: THREAD_ID,
|
||||
});
|
||||
const projectRefs = harness.registry.get(projectRefsAtom);
|
||||
const threadRefs = harness.registry.get(threadRefsAtom);
|
||||
const projects = harness.registry.get(projectsAtom);
|
||||
const project = harness.registry.get(projectAtom);
|
||||
const thread = harness.registry.get(threadAtom);
|
||||
|
||||
harness.registry.set(
|
||||
harness.shellStateAtom,
|
||||
AsyncResult.success(
|
||||
shellState({
|
||||
...SNAPSHOT,
|
||||
snapshotSequence: 2,
|
||||
threads: SNAPSHOT.threads.map((candidate) =>
|
||||
candidate.id === OTHER_THREAD_ID
|
||||
? { ...candidate, title: "Renamed other thread" }
|
||||
: candidate,
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(harness.registry.get(projectRefsAtom)).toBe(projectRefs);
|
||||
expect(harness.registry.get(threadRefsAtom)).toBe(threadRefs);
|
||||
expect(harness.registry.get(projectsAtom)).toBe(projects);
|
||||
expect(harness.registry.get(projectAtom)).toBe(project);
|
||||
expect(harness.registry.get(threadAtom)).toBe(thread);
|
||||
});
|
||||
|
||||
it("preserves project-scoped thread collections across unrelated project updates", () => {
|
||||
const harness = makeHarness();
|
||||
const projectRef = {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
};
|
||||
const refsByProjectAtom =
|
||||
harness.threadShells.environmentThreadRefsByProjectAtom(ENVIRONMENT_ID);
|
||||
const threadsAtom = harness.threadShells.threadShellsForProjectRefsAtom([projectRef]);
|
||||
const refs = harness.registry.get(refsByProjectAtom).get(PROJECT_ID);
|
||||
const threads = harness.registry.get(threadsAtom);
|
||||
|
||||
expect(threads).toHaveLength(1);
|
||||
expect(threads[0]?.id).toBe(THREAD_ID);
|
||||
|
||||
harness.registry.set(
|
||||
harness.shellStateAtom,
|
||||
AsyncResult.success(
|
||||
shellState({
|
||||
...SNAPSHOT,
|
||||
snapshotSequence: 2,
|
||||
threads: SNAPSHOT.threads.map((thread) =>
|
||||
thread.id === OTHER_THREAD_ID ? { ...thread, title: "Updated elsewhere" } : thread,
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(harness.registry.get(refsByProjectAtom).get(PROJECT_ID)).toBe(refs);
|
||||
expect(harness.registry.get(threadsAtom)).toBe(threads);
|
||||
});
|
||||
|
||||
it("updates only the requested thread detail and preserves untouched field identities", () => {
|
||||
const harness = makeHarness();
|
||||
const threadRef = {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
threadId: THREAD_ID,
|
||||
};
|
||||
const otherThreadRef = {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
threadId: OTHER_THREAD_ID,
|
||||
};
|
||||
const threadDetailAtom = harness.threadDetails.detailAtom(threadRef);
|
||||
const messagesAtom = harness.threadDetails.messagesAtom(threadRef);
|
||||
const activitiesAtom = harness.threadDetails.activitiesAtom(threadRef);
|
||||
const statusAtom = harness.threadDetails.statusAtom(threadRef);
|
||||
const otherThreadDetailAtom = harness.threadDetails.detailAtom(otherThreadRef);
|
||||
const otherValue = harness.registry.get(otherThreadDetailAtom);
|
||||
const detail = {
|
||||
...THREAD_SHELL,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
} satisfies OrchestrationThread;
|
||||
|
||||
harness.registry.set(
|
||||
harness.threadStateAtom(THREAD_ID),
|
||||
AsyncResult.success<EnvironmentThreadState>({
|
||||
data: Option.some(detail),
|
||||
status: "live",
|
||||
error: Option.none(),
|
||||
}),
|
||||
);
|
||||
|
||||
const scopedDetail = harness.registry.get(threadDetailAtom);
|
||||
const messages = harness.registry.get(messagesAtom);
|
||||
const activities = harness.registry.get(activitiesAtom);
|
||||
|
||||
expect(scopedDetail).toEqual({ ...detail, environmentId: ENVIRONMENT_ID });
|
||||
expect(harness.registry.get(statusAtom)).toBe("live");
|
||||
expect(harness.registry.get(otherThreadDetailAtom)).toBe(otherValue);
|
||||
|
||||
harness.registry.set(
|
||||
harness.threadStateAtom(THREAD_ID),
|
||||
AsyncResult.success<EnvironmentThreadState>({
|
||||
data: Option.some({
|
||||
...detail,
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-06-01T00:01:00.000Z",
|
||||
},
|
||||
}),
|
||||
status: "live",
|
||||
error: Option.none(),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(harness.registry.get(messagesAtom)).toBe(messages);
|
||||
expect(harness.registry.get(activitiesAtom)).toBe(activities);
|
||||
});
|
||||
});
|
||||
@@ -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<ChatAttachment>;
|
||||
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<ThreadUserInputQuestion>;
|
||||
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<string>;
|
||||
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<ThreadRunSummary>;
|
||||
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<ThreadConversationMessage>;
|
||||
readonly workEntries: ReadonlyArray<ThreadWorkEntry>;
|
||||
readonly proposedPlans: ReadonlyArray<ThreadProposedPlan>;
|
||||
readonly todoPlans: ReadonlyArray<ThreadTodoPlan>;
|
||||
readonly pendingApprovals: ReadonlyArray<ThreadPendingApproval>;
|
||||
readonly pendingUserInputs: ReadonlyArray<ThreadPendingUserInput>;
|
||||
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
|
||||
}
|
||||
|
||||
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<string>;
|
||||
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<ThreadWorkEntry> {
|
||||
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<ThreadRunSummary> {
|
||||
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<ThreadConversationMessage> {
|
||||
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<ThreadProposedPlan> {
|
||||
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<ThreadTodoPlan> {
|
||||
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<ThreadPendingApproval>;
|
||||
readonly userInputs: ReadonlyArray<ThreadPendingUserInput>;
|
||||
} {
|
||||
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<ThreadCheckpointSummary> {
|
||||
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;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ORCHESTRATION_V2_WS_METHODS, ORCHESTRATION_WS_METHODS } from "@t3tools/contracts";
|
||||
import { ORCHESTRATION_V2_WS_METHODS } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import {
|
||||
@@ -35,15 +35,15 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
|
||||
},
|
||||
turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:orchestration:turn-diff",
|
||||
tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
|
||||
tag: ORCHESTRATION_V2_WS_METHODS.getTurnDiff,
|
||||
}),
|
||||
fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:orchestration:full-thread-diff",
|
||||
tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff,
|
||||
tag: ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff,
|
||||
}),
|
||||
archivedShellSnapshot: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:orchestration:archived-shell-snapshot",
|
||||
tag: ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
|
||||
tag: ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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. */
|
||||
|
||||
@@ -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: [],
|
||||
};
|
||||
@@ -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<EnvironmentCatalogState>;
|
||||
readonly snapshotAtom: (
|
||||
environmentId: EnvironmentId,
|
||||
) => Atom.Atom<OrchestrationShellSnapshot | null>;
|
||||
) => Atom.Atom<OrchestrationV2ShellSnapshot | null>;
|
||||
}) {
|
||||
const environmentProjectsAtom = Atom.family((environmentId: EnvironmentId) =>
|
||||
Atom.make(
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import {
|
||||
EnvironmentId,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationShellStreamItem,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ShellStreamItem,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -21,6 +21,7 @@ import * as Persistence from "../platform/persistence.ts";
|
||||
import * as RpcSession from "../rpc/session.ts";
|
||||
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
|
||||
import { makeEnvironmentShellState } from "./shell.ts";
|
||||
import { v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts";
|
||||
|
||||
const TARGET = new PrimaryConnectionTarget({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
@@ -29,11 +30,9 @@ const TARGET = new PrimaryConnectionTarget({
|
||||
wsBaseUrl: "wss://environment.example.test",
|
||||
});
|
||||
|
||||
const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = {
|
||||
const LIVE_SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
|
||||
...v2ShellSnapshot,
|
||||
snapshotSequence: 1,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: "2026-06-06T00:00:00.000Z",
|
||||
};
|
||||
|
||||
function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
|
||||
@@ -49,9 +48,9 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
|
||||
describe("environment shell synchronization", () => {
|
||||
it.effect("publishes live state before persistence and preserves it when ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const events = yield* Queue.unbounded<OrchestrationShellStreamItem>();
|
||||
const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();
|
||||
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<Option.Option<RpcSession.RpcSession>>(
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import {
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
type EnvironmentId,
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationShellStreamItem,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ShellStreamItem,
|
||||
type ServerConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Queue from "effect/Queue";
|
||||
@@ -26,7 +27,7 @@ import { followStreamInEnvironment } from "./runtime.ts";
|
||||
export type EnvironmentShellStatus = "empty" | "cached" | "synchronizing" | "live";
|
||||
|
||||
export interface EnvironmentShellState {
|
||||
readonly snapshot: Option.Option<OrchestrationShellSnapshot>;
|
||||
readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;
|
||||
readonly status: EnvironmentShellStatus;
|
||||
readonly error: Option.Option<string>;
|
||||
}
|
||||
@@ -38,7 +39,7 @@ const EMPTY_SHELL_STATE: EnvironmentShellState = {
|
||||
};
|
||||
|
||||
function shellStatusForSnapshot(
|
||||
snapshot: Option.Option<OrchestrationShellSnapshot>,
|
||||
snapshot: Option.Option<OrchestrationV2ShellSnapshot>,
|
||||
): EnvironmentShellStatus {
|
||||
return Option.isSome(snapshot) ? "cached" : "empty";
|
||||
}
|
||||
@@ -56,7 +57,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
|
||||
environmentId,
|
||||
...safeErrorLogAttributes(error),
|
||||
}),
|
||||
Effect.as(Option.none<OrchestrationShellSnapshot>()),
|
||||
Effect.as(Option.none<OrchestrationV2ShellSnapshot>()),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -65,10 +66,10 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
|
||||
status: shellStatusForSnapshot(cachedSnapshot),
|
||||
error: Option.none(),
|
||||
});
|
||||
const persistence = yield* Queue.sliding<OrchestrationShellSnapshot>(1);
|
||||
const persistence = yield* Queue.sliding<OrchestrationV2ShellSnapshot>(1);
|
||||
|
||||
const persist = Effect.fn("EnvironmentShellState.persist")(function* (
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
snapshot: OrchestrationV2ShellSnapshot,
|
||||
) {
|
||||
yield* cache.saveShell(environmentId, snapshot).pipe(
|
||||
Effect.catch((error) =>
|
||||
@@ -122,7 +123,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
|
||||
);
|
||||
|
||||
const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* (
|
||||
item: OrchestrationShellStreamItem,
|
||||
item: OrchestrationV2ShellStreamItem,
|
||||
) {
|
||||
const current = yield* SubscriptionRef.get(state);
|
||||
const nextSnapshot =
|
||||
@@ -148,7 +149,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
|
||||
});
|
||||
|
||||
yield* subscribe(
|
||||
ORCHESTRATION_WS_METHODS.subscribeShell,
|
||||
ORCHESTRATION_V2_WS_METHODS.subscribeShell,
|
||||
{},
|
||||
{
|
||||
onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
|
||||
@@ -249,8 +250,20 @@ export function createEnvironmentShellSummaryAtom(input: {
|
||||
continue;
|
||||
}
|
||||
hasSnapshot = true;
|
||||
const updatedAt = state.snapshot.value.updatedAt;
|
||||
if (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) {
|
||||
const snapshot = state.snapshot.value;
|
||||
const updatedAt = snapshot.threads.concat(snapshot.archivedThreads).reduce<string | null>(
|
||||
(latest, thread) => {
|
||||
const value = DateTime.formatIso(thread.updatedAt);
|
||||
return latest === null || value > latest ? value : latest;
|
||||
},
|
||||
snapshot.projects.reduce<string | null>((latest, project) => {
|
||||
return latest === null || project.updatedAt > latest ? project.updatedAt : latest;
|
||||
}, null),
|
||||
);
|
||||
if (
|
||||
updatedAt !== null &&
|
||||
(latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt)
|
||||
) {
|
||||
latestSnapshotUpdatedAt = updatedAt;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,183 +1,84 @@
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
|
||||
|
||||
import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
|
||||
import { applyShellStreamEvent } from "./shellReducer.ts";
|
||||
|
||||
const baseSnapshot: OrchestrationShellSnapshot = {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
const stubProject = {
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Test Project",
|
||||
workspaceRoot: "/workspace/test",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
} as const;
|
||||
|
||||
const stubThread = {
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Test Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access" as const,
|
||||
interactionMode: "default" as const,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
session: null,
|
||||
} as const;
|
||||
|
||||
describe("applyShellStreamEvent", () => {
|
||||
it("ignores stale project upserts without mutating the snapshot", () => {
|
||||
const snapshotWithProject: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
it("ignores stale project updates without mutating the snapshot", () => {
|
||||
const snapshotWithProject = {
|
||||
...v2ShellSnapshot,
|
||||
snapshotSequence: 4,
|
||||
projects: [stubProject],
|
||||
projects: [v2Project],
|
||||
};
|
||||
|
||||
for (const sequence of [3, 4]) {
|
||||
const next = applyShellStreamEvent(snapshotWithProject, {
|
||||
kind: "project-upserted",
|
||||
kind: "project.updated",
|
||||
sequence,
|
||||
project: { ...stubProject, title: "Stale Title" },
|
||||
project: { ...v2Project, title: "Stale Title" },
|
||||
});
|
||||
|
||||
expect(next).toBe(snapshotWithProject);
|
||||
expect(next.snapshotSequence).toBe(4);
|
||||
expect(next.projects[0]?.title).toBe("Test Project");
|
||||
expect(next.projects[0]?.title).toBe(v2Project.title);
|
||||
}
|
||||
});
|
||||
|
||||
describe("project-upserted", () => {
|
||||
it("adds a new project", () => {
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "project-upserted",
|
||||
sequence: 1,
|
||||
project: stubProject,
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(baseSnapshot, event);
|
||||
|
||||
expect(next.projects).toHaveLength(1);
|
||||
expect(next.projects[0]?.id).toBe("project-1");
|
||||
expect(next.snapshotSequence).toBe(1);
|
||||
it("applies project updates and removals", () => {
|
||||
const updated = applyShellStreamEvent(v2ShellSnapshot, {
|
||||
kind: "project.updated",
|
||||
sequence: 1,
|
||||
project: { ...v2Project, title: "Updated" },
|
||||
});
|
||||
expect(updated.projects[0]?.title).toBe("Updated");
|
||||
expect(updated.snapshotSequence).toBe(1);
|
||||
|
||||
it("updates an existing project", () => {
|
||||
const snapshotWithProject: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
projects: [stubProject],
|
||||
};
|
||||
|
||||
const updatedProject = { ...stubProject, title: "Updated Title" };
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "project-upserted",
|
||||
sequence: 2,
|
||||
project: updatedProject,
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(snapshotWithProject, event);
|
||||
|
||||
expect(next.projects).toHaveLength(1);
|
||||
expect(next.projects[0]?.title).toBe("Updated Title");
|
||||
expect(next.snapshotSequence).toBe(2);
|
||||
const removed = applyShellStreamEvent(updated, {
|
||||
kind: "project.removed",
|
||||
sequence: 2,
|
||||
projectId: ProjectId.make(v2Project.id),
|
||||
});
|
||||
expect(removed.projects).toEqual([]);
|
||||
});
|
||||
|
||||
describe("project-removed", () => {
|
||||
it("removes a project by id", () => {
|
||||
const snapshotWithProject: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
projects: [stubProject],
|
||||
};
|
||||
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "project-removed",
|
||||
sequence: 3,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(snapshotWithProject, event);
|
||||
|
||||
expect(next.projects).toHaveLength(0);
|
||||
expect(next.snapshotSequence).toBe(3);
|
||||
it("moves a thread between active and archive without duplicating it", () => {
|
||||
const archived = applyShellStreamEvent(v2ShellSnapshot, {
|
||||
kind: "thread.updated",
|
||||
sequence: 3,
|
||||
location: "archive",
|
||||
thread: { ...v2ThreadShell, archivedAt: v2ThreadShell.updatedAt },
|
||||
});
|
||||
expect(archived.threads).toEqual([]);
|
||||
expect(archived.archivedThreads).toHaveLength(1);
|
||||
|
||||
const active = applyShellStreamEvent(archived, {
|
||||
kind: "thread.updated",
|
||||
sequence: 4,
|
||||
location: "active",
|
||||
thread: v2ThreadShell,
|
||||
});
|
||||
expect(active.threads).toHaveLength(1);
|
||||
expect(active.archivedThreads).toEqual([]);
|
||||
});
|
||||
|
||||
describe("thread-upserted", () => {
|
||||
it("adds a new thread", () => {
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "thread-upserted",
|
||||
sequence: 4,
|
||||
thread: stubThread,
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(baseSnapshot, event);
|
||||
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.id).toBe("thread-1");
|
||||
expect(next.snapshotSequence).toBe(4);
|
||||
});
|
||||
|
||||
it("updates an existing thread", () => {
|
||||
const snapshotWithThread: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
threads: [stubThread],
|
||||
};
|
||||
|
||||
const updatedThread = { ...stubThread, title: "Updated Thread" };
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "thread-upserted",
|
||||
sequence: 5,
|
||||
thread: updatedThread,
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(snapshotWithThread, event);
|
||||
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.title).toBe("Updated Thread");
|
||||
it("removes a thread from either collection", () => {
|
||||
const next = applyShellStreamEvent(v2ShellSnapshot, {
|
||||
kind: "thread.removed",
|
||||
sequence: 5,
|
||||
location: "active",
|
||||
threadId: ThreadId.make(v2ThreadShell.id),
|
||||
});
|
||||
expect(next.threads).toEqual([]);
|
||||
expect(next.snapshotSequence).toBe(5);
|
||||
});
|
||||
|
||||
describe("thread-removed", () => {
|
||||
it("removes a thread by id", () => {
|
||||
const snapshotWithThread: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
threads: [stubThread],
|
||||
};
|
||||
it("leaves unknown future events unchanged", () => {
|
||||
const next = applyShellStreamEvent(
|
||||
v2ShellSnapshot,
|
||||
{ kind: "future.event", sequence: 99 } as never,
|
||||
);
|
||||
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "thread-removed",
|
||||
sequence: 6,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(snapshotWithThread, event);
|
||||
|
||||
expect(next.threads).toHaveLength(0);
|
||||
expect(next.snapshotSequence).toBe(6);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns original snapshot for unrecognized event kinds", () => {
|
||||
const unknownEvent = { kind: "unknown-future-event", sequence: 99 } as any;
|
||||
const next = applyShellStreamEvent(baseSnapshot, unknownEvent);
|
||||
expect(next).toBe(baseSnapshot);
|
||||
expect(next).toBe(v2ShellSnapshot);
|
||||
});
|
||||
});
|
||||
@@ -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<T extends { readonly id: unknown }>(
|
||||
items: ReadonlyArray<T>,
|
||||
item: T,
|
||||
): ReadonlyArray<T> {
|
||||
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<OrchestrationV2ShellStreamItem, { readonly kind: "snapshot" }>,
|
||||
): 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:
|
||||
|
||||
@@ -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<E>(
|
||||
) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, E>>,
|
||||
) {
|
||||
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),
|
||||
|
||||
@@ -44,6 +44,7 @@ export type {
|
||||
SetThreadRuntimeModeInput,
|
||||
StartThreadTurnInput,
|
||||
StopThreadSessionInput,
|
||||
ThreadCommandInput,
|
||||
UnarchiveThreadInput,
|
||||
UpdateThreadMetadataInput,
|
||||
} from "../operations/commands.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<EnvironmentThreadState, never> = 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();
|
||||
});
|
||||
});
|
||||
Loaded 100 of 111 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user