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
1bbbaafb1e
commit
f456ee9630
110 files changed
+7068
-10956
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.
|
||||
|
||||
@@ -2,6 +2,11 @@ import {
|
||||
ConnectionPersistenceError,
|
||||
ConnectionRegistrationStore,
|
||||
ConnectionTargetStore,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
decodeOrDiscardOrchestrationCache,
|
||||
registerConnectionInCatalog,
|
||||
removeConnectionFromCatalog,
|
||||
removeCatalogValue,
|
||||
@@ -13,11 +18,88 @@ import {
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as CatalogStore from "./catalog-store";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SecureStore from "expo-secure-store";
|
||||
|
||||
import { makeCatalogStore, type SecureCatalogStorage } from "./catalog-store";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
|
||||
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
|
||||
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
|
||||
|
||||
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
|
||||
const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot);
|
||||
const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot);
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot);
|
||||
|
||||
function catalogError(operation: string, cause: unknown) {
|
||||
return new ConnectionTransientError({
|
||||
reason: "remote-unavailable",
|
||||
detail: `Could not ${operation} the local connection catalog: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function shellPersistenceError(
|
||||
operation:
|
||||
| "load-shell"
|
||||
| "save-shell"
|
||||
| "load-thread"
|
||||
| "save-thread"
|
||||
| "remove-thread"
|
||||
| "clear-environment",
|
||||
cause: unknown,
|
||||
) {
|
||||
return new ConnectionPersistenceError({
|
||||
operation,
|
||||
message: `Could not ${operation.replaceAll("-", " ")}: ${String(cause)}`,
|
||||
});
|
||||
}
|
||||
|
||||
function threadSnapshotFileName(threadId: ThreadId): string {
|
||||
return `${encodeURIComponent(threadId)}.json`;
|
||||
}
|
||||
|
||||
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
|
||||
function* (
|
||||
environmentId: EnvironmentId,
|
||||
operation: "load-thread" | "save-thread" | "remove-thread" | "clear-environment",
|
||||
) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: async () => {
|
||||
const { Directory, Paths } = await import("expo-file-system");
|
||||
const directory = new Directory(
|
||||
Paths.document,
|
||||
THREAD_SNAPSHOT_CACHE_DIRECTORY,
|
||||
encodeURIComponent(environmentId),
|
||||
);
|
||||
if (operation !== "clear-environment") {
|
||||
directory.create({ idempotent: true, intermediates: true });
|
||||
}
|
||||
return directory;
|
||||
},
|
||||
catch: (cause) => shellPersistenceError(operation, cause),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const threadSnapshotFile = Effect.fn("mobile.connectionStorage.threadSnapshotFile")(function* (
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
operation: "load-thread" | "save-thread" | "remove-thread",
|
||||
) {
|
||||
const { File } = yield* Effect.promise(() => import("expo-file-system"));
|
||||
return new File(
|
||||
yield* threadSnapshotDirectory(environmentId, operation),
|
||||
threadSnapshotFileName(threadId),
|
||||
);
|
||||
});
|
||||
|
||||
function targetPersistenceError(
|
||||
operation: "list-targets" | "register-connection" | "remove-connection",
|
||||
@@ -128,6 +210,172 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
),
|
||||
})),
|
||||
});
|
||||
const cacheStore = EnvironmentCacheStore.of({
|
||||
loadShell: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "load-shell");
|
||||
if (file.exists) {
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-shell", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none();
|
||||
}
|
||||
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "load-shell");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
});
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
}).pipe((decode) =>
|
||||
decodeOrDiscardOrchestrationCache(
|
||||
decode,
|
||||
shellSnapshotFile(environmentId, "load-shell").pipe(
|
||||
Effect.flatMap((file) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (file.exists) file.delete();
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("load-shell", cause),
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.void),
|
||||
),
|
||||
),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "save-shell");
|
||||
const stored = {
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
} as const;
|
||||
const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("save-shell", cause)),
|
||||
);
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-shell", cause),
|
||||
});
|
||||
}),
|
||||
loadThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
|
||||
if (!file.exists) {
|
||||
return Option.none();
|
||||
}
|
||||
const raw = yield* Effect.tryPromise({
|
||||
try: () => file.text(),
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const parsed = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
});
|
||||
const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe(
|
||||
Effect.mapError((cause) => shellPersistenceError("load-thread", cause)),
|
||||
);
|
||||
return stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none();
|
||||
}).pipe((decode) =>
|
||||
decodeOrDiscardOrchestrationCache(
|
||||
decode,
|
||||
threadSnapshotFile(environmentId, threadId, "load-thread").pipe(
|
||||
Effect.flatMap((file) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (file.exists) file.delete();
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("load-thread", cause),
|
||||
}),
|
||||
),
|
||||
Effect.catch(() => Effect.void),
|
||||
),
|
||||
),
|
||||
),
|
||||
saveThread: (environmentId, thread) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, thread.thread.id, "save-thread");
|
||||
const encoded = yield* Effect.fromResult(
|
||||
encodeStoredThreadSnapshot({
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId: thread.thread.id,
|
||||
thread,
|
||||
}),
|
||||
).pipe(Effect.mapError((cause) => shellPersistenceError("save-thread", cause)));
|
||||
yield* Effect.try({
|
||||
try: () => {
|
||||
if (!file.exists) {
|
||||
file.create({ intermediates: true, overwrite: true });
|
||||
}
|
||||
file.write(JSON.stringify(encoded));
|
||||
},
|
||||
catch: (cause) => shellPersistenceError("save-thread", cause),
|
||||
});
|
||||
}),
|
||||
removeThread: (environmentId, threadId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
|
||||
if (file.exists) {
|
||||
file.delete();
|
||||
}
|
||||
}).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: shellPersistenceError("remove-thread", cause),
|
||||
),
|
||||
),
|
||||
clear: (environmentId) =>
|
||||
Effect.gen(function* () {
|
||||
const file = yield* shellSnapshotFile(environmentId, "clear-environment");
|
||||
if (file.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => file.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const legacyFile = yield* legacyShellSnapshotFile(environmentId, "clear-environment");
|
||||
if (legacyFile.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => legacyFile.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
const threadDirectory = yield* threadSnapshotDirectory(
|
||||
environmentId,
|
||||
"clear-environment",
|
||||
);
|
||||
if (threadDirectory.exists) {
|
||||
yield* Effect.try({
|
||||
try: () => threadDirectory.delete(),
|
||||
catch: (cause) => shellPersistenceError("clear-environment", cause),
|
||||
});
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
return Context.make(ConnectionTargetStore, targetStore).pipe(
|
||||
Context.add(ConnectionRegistrationStore, registrationStore),
|
||||
Context.add(ProfileStore.ConnectionProfileStore, profileStore),
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { buildArchivedThreadGroups } from "./archivedThreadList";
|
||||
import { makeRawThreadShell } from "../../test-fixtures";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
@@ -22,42 +24,30 @@ function makeProject(
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThreadShell> &
|
||||
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: "2026-06-02T00:00:00.000Z",
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
input: Pick<OrchestrationV2ThreadShell, "id" | "projectId" | "title"> & {
|
||||
readonly branch?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
},
|
||||
): OrchestrationV2ThreadShell {
|
||||
const archivedAt = input.archivedAt === undefined ? "2026-06-02T00:00:00.000Z" : input.archivedAt;
|
||||
return makeRawThreadShell({
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
archivedAt: archivedAt === null ? null : DateTime.makeUnsafe(archivedAt),
|
||||
});
|
||||
}
|
||||
|
||||
function makeSnapshot(
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
|
||||
targetEnvironmentId = environmentId,
|
||||
): ArchivedSnapshotEntry {
|
||||
return {
|
||||
environmentId: targetEnvironmentId,
|
||||
snapshot: {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 1,
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -123,14 +123,51 @@ interface HomeScreenProps {
|
||||
|
||||
/* ─── Layout constants ───────────────────────────────────────────────── */
|
||||
|
||||
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
|
||||
const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44;
|
||||
/**
|
||||
* Top spacing between the list and the Android custom header. The Android
|
||||
* header (AndroidHomeHeader) is rendered in-flow above this screen and
|
||||
* already consumes the top safe-area inset, so the list only needs breathing
|
||||
* room here.
|
||||
*/
|
||||
function statusColors(thread: EnvironmentThreadShell): { bg: string; fg: string } {
|
||||
switch (thread.runtime?.status) {
|
||||
case "running":
|
||||
case "waiting":
|
||||
return { bg: "rgba(249,115,22,0.14)", fg: "#f97316" };
|
||||
case "completed":
|
||||
return { bg: "rgba(34,197,94,0.14)", fg: "#22c55e" };
|
||||
case "queued":
|
||||
case "starting":
|
||||
return { bg: "rgba(59,130,246,0.14)", fg: "#3b82f6" };
|
||||
case "failed":
|
||||
return { bg: "rgba(239,68,68,0.14)", fg: "#ef4444" };
|
||||
default:
|
||||
return { bg: "rgba(163,163,163,0.10)", fg: "#a3a3a3" };
|
||||
}
|
||||
}
|
||||
|
||||
const COLLAPSED_THREAD_LIMIT = 6;
|
||||
const THREAD_LAYOUT_TRANSITION = LinearTransition.duration(220).easing(Easing.out(Easing.cubic));
|
||||
|
||||
function threadRowExit(values: ExitAnimationsValues) {
|
||||
"worklet";
|
||||
|
||||
return {
|
||||
initialValues: {
|
||||
height: values.currentHeight,
|
||||
opacity: 1,
|
||||
originX: values.currentOriginX,
|
||||
},
|
||||
animations: {
|
||||
height: withDelay(
|
||||
90,
|
||||
withTiming(0, {
|
||||
duration: 170,
|
||||
easing: Easing.inOut(Easing.cubic),
|
||||
}),
|
||||
),
|
||||
opacity: withDelay(80, withTiming(0, { duration: 100 })),
|
||||
originX: withTiming(values.currentOriginX - values.windowWidth, {
|
||||
duration: 190,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function deriveEmptyState(props: {
|
||||
readonly catalogState: WorkspaceState;
|
||||
@@ -190,7 +227,7 @@ function deriveEmptyState(props: {
|
||||
|
||||
return {
|
||||
title: "No threads yet",
|
||||
detail: "Create a task to start a new coding session in one of your connected projects.",
|
||||
detail: "Create a task to start a new coding runtime in one of your connected projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
@@ -1071,6 +1108,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
variant="plain"
|
||||
/>
|
||||
<<<<<<< HEAD
|
||||
{emptyState.loading ? (
|
||||
<View className="mt-4 items-center">
|
||||
<ActivityIndicator color={accentColor} />
|
||||
@@ -1080,6 +1118,19 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
</View>
|
||||
);
|
||||
}
|
||||
=======
|
||||
) : !hasResults ? (
|
||||
<EmptyState
|
||||
title="No threads yet"
|
||||
detail="Create a task to start a new coding runtime."
|
||||
/>
|
||||
) : (
|
||||
projectGroups.map((group) => {
|
||||
const isExpanded = expandedProjects.has(group.key);
|
||||
const visibleThreads = isExpanded
|
||||
? group.threads
|
||||
: group.threads.slice(0, COLLAPSED_THREAD_LIMIT);
|
||||
>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover)
|
||||
|
||||
const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
|
||||
|
||||
|
||||
@@ -6,11 +6,8 @@ import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-searc
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
import { buildHomeThreadGroups } from "./homeThreadList";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -30,25 +27,21 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
|
||||
|
||||
@@ -1,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,16 +6,21 @@ import type { PendingApproval } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingApprovalCardProps {
|
||||
readonly approval: PendingApproval;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly onRespond: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
<<<<<<< HEAD
|
||||
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
|
||||
// behind this card, so a translucent surface bleeds messages through it.
|
||||
=======
|
||||
const canRespond = props.approval.responseCapability === "live";
|
||||
const disabled = !canRespond || props.respondingApprovalId === props.approval.requestId;
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
@@ -29,17 +34,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">
|
||||
@@ -48,7 +59,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,342 +1,118 @@
|
||||
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
|
||||
import Animated, {
|
||||
Easing,
|
||||
FadeInUp,
|
||||
FadeOutDown,
|
||||
LinearTransition,
|
||||
useAnimatedStyle,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import type { RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import {
|
||||
isPendingUserInputOptionSelected,
|
||||
type PendingUserInput,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingUserInputCardProps {
|
||||
readonly pendingUserInput: PendingUserInput;
|
||||
/**
|
||||
* Constant while a request is pending (it reserves keyboard space), so the
|
||||
* keyboard transition is pure translation; changes only on rare discrete
|
||||
* corrections, which the layout transition smooths.
|
||||
*/
|
||||
readonly maxHeight: number;
|
||||
readonly collapsed: boolean;
|
||||
readonly onToggleCollapsed: () => void;
|
||||
/** Renders a stop control on the collapsed bar, which replaces the composer. */
|
||||
readonly onStopThread?: () => void;
|
||||
/**
|
||||
* 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the
|
||||
* collapsed bar (inside a clipping window) on the UI thread; the host
|
||||
* animates it directly from the tap handler so the card and the feed
|
||||
* inset glide start the same frame.
|
||||
*/
|
||||
readonly cardProgress?: SharedValue<number>;
|
||||
/**
|
||||
* Receives how far the expanded card extends above the bar footprint
|
||||
* (written from onLayout with no re-render); the host adds it to the
|
||||
* thread feed's end inset so the end of the chat stays visible above the
|
||||
* card.
|
||||
*/
|
||||
readonly cardCoverage?: SharedValue<number>;
|
||||
/** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */
|
||||
readonly onInputFocusChange?: (focused: boolean) => void;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly answers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly onSelectOption: (requestId: RuntimeRequestId, questionId: string, label: string) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
readonly onSubmit: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
/**
|
||||
* On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
|
||||
* card is an absolutely-positioned overlay rising above it. The overlay's
|
||||
* measured height (which drives the thread feed's bottom inset) therefore
|
||||
* never changes on collapse/expand, so the transcript stays perfectly still
|
||||
* while the card animates over it.
|
||||
*
|
||||
* Android cannot use the overlay: it does not hit-test touches outside a
|
||||
* parent's bounds, which made everything above the bar-sized wrapper
|
||||
* untouchable. There the expanded card renders in-flow instead (the wrapper
|
||||
* grows with it, and the host skips the coverage inset since the measured
|
||||
* overlay already includes the card).
|
||||
*/
|
||||
const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
|
||||
|
||||
const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
const questionCount = props.pendingUserInput.questions.length;
|
||||
|
||||
const cardCoverage = props.cardCoverage;
|
||||
const barHeightRef = useRef(0);
|
||||
const cardHeightRef = useRef(0);
|
||||
// Measured card height, written straight from onLayout: the collapse slide
|
||||
// distance. Not animated — it only changes on discrete relayouts.
|
||||
const cardHeight = useSharedValue(0);
|
||||
const notifyCoverage = useCallback(() => {
|
||||
if (!cardCoverage) {
|
||||
return;
|
||||
}
|
||||
const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
|
||||
if (coverage === cardCoverage.value) {
|
||||
return;
|
||||
}
|
||||
if (cardCoverage.value === 0) {
|
||||
// First measurement lands while the list is doing its initial
|
||||
// end-pin (thread opened onto a pending request); animating it from
|
||||
// zero would move the end anchor out from under that scroll.
|
||||
cardCoverage.value = coverage;
|
||||
return;
|
||||
}
|
||||
// Animated so a coverage change at rest (discrete max-height
|
||||
// corrections) glides the feed instead of stepping it; toggle timing is
|
||||
// owned by the host's progress values.
|
||||
cardCoverage.value = withTiming(coverage, {
|
||||
duration: USER_INPUT_TOGGLE_DURATION_MS,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
});
|
||||
}, [cardCoverage]);
|
||||
const handleBarLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
barHeightRef.current = event.nativeEvent.layout.height;
|
||||
notifyCoverage();
|
||||
},
|
||||
[notifyCoverage],
|
||||
);
|
||||
const handleCardLayout = useCallback(
|
||||
(event: LayoutChangeEvent) => {
|
||||
cardHeightRef.current = event.nativeEvent.layout.height;
|
||||
cardHeight.value = event.nativeEvent.layout.height;
|
||||
notifyCoverage();
|
||||
},
|
||||
[cardHeight, notifyCoverage],
|
||||
);
|
||||
const cardProgress = props.cardProgress;
|
||||
// No opacity: fading an opaque card over the live transcript reads as a
|
||||
// crossfade (card text, transcript, and bar all half-visible at once).
|
||||
// Instead the card stays opaque and slides its full height down past the
|
||||
// clipping window's bottom edge, so the transcript is only revealed where
|
||||
// the card has physically left.
|
||||
const cardAnimatedStyle = useAnimatedStyle(() => {
|
||||
const progress = cardProgress === undefined ? 1 : cardProgress.value;
|
||||
return {
|
||||
transform: [{ translateY: (1 - progress) * cardHeight.value }],
|
||||
};
|
||||
});
|
||||
|
||||
// On iOS the card stays MOUNTED while collapsed (hidden via the animated
|
||||
// style): expanding animates existing views on the UI thread the same
|
||||
// frame the host starts the progress timing, instead of paying a React
|
||||
// mount + layout before anything moves.
|
||||
const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
|
||||
const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
|
||||
// The bar renders UNDER the card (earlier in JSX), always opaque: while
|
||||
// expanded the opaque card covers it, and during the collapse slide the
|
||||
// card's top edge wipes past and reveals it — no opacity handoff, so no
|
||||
// crossfade frames.
|
||||
const bar = showBar ? (
|
||||
<View
|
||||
onLayout={handleBarLayout}
|
||||
pointerEvents={props.collapsed ? "auto" : "none"}
|
||||
accessibilityElementsHidden={!props.collapsed}
|
||||
importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
|
||||
className="flex-row items-center gap-2 rounded-full border border-neutral-200 bg-neutral-100 py-1.5 pl-4 pr-1.5 dark:border-white/6 dark:bg-neutral-900"
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Expand user input, ${questionCount} question${
|
||||
questionCount === 1 ? "" : "s"
|
||||
}`}
|
||||
onPress={props.onToggleCollapsed}
|
||||
className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
|
||||
>
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
<<<<<<< HEAD
|
||||
// The surface is opaque on purpose: the card floats over the thread feed
|
||||
// with no blur behind it, so a translucent background renders the questions
|
||||
// on top of whatever message happens to sit underneath.
|
||||
=======
|
||||
const canRespond = props.pendingUserInput.responseCapability === "live";
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
<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>
|
||||
<Text className="font-sans text-xs text-neutral-500 dark:text-neutral-400">
|
||||
{questionCount} question{questionCount === 1 ? "" : "s"}
|
||||
</Text>
|
||||
<View className="flex-1" />
|
||||
<SymbolView name="chevron.up" size={12} tintColor={iconSubtle} type="monochrome" />
|
||||
</Pressable>
|
||||
{props.onStopThread ? (
|
||||
<ControlPill
|
||||
accessibilityLabel="Stop"
|
||||
icon="stop.fill"
|
||||
variant="danger"
|
||||
className="h-9 w-9"
|
||||
onPress={props.onStopThread}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
) : null;
|
||||
const card = renderCard ? (
|
||||
// The surface is opaque on purpose: the card floats over the thread
|
||||
// feed with no blur behind it, so a translucent background renders
|
||||
// the questions on top of whatever message happens to sit underneath.
|
||||
<Animated.View
|
||||
onLayout={handleCardLayout}
|
||||
pointerEvents={props.collapsed ? "none" : "auto"}
|
||||
accessibilityElementsHidden={props.collapsed}
|
||||
importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
|
||||
entering={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? undefined
|
||||
: FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
|
||||
}
|
||||
exiting={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? undefined
|
||||
: FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
|
||||
}
|
||||
layout={CARD_LAYOUT_TRANSITION}
|
||||
className="overflow-hidden gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900"
|
||||
style={
|
||||
EXPANDED_CARD_IS_OVERLAY
|
||||
? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
|
||||
: { maxHeight: props.maxHeight }
|
||||
}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Collapse user input"
|
||||
onPress={props.onToggleCollapsed}
|
||||
className="flex-row items-start gap-2"
|
||||
>
|
||||
<View className="flex-1 gap-2.5">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
Fill in the pending answers
|
||||
</Text>
|
||||
</View>
|
||||
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/8">
|
||||
<SymbolView name="chevron.down" size={13} tintColor={iconSubtle} type="monochrome" />
|
||||
</View>
|
||||
</Pressable>
|
||||
<ScrollView
|
||||
bounces={false}
|
||||
className="min-h-0"
|
||||
contentContainerClassName="gap-2.5 pb-1"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
nestedScrollEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ flexShrink: 1 }}
|
||||
>
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
<View key={question.id} className="gap-2 pt-1">
|
||||
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
|
||||
{question.header}
|
||||
</Text>
|
||||
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
|
||||
{question.question}
|
||||
</Text>
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
{question.options.map((option) => {
|
||||
const selected = isPendingUserInputOptionSelected(draft, option.label);
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
<View key={question.id} className="gap-2 pt-1">
|
||||
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
|
||||
{question.header}
|
||||
</Text>
|
||||
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
|
||||
{question.question}
|
||||
</Text>
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
{question.options.map((option) => {
|
||||
const selected =
|
||||
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
disabled={!canRespond}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
|
||||
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
|
||||
)}
|
||||
onPress={() =>
|
||||
props.onSelectOption(
|
||||
props.pendingUserInput.requestId,
|
||||
question.id,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
"font-t3-bold text-sm",
|
||||
selected
|
||||
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
|
||||
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
|
||||
? "text-sky-700 dark:text-sky-300"
|
||||
: "text-neutral-600 dark:text-neutral-300",
|
||||
)}
|
||||
onPress={() =>
|
||||
props.onSelectOption(
|
||||
props.pendingUserInput.requestId,
|
||||
question,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-bold text-sm",
|
||||
selected
|
||||
? "text-sky-700 dark:text-sky-300"
|
||||
: "text-neutral-600 dark:text-neutral-300",
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
}
|
||||
onFocus={() => props.onInputFocusChange?.(true)}
|
||||
onBlur={() => props.onInputFocusChange?.(false)}
|
||||
placeholder="Or type a custom answer"
|
||||
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
|
||||
/>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
<TextInput
|
||||
editable={canRespond}
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
}
|
||||
placeholder="Or type a custom answer"
|
||||
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
<Pressable
|
||||
className={cn(
|
||||
"items-center justify-center rounded-2xl px-4 py-3.5",
|
||||
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()}
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
|
||||
</Pressable>
|
||||
</Animated.View>
|
||||
) : null;
|
||||
return (
|
||||
<View className="relative">
|
||||
{bar}
|
||||
{EXPANDED_CARD_IS_OVERLAY ? (
|
||||
// Clipping window for the collapse slide: same footprint as the
|
||||
// expanded card, bottom edge on the bar's bottom edge. The sliding
|
||||
// card exits through the bottom edge instead of drawing over the
|
||||
// composer area, wiping the bar (and the transcript) into view.
|
||||
<View
|
||||
pointerEvents={props.collapsed ? "none" : "box-none"}
|
||||
className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
|
||||
style={{ height: props.maxHeight }}
|
||||
>
|
||||
{card}
|
||||
</View>
|
||||
) : (
|
||||
card
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,12 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
@@ -13,7 +17,6 @@ import {
|
||||
serializeComposerFileLink,
|
||||
type ComposerTrigger,
|
||||
} from "@t3tools/shared/composerTrigger";
|
||||
import { StackActions, useFocusEffect, useNavigation } from "@react-navigation/native";
|
||||
import type { ReactNode } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
@@ -40,18 +43,17 @@ import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { GlassSurface } from "../../components/GlassSurface";
|
||||
import {
|
||||
ComposerEditor,
|
||||
type ComposerEditorHandle,
|
||||
type ComposerEditorSelection,
|
||||
} from "../../components/ComposerEditor";
|
||||
import {
|
||||
ComposerInlineControl,
|
||||
ComposerToolbarButton,
|
||||
ComposerToolbarRow,
|
||||
ComposerToolbarScroller,
|
||||
} from "../../components/ComposerToolbar";
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
@@ -66,14 +68,8 @@ import {
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
import {
|
||||
type ExistingThreadSettingsRouteSession,
|
||||
useExistingThreadSettingsRoutePresentation,
|
||||
} from "./ThreadSettingsSheet";
|
||||
import {
|
||||
useThreadSettingsSheetPresentation,
|
||||
type NavigationWithFinishTransitioning,
|
||||
} from "./use-thread-settings-sheet-presentation";
|
||||
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
|
||||
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
/**
|
||||
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
|
||||
@@ -85,7 +81,7 @@ export const COMPOSER_COLLAPSED_CHROME = 60;
|
||||
* Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
|
||||
* Used by the parent to compute the larger feed bottom inset when the composer is focused.
|
||||
*/
|
||||
export const COMPOSER_EXPANDED_CHROME = 156;
|
||||
export const COMPOSER_EXPANDED_CHROME = 174;
|
||||
|
||||
export interface ThreadComposerProps {
|
||||
readonly draftMessage: string;
|
||||
@@ -96,13 +92,7 @@ export interface ThreadComposerProps {
|
||||
readonly connectionState: RemoteClientConnectionState;
|
||||
readonly connectionError: string | null;
|
||||
readonly environmentLabel: string | null;
|
||||
/**
|
||||
* Message sync phase for the selected thread (drives the status pill):
|
||||
* "loading" = first fetch, nothing to show yet; "syncing" = cached messages
|
||||
* are on screen while they reconcile with the server.
|
||||
*/
|
||||
readonly threadSyncPhase?: "loading" | "syncing" | null;
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly queueCount: number;
|
||||
readonly environmentId: EnvironmentId;
|
||||
@@ -119,13 +109,11 @@ export interface ThreadComposerProps {
|
||||
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onReconnectEnvironment: () => void;
|
||||
readonly onExpandedChange?: (expanded: boolean) => void;
|
||||
/** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
|
||||
readonly onEditorFocusChange?: (focused: boolean) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pill / card container — renders with Expo's native GlassView on supported
|
||||
* iOS 26+ devices and keeps the existing opaque fallback elsewhere.
|
||||
* The pill / card container — renders as LiquidGlassView on supported
|
||||
* iOS 26+ devices (progressive blur, native morph), opaque View otherwise.
|
||||
* Exported so NewTaskDraftScreen can render the same composer chrome.
|
||||
*/
|
||||
// One timing for every piece of the expanded↔compact morph so the surface,
|
||||
@@ -141,8 +129,6 @@ export function ComposerSurface(props: {
|
||||
readonly children: ReactNode;
|
||||
readonly style: ViewStyle;
|
||||
readonly isDarkMode: boolean;
|
||||
/** Existing thread composers morph between pill and card layouts. */
|
||||
readonly animateLayout?: boolean;
|
||||
}) {
|
||||
// Drop shadow lives on a wrapper: `overflow: "hidden"` on the surface itself
|
||||
// (needed to clip content to the pill shape) would clip the shadow on iOS.
|
||||
@@ -155,26 +141,35 @@ export function ComposerSurface(props: {
|
||||
elevation: 10,
|
||||
};
|
||||
|
||||
if (isLiquidGlassSupported) {
|
||||
return (
|
||||
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
|
||||
<LiquidGlassView
|
||||
effect="regular"
|
||||
interactive
|
||||
colorScheme={props.isDarkMode ? "dark" : "light"}
|
||||
style={props.style}
|
||||
>
|
||||
{props.children}
|
||||
</LiquidGlassView>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
layout={props.animateLayout === false ? undefined : COMPOSER_LAYOUT_TRANSITION}
|
||||
style={shadowStyle}
|
||||
>
|
||||
<GlassSurface
|
||||
chrome="none"
|
||||
fallbackStyle={{
|
||||
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
|
||||
borderWidth: 1,
|
||||
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
|
||||
}}
|
||||
glassEffectStyle="regular"
|
||||
// The composer is a passive material containing interactive controls.
|
||||
// Expo GlassView defaults to non-interactive and both layouts share it.
|
||||
tintColor="transparent"
|
||||
style={props.style}
|
||||
<Animated.View layout={COMPOSER_LAYOUT_TRANSITION} style={shadowStyle}>
|
||||
<View
|
||||
style={[
|
||||
props.style,
|
||||
{
|
||||
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
|
||||
borderWidth: 1,
|
||||
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
|
||||
},
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</GlassSurface>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
@@ -265,7 +260,6 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
});
|
||||
|
||||
export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposerProps) {
|
||||
const navigation = useNavigation();
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
const bodyText = useScaledTextRole("body");
|
||||
@@ -276,16 +270,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
editorRef: inputRef,
|
||||
isEditorFocused: isFocused,
|
||||
});
|
||||
const settingsRoutePresentation = useExistingThreadSettingsRoutePresentation();
|
||||
const settingsRoutePresentedRef = useRef(false);
|
||||
const wasExpandedBeforePreviewRef = useRef(false);
|
||||
const inFlightThreadIdsRef = useRef(new Set<string>());
|
||||
const { onExpandedChange } = props;
|
||||
|
||||
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
|
||||
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
|
||||
// Opening and presentation count as active so the composer stays expanded
|
||||
// while focus moves between its native editor and the settings picker.
|
||||
// Opening and closing count as active so the composer stays expanded while
|
||||
// focus moves between its native editor and the settings modal.
|
||||
const isExpanded = isFocused || settingsSheetPresentation.isActive;
|
||||
const canSend = hasContent;
|
||||
|
||||
@@ -311,24 +303,28 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}
|
||||
}, [inputRef]);
|
||||
|
||||
const onEditorFocusChange = props.onEditorFocusChange;
|
||||
const handleFocus = useCallback(() => {
|
||||
setIsFocused(true);
|
||||
onEditorFocusChange?.(true);
|
||||
}, [onEditorFocusChange]);
|
||||
}, []);
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setIsFocused(false);
|
||||
onEditorFocusChange?.(false);
|
||||
}, [onEditorFocusChange]);
|
||||
<<<<<<< HEAD
|
||||
}, []);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
=======
|
||||
onExpandedChange?.(false);
|
||||
}, [onExpandedChange]);
|
||||
const showStopAction = threadRuntimeIsActive(props.selectedThread.runtime);
|
||||
>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover)
|
||||
|
||||
const sendLabel =
|
||||
props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
|
||||
const currentModelSelection = props.selectedThread.modelSelection;
|
||||
const currentRuntimeMode = props.selectedThread.runtimeMode;
|
||||
const currentInteractionMode = props.selectedThread.interactionMode ?? "default";
|
||||
const connectionStatus = composerConnectionStatus({
|
||||
connectionError: props.connectionError,
|
||||
connectionState: props.connectionState,
|
||||
@@ -538,7 +534,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
// after the send so its preference read and native Activity start don't
|
||||
// contend with the queued-message feedback on the tap frame.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: props.environmentId,
|
||||
threadTitle: props.selectedThread.title,
|
||||
projectTitle: props.environmentLabel ?? "T3 Code",
|
||||
});
|
||||
@@ -621,71 +616,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}),
|
||||
[currentModelOption?.capabilities, currentModelSelection.options],
|
||||
);
|
||||
const settingsOwnerId = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const settingsRouteSession = useMemo<ExistingThreadSettingsRouteSession>(
|
||||
() => ({
|
||||
ownerId: settingsOwnerId,
|
||||
providerGroups: threadProviderGroups,
|
||||
selectedModel: currentModelSelection,
|
||||
onSelectModel: (option) => props.onUpdateModelSelection(option.selection),
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
onUpdateOptionSelections: (options) =>
|
||||
props.onUpdateModelSelection({ ...currentModelSelection, options }),
|
||||
runtimeMode: currentRuntimeMode,
|
||||
onUpdateRuntimeMode: props.onUpdateRuntimeMode,
|
||||
}),
|
||||
[
|
||||
currentModelSelection,
|
||||
currentRuntimeMode,
|
||||
props.onUpdateModelSelection,
|
||||
props.onUpdateRuntimeMode,
|
||||
providerOptionDescriptors,
|
||||
settingsOwnerId,
|
||||
threadProviderGroups,
|
||||
],
|
||||
);
|
||||
const openSettings = useCallback(() => {
|
||||
settingsRoutePresentation.present(settingsRouteSession);
|
||||
settingsSheetPresentation.open();
|
||||
}, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.open]);
|
||||
|
||||
useEffect(() => {
|
||||
if (settingsSheetPresentation.isActive) {
|
||||
settingsRoutePresentation.present(settingsRouteSession);
|
||||
}
|
||||
}, [settingsRoutePresentation.present, settingsRouteSession, settingsSheetPresentation.isActive]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!settingsSheetPresentation.isVisible || settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = true;
|
||||
navigation.dispatch(StackActions.push("ThreadSettingsSheet"));
|
||||
}, [navigation, settingsSheetPresentation.isVisible]);
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
if (!settingsRoutePresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
settingsRoutePresentedRef.current = false;
|
||||
settingsSheetPresentation.onDismissed();
|
||||
settingsRoutePresentation.clear(settingsOwnerId);
|
||||
}, [settingsOwnerId, settingsRoutePresentation.clear, settingsSheetPresentation.onDismissed]),
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() =>
|
||||
// UIKit's completion callback for the sheet dismissal, surfaced by the
|
||||
// native-stack patch. This is when the queued keyboard restore runs.
|
||||
(navigation as unknown as NavigationWithFinishTransitioning).addListener(
|
||||
"finishTransitioning",
|
||||
settingsSheetPresentation.onStackTransitionsFinished,
|
||||
),
|
||||
[navigation, settingsSheetPresentation.onStackTransitionsFinished],
|
||||
);
|
||||
const settingsSummaryLabel = threadSettingsSummaryLabel({
|
||||
modelLabel: currentModelOption?.label ?? currentModelSelection.model,
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: currentRuntimeMode,
|
||||
interactionMode: currentInteractionMode,
|
||||
});
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
@@ -738,12 +674,10 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
borderRadius: 26,
|
||||
minHeight: 140,
|
||||
borderRadius: 20,
|
||||
overflow: "hidden" as const,
|
||||
paddingBottom: 6,
|
||||
paddingHorizontal: 14,
|
||||
paddingTop: 14,
|
||||
paddingVertical: 12,
|
||||
}
|
||||
: {
|
||||
borderRadius: 999,
|
||||
@@ -793,7 +727,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
minHeight: 72,
|
||||
minHeight: 80,
|
||||
maxHeight: 160,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
@@ -842,12 +776,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
)}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
{isExpanded ? (
|
||||
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
|
||||
</ComposerSurface>
|
||||
|
||||
{isExpanded ? (
|
||||
// Toolbar row — matches draft page layout (expanded only)
|
||||
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
|
||||
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={toolbarFadeOpaque}
|
||||
fadeTransparent={toolbarFadeTransparent}
|
||||
contentPaddingRight={8}
|
||||
>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Add attachment"
|
||||
@@ -855,15 +792,14 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ComposerInlineControl
|
||||
accessibilityLabel="Model and reasoning settings"
|
||||
emphasized
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={currentModelOption?.label ?? currentModelSelection.model}
|
||||
maxWidth={152}
|
||||
onPress={openSettings}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
@@ -884,8 +820,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
showChevron={false}
|
||||
/>
|
||||
</ComposerToolbarRow>
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
|
||||
{/* Queue count */}
|
||||
{props.queueCount > 0 ? (
|
||||
@@ -898,6 +834,21 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
) : null}
|
||||
</Animated.View>
|
||||
|
||||
<ThreadSettingsSheet
|
||||
visible={settingsSheetPresentation.isVisible}
|
||||
onClose={settingsSheetPresentation.close}
|
||||
onDismissed={settingsSheetPresentation.onDismissed}
|
||||
providerGroups={threadProviderGroups}
|
||||
selectedModel={currentModelSelection}
|
||||
onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}
|
||||
optionDescriptors={providerOptionDescriptors}
|
||||
onUpdateOptionSelections={(options) =>
|
||||
props.onUpdateModelSelection({ ...currentModelSelection, options })
|
||||
}
|
||||
runtimeMode={currentRuntimeMode}
|
||||
onUpdateRuntimeMode={props.onUpdateRuntimeMode}
|
||||
/>
|
||||
|
||||
<ImageViewing
|
||||
images={previewImageUri ? [{ uri: previewImageUri }] : []}
|
||||
imageIndex={0}
|
||||
|
||||
@@ -1,63 +1,29 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
|
||||
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 { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
RuntimeRequestId,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import {
|
||||
AppState,
|
||||
Keyboard,
|
||||
Platform,
|
||||
useColorScheme,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
type GestureResponderEvent,
|
||||
} from "react-native";
|
||||
import {
|
||||
KeyboardController,
|
||||
KeyboardStickyView,
|
||||
useKeyboardState,
|
||||
} from "react-native-keyboard-controller";
|
||||
import Animated, {
|
||||
Easing,
|
||||
FadeInDown,
|
||||
FadeOut,
|
||||
useAnimatedReaction,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
} from "react-native-reanimated";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Platform, View, type GestureResponderEvent } from "react-native";
|
||||
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
|
||||
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import type {
|
||||
PendingApproval,
|
||||
@@ -67,11 +33,6 @@ import type {
|
||||
} from "../../lib/threadActivity";
|
||||
import { PendingApprovalCard } from "./PendingApprovalCard";
|
||||
import { PendingUserInputCard } from "./PendingUserInputCard";
|
||||
import {
|
||||
derivePendingUserInputMaxHeight,
|
||||
ESTIMATED_KEYBOARD_HEIGHT,
|
||||
USER_INPUT_TOGGLE_DURATION_MS,
|
||||
} from "./pendingUserInputLayout";
|
||||
import {
|
||||
COMPOSER_COLLAPSED_CHROME,
|
||||
COMPOSER_EXPANDED_CHROME,
|
||||
@@ -81,7 +42,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;
|
||||
@@ -89,11 +50,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 | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly activePendingUserInputAnswers: Record<string, string> | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
@@ -101,6 +62,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
readonly threadCwd: string | null;
|
||||
@@ -121,16 +83,16 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -208,48 +170,8 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
|
||||
}, [threadId, feed]);
|
||||
}
|
||||
|
||||
const USER_INPUT_TOGGLE_TIMING = {
|
||||
duration: USER_INPUT_TOGGLE_DURATION_MS,
|
||||
easing: Easing.out(Easing.cubic),
|
||||
};
|
||||
|
||||
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const liveKeyboardHeight = useKeyboardState((state) => state.height);
|
||||
// Android can swallow the IME hide callbacks when the app is backgrounded
|
||||
// mid keyboard-hide (the reported repro: send — which blurs and starts the
|
||||
// hide — then Home within a second). The keyboard library's height AND
|
||||
// visibility then stay frozen open, so gating the sticky translation on
|
||||
// visibility alone still strands the composer after resume. Quarantine the
|
||||
// translation on every Android resume instead; any sign of a live keyboard
|
||||
// stream — an owned input gaining focus, or any visibility/height movement —
|
||||
// lifts it. A healthy resume sees no visual difference (the translation is
|
||||
// already zero while the keyboard is closed).
|
||||
const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
|
||||
useEffect(() => {
|
||||
if (Platform.OS !== "android") {
|
||||
return;
|
||||
}
|
||||
const subscription = AppState.addEventListener("change", (state) => {
|
||||
if (state === "active") {
|
||||
setKeyboardStateSuspect(true);
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
subscription.remove();
|
||||
};
|
||||
}, []);
|
||||
useEffect(() => {
|
||||
setKeyboardStateSuspect(false);
|
||||
}, [isKeyboardVisible, liveKeyboardHeight]);
|
||||
const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
|
||||
if (focused) {
|
||||
setKeyboardStateSuspect(false);
|
||||
}
|
||||
}, []);
|
||||
const windowHeight = useWindowDimensions().height;
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + IOS_NAV_BAR_HEIGHT;
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
@@ -260,17 +182,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
|
||||
// Android keys the safe-area padding on keyboard visibility (#5988): the
|
||||
// back gesture closes the keyboard while the editor stays focused, and a
|
||||
// focus-keyed inset would leave the toolbar under the gesture bar. iOS must
|
||||
// NOT use visibility — it only flips on keyboardDidHide, after the hide
|
||||
// animation, so the composer would ride down flush to the screen edge and
|
||||
// then snap up into the inset. On iOS blur precedes the hide, so the
|
||||
// focus-keyed inset is already in place while the composer rides down.
|
||||
const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded)
|
||||
? 0
|
||||
: Math.max(insets.bottom, 12);
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
// The raw sync status enters "synchronizing" on every full fetch, cached or
|
||||
// not. Whether messages are already on screen decides the pill label: no
|
||||
@@ -291,41 +203,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
// While a user-input request is pending, the questionnaire owns the
|
||||
// composer slot outright: expanded it is the full card, collapsed it is a
|
||||
// composer-style bar in the same place (with its own stop control). The
|
||||
// composer never mounts into the transition, which keeps the collapse and
|
||||
// keyboard animations coherent. Collapse state is keyed by request id so a
|
||||
// new request re-expands automatically.
|
||||
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
|
||||
useState<ApprovalRequestId | null>(null);
|
||||
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
|
||||
const userInputCollapsed =
|
||||
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
|
||||
// The card's height RESERVES keyboard space at all times instead of
|
||||
// tracking the keyboard: transforms (the sticky translation) apply
|
||||
// same-frame on the UI thread while layout props lag a Yoga pass behind,
|
||||
// so any height that follows the keyboard flashes the card over the nav
|
||||
// header on the way up. With a constant height the keyboard transition is
|
||||
// pure translation — frame-perfect by construction — and the resting card
|
||||
// stays compact over the transcript. Before the first open the reserve is
|
||||
// an estimate; once a real height is known the card corrects once,
|
||||
// discretely.
|
||||
const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
|
||||
useEffect(() => {
|
||||
if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
|
||||
setLastKnownKeyboardHeight(liveKeyboardHeight);
|
||||
}
|
||||
}, [lastKnownKeyboardHeight, liveKeyboardHeight]);
|
||||
const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
|
||||
windowHeight,
|
||||
keyboardHeight:
|
||||
lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
|
||||
navigationHeaderHeight,
|
||||
// The questionnaire owns the composer slot, so only the composer's
|
||||
// bottom inset still overlaps.
|
||||
composerOverlapHeight: composerBottomInset,
|
||||
});
|
||||
const estimatedOverlayHeight = composerOverlapHeight;
|
||||
// The overlay's measured height includes the home-indicator inset (the
|
||||
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
|
||||
@@ -342,103 +219,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
|
||||
-nativeInsetOvercount,
|
||||
);
|
||||
// The expanded questionnaire is an absolute overlay on iOS, so it never
|
||||
// changes the measured overlay height (that constancy is what keeps the
|
||||
// feed from snapping on collapse/expand). The toggle choreography runs on
|
||||
// SHARED VALUES set directly in the tap handler — one JS hop, then the
|
||||
// card's rise/sink and the feed's end-inset glide animate in lockstep on
|
||||
// the UI thread, keyboard-style, instead of waiting on React mount +
|
||||
// onLayout + state round trips. Coverage (how far the card extends above
|
||||
// the bar) is measured straight into a shared value by the card's
|
||||
// onLayout, with no re-render.
|
||||
const userInputCardProgress = useSharedValue(1);
|
||||
const userInputInsetProgress = useSharedValue(1);
|
||||
const userInputCardCoverage = useSharedValue(0);
|
||||
// Android renders the expanded card in-flow (it cannot hit-test the iOS
|
||||
// overlay outside the bar's bounds), so its measured overlay height already
|
||||
// includes the card — the coverage extra is iOS-only.
|
||||
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
|
||||
const combinedContentInsetEndAdjustment = useSharedValue(
|
||||
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
|
||||
);
|
||||
useAnimatedReaction(
|
||||
() =>
|
||||
contentInsetEndAdjustment.value +
|
||||
(userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
|
||||
(value) => {
|
||||
combinedContentInsetEndAdjustment.value = value;
|
||||
},
|
||||
[userInputCoverageApplies],
|
||||
);
|
||||
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
|
||||
const endFollowEnabledRef = useRef(true);
|
||||
endFollowEnabledRef.current = endFollowEnabled;
|
||||
const userInputRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
// The list's own corrections for these inset changes drift on short
|
||||
// content (and the error compounds across toggles), so deterministically
|
||||
// re-pin the end once a toggle settles: a no-op when the resting position
|
||||
// is already right, corrective when it is not. Follow state is re-checked
|
||||
// inside the callback — the user may grab the list during the settle
|
||||
// window, and yanking them back would override a live gesture.
|
||||
const scheduleUserInputRepin = useCallback(
|
||||
(delayMs: number) => {
|
||||
if (userInputRepinTimerRef.current !== null) {
|
||||
clearTimeout(userInputRepinTimerRef.current);
|
||||
}
|
||||
userInputRepinTimerRef.current = setTimeout(() => {
|
||||
userInputRepinTimerRef.current = null;
|
||||
if (!endFollowEnabledRef.current) {
|
||||
return;
|
||||
}
|
||||
void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
|
||||
freeze.set(false);
|
||||
});
|
||||
}, delayMs);
|
||||
},
|
||||
[freeze, scrollMessageToEnd],
|
||||
);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (userInputRepinTimerRef.current !== null) {
|
||||
clearTimeout(userInputRepinTimerRef.current);
|
||||
}
|
||||
},
|
||||
[],
|
||||
);
|
||||
const handleToggleUserInputCollapsed = useCallback(() => {
|
||||
if (activeUserInputRequestId === null) {
|
||||
return;
|
||||
}
|
||||
if (userInputCollapsed) {
|
||||
// Expanding: card and feed glide start NOW, on the UI thread.
|
||||
userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
|
||||
userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
|
||||
setCollapsedUserInputRequestId(null);
|
||||
scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
|
||||
} else {
|
||||
// Collapsing hides the custom-answer inputs; release the keyboard with
|
||||
// them instead of leaving it up over a dead responder.
|
||||
Keyboard.dismiss();
|
||||
userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
|
||||
// Instant: the sinking card still covers the strip being revealed, and
|
||||
// animating the inset downward is what drifted the short-content end
|
||||
// anchor.
|
||||
userInputInsetProgress.value = 0;
|
||||
setCollapsedUserInputRequestId(activeUserInputRequestId);
|
||||
scheduleUserInputRepin(60);
|
||||
}
|
||||
}, [
|
||||
activeUserInputRequestId,
|
||||
scheduleUserInputRepin,
|
||||
userInputCardProgress,
|
||||
userInputCollapsed,
|
||||
userInputInsetProgress,
|
||||
]);
|
||||
useEffect(() => {
|
||||
// A new request always arrives expanded.
|
||||
userInputCardProgress.value = 1;
|
||||
userInputInsetProgress.value = 1;
|
||||
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
|
||||
const showContent = props.showContent ?? true;
|
||||
const layoutVariant = props.layoutVariant ?? "compact";
|
||||
const isSplitLayout = layoutVariant === "split";
|
||||
@@ -459,7 +240,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
setEndFollowEnabled(true);
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
@@ -531,16 +311,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
composerEditorRef.current?.blur();
|
||||
}, []);
|
||||
|
||||
const handleScrollToEnd = useCallback(() => {
|
||||
void Haptics.selectionAsync();
|
||||
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
|
||||
freeze.set(false);
|
||||
});
|
||||
}, [freeze, scrollMessageToEnd]);
|
||||
|
||||
const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
|
||||
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
|
||||
feedTouchStartRef.current = {
|
||||
pageX: event.nativeEvent.pageX,
|
||||
@@ -572,6 +342,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<<<<<<< HEAD
|
||||
<View className="flex-1">
|
||||
{showContent ? (
|
||||
<View
|
||||
@@ -594,14 +365,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
onEndFollowEnabledChange={setEndFollowEnabled}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
@@ -609,14 +379,55 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : (
|
||||
<View className="flex-1" />
|
||||
)}
|
||||
=======
|
||||
<GestureDetector gesture={headerDrawerGesture}>
|
||||
<View className="flex-1">
|
||||
{showContent ? (
|
||||
<View
|
||||
style={{ flex: 1 }}
|
||||
onTouchStart={handleFeedTouchStart}
|
||||
onTouchMove={handleFeedTouchMove}
|
||||
onTouchEnd={handleFeedTouchEnd}
|
||||
onTouchCancel={handleFeedTouchCancel}
|
||||
>
|
||||
<ThreadFeed
|
||||
key={props.selectedThread.id}
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
workspaceRoot={props.threadCwd}
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestRun={props.selectedThread.latestRun}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
anchorMessageId={anchorMessageId}
|
||||
contentInsetEndAdjustment={contentInsetEndAdjustment}
|
||||
contentTopInset={headerHeight}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
layoutVariant={layoutVariant}
|
||||
skills={selectedProviderSkills}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
<View style={{ flex: 1 }} />
|
||||
)}
|
||||
|
||||
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
|
||||
{showContent ? (
|
||||
<KeyboardStickyView
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} style={{ paddingTop: 8 }}>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
|
||||
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
|
||||
{showContent ? (
|
||||
<KeyboardStickyView
|
||||
// The animated keyboard height can remain stale after a dismissed
|
||||
// IME on both platforms. Visibility is the authoritative closed
|
||||
// state, so disable the translation rather than stranding the pill.
|
||||
enabled={isKeyboardVisible && !keyboardStateSuspect}
|
||||
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
|
||||
offset={{ closed: 0, opened: 0 }}
|
||||
>
|
||||
@@ -624,60 +435,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
list's bottom inset, so any padding above the pill/composer
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
{showScrollToEndButton ? (
|
||||
<Animated.View
|
||||
pointerEvents="box-none"
|
||||
className="absolute -top-11 left-0 right-0 z-20 items-center"
|
||||
entering={FadeInDown.duration(160)}
|
||||
exiting={FadeOut.duration(100)}
|
||||
>
|
||||
{isLiquidGlassSupported ? (
|
||||
<LiquidGlassView
|
||||
colorScheme={isDarkMode ? "dark" : "light"}
|
||||
effect="regular"
|
||||
interactive
|
||||
// Interactive glass can render larger than the requested
|
||||
// box (minimum touch size), so center the pill instead of
|
||||
// relying on it filling the glass exactly.
|
||||
style={{
|
||||
alignItems: "center",
|
||||
borderRadius: 18,
|
||||
height: 36,
|
||||
justifyContent: "center",
|
||||
overflow: "hidden",
|
||||
width: 36,
|
||||
}}
|
||||
>
|
||||
<ControlPill
|
||||
accessibilityLabel="Scroll to end"
|
||||
activateOnPressIn
|
||||
className="h-9 w-9 bg-transparent"
|
||||
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
|
||||
onPress={handleScrollToEnd}
|
||||
/>
|
||||
</LiquidGlassView>
|
||||
) : (
|
||||
<ControlPill
|
||||
accessibilityLabel="Scroll to end"
|
||||
activateOnPressIn
|
||||
className="h-9 w-9 border border-border bg-card shadow-md shadow-black/10"
|
||||
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
|
||||
onPress={handleScrollToEnd}
|
||||
/>
|
||||
)}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
// The questionnaire replaces the composer, so it must pad
|
||||
// the home indicator the composer normally covers.
|
||||
style={
|
||||
activeUserInputRequestId !== null
|
||||
? { paddingBottom: composerBottomInset }
|
||||
: undefined
|
||||
}
|
||||
entering={FadeInDown.duration(220)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
>
|
||||
@@ -691,13 +452,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
{props.activePendingUserInput ? (
|
||||
<PendingUserInputCard
|
||||
pendingUserInput={props.activePendingUserInput}
|
||||
maxHeight={pendingUserInputMaxHeight}
|
||||
collapsed={userInputCollapsed}
|
||||
onToggleCollapsed={handleToggleUserInputCollapsed}
|
||||
onStopThread={props.onStopThread}
|
||||
cardProgress={userInputCardProgress}
|
||||
cardCoverage={userInputCardCoverage}
|
||||
onInputFocusChange={handleOwnedInputFocusChange}
|
||||
drafts={props.activePendingUserInputDrafts}
|
||||
answers={props.activePendingUserInputAnswers}
|
||||
respondingUserInputId={props.respondingUserInputId}
|
||||
@@ -710,39 +464,35 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{/* Hidden (not unmounted) while a user-input request owns the
|
||||
composer slot, so composer drafts and editor state survive. */}
|
||||
<View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
onEditorFocusChange={handleOwnedInputFocusChange}
|
||||
/>
|
||||
</View>
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
/>
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, MessageId, RunId, ThreadId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -48,7 +48,6 @@ import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reani
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
|
||||
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
|
||||
@@ -88,13 +87,9 @@ import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/l
|
||||
import {
|
||||
deriveThreadFeedPresentation,
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
type ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
resolveThreadFeedLiveFollow,
|
||||
type ThreadFeedLiveFollowEvent,
|
||||
} from "./thread-feed-live-follow";
|
||||
import {
|
||||
collapsedWorkLogHeight,
|
||||
ThreadWorkGroupToggle,
|
||||
@@ -147,8 +142,7 @@ export interface ThreadFeedProps {
|
||||
readonly feed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly latestRun: ThreadFeedLatestRun | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
@@ -159,7 +153,6 @@ export interface ThreadFeedProps {
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: {
|
||||
@@ -825,11 +818,11 @@ function renderFeedEntry(
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkRows: Record<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;
|
||||
@@ -843,16 +836,12 @@ function renderFeedEntry(
|
||||
const entry = info.item;
|
||||
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
||||
|
||||
if (entry.type === "working") {
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
if (entry.type === "run-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: entry.expanded }}
|
||||
onPress={() => props.onToggleTurnFold(entry.turnId)}
|
||||
onPress={() => props.onToggleTurnFold(entry.runId)}
|
||||
hitSlop={4}
|
||||
className="mb-3 min-h-11 flex-row items-center gap-2 border-b border-neutral-200/80 px-2 dark:border-white/[0.08]"
|
||||
>
|
||||
@@ -897,7 +886,7 @@ function renderFeedEntry(
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
message.turnId === props.unsettledTurnId;
|
||||
message.runId === props.unsettledTurnId;
|
||||
const showAssistantMeta =
|
||||
message.role === "assistant" &&
|
||||
props.terminalAssistantMessageIds.has(message.id) &&
|
||||
@@ -1332,10 +1321,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
<<<<<<< HEAD
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const headerMaterialVisibleRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const { appearance } = useAppearancePreferences();
|
||||
const [viewportWidth, setViewportWidth] = useState(() =>
|
||||
@@ -1354,28 +1343,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// momentum; only motion inside a session can break follow, so MVCP
|
||||
// compensations and programmatic scrolls never strand a follower.
|
||||
const userScrollSessionRef = useRef(false);
|
||||
const setEndFollow = useCallback(
|
||||
(enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
props.onEndFollowEnabledChange?.(enabled);
|
||||
},
|
||||
[props.onEndFollowEnabledChange],
|
||||
);
|
||||
const transitionEndFollow = useCallback(
|
||||
(event: ThreadFeedLiveFollowEvent) => {
|
||||
setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
|
||||
},
|
||||
[setEndFollow],
|
||||
);
|
||||
const setEndFollow = useCallback((enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
}, []);
|
||||
=======
|
||||
const previousLatestTurnRef = useRef(props.latestRun);
|
||||
const { width: viewportWidth } = useWindowDimensions();
|
||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly expandedTurnIds: ReadonlySet<TurnId>;
|
||||
readonly expandedTurnIds: ReadonlySet<RunId>;
|
||||
}>({
|
||||
copiedRowId: null,
|
||||
expandedWorkGroups: {},
|
||||
@@ -1465,15 +1449,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
viewportWidth,
|
||||
],
|
||||
);
|
||||
const reportHeaderMaterialVisibility = useCallback(
|
||||
(visible: boolean) => {
|
||||
if (headerMaterialVisibleRef.current === visible) {
|
||||
return;
|
||||
}
|
||||
headerMaterialVisibleRef.current = visible;
|
||||
props.onHeaderMaterialVisibilityChange?.(visible);
|
||||
},
|
||||
[props.onHeaderMaterialVisibilityChange],
|
||||
const presentedFeed = useMemo(
|
||||
() => deriveThreadFeedPresentation(props.feed, props.latestRun, expandedTurnIds),
|
||||
[expandedTurnIds, props.feed, props.latestRun],
|
||||
);
|
||||
const handleScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
@@ -1482,72 +1460,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
|
||||
// header height back or the material toggles a full header too late.
|
||||
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
|
||||
// LegendList recomputes its inset-aware end distance before invoking
|
||||
// this handler, so getState() is current. Only the actual end re-arms
|
||||
// follow: its broader maintain-scroll threshold is large enough for a
|
||||
// streaming chunk to pull a user back before their upward drag escapes.
|
||||
// A live user-scroll session still wins even if the first scroll event
|
||||
// remains inside LegendList's at-end tolerance.
|
||||
// Latch bookkeeping. LegendList recomputes its inset-aware end distance
|
||||
// before invoking this handler, so getState() is current. Returning to
|
||||
// the end re-arms follow no matter who scrolled (the user, or our own
|
||||
// scroll-to-end); moving away breaks it only during a user-initiated
|
||||
// scroll session, so MVCP compensations and programmatic repositioning
|
||||
// can never strand a follower.
|
||||
const listState = props.listRef.current?.getState();
|
||||
if (listState) {
|
||||
transitionEndFollow({
|
||||
type: "scroll",
|
||||
isAtEnd: listState.isAtEnd,
|
||||
userScrollSessionActive: userScrollSessionRef.current,
|
||||
});
|
||||
if (listState.isWithinMaintainScrollAtEndThreshold) {
|
||||
setEndFollow(true);
|
||||
} else if (userScrollSessionRef.current) {
|
||||
setEndFollow(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
|
||||
);
|
||||
const clearUserScrollSettle = useCallback(() => {
|
||||
if (userScrollSettleTimerRef.current !== null) {
|
||||
clearTimeout(userScrollSettleTimerRef.current);
|
||||
userScrollSettleTimerRef.current = null;
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
userScrollSessionRef.current = true;
|
||||
}, []);
|
||||
// The session must survive past finger-lift so momentum that carries the
|
||||
// user away from the end still breaks follow; a drag released with no
|
||||
// momentum ends its session at the release itself, otherwise at momentum
|
||||
// end. Leaving a session open would let a later animated maintain-scroll
|
||||
// read as user motion and break follow spuriously.
|
||||
const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
const velocity = event.nativeEvent.velocity?.y ?? 0;
|
||||
if (Math.abs(velocity) < 0.05) {
|
||||
userScrollSessionRef.current = false;
|
||||
}
|
||||
}, []);
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = true;
|
||||
// Pause before the first scroll event. Otherwise a stream update can run
|
||||
// maintainScrollAtEnd between touch-down and the drag leaving its threshold.
|
||||
transitionEndFollow({ type: "user-scroll-begin" });
|
||||
}, [clearUserScrollSettle, transitionEndFollow]);
|
||||
const finishUserScroll = useCallback(
|
||||
(releaseIsAtEnd?: boolean) => {
|
||||
clearUserScrollSettle();
|
||||
const userScrollSessionActive = userScrollSessionRef.current;
|
||||
userScrollSessionRef.current = false;
|
||||
transitionEndFollow({
|
||||
type: "user-scroll-end",
|
||||
// With no momentum, preserve the finger-release position. Streaming
|
||||
// growth during the native momentum-detection window must not turn a
|
||||
// release at the live edge into an opt-out from follow.
|
||||
isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false,
|
||||
userScrollSessionActive,
|
||||
});
|
||||
},
|
||||
[clearUserScrollSettle, props.listRef, transitionEndFollow],
|
||||
);
|
||||
// Finger-lift velocity is not a reliable momentum signal: a gentle fling
|
||||
// can report zero and still decelerate. Give native momentum a short window
|
||||
// to announce itself; if it does, onMomentumScrollBegin cancels this fallback
|
||||
// and the session survives until the settled momentum-end position. This
|
||||
// mirrors the native-event handoff used by the home thread list's scroll gate.
|
||||
const handleScrollEndDrag = useCallback(() => {
|
||||
clearUserScrollSettle();
|
||||
const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false;
|
||||
userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160);
|
||||
}, [clearUserScrollSettle, finishUserScroll, props.listRef]);
|
||||
const handleMomentumScrollBegin = useCallback(() => {
|
||||
if (userScrollSessionRef.current) {
|
||||
clearUserScrollSettle();
|
||||
}
|
||||
}, [clearUserScrollSettle]);
|
||||
const handleMomentumScrollEnd = useCallback(() => {
|
||||
finishUserScroll();
|
||||
}, [finishUserScroll]);
|
||||
|
||||
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
|
||||
userScrollSessionRef.current = false;
|
||||
}, []);
|
||||
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
@@ -1556,30 +1502,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
|
||||
}, []);
|
||||
|
||||
// Thread identity is env-scoped: two environments can hold the same
|
||||
// ThreadId, and keying resets (or the list mount) on the bare id would
|
||||
// carry stale scroll/follow state across an environment switch.
|
||||
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
|
||||
|
||||
useEffect(() => {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [feedThreadKey, reportHeaderMaterialVisibility]);
|
||||
}, [props.threadId, reportHeaderMaterialVisibility]);
|
||||
|
||||
// A thread switch opens pinned to the end; a send explicitly returns to the
|
||||
// live edge (ThreadDetailScreen scrolls the new message into place). Both
|
||||
// re-arm follow regardless of where the user had scrolled before.
|
||||
useEffect(() => {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = false;
|
||||
transitionEndFollow({ type: "reset" });
|
||||
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
|
||||
setEndFollow(true);
|
||||
}, [props.threadId, setEndFollow]);
|
||||
useEffect(() => {
|
||||
if (props.anchorMessageId !== null) {
|
||||
clearUserScrollSettle();
|
||||
userScrollSessionRef.current = false;
|
||||
transitionEndFollow({ type: "reset" });
|
||||
setEndFollow(true);
|
||||
}
|
||||
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
|
||||
}, [props.anchorMessageId, setEndFollow]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
@@ -1615,7 +1554,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// initial scroll-to-end computes with a zero end inset and rests one
|
||||
// composer-height short of the end. Layout effect: it must land before the
|
||||
// list's first positioning tick or the one-shot initial scroll misses it.
|
||||
const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
|
||||
useLayoutEffect(() => {
|
||||
const bottom = props.contentInsetEndAdjustment.value;
|
||||
if (bottom > 0) {
|
||||
@@ -1634,29 +1573,29 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[presentedFeed, props.anchorMessageId, anchorTopInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<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),
|
||||
@@ -1665,14 +1604,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
return;
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
if (!current.expandedTurnIds.has(previous.turnId)) {
|
||||
if (!current.expandedTurnIds.has(previous.runId)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
next.delete(previous.turnId);
|
||||
next.delete(previous.runId);
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
}, [props.latestTurn]);
|
||||
}, [props.latestRun]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1766,17 +1705,28 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
|
||||
const onToggleTurnFold = useCallback(
|
||||
(turnId: TurnId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
const onToggleTurnFold = useCallback((runId: RunId) => {
|
||||
setFoldToggleSettling(true);
|
||||
if (foldSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleFrameRef.current);
|
||||
}
|
||||
if (foldSettleSecondFrameRef.current !== null) {
|
||||
cancelAnimationFrame(foldSettleSecondFrameRef.current);
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
} else {
|
||||
next.add(runId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
foldSettleFrameRef.current = requestAnimationFrame(() => {
|
||||
foldSettleSecondFrameRef.current = requestAnimationFrame(() => {
|
||||
setFoldToggleSettling(false);
|
||||
foldSettleFrameRef.current = null;
|
||||
foldSettleSecondFrameRef.current = null;
|
||||
});
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
@@ -1982,7 +1932,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onScroll={handleScroll}
|
||||
onScrollBeginDrag={handleScrollBeginDrag}
|
||||
onScrollEndDrag={handleScrollEndDrag}
|
||||
onMomentumScrollBegin={handleMomentumScrollBegin}
|
||||
onMomentumScrollEnd={handleMomentumScrollEnd}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import {
|
||||
StackActions,
|
||||
useFocusEffect,
|
||||
useNavigation,
|
||||
type StaticScreenProps,
|
||||
} from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import { Stack, useLocalSearchParams, useRouter } from "expo-router";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -479,20 +474,15 @@ function ThreadRouteContent(
|
||||
void navigation.navigate("Connections");
|
||||
}, [navigation]);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
(selectedThread.session?.status !== "running" &&
|
||||
selectedThread.session?.status !== "starting")
|
||||
) {
|
||||
const runtime = selectedThread?.runtime;
|
||||
if (!selectedThread || !runtime || !threadRuntimeIsActive(runtime)) {
|
||||
return;
|
||||
}
|
||||
return interruptThreadTurn({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
...(selectedThread.session.activeTurnId
|
||||
? { turnId: selectedThread.session.activeTurnId }
|
||||
: {}),
|
||||
...(runtime.activeRunId ? { runId: runtime.activeRunId } : {}),
|
||||
},
|
||||
});
|
||||
}, [interruptThreadTurn, selectedThread]);
|
||||
@@ -522,7 +512,7 @@ function ThreadRouteContent(
|
||||
terminalDebugLog("terminal-menu:open-new", {
|
||||
hasThread: Boolean(selectedThread),
|
||||
hasWorkspaceRoot: Boolean(selectedThreadProject?.workspaceRoot),
|
||||
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
||||
});
|
||||
|
||||
if (!selectedThread || !selectedThreadProject?.workspaceRoot) {
|
||||
@@ -530,7 +520,7 @@ function ThreadRouteContent(
|
||||
}
|
||||
|
||||
const nextId = nextOpenTerminalId({
|
||||
listedTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
listedTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
||||
});
|
||||
void navigation.navigate("ThreadTerminal", {
|
||||
environmentId: String(selectedThread.environmentId),
|
||||
@@ -557,9 +547,9 @@ function ThreadRouteContent(
|
||||
}
|
||||
|
||||
const targetTerminalId = resolveProjectScriptTerminalId({
|
||||
existingTerminalIds: terminalMenuSessions.map((session) => session.terminalId),
|
||||
existingTerminalIds: terminalMenuSessions.map((runtime) => runtime.terminalId),
|
||||
hasRunningTerminal: terminalMenuSessions.some(
|
||||
(session) => session.status === "running" || session.status === "starting",
|
||||
(runtime) => runtime.status === "running" || runtime.status === "starting",
|
||||
),
|
||||
});
|
||||
const preferredWorktreePath = resolvePreferredThreadWorktreePath({
|
||||
|
||||
@@ -7,49 +7,9 @@ export function threadSortValue(thread: EnvironmentThreadShell): number {
|
||||
return Number.isNaN(candidate) ? 0 : candidate;
|
||||
}
|
||||
|
||||
export type ThreadStatusKind =
|
||||
| "pending-approval"
|
||||
| "awaiting-input"
|
||||
| "working"
|
||||
| "connecting"
|
||||
| "error"
|
||||
| "plan-ready";
|
||||
|
||||
export interface ThreadStatusPresentation extends StatusTone {
|
||||
readonly kind: ThreadStatusKind;
|
||||
/** Foreground color for the leading status icon. */
|
||||
readonly iconColor: string;
|
||||
/** Background color for the leading status icon circle. */
|
||||
readonly iconBackground: string;
|
||||
/** Whether the indicator represents in-flight activity. */
|
||||
readonly pulse: boolean;
|
||||
}
|
||||
|
||||
/** Neutral icon colors for threads with no actionable status. */
|
||||
export const THREAD_STATUS_NEUTRAL_ICON = {
|
||||
iconColor: "#8e8e93",
|
||||
iconBackground: "rgba(142,142,147,0.22)",
|
||||
} as const;
|
||||
|
||||
function isLatestTurnSettled(
|
||||
latestTurn: OrchestrationLatestTurn | null,
|
||||
session: OrchestrationSession | null,
|
||||
): boolean {
|
||||
if (!latestTurn?.startedAt) return false;
|
||||
if (!latestTurn.completedAt) return false;
|
||||
if (!session) return true;
|
||||
return session.status !== "running";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the user-facing status of a thread, in priority order. Returns
|
||||
* `null` for quiescent threads so rows stay free of "Idle"-style noise.
|
||||
* Mirrors `resolveThreadStatusPill` in apps/web/src/components/Sidebar.logic.ts.
|
||||
*/
|
||||
export function resolveThreadStatus(
|
||||
thread: EnvironmentThreadShell,
|
||||
): ThreadStatusPresentation | null {
|
||||
if (thread.hasPendingApprovals) {
|
||||
export function threadStatusTone(thread: EnvironmentThreadShell): StatusTone {
|
||||
const status = thread.runtime?.status;
|
||||
if (status === "running" || status === "waiting") {
|
||||
return {
|
||||
kind: "pending-approval",
|
||||
label: "Needs Approval",
|
||||
@@ -60,8 +20,7 @@ export function resolveThreadStatus(
|
||||
pulse: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.hasPendingUserInput) {
|
||||
if (status === "completed") {
|
||||
return {
|
||||
kind: "awaiting-input",
|
||||
label: "Awaiting Input",
|
||||
@@ -72,8 +31,7 @@ export function resolveThreadStatus(
|
||||
pulse: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "running") {
|
||||
if (status === "queued" || status === "starting") {
|
||||
return {
|
||||
kind: "working",
|
||||
label: "Working",
|
||||
@@ -84,8 +42,7 @@ export function resolveThreadStatus(
|
||||
pulse: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "starting") {
|
||||
if (status === "failed") {
|
||||
return {
|
||||
kind: "connecting",
|
||||
label: "Connecting",
|
||||
|
||||
@@ -58,15 +58,16 @@ export function useCreateProjectThread() {
|
||||
|
||||
const result = await startTurn({
|
||||
environmentId: input.project.environmentId,
|
||||
input: buildProjectThreadStartTurnInput({
|
||||
projectId: input.project.id,
|
||||
projectCwd: input.project.workspaceRoot,
|
||||
threadId: metadata.threadId,
|
||||
commandId: metadata.commandId,
|
||||
messageId: metadata.messageId,
|
||||
createdAt: metadata.createdAt,
|
||||
text: initialMessageText,
|
||||
attachments: input.initialAttachments,
|
||||
input: {
|
||||
commandId: CommandId.make(metadata.commandId),
|
||||
creationSource: "mobile",
|
||||
threadId,
|
||||
message: {
|
||||
messageId: MessageId.make(metadata.messageId),
|
||||
role: "user",
|
||||
text: initialMessageText,
|
||||
attachments: input.initialAttachments,
|
||||
},
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
|
||||
@@ -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,561 +1,112 @@
|
||||
import type { ThreadWorkEntry } from "@t3tools/client-runtime/state/shell";
|
||||
import { MessageId, RunId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
import { buildThreadFeed, deriveThreadFeedPresentation } from "./threadActivity";
|
||||
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
isPendingUserInputOptionSelected,
|
||||
setPendingUserInputCustomAnswer,
|
||||
togglePendingUserInputOptionSelection,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
} from "./threadActivity";
|
||||
const runId = RunId.make("run-1");
|
||||
|
||||
const singleSelectQuestion = {
|
||||
id: "runtime",
|
||||
header: "Runtime",
|
||||
question: "Which runtime should be used?",
|
||||
options: [
|
||||
{ label: "Go", description: "One binary" },
|
||||
{ label: "Node.js", description: "Reuse TypeScript" },
|
||||
],
|
||||
multiSelect: false,
|
||||
} as const;
|
||||
|
||||
const multiSelectQuestion = {
|
||||
id: "scope",
|
||||
header: "Scope",
|
||||
question: "Which data should be collected?",
|
||||
options: [
|
||||
{ label: "Orders", description: "Receipts" },
|
||||
{ label: "Listings", description: "Inventory" },
|
||||
],
|
||||
multiSelect: true,
|
||||
} as const;
|
||||
|
||||
describe("pending user input answers", () => {
|
||||
it("replaces single-select options and toggles multi-select options", () => {
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(
|
||||
singleSelectQuestion,
|
||||
{ selectedOptionLabels: ["Go"] },
|
||||
"Node.js",
|
||||
),
|
||||
).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] });
|
||||
|
||||
const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");
|
||||
const ordersAndListings = togglePendingUserInputOptionSelection(
|
||||
multiSelectQuestion,
|
||||
orders,
|
||||
"Listings",
|
||||
);
|
||||
expect(ordersAndListings).toEqual({
|
||||
customAnswer: "",
|
||||
selectedOptionLabels: ["Orders", "Listings"],
|
||||
});
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),
|
||||
).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] });
|
||||
|
||||
const paddedOrders = togglePendingUserInputOptionSelection(
|
||||
multiSelectQuestion,
|
||||
undefined,
|
||||
" Orders ",
|
||||
);
|
||||
expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] });
|
||||
expect(
|
||||
togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "),
|
||||
).toEqual({ customAnswer: "" });
|
||||
});
|
||||
|
||||
it("builds array answers for multi-select questions", () => {
|
||||
expect(
|
||||
buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {
|
||||
runtime: { selectedOptionLabels: ["Go"] },
|
||||
scope: { selectedOptionLabels: ["Orders", "Listings"] },
|
||||
}),
|
||||
).toEqual({
|
||||
runtime: "Go",
|
||||
scope: ["Orders", "Listings"],
|
||||
});
|
||||
});
|
||||
|
||||
it("clears selected options while a custom answer is active", () => {
|
||||
expect(
|
||||
setPendingUserInputCustomAnswer(
|
||||
{ selectedOptionLabels: ["Orders", "Listings"] },
|
||||
"Orders first",
|
||||
),
|
||||
).toEqual({ customAnswer: "Orders first" });
|
||||
});
|
||||
|
||||
it("matches selected chips against normalized option labels", () => {
|
||||
expect(
|
||||
isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isPendingUserInputOptionSelected(
|
||||
{ selectedOptionLabels: ["Orders"], customAnswer: "Orders first" },
|
||||
" Orders ",
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
|
||||
): OrchestrationThreadActivity {
|
||||
function message(role: "user" | "assistant", text: string, createdAt: string, id: string) {
|
||||
return {
|
||||
tone: "info",
|
||||
payload: {},
|
||||
turnId: null,
|
||||
...input,
|
||||
};
|
||||
id: MessageId.make(id),
|
||||
role,
|
||||
text,
|
||||
attachments: [],
|
||||
runId: role === "assistant" ? runId : null,
|
||||
streaming: false,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
} as const;
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<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,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
id: "item-1",
|
||||
createdAt: "2026-06-20T00:00:02.000Z",
|
||||
runId,
|
||||
label: "Ran command",
|
||||
command: "vp check",
|
||||
detail: "ok",
|
||||
tone: "tool",
|
||||
itemType: "command_execution",
|
||||
toolLifecycleStatus: "completed",
|
||||
structuredPayload,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadFeed", () => {
|
||||
it("keeps historic work entries attributed to their turns", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Runtime warning thread",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("activity-old"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-old"),
|
||||
payload: {
|
||||
message: "Old warning",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("activity-latest"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:03.000Z",
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
payload: {
|
||||
message: "Latest warning",
|
||||
},
|
||||
}),
|
||||
it("orders V2 messages and work entries while retaining structured tool data", () => {
|
||||
const thread = makeThreadFixture({
|
||||
messages: [
|
||||
message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"),
|
||||
message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"),
|
||||
],
|
||||
workEntries: [commandEntry()],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-old",
|
||||
activities: [{ id: "activity-old", turnId: "turn-old" }],
|
||||
},
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-latest",
|
||||
activities: [{ id: "activity-latest", turnId: "turn-latest" }],
|
||||
},
|
||||
expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
|
||||
const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
|
||||
expect(activity?.runId).toBe(runId);
|
||||
expect(activity?.fullDetail).toContain('"input": "vp check"');
|
||||
});
|
||||
|
||||
it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
|
||||
const thread = makeThreadFixture({
|
||||
messages: [
|
||||
message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user"),
|
||||
message("assistant", "Done", "2026-06-20T00:00:03.000Z", "message-assistant"),
|
||||
],
|
||||
workEntries: [commandEntry()],
|
||||
});
|
||||
const feed = buildThreadFeed(thread);
|
||||
const latestRun = {
|
||||
runId,
|
||||
status: "completed" as const,
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: "2026-06-20T00:00:03.000Z",
|
||||
};
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
|
||||
expect(collapsed.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
|
||||
expect(expanded.map((entry) => entry.type)).toEqual([
|
||||
"message",
|
||||
"run-fold",
|
||||
"activity-group",
|
||||
"message",
|
||||
]);
|
||||
});
|
||||
|
||||
it("collapses matching tool lifecycle rows like desktop", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Collapsed tools",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-updated"),
|
||||
kind: "tool.updated",
|
||||
tone: "tool",
|
||||
summary: "Run tests",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run tests completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
],
|
||||
it("keeps an active run expanded and marks failed tools as failures", () => {
|
||||
const thread = makeThreadFixture({
|
||||
messages: [message("user", "Run checks", "2026-06-20T00:00:01.000Z", "message-user")],
|
||||
workEntries: [commandEntry({ tone: "error", toolLifecycleStatus: "failed" })],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
type: "activity-group",
|
||||
});
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities).toHaveLength(1);
|
||||
expect(group.activities[0]).toMatchObject({
|
||||
id: "tool-completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: "turn-1",
|
||||
summary: "Run tests",
|
||||
detail: "bun run test",
|
||||
canExpand: true,
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status: "success",
|
||||
});
|
||||
expect(group.activities[0]?.getFullDetail()).toBe("/bin/zsh -lc 'bun run test'");
|
||||
expect(group.activities[0]?.getCopyText()).toBe(
|
||||
"Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps MCP inputs available to expanded mobile work rows", () => {
|
||||
const turnId = TurnId.make("turn-mcp");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-mcp"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Expandable MCP call",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("mcp-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Call repository tool",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Call repository tool",
|
||||
itemType: "mcp_tool_call",
|
||||
detail: "repository.search",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
server: "repository",
|
||||
tool: "search",
|
||||
arguments: { query: "work log" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities[0]?.icon).toBe("wrench");
|
||||
expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"');
|
||||
expect(group.activities[0]?.getFullDetail()).toContain("repository.search");
|
||||
});
|
||||
|
||||
it("defers large tool output expansion until a work row is opened or copied", () => {
|
||||
let serializedToolOutputs = 0;
|
||||
const activities = Array.from({ length: 5_000 }, (_, index) =>
|
||||
makeActivity({
|
||||
id: EventId.make(`large-tool-${index}`),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: `Tool ${index}`,
|
||||
createdAt: new Date(Date.UTC(2026, 3, 1, 0, 0, index)).toISOString(),
|
||||
payload: {
|
||||
title: `Tool ${index}`,
|
||||
itemType: "mcp_tool_call",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
toJSON: () => {
|
||||
serializedToolOutputs += 1;
|
||||
return { output: "x".repeat(32_768) };
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-large-tools"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Large tools",
|
||||
activities,
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(serializedToolOutputs).toBe(0);
|
||||
|
||||
const group = feed[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities).toHaveLength(5_000);
|
||||
expect(group.activities[0]?.getFullDetail()).toContain('"output"');
|
||||
expect(serializedToolOutputs).toBe(1);
|
||||
expect(group.activities[0]?.getCopyText()).toContain('"output"');
|
||||
expect(serializedToolOutputs).toBe(1);
|
||||
});
|
||||
|
||||
it("folds settled turn work while leaving the terminal answer visible", () => {
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-3"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Folded work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:18.000Z",
|
||||
assistantMessageId: MessageId.make("assistant-final"),
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "I am checking.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
updatedAt: "2026-04-01T00:00:03.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-final"),
|
||||
role: "assistant",
|
||||
text: "Done.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:18.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Read files",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Read files",
|
||||
itemType: "file_read",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
type: "turn-fold",
|
||||
label: "Worked for 17s",
|
||||
expanded: false,
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set([turnId]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"turn-fold:turn-1",
|
||||
"assistant-commentary",
|
||||
"tool-completed",
|
||||
"assistant-final",
|
||||
]);
|
||||
});
|
||||
|
||||
it("measures a steer-superseded turn from its user boundary through trailing work", () => {
|
||||
const firstTurnId = TurnId.make("turn-1");
|
||||
const secondTurnId = TurnId.make("turn-2");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-steered"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Steered work",
|
||||
latestTurn: {
|
||||
turnId: secondTurnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:14.000Z",
|
||||
startedAt: "2026-04-01T00:00:14.000Z",
|
||||
const presented = deriveThreadFeedPresentation(
|
||||
feed,
|
||||
{
|
||||
runId,
|
||||
status: "running",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: MessageId.make("assistant-next"),
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("user-1"),
|
||||
role: "user",
|
||||
text: "Do it once more.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "Kicking off call 1.",
|
||||
turnId: firstTurnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:09.000Z",
|
||||
updatedAt: "2026-04-01T00:00:09.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("user-2"),
|
||||
role: "user",
|
||||
text: "Actually do 15.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:14.000Z",
|
||||
updatedAt: "2026-04-01T00:00:14.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-next"),
|
||||
role: "assistant",
|
||||
text: "One down - adjusting.",
|
||||
turnId: secondTurnId,
|
||||
streaming: true,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:17.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("work-1"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Ran command",
|
||||
createdAt: "2026-04-01T00:00:12.000Z",
|
||||
turnId: firstTurnId,
|
||||
payload: {
|
||||
title: "Ran command",
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
new Set(),
|
||||
);
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
label: "Worked for 12s",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an active turn expanded and classifies error-shaped tool output", () => {
|
||||
const turnId = TurnId.make("turn-running");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-4"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Running work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-failed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run command",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Run command",
|
||||
itemType: "command_execution",
|
||||
detail: "zsh: command not found: nope",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
activities: [{ status: "failure" }],
|
||||
});
|
||||
expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
|
||||
expect(presented.find((entry) => entry.type === "activity-group")?.activities[0]?.status).toBe(
|
||||
"failure",
|
||||
);
|
||||
});
|
||||
|
||||
it("appends active work as a normal timeline row", () => {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,23 +1,9 @@
|
||||
import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
ThreadId,
|
||||
VcsListRefsResult,
|
||||
VcsRef,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
createThreadSearchResultsAtomFamily,
|
||||
makeThreadSearchKey,
|
||||
type EnvironmentThreadSearchMatch,
|
||||
} from "@t3tools/client-runtime/state/thread-search";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import * as Cause from "effect/Cause";
|
||||
import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { orchestrationEnvironment } from "./orchestration";
|
||||
import { projectEnvironment } from "./projects";
|
||||
import { useEnvironmentQuery } from "./query";
|
||||
@@ -33,8 +19,6 @@ const COMPOSER_PATH_SEARCH_DEBOUNCE_MS = 200;
|
||||
const COMPOSER_PATH_SEARCH_LIMIT = 20;
|
||||
const THREAD_SEARCH_DEBOUNCE_MS = 200;
|
||||
const VCS_REF_LIST_LIMIT = 100;
|
||||
const EMPTY_REFS: ReadonlyArray<VcsRef> = [];
|
||||
const INITIAL_BRANCH_CURSORS = [undefined] as const;
|
||||
const EMPTY_THREAD_SEARCH_MATCHES: ReadonlyArray<EnvironmentThreadSearchMatch> = Object.freeze([]);
|
||||
const EMPTY_THREAD_SEARCH_ATOM = Atom.make({
|
||||
matches: EMPTY_THREAD_SEARCH_MATCHES,
|
||||
@@ -51,7 +35,7 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
|
||||
});
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: OrchestrationThread | null;
|
||||
readonly data: EnvironmentThread | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly isDeleted: boolean;
|
||||
@@ -63,7 +47,7 @@ export interface ComposerPathSearchTarget {
|
||||
readonly query: string | null;
|
||||
}
|
||||
|
||||
export function useDebouncedValue<A>(value: A, delayMs: number): A {
|
||||
function useDebouncedValue<A>(value: A, delayMs: number): A {
|
||||
const [debounced, setDebounced] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -136,113 +120,6 @@ export function useBranches(input: {
|
||||
);
|
||||
}
|
||||
|
||||
export function usePaginatedBranches(target: VcsRefTarget) {
|
||||
const query = target.query?.trim() ?? "";
|
||||
const targetKey =
|
||||
target.environmentId !== null && target.cwd !== null
|
||||
? JSON.stringify([target.environmentId, target.cwd, query])
|
||||
: null;
|
||||
const [pagination, setPagination] = useState<{
|
||||
readonly targetKey: string | null;
|
||||
readonly cursors: ReadonlyArray<number | undefined>;
|
||||
}>({
|
||||
targetKey,
|
||||
cursors: INITIAL_BRANCH_CURSORS,
|
||||
});
|
||||
const cursors = pagination.targetKey === targetKey ? pagination.cursors : INITIAL_BRANCH_CURSORS;
|
||||
const pageAtoms = useMemo(
|
||||
() =>
|
||||
target.environmentId !== null && target.cwd !== null
|
||||
? cursors.map((cursor) =>
|
||||
vcsEnvironment.listRefs({
|
||||
environmentId: target.environmentId!,
|
||||
input: {
|
||||
cwd: target.cwd!,
|
||||
...(query.length > 0 ? { query } : {}),
|
||||
...(cursor === undefined ? {} : { cursor }),
|
||||
limit: VCS_REF_LIST_LIMIT,
|
||||
},
|
||||
}),
|
||||
)
|
||||
: [],
|
||||
[cursors, query, target.cwd, target.environmentId],
|
||||
);
|
||||
const pagesAtom = useMemo(
|
||||
() =>
|
||||
Atom.make((get) => pageAtoms.map((atom) => get(atom))).pipe(
|
||||
Atom.withLabel(`mobile:vcs-ref-pages:${targetKey ?? "empty"}`),
|
||||
),
|
||||
[pageAtoms, targetKey],
|
||||
);
|
||||
const results = useAtomValue(pagesAtom);
|
||||
const values = results.flatMap((result) => {
|
||||
const value = Option.getOrNull(AsyncResult.value(result));
|
||||
return value === null ? [] : [value];
|
||||
});
|
||||
const refs = new Map<string, VcsRef>();
|
||||
for (const value of values) {
|
||||
for (const ref of value.refs) {
|
||||
refs.set(ref.name, ref);
|
||||
}
|
||||
}
|
||||
const first = values[0] ?? null;
|
||||
const last = values.at(-1) ?? null;
|
||||
const data: VcsListRefsResult | null =
|
||||
first === null || last === null
|
||||
? null
|
||||
: {
|
||||
refs: [...refs.values()],
|
||||
isRepo: first.isRepo,
|
||||
hasPrimaryRemote: first.hasPrimaryRemote,
|
||||
nextCursor: last.nextCursor,
|
||||
totalCount: Math.max(...values.map((value) => value.totalCount)),
|
||||
};
|
||||
const lastResult = results.at(-1);
|
||||
const isFetchingNextPage =
|
||||
results.length > 1 &&
|
||||
lastResult?.waiting === true &&
|
||||
Option.isNone(AsyncResult.value(lastResult));
|
||||
const failed = results.find((result) => result._tag === "Failure");
|
||||
const error =
|
||||
failed?._tag === "Failure"
|
||||
? (() => {
|
||||
const cause = Cause.squash(failed.cause);
|
||||
return cause instanceof Error && cause.message.trim().length > 0
|
||||
? cause.message
|
||||
: "Failed to load refs.";
|
||||
})()
|
||||
: null;
|
||||
const refresh = useCallback(() => {
|
||||
const firstPage = pageAtoms[0];
|
||||
setPagination({ targetKey, cursors: INITIAL_BRANCH_CURSORS });
|
||||
if (firstPage !== undefined) {
|
||||
appAtomRegistry.refresh(firstPage);
|
||||
}
|
||||
}, [pageAtoms, targetKey]);
|
||||
const loadNext = useCallback(() => {
|
||||
if (targetKey === null || data?.nextCursor === null || data?.nextCursor === undefined) {
|
||||
return;
|
||||
}
|
||||
setPagination((current) => {
|
||||
const currentCursors =
|
||||
current.targetKey === targetKey ? current.cursors : INITIAL_BRANCH_CURSORS;
|
||||
return currentCursors.includes(data.nextCursor!)
|
||||
? { targetKey, cursors: currentCursors }
|
||||
: { targetKey, cursors: [...currentCursors, data.nextCursor!] };
|
||||
});
|
||||
}, [data?.nextCursor, targetKey]);
|
||||
|
||||
return {
|
||||
data,
|
||||
refs: data?.refs ?? EMPTY_REFS,
|
||||
error,
|
||||
isPending: results.some((result) => result.waiting),
|
||||
isFetchingNextPage,
|
||||
refresh,
|
||||
loadNext,
|
||||
};
|
||||
}
|
||||
|
||||
export function useComposerPathSearch(target: ComposerPathSearchTarget) {
|
||||
const normalizedTarget = useMemo(
|
||||
() => ({
|
||||
|
||||
@@ -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,22 +1,15 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
import { scopedRequestKey } from "../lib/scopedEntities";
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
togglePendingUserInputOptionSelection,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
@@ -28,21 +21,15 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
|
||||
Record<string, Record<string, PendingUserInputDraftAnswer>>
|
||||
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
|
||||
|
||||
function setUserInputDraftOption(
|
||||
requestKey: string,
|
||||
question: UserInputQuestion,
|
||||
label: string,
|
||||
): void {
|
||||
function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
|
||||
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
|
||||
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
|
||||
...current,
|
||||
[requestKey]: {
|
||||
...current[requestKey],
|
||||
[question.id]: togglePendingUserInputOptionSelection(
|
||||
question,
|
||||
current[requestKey]?.[question.id],
|
||||
label,
|
||||
),
|
||||
[questionId]: {
|
||||
selectedOptionLabel: label,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -77,14 +64,11 @@ export function useSelectedThreadRequests() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
|
||||
null,
|
||||
);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
|
||||
|
||||
// Sort once; both derivations expect the same lifecycle ordering.
|
||||
const sortedActivities = useMemo(
|
||||
() => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
|
||||
const activePendingApprovals = useMemo(
|
||||
() => selectedThread?.pendingApprovals ?? [],
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApprovals = useMemo(
|
||||
@@ -93,8 +77,8 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => derivePendingUserInputs(sortedActivities),
|
||||
[sortedActivities],
|
||||
() => selectedThread?.pendingUserInputs ?? [],
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
@@ -108,19 +92,19 @@ export function useSelectedThreadRequests() {
|
||||
: null;
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => {
|
||||
(requestId: RuntimeRequestId, questionId: string, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
|
||||
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
|
||||
setUserInputDraftOption(requestKey, question, label);
|
||||
setUserInputDraftOption(requestKey, questionId, label);
|
||||
},
|
||||
[selectedThreadShell],
|
||||
);
|
||||
|
||||
const onChangeUserInputCustomAnswer = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
|
||||
(requestId: RuntimeRequestId, questionId: string, customAnswer: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
@@ -132,10 +116,16 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
activePendingApprovals.find((approval) => approval.requestId === requestId)
|
||||
?.responseCapability !== "live"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRespondingApprovalId(requestId);
|
||||
const result = await respondToApproval({
|
||||
@@ -149,11 +139,16 @@ export function useSelectedThreadRequests() {
|
||||
setRespondingApprovalId((current) => (current === requestId ? null : current));
|
||||
return result;
|
||||
},
|
||||
[respondToApproval, selectedThreadShell],
|
||||
[activePendingApprovals, respondToApproval, selectedThreadShell],
|
||||
);
|
||||
|
||||
const onSubmitUserInput = useCallback(async () => {
|
||||
if (!selectedThreadShell || !activePendingUserInput || !activePendingUserInputAnswers) {
|
||||
if (
|
||||
!selectedThreadShell ||
|
||||
!activePendingUserInput ||
|
||||
activePendingUserInput.responseCapability !== "live" ||
|
||||
!activePendingUserInputAnswers
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import {
|
||||
@@ -106,13 +107,13 @@ export function useThreadComposerState() {
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread?.session) {
|
||||
if (!selectedThread?.runtime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
orchestrationStatus: selectedThread.session.status,
|
||||
activeTurnId: selectedThread.session.activeTurnId ?? undefined,
|
||||
orchestrationStatus: selectedThread.runtime.status,
|
||||
activeRunId: selectedThread.runtime.activeRunId ?? undefined,
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
|
||||
@@ -123,12 +124,14 @@ export function useThreadComposerState() {
|
||||
}
|
||||
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThread.latestRun,
|
||||
selectedThreadSessionActivity,
|
||||
null,
|
||||
);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
|
||||
const activeThreadBusy = !!selectedThread && threadRuntimeIsActive(selectedThread.runtime);
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
return null;
|
||||
@@ -304,6 +307,7 @@ export function useThreadComposerState() {
|
||||
modelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
onPasteIntoDraft,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import {
|
||||
@@ -221,6 +221,7 @@ export function useThreadOutboxDrain(): void {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: queuedMessage.commandId,
|
||||
creationSource: "mobile",
|
||||
threadId: queuedMessage.threadId,
|
||||
message: {
|
||||
messageId: queuedMessage.messageId,
|
||||
@@ -314,7 +315,7 @@ export function useThreadOutboxDrain(): void {
|
||||
threadExists: thread !== undefined,
|
||||
shellStatus,
|
||||
environmentConnected: environment?.connectionState === "connected",
|
||||
threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting",
|
||||
threadBusy: threadRuntimeIsActive(thread?.runtime),
|
||||
});
|
||||
if (deliveryAction === "wait") {
|
||||
continue;
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
@@ -111,7 +118,7 @@ const providerTurnStartServiceProvided = providerTurnStartServiceLayer.pipe(
|
||||
projectionStoreLayer,
|
||||
providerSessionManagerProvided,
|
||||
runExecutionServiceProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -130,7 +137,7 @@ const checkpointRollbackServiceProvided = checkpointRollbackServiceLayer.pipe(
|
||||
idAllocatorLayer,
|
||||
projectionStoreLayer,
|
||||
providerSessionManagerProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -189,7 +196,7 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
idAllocatorLayer,
|
||||
providerAdapterRegistryProvided,
|
||||
providerEventIngestorProvided,
|
||||
runtimePolicyLayer,
|
||||
runtimePolicyProvided,
|
||||
providerSessionManagerProvided,
|
||||
providerSwitchServiceProvided,
|
||||
runExecutionServiceProvided,
|
||||
@@ -201,9 +208,6 @@ const orchestratorProvided = orchestratorLayer.pipe(
|
||||
const threadManagementProvided = threadManagementServiceLayer.pipe(
|
||||
Layer.provide(orchestratorProvided),
|
||||
);
|
||||
export const ProjectServiceLayerLive = projectServiceLayer.pipe(
|
||||
Layer.provide(Layer.merge(ProjectionProjectRepositoryLive, OrchestrationLayerLive)),
|
||||
);
|
||||
export const ProjectSetupScriptRunnerLayerLive = projectSetupScriptRunnerLayer.pipe(
|
||||
Layer.provide(ProjectServiceLayerLive),
|
||||
);
|
||||
|
||||
+199
-28
@@ -1,8 +1,11 @@
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Result from "effect/Result";
|
||||
@@ -13,9 +16,11 @@ import {
|
||||
type AuthAccessStreamEvent,
|
||||
type AuthEnvironmentScope,
|
||||
AuthSessionId,
|
||||
CommandId,
|
||||
type DiscoveredLocalServerList,
|
||||
type GitActionProgressEvent,
|
||||
type GitManagerServiceError,
|
||||
type MessageId,
|
||||
OrchestrationGetFullThreadDiffError,
|
||||
OrchestrationGetTurnDiffError,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
@@ -28,18 +33,21 @@ import {
|
||||
type ProjectEntriesFailure,
|
||||
type ProjectFileFailure,
|
||||
type ProjectFileOperation,
|
||||
type ProjectMutation,
|
||||
ProjectListEntriesError,
|
||||
ProjectReadFileError,
|
||||
ProjectSearchContentsError,
|
||||
ProjectSearchEntriesError,
|
||||
ProjectWriteFileError,
|
||||
ProjectMutationError,
|
||||
RelayClientInstallFailedError,
|
||||
type RelayClientInstallProgressEvent,
|
||||
type FilesystemBrowseFailure,
|
||||
FilesystemBrowseError,
|
||||
AssetWorkspaceContextNotFoundError,
|
||||
AssetWorkspaceContextResolutionError,
|
||||
RpcClientId,
|
||||
ChatAttachmentId,
|
||||
PersistChatAttachmentsError,
|
||||
EnvironmentAuthorizationError,
|
||||
ThreadId,
|
||||
type TerminalAttachStreamEvent,
|
||||
@@ -81,6 +89,8 @@ import * as TerminalManager from "./terminal/Manager.ts";
|
||||
import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
|
||||
import * as PreviewManager from "./preview/Manager.ts";
|
||||
import { issueAssetUrl } from "./assets/AssetAccess.ts";
|
||||
import { attachmentRelativePath, createDeterministicAttachmentId } from "./attachmentStore.ts";
|
||||
import { parseBase64DataUrl } from "./imageMime.ts";
|
||||
import * as PortScanner from "./preview/PortScanner.ts";
|
||||
import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
|
||||
import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
|
||||
@@ -121,6 +131,73 @@ function unexpectedCompatibilityError(error: never): never {
|
||||
throw new Error(`Unhandled compatibility error: ${String(error)}`);
|
||||
}
|
||||
|
||||
const persistChatAttachments = Effect.fn("ws.assets.persistChatAttachments")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageId: MessageId;
|
||||
readonly attachments: ReadonlyArray<{
|
||||
readonly type: "image";
|
||||
readonly name: string;
|
||||
readonly mimeType: string;
|
||||
readonly sizeBytes: number;
|
||||
readonly dataUrl: string;
|
||||
}>;
|
||||
}) {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
return yield* Effect.forEach(
|
||||
input.attachments.map((attachment, index) => ({ attachment, index })),
|
||||
Effect.fn("ws.assets.persistChatAttachment")(function* ({ attachment, index }) {
|
||||
const parsed = parseBase64DataUrl(attachment.dataUrl);
|
||||
if (parsed === null || parsed.mimeType !== attachment.mimeType.toLowerCase()) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} has an invalid image payload.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* Effect.fromResult(Encoding.decodeBase64(parsed.base64)).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} is not valid base64.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (bytes.byteLength !== attachment.sizeBytes) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: `Attachment ${attachment.name} size does not match its payload.`,
|
||||
});
|
||||
}
|
||||
const rawId = createDeterministicAttachmentId(input.threadId, `${input.messageId}:${index}`);
|
||||
if (rawId === null) {
|
||||
return yield* new PersistChatAttachmentsError({
|
||||
message: "Could not allocate an attachment identifier.",
|
||||
});
|
||||
}
|
||||
const persisted = {
|
||||
type: "image" as const,
|
||||
id: ChatAttachmentId.make(rawId),
|
||||
name: attachment.name,
|
||||
mimeType: attachment.mimeType,
|
||||
sizeBytes: attachment.sizeBytes,
|
||||
};
|
||||
yield* fileSystem
|
||||
.writeFile(path.join(config.attachmentsDir, attachmentRelativePath(persisted)), bytes)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new PersistChatAttachmentsError({
|
||||
message: `Could not persist attachment ${attachment.name}.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return persisted;
|
||||
}),
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
});
|
||||
|
||||
function projectEntriesFailureContext(error: WorkspaceEntries.WorkspaceEntriesError): {
|
||||
readonly failure: ProjectEntriesFailure;
|
||||
readonly normalizedCwd?: string;
|
||||
@@ -256,8 +333,11 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
|
||||
[WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.projectsSearchEntries, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.projectsWriteFile, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.projectsMutate, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.shellOpenInEditor, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.filesystemBrowse, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.assetsCreateUrl, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.assetsPersistChatAttachments, AuthOrchestrationOperateScope],
|
||||
[WS_METHODS.subscribeVcsStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsRefreshStatus, AuthOrchestrationReadScope],
|
||||
[WS_METHODS.vcsPull, AuthOrchestrationOperateScope],
|
||||
@@ -627,20 +707,28 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
},
|
||||
);
|
||||
|
||||
const getOrchestrationV2ArchivedShellSnapshot = threadManagement.getShellSnapshot().pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
schemaVersion: snapshot.schemaVersion,
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
threads: snapshot.archivedThreads,
|
||||
})),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed to load archived thread snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const getOrchestrationV2ArchivedShellSnapshot = sql
|
||||
.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
const projects = yield* projectionSnapshotQuery.getShellSnapshot();
|
||||
const threads = yield* threadManagement.getShellSnapshot();
|
||||
return {
|
||||
schemaVersion: threads.schemaVersion,
|
||||
snapshotSequence: yield* applicationEvents.latestApplicationSequence,
|
||||
projects: projects.projects,
|
||||
threads: threads.archivedThreads,
|
||||
} as const;
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new OrchestrationV2GetShellSnapshotError({
|
||||
message: "Failed to load archived thread snapshot",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const subscribeOrchestrationV2ArchivedShell = Effect.fn(
|
||||
"ws.orchestrationV2.subscribeArchivedShell",
|
||||
@@ -675,6 +763,64 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
return Stream.concat(Stream.make({ kind: "snapshot" as const, snapshot }), live);
|
||||
});
|
||||
|
||||
const mutateProject = Effect.fn("ws.projects.mutate")(function* (mutation: ProjectMutation) {
|
||||
switch (mutation.type) {
|
||||
case "project.create":
|
||||
return yield* projectService.create({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
title: mutation.title,
|
||||
workspaceRoot: mutation.workspaceRoot,
|
||||
...(mutation.createWorkspaceRootIfMissing === undefined
|
||||
? {}
|
||||
: { createWorkspaceRootIfMissing: mutation.createWorkspaceRootIfMissing }),
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
});
|
||||
case "project.update":
|
||||
return yield* projectService.update({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
...(mutation.title === undefined ? {} : { title: mutation.title }),
|
||||
...(mutation.workspaceRoot === undefined
|
||||
? {}
|
||||
: { workspaceRoot: mutation.workspaceRoot }),
|
||||
...(mutation.defaultModelSelection === undefined
|
||||
? {}
|
||||
: { defaultModelSelection: mutation.defaultModelSelection }),
|
||||
...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
|
||||
});
|
||||
case "project.delete": {
|
||||
const snapshot = yield* threadManagement.getShellSnapshot();
|
||||
const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].filter(
|
||||
(thread) => thread.projectId === mutation.projectId,
|
||||
);
|
||||
if (projectThreads.length > 0 && mutation.force !== true) {
|
||||
return yield* new ProjectMutationError({
|
||||
commandId: mutation.commandId,
|
||||
message: `Project ${mutation.projectId} is not empty.`,
|
||||
});
|
||||
}
|
||||
yield* Effect.forEach(
|
||||
projectThreads,
|
||||
(thread) =>
|
||||
threadManagement.dispatch({
|
||||
type: "thread.delete",
|
||||
commandId: CommandId.make(`${mutation.commandId}:delete-thread:${thread.id}`),
|
||||
threadId: thread.id,
|
||||
}),
|
||||
{ concurrency: 1, discard: true },
|
||||
);
|
||||
return yield* projectService.delete({
|
||||
commandId: mutation.commandId,
|
||||
projectId: mutation.projectId,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const handlers = ServerWsRpcGroup.of({
|
||||
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command) =>
|
||||
observeRpcEffect(
|
||||
@@ -684,7 +830,7 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
threadManagement.dispatch(
|
||||
ThreadManagementService.withCreationProvenance(command, {
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
creationSource: "creationSource" in command ? command.creationSource : "web",
|
||||
}),
|
||||
),
|
||||
)
|
||||
@@ -775,26 +921,29 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
.enqueueCommand(
|
||||
threadLaunch.launch({
|
||||
commandId: input.commandId,
|
||||
...(input.threadId === undefined ? {} : { threadId: input.threadId }),
|
||||
...(input.reuseExistingThread === undefined
|
||||
? {}
|
||||
: { reuseExistingThread: input.reuseExistingThread }),
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
modelSelection: input.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
workspaceStrategy:
|
||||
input.workspaceStrategy.type === "root"
|
||||
? { type: "root" }
|
||||
: {
|
||||
type: "worktree",
|
||||
baseRef: input.workspaceStrategy.baseRef,
|
||||
...(input.workspaceStrategy.branch === undefined
|
||||
? {}
|
||||
: { branch: input.workspaceStrategy.branch }),
|
||||
},
|
||||
workspaceStrategy: input.workspaceStrategy,
|
||||
...(input.initialMessage === undefined
|
||||
? {}
|
||||
: { initialMessage: input.initialMessage }),
|
||||
: {
|
||||
initialMessage: {
|
||||
...(input.initialMessage.messageId === undefined
|
||||
? {}
|
||||
: { messageId: input.initialMessage.messageId }),
|
||||
text: input.initialMessage.text,
|
||||
attachments: input.initialMessage.attachments,
|
||||
},
|
||||
}),
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
creationSource: input.creationSource ?? "web",
|
||||
}),
|
||||
)
|
||||
.pipe(
|
||||
@@ -1223,6 +1372,22 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.projectsMutate]: (mutation) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.projectsMutate,
|
||||
startup.enqueueCommand(mutateProject(mutation)).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ProjectMutationError"
|
||||
? cause
|
||||
: new ProjectMutationError({
|
||||
commandId: mutation.commandId,
|
||||
message: "Failed to mutate project.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.shellOpenInEditor]: (input) =>
|
||||
observeRpcEffect(WS_METHODS.shellOpenInEditor, externalLauncher.launchEditor(input), {
|
||||
"rpc.aggregate": "workspace",
|
||||
@@ -1305,6 +1470,12 @@ const makeWsRpcLayer = (currentSession: EnvironmentAuth.AuthenticatedSession) =>
|
||||
}),
|
||||
{ "rpc.aggregate": "workspace" },
|
||||
),
|
||||
[WS_METHODS.assetsPersistChatAttachments]: (input) =>
|
||||
observeRpcEffect(
|
||||
WS_METHODS.assetsPersistChatAttachments,
|
||||
persistChatAttachments(input).pipe(Effect.map((attachments) => ({ attachments }))),
|
||||
{ "rpc.aggregate": "orchestration" },
|
||||
),
|
||||
[WS_METHODS.subscribeVcsStatus]: (input) =>
|
||||
observeRpcStream(
|
||||
WS_METHODS.subscribeVcsStatus,
|
||||
|
||||
@@ -118,6 +118,8 @@ export function BranchToolbarBranchSelector({
|
||||
() => scopeThreadRef(environmentId, threadId),
|
||||
[environmentId, threadId],
|
||||
);
|
||||
const serverThread = useThread(threadRef);
|
||||
const serverSession = serverThread?.runtime ?? null;
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
draftId ? store.getDraftSession(draftId) : store.getDraftThreadByRef(threadRef),
|
||||
);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<<<<<<< HEAD
|
||||
import {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
@@ -7,8 +8,13 @@ import {
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
=======
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, RunId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover)
|
||||
|
||||
import type { Thread, ThreadShell } from "../types";
|
||||
import type { Thread } from "../types";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
import {
|
||||
MAX_HIDDEN_MOUNTED_PREVIEW_THREADS,
|
||||
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
|
||||
@@ -76,7 +82,7 @@ describe("environment reconnect warning grace", () => {
|
||||
});
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: threadId,
|
||||
environmentId,
|
||||
projectId,
|
||||
@@ -87,27 +93,25 @@ 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,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const completedTurn = {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed" as const,
|
||||
runId: RunId.make("turn-1"),
|
||||
status: "completed" as const,
|
||||
requestedAt: now,
|
||||
startedAt: "2026-03-29T00:00:01.000Z",
|
||||
completedAt: "2026-03-29T00:00:10.000Z",
|
||||
@@ -115,12 +119,10 @@ const completedTurn = {
|
||||
};
|
||||
|
||||
const readySession = {
|
||||
threadId,
|
||||
status: "ready" as const,
|
||||
status: "completed" as const,
|
||||
providerName: "codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access" as const,
|
||||
activeTurnId: null,
|
||||
activeRunId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-29T00:00:10.000Z",
|
||||
};
|
||||
@@ -566,16 +568,15 @@ describe("startNewThreadForProject", () => {
|
||||
describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
it("does not acknowledge unchanged server state", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: completedTurn, session: readySession }),
|
||||
makeThread({ latestRun: completedTurn, runtime: readySession }),
|
||||
);
|
||||
|
||||
expect(
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: completedTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: readySession,
|
||||
latestRun: completedTurn,
|
||||
runtime: readySession,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
@@ -585,11 +586,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
|
||||
it("acknowledges a settled newer turn", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: completedTurn, session: readySession }),
|
||||
makeThread({ latestRun: completedTurn, runtime: readySession }),
|
||||
);
|
||||
const newerTurn = {
|
||||
...completedTurn,
|
||||
turnId: TurnId.make("turn-2"),
|
||||
runId: RunId.make("turn-2"),
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: "2026-03-29T00:01:30.000Z",
|
||||
@@ -599,9 +600,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "ready",
|
||||
latestTurn: newerTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: { ...readySession, updatedAt: newerTurn.completedAt },
|
||||
latestRun: newerTurn,
|
||||
runtime: { ...readySession, updatedAt: newerTurn.completedAt },
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
@@ -611,12 +611,12 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
|
||||
it("waits for the matching running turn before acknowledging", () => {
|
||||
const localDispatch = createLocalDispatchSnapshot(
|
||||
makeThread({ latestTurn: completedTurn, session: readySession }),
|
||||
makeThread({ latestRun: completedTurn, runtime: readySession }),
|
||||
);
|
||||
const runningTurn = {
|
||||
...completedTurn,
|
||||
turnId: TurnId.make("turn-2"),
|
||||
state: "running" as const,
|
||||
runId: RunId.make("turn-2"),
|
||||
status: "running" as const,
|
||||
requestedAt: "2026-03-29T00:01:00.000Z",
|
||||
startedAt: "2026-03-29T00:01:01.000Z",
|
||||
completedAt: null,
|
||||
@@ -626,12 +626,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: {
|
||||
latestRun: runningTurn,
|
||||
runtime: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
activeTurnId: TurnId.make("turn-other"),
|
||||
activeRunId: RunId.make("turn-other"),
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -642,12 +641,11 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
hasServerAcknowledgedLocalDispatch({
|
||||
localDispatch,
|
||||
phase: "running",
|
||||
latestTurn: runningTurn,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: {
|
||||
latestRun: runningTurn,
|
||||
runtime: {
|
||||
...readySession,
|
||||
status: "running",
|
||||
activeTurnId: runningTurn.turnId,
|
||||
activeRunId: runningTurn.runId,
|
||||
},
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
@@ -704,9 +702,8 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
|
||||
const common = {
|
||||
localDispatch,
|
||||
phase: "ready" as const,
|
||||
latestTurn: null,
|
||||
latestUserMessageId: localDispatch.latestUserMessageId,
|
||||
session: null,
|
||||
latestRun: null,
|
||||
runtime: null,
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
threadError: null,
|
||||
|
||||
@@ -8,9 +8,11 @@ import {
|
||||
type ScopedProjectRef,
|
||||
type ScopedThreadRef,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import { type ChatMessage, type SessionPhase, type Thread, type ThreadShell } from "../types";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { presentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import { type ChatMessage, type SessionPhase, type Thread } from "../types";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
@@ -83,29 +85,46 @@ export function buildLocalDraftThread(
|
||||
draftThread: DraftThreadState,
|
||||
fallbackModelSelection: ModelSelection,
|
||||
): Thread {
|
||||
return {
|
||||
id: threadId,
|
||||
environmentId: draftThread.environmentId,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
modelSelection: fallbackModelSelection,
|
||||
runtimeMode: draftThread.runtimeMode,
|
||||
interactionMode: draftThread.interactionMode,
|
||||
session: null,
|
||||
const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
|
||||
return presentThread(draftThread.environmentId, {
|
||||
thread: {
|
||||
id: threadId,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
providerInstanceId: fallbackModelSelection.instanceId,
|
||||
modelSelection: fallbackModelSelection,
|
||||
runtimeMode: draftThread.runtimeMode,
|
||||
interactionMode: draftThread.interactionMode,
|
||||
branch: draftThread.branch,
|
||||
worktreePath: draftThread.worktreePath,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
createdAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
runs: [],
|
||||
attempts: [],
|
||||
nodes: [],
|
||||
subagents: [],
|
||||
providerSessions: [],
|
||||
providerThreads: [],
|
||||
providerTurns: [],
|
||||
runtimeRequests: [],
|
||||
messages: [],
|
||||
createdAt: draftThread.createdAt,
|
||||
updatedAt: draftThread.createdAt,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
latestTurn: null,
|
||||
branch: draftThread.branch,
|
||||
worktreePath: draftThread.worktreePath,
|
||||
plans: [],
|
||||
turnItems: [],
|
||||
checkpointScopes: [],
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
};
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt: timestamp,
|
||||
});
|
||||
}
|
||||
|
||||
export function buildLoadingThreadFromShell(shell: ThreadShell): Thread {
|
||||
@@ -366,7 +385,7 @@ export function isBranchMismatchDismissedForSession(key: string | null): boolean
|
||||
|
||||
export function threadHasStarted(thread: Thread | null | undefined): boolean {
|
||||
return Boolean(
|
||||
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
|
||||
thread && (thread.latestRun !== null || thread.messages.length > 0 || thread.runtime !== null),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -390,7 +409,7 @@ export function deriveLockedProvider(input: {
|
||||
if (!threadHasStarted(input.thread)) {
|
||||
return null;
|
||||
}
|
||||
const sessionProvider = input.thread?.session?.providerName ?? null;
|
||||
const sessionProvider = input.thread?.runtime?.providerName ?? null;
|
||||
if (sessionProvider && isProviderDriverKind(sessionProvider)) {
|
||||
return sessionProvider;
|
||||
}
|
||||
@@ -491,41 +510,37 @@ export async function waitForStartedServerThread(
|
||||
export interface LocalDispatchSnapshot {
|
||||
startedAt: string;
|
||||
preparingWorktree: boolean;
|
||||
latestUserMessageId: ChatMessage["id"] | null;
|
||||
latestTurnTurnId: TurnId | null;
|
||||
latestTurnRequestedAt: string | null;
|
||||
latestTurnStartedAt: string | null;
|
||||
latestTurnCompletedAt: string | null;
|
||||
sessionStatus: NonNullable<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 latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
|
||||
const latestRun = activeThread?.latestRun ?? null;
|
||||
const runtime = activeThread?.runtime ?? null;
|
||||
return {
|
||||
startedAt: new Date().toISOString(),
|
||||
preparingWorktree: Boolean(options?.preparingWorktree),
|
||||
latestUserMessageId: latestUserMessage?.id ?? null,
|
||||
latestTurnTurnId: latestTurn?.turnId ?? null,
|
||||
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
|
||||
latestTurnStartedAt: latestTurn?.startedAt ?? null,
|
||||
latestTurnCompletedAt: latestTurn?.completedAt ?? null,
|
||||
sessionStatus: session?.status ?? null,
|
||||
sessionUpdatedAt: session?.updatedAt ?? null,
|
||||
latestRunId: latestRun?.runId ?? null,
|
||||
latestRunRequestedAt: latestRun?.requestedAt ?? null,
|
||||
latestRunStartedAt: latestRun?.startedAt ?? null,
|
||||
latestRunCompletedAt: latestRun?.completedAt ?? null,
|
||||
runtimeStatus: runtime?.status ?? null,
|
||||
runtimeUpdatedAt: runtime?.updatedAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
localDispatch: LocalDispatchSnapshot | null;
|
||||
phase: SessionPhase;
|
||||
latestTurn: Thread["latestTurn"] | null;
|
||||
latestUserMessageId: ChatMessage["id"] | null;
|
||||
session: Thread["session"] | null;
|
||||
latestRun: Thread["latestRun"] | null;
|
||||
runtime: Thread["runtime"] | null;
|
||||
hasPendingApproval: boolean;
|
||||
hasPendingUserInput: boolean;
|
||||
threadError: string | null | undefined;
|
||||
@@ -537,34 +552,25 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
return true;
|
||||
}
|
||||
|
||||
const latestTurn = input.latestTurn ?? null;
|
||||
const session = input.session ?? null;
|
||||
const latestUserMessageChanged =
|
||||
input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
|
||||
const latestTurnChanged =
|
||||
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
|
||||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
|
||||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
|
||||
const latestRun = input.latestRun ?? null;
|
||||
const runtime = input.runtime ?? null;
|
||||
const latestRunChanged =
|
||||
input.localDispatch.latestRunId !== (latestRun?.runId ?? null) ||
|
||||
input.localDispatch.latestRunRequestedAt !== (latestRun?.requestedAt ?? null) ||
|
||||
input.localDispatch.latestRunStartedAt !== (latestRun?.startedAt ?? null) ||
|
||||
input.localDispatch.latestRunCompletedAt !== (latestRun?.completedAt ?? null);
|
||||
|
||||
if (input.phase === "running") {
|
||||
// Steering adds a user message to the current running turn without
|
||||
// necessarily changing any of the turn timestamps. Treat that projected
|
||||
// message as the server acknowledgment so the composer does not remain
|
||||
// stuck in its local "Sending" state until the turn settles.
|
||||
if (latestUserMessageChanged) {
|
||||
return true;
|
||||
}
|
||||
if (!latestTurnChanged) {
|
||||
if (!latestRunChanged) {
|
||||
return false;
|
||||
}
|
||||
if (latestTurn?.startedAt === null || latestTurn === null) {
|
||||
if (latestRun?.startedAt === null || latestRun === null) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
session?.activeTurnId !== null &&
|
||||
session?.activeTurnId !== undefined &&
|
||||
latestTurn?.turnId !== session.activeTurnId
|
||||
runtime?.activeRunId !== null &&
|
||||
runtime?.activeRunId !== undefined &&
|
||||
latestRun?.runId !== runtime.activeRunId
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -572,8 +578,8 @@ export function hasServerAcknowledgedLocalDispatch(input: {
|
||||
}
|
||||
|
||||
return (
|
||||
latestTurnChanged ||
|
||||
input.localDispatch.sessionStatus !== (session?.status ?? null) ||
|
||||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
|
||||
latestRunChanged ||
|
||||
input.localDispatch.runtimeStatus !== (runtime?.status ?? null) ||
|
||||
input.localDispatch.runtimeUpdatedAt !== (runtime?.updatedAt ?? null)
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { Thread } from "../types";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
import {
|
||||
browseInputEndPaddingClass,
|
||||
buildBrowseGroups,
|
||||
@@ -143,7 +144,7 @@ const LOCAL_ENVIRONMENT_ID = EnvironmentId.make("environment-local");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: LOCAL_ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
@@ -151,7 +152,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-01T00:00:00.000Z",
|
||||
@@ -160,13 +161,11 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-01T00:00:00.000Z",
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("buildThreadActionItems", () => {
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
|
||||
import type { ScopedThreadRef, RunId } from "@t3tools/contracts";
|
||||
import {
|
||||
ArrowRightIcon,
|
||||
CheckIcon,
|
||||
@@ -161,55 +161,55 @@ export default function DiffPanel({
|
||||
),
|
||||
);
|
||||
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
|
||||
const { turnDiffSummaries, inferredCheckpointTurnCountByRunId } =
|
||||
useTurnDiffSummaries(activeThread);
|
||||
const orderedTurnDiffSummaries = useMemo(
|
||||
() =>
|
||||
[...turnDiffSummaries].toSorted((left, right) => {
|
||||
const leftTurnCount =
|
||||
left.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[left.turnId] ?? 0;
|
||||
left.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[left.runId] ?? 0;
|
||||
const rightTurnCount =
|
||||
right.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[right.turnId] ?? 0;
|
||||
right.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[right.runId] ?? 0;
|
||||
if (leftTurnCount !== rightTurnCount) {
|
||||
return rightTurnCount - leftTurnCount;
|
||||
}
|
||||
return right.completedAt.localeCompare(left.completedAt);
|
||||
}),
|
||||
[inferredCheckpointTurnCountByTurnId, turnDiffSummaries],
|
||||
[inferredCheckpointTurnCountByRunId, turnDiffSummaries],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!routeThreadRef || diffSelection.kind !== "turn") return;
|
||||
useDiffPanelStore.getState().reconcileTurnSelection(
|
||||
routeThreadRef,
|
||||
orderedTurnDiffSummaries.map((summary) => summary.turnId),
|
||||
orderedTurnDiffSummaries.map((summary) => summary.runId),
|
||||
);
|
||||
}, [diffSelection, orderedTurnDiffSummaries, routeThreadRef]);
|
||||
|
||||
const selectedTurnId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
|
||||
const selectedRunId = diffSelection.kind === "turn" ? diffSelection.turnId : null;
|
||||
const selectedGitScope = diffSelection.kind === "unstaged" ? "unstaged" : "branch";
|
||||
const selectedBaseRef = diffSelection.kind === "branch" ? diffSelection.baseRef : null;
|
||||
const selectedFilePath = diffSelection.kind === "turn" ? diffSelection.filePath : null;
|
||||
const selectedFileRevealRequestId =
|
||||
diffSelection.kind === "turn" ? diffSelection.revealRequestId : 0;
|
||||
const selectedTurn =
|
||||
selectedTurnId === null
|
||||
selectedRunId === null
|
||||
? undefined
|
||||
: (orderedTurnDiffSummaries.find((summary) => summary.turnId === selectedTurnId) ??
|
||||
: (orderedTurnDiffSummaries.find((summary) => summary.runId === selectedRunId) ??
|
||||
orderedTurnDiffSummaries[0]);
|
||||
const selectedCheckpointTurnCount =
|
||||
selectedTurn &&
|
||||
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[selectedTurn.turnId]);
|
||||
(selectedTurn.checkpointTurnCount ?? inferredCheckpointTurnCountByRunId[selectedTurn.runId]);
|
||||
const latestTurn = orderedTurnDiffSummaries[0];
|
||||
const selectedScopeLabel =
|
||||
selectedTurnId === null
|
||||
selectedRunId === null
|
||||
? selectedGitScope === "unstaged"
|
||||
? "Working tree"
|
||||
: "Branch changes"
|
||||
: selectedTurn?.turnId === latestTurn?.turnId
|
||||
: selectedTurn?.runId === latestTurn?.runId
|
||||
? "Latest turn"
|
||||
: `Turn ${selectedCheckpointTurnCount ?? "?"}`;
|
||||
const reviewSectionId = selectedTurn ? `turn:${selectedTurn.turnId}` : selectedGitScope;
|
||||
const reviewSectionId = selectedTurn ? `turn:${selectedTurn.runId}` : selectedGitScope;
|
||||
const collapseScopeKey = routeThreadRef
|
||||
? `${routeThreadRef.environmentId}:${routeThreadRef.threadId}:${reviewSectionId}`
|
||||
: null;
|
||||
@@ -240,12 +240,12 @@ export default function DiffPanel({
|
||||
fromTurnCount: selectedCheckpointRange?.fromTurnCount ?? null,
|
||||
toTurnCount: selectedCheckpointRange?.toTurnCount ?? null,
|
||||
ignoreWhitespace: diffIgnoreWhitespace,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.turnId}` : null,
|
||||
cacheScope: selectedTurn ? `turn:${selectedTurn.runId}` : null,
|
||||
},
|
||||
{ enabled: isGitRepo && selectedTurn !== undefined },
|
||||
);
|
||||
const primaryBranchDiffPreview = useEnvironmentQuery(
|
||||
selectedTurnId === null && activeThread && activeCwd
|
||||
selectedRunId === null && activeThread && activeCwd
|
||||
? reviewEnvironment.diffPreview({
|
||||
environmentId: activeThread.environmentId,
|
||||
input: {
|
||||
@@ -257,7 +257,7 @@ export default function DiffPanel({
|
||||
: null,
|
||||
);
|
||||
const shouldRetryBranchDiffAtEnvironmentCwd =
|
||||
selectedTurnId === null &&
|
||||
selectedRunId === null &&
|
||||
primaryBranchDiffPreview.error?.includes("configured workspace root") === true &&
|
||||
serverConfig?.cwd !== undefined &&
|
||||
serverConfig.cwd !== activeCwd;
|
||||
@@ -333,7 +333,7 @@ export default function DiffPanel({
|
||||
selectedTurnId,
|
||||
]);
|
||||
const localBranchRefs = useEnvironmentQuery(
|
||||
selectedTurnId === null &&
|
||||
selectedRunId === null &&
|
||||
selectedGitScope === "branch" &&
|
||||
activeThread &&
|
||||
branchDiffPreview.data?.cwd
|
||||
@@ -350,7 +350,7 @@ export default function DiffPanel({
|
||||
: null,
|
||||
);
|
||||
const remoteBranchRefs = useEnvironmentQuery(
|
||||
selectedTurnId === null &&
|
||||
selectedRunId === null &&
|
||||
selectedGitScope === "branch" &&
|
||||
activeThread &&
|
||||
branchDiffPreview.data?.cwd
|
||||
@@ -393,9 +393,9 @@ export default function DiffPanel({
|
||||
const renderablePatch = useMemo(
|
||||
() =>
|
||||
getRenderablePatch(selectedPatch, `diff-panel:${resolvedTheme}`, {
|
||||
compactPartialHunkOffsets: selectedTurnId === null,
|
||||
compactPartialHunkOffsets: selectedRunId === null,
|
||||
}),
|
||||
[resolvedTheme, selectedPatch, selectedTurnId],
|
||||
[resolvedTheme, selectedPatch, selectedRunId],
|
||||
);
|
||||
const renderableFiles = useMemo(() => {
|
||||
if (!renderablePatch || renderablePatch.kind !== "files") {
|
||||
@@ -496,9 +496,9 @@ export default function DiffPanel({
|
||||
});
|
||||
}, [collapseScopeKey, diffFileKeys]);
|
||||
|
||||
const selectTurn = (turnId: TurnId) => {
|
||||
const selectTurn = (runId: RunId) => {
|
||||
if (!routeThreadRef) return;
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, turnId);
|
||||
useDiffPanelStore.getState().selectTurn(routeThreadRef, runId);
|
||||
};
|
||||
const selectGitScope = (scope: "branch" | "unstaged") => {
|
||||
if (!routeThreadRef) return;
|
||||
@@ -530,6 +530,15 @@ export default function DiffPanel({
|
||||
onClick={() => selectGitScope("unstaged")}
|
||||
>
|
||||
<span>Working tree</span>
|
||||
{selectedRunId === null && selectedGitScope === "unstaged" && (
|
||||
<CheckIcon className="ml-auto" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={() => selectGitScope("branch")}>
|
||||
<span>Branch changes</span>
|
||||
{selectedRunId === null && selectedGitScope === "branch" && (
|
||||
<CheckIcon className="ml-auto" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
className={
|
||||
@@ -548,10 +557,13 @@ export default function DiffPanel({
|
||||
: undefined
|
||||
}
|
||||
onClick={() => {
|
||||
if (latestTurn) selectTurn(latestTurn.turnId);
|
||||
if (latestTurn) selectTurn(latestTurn.runId);
|
||||
}}
|
||||
>
|
||||
<span>Latest turn</span>
|
||||
{selectedRunId !== null && selectedTurn?.runId === latestTurn?.runId && (
|
||||
<CheckIcon className="ml-auto" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSub>
|
||||
<DropdownMenuSubTrigger>Turn</DropdownMenuSubTrigger>
|
||||
@@ -559,20 +571,15 @@ export default function DiffPanel({
|
||||
{orderedTurnDiffSummaries.map((summary) => {
|
||||
const turnCount =
|
||||
summary.checkpointTurnCount ??
|
||||
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
|
||||
inferredCheckpointTurnCountByRunId[summary.runId] ??
|
||||
"?";
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
key={summary.turnId}
|
||||
className={
|
||||
summary.turnId === selectedTurn?.turnId ? "bg-foreground/[0.08]" : undefined
|
||||
}
|
||||
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.runId === selectedTurn?.runId && <CheckIcon className="ml-1" />}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
})}
|
||||
@@ -580,7 +587,7 @@ export default function DiffPanel({
|
||||
</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}`}
|
||||
@@ -823,7 +830,7 @@ export default function DiffPanel({
|
||||
<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>
|
||||
|
||||
@@ -36,20 +36,14 @@ import {
|
||||
shouldCreateNewThreadInCurrentProject,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationLatestTurn,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type Thread,
|
||||
} from "../types";
|
||||
import { makeThreadFixture } from "../test-fixtures";
|
||||
|
||||
const localEnvironmentId = EnvironmentId.make("environment-local");
|
||||
|
||||
@@ -244,13 +238,13 @@ describe("resolveSidebarStageBadgeLabel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
function makeLatestTurn(overrides?: {
|
||||
function makeLatestRun(overrides?: {
|
||||
completedAt?: string | null;
|
||||
startedAt?: string | null;
|
||||
}): OrchestrationLatestTurn {
|
||||
}): NonNullable<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:
|
||||
@@ -268,9 +262,9 @@ describe("hasUnseenCompletion", () => {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "default",
|
||||
latestTurn: makeLatestTurn(),
|
||||
latestRun: makeLatestRun(),
|
||||
lastVisitedAt: "2026-03-09T10:04:00.000Z",
|
||||
session: null,
|
||||
runtime: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -282,9 +276,9 @@ describe("hasUnseenCompletion", () => {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "default",
|
||||
latestTurn: makeLatestTurn(),
|
||||
latestRun: makeLatestRun(),
|
||||
lastVisitedAt: undefined,
|
||||
session: null,
|
||||
runtime: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -1052,15 +1046,13 @@ describe("resolveThreadStatusPill", () => {
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
interactionMode: "plan" as const,
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
lastVisitedAt: undefined,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
runtime: {
|
||||
status: "running" as const,
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
activeTurnId: "turn-1" as never,
|
||||
activeRunId: "turn-1" as never,
|
||||
lastError: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
},
|
||||
@@ -1103,11 +1095,11 @@ describe("resolveThreadStatusPill", () => {
|
||||
thread: {
|
||||
...baseThread,
|
||||
hasActionableProposedPlan: true,
|
||||
latestTurn: makeLatestTurn(),
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
latestRun: makeLatestRun(),
|
||||
runtime: {
|
||||
...baseThread.runtime,
|
||||
status: "completed",
|
||||
activeRunId: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -1119,11 +1111,11 @@ describe("resolveThreadStatusPill", () => {
|
||||
resolveThreadStatusPill({
|
||||
thread: {
|
||||
...baseThread,
|
||||
latestTurn: makeLatestTurn(),
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
latestRun: makeLatestRun(),
|
||||
runtime: {
|
||||
...baseThread.runtime,
|
||||
status: "completed",
|
||||
activeRunId: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -1136,12 +1128,12 @@ describe("resolveThreadStatusPill", () => {
|
||||
thread: {
|
||||
...baseThread,
|
||||
interactionMode: "default",
|
||||
latestTurn: makeLatestTurn(),
|
||||
latestRun: makeLatestRun(),
|
||||
lastVisitedAt: "2026-03-09T10:04:00.000Z",
|
||||
session: {
|
||||
...baseThread.session,
|
||||
status: "ready",
|
||||
activeTurnId: null,
|
||||
runtime: {
|
||||
...baseThread.runtime,
|
||||
status: "completed",
|
||||
activeRunId: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
@@ -1293,7 +1285,7 @@ function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
}
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
return makeThreadFixture({
|
||||
id: ThreadId.make("thread-1"),
|
||||
environmentId: localEnvironmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
@@ -1305,7 +1297,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
session: null,
|
||||
runtime: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
@@ -1314,13 +1306,11 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("getFallbackThreadIdAfterDelete", () => {
|
||||
@@ -1404,7 +1394,7 @@ describe("sortProjectsForSidebar", () => {
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older project user message",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
@@ -1420,7 +1410,7 @@ describe("sortProjectsForSidebar", () => {
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer project user message",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
streaming: false,
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
import type { SidebarThreadSummary, Thread } from "../types";
|
||||
import type { ThreadRouteTarget } from "../threadRoutes";
|
||||
import { cn } from "../lib/utils";
|
||||
import { isLatestTurnSettled } from "../session-logic";
|
||||
import { isLatestRunSettled } from "../session-logic";
|
||||
import { resolveServerBackedAppStageLabel } from "../branding.logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
@@ -150,9 +150,14 @@ type ThreadStatusInput = Pick<
|
||||
| "hasPendingApprovals"
|
||||
| "hasPendingUserInput"
|
||||
| "interactionMode"
|
||||
<<<<<<< HEAD
|
||||
| "latestTurn"
|
||||
| "session"
|
||||
| "backgroundLiveness"
|
||||
=======
|
||||
| "latestRun"
|
||||
| "runtime"
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
> & {
|
||||
lastVisitedAt?: string | undefined;
|
||||
};
|
||||
@@ -250,8 +255,8 @@ export function useThreadJumpHintVisibility(): {
|
||||
}
|
||||
|
||||
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
if (!thread.latestRun?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestRun.completedAt);
|
||||
if (Number.isNaN(completedAt)) return false;
|
||||
if (!thread.lastVisitedAt) return false;
|
||||
|
||||
@@ -658,7 +663,7 @@ export function resolveThreadStatusPill(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "running") {
|
||||
if (thread.runtime?.status === "running" || thread.runtime?.status === "waiting") {
|
||||
return {
|
||||
label: "Working",
|
||||
colorClass: "text-sky-600 dark:text-sky-300/80",
|
||||
@@ -667,7 +672,7 @@ export function resolveThreadStatusPill(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "starting") {
|
||||
if (thread.runtime?.status === "starting" || thread.runtime?.status === "queued") {
|
||||
return {
|
||||
label: "Connecting",
|
||||
colorClass: "text-sky-600 dark:text-sky-300/80",
|
||||
@@ -681,7 +686,7 @@ export function resolveThreadStatusPill(input: {
|
||||
const hasPlanReadyPrompt =
|
||||
!thread.hasPendingUserInput &&
|
||||
thread.interactionMode === "plan" &&
|
||||
isLatestTurnSettled(thread.latestTurn, thread.session) &&
|
||||
isLatestRunSettled(thread.latestRun, thread.runtime) &&
|
||||
thread.hasActionableProposedPlan;
|
||||
if (hasPlanReadyPrompt) {
|
||||
return {
|
||||
|
||||
+199
-185
@@ -143,15 +143,10 @@ import {
|
||||
import { resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic";
|
||||
import {
|
||||
ThreadWorktreeIndicator,
|
||||
nextThreadChangeRequestSnapshot,
|
||||
prStatusIndicator,
|
||||
resolveDisplayedThreadPr,
|
||||
resolveDisplayedThreadPrProvider,
|
||||
setThreadChangeRequestSnapshot,
|
||||
resolveThreadPr,
|
||||
settledPrHoverColorClass,
|
||||
terminalStatusFromRunningIds,
|
||||
threadChangeRequestSnapshotsAtom,
|
||||
type ThreadChangeRequestSnapshot,
|
||||
type TerminalStatusIndicator,
|
||||
} from "./ThreadStatusIndicators";
|
||||
import {
|
||||
@@ -163,11 +158,7 @@ import {
|
||||
import { ProjectFavicon } from "./ProjectFavicon";
|
||||
import { ProviderInstanceIcon } from "./chat/ProviderInstanceIcon";
|
||||
import { getTriggerDisplayModelLabel } from "./chat/providerIconUtils";
|
||||
import {
|
||||
deriveProviderInstanceEntries,
|
||||
shouldShowInstanceBadge,
|
||||
type ProviderInstanceEntry,
|
||||
} from "../providerInstances";
|
||||
import { deriveProviderInstanceEntries, type ProviderInstanceEntry } from "../providerInstances";
|
||||
import { primaryServerProvidersAtom } from "../state/server";
|
||||
import { useThreadRunningTerminalIds } from "../state/terminalSessions";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
@@ -256,8 +247,7 @@ function SidebarThreadTooltip({
|
||||
projectCwd,
|
||||
projectFaviconPath,
|
||||
environmentLabel,
|
||||
providerEntry,
|
||||
showInstanceBadge,
|
||||
driverKind,
|
||||
modelInstanceId,
|
||||
modelLabel,
|
||||
branchMismatch,
|
||||
@@ -269,8 +259,7 @@ function SidebarThreadTooltip({
|
||||
projectCwd: string | null;
|
||||
projectFaviconPath: string | null;
|
||||
environmentLabel: string | null;
|
||||
providerEntry: ProviderInstanceEntry | null;
|
||||
showInstanceBadge: boolean;
|
||||
driverKind: ProviderInstanceEntry["driverKind"] | null;
|
||||
modelInstanceId: string;
|
||||
modelLabel: string;
|
||||
branchMismatch: {
|
||||
@@ -280,7 +269,6 @@ function SidebarThreadTooltip({
|
||||
terminalStatus: TerminalStatusIndicator | null;
|
||||
terminalProcessCount: number;
|
||||
}) {
|
||||
const driverKind = providerEntry?.driverKind ?? null;
|
||||
return (
|
||||
<TooltipPopup
|
||||
side="right"
|
||||
@@ -329,21 +317,10 @@ function SidebarThreadTooltip({
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<ProviderInstanceIcon
|
||||
driverKind={driverKind}
|
||||
displayName={
|
||||
providerEntry?.displayName ?? thread.session?.providerName ?? modelInstanceId
|
||||
}
|
||||
accentColor={providerEntry?.accentColor}
|
||||
// Initials would swallow a size-3 glyph: accent dot, name in label.
|
||||
showBadge={showInstanceBadge && providerEntry?.accentColor !== undefined}
|
||||
badgeContent="none"
|
||||
badgeClassName="h-2 min-w-2 px-0"
|
||||
displayName={thread.session?.providerName ?? modelInstanceId}
|
||||
iconClassName="size-3 shrink-0 grayscale opacity-60"
|
||||
/>
|
||||
<div className="min-w-0 truncate text-foreground/75">
|
||||
{showInstanceBadge && providerEntry
|
||||
? `${modelLabel} · ${providerEntry.displayName}`
|
||||
: modelLabel}
|
||||
</div>
|
||||
<div className="min-w-0 truncate text-foreground/75">{modelLabel}</div>
|
||||
</div>
|
||||
) : null}
|
||||
{terminalStatus ? (
|
||||
@@ -389,26 +366,19 @@ function SnoozePopoverButton(props: {
|
||||
);
|
||||
return (
|
||||
<Popover open={open} onOpenChange={onOpenChange}>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Snooze thread"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onDoubleClick={(event) => event.stopPropagation()}
|
||||
className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ClockIcon className="size-3" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup>Snooze thread</TooltipPopup>
|
||||
</Tooltip>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Snooze thread"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onDoubleClick={(event) => event.stopPropagation()}
|
||||
className="inline-flex h-full cursor-pointer items-center gap-0.5 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ClockIcon className="size-3" />
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup side="bottom" align="end" className="w-56" viewportClassName="p-1">
|
||||
{presets.map((preset) => (
|
||||
<button
|
||||
@@ -734,16 +704,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
onUnsnooze: (threadRef: ScopedThreadRef) => void;
|
||||
onUnpin: (threadRef: ScopedThreadRef) => void;
|
||||
onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void;
|
||||
changeRequestSnapshot: ThreadChangeRequestSnapshot | null;
|
||||
onChangeRequestSnapshot: (
|
||||
threadKey: string,
|
||||
snapshot: ThreadChangeRequestSnapshot | null,
|
||||
) => void;
|
||||
onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void;
|
||||
}) {
|
||||
const {
|
||||
isRenaming,
|
||||
changeRequestSnapshot,
|
||||
onChangeRequestSnapshot,
|
||||
onChangeRequestState,
|
||||
onCancelRename,
|
||||
onCommitRename,
|
||||
onContextMenu,
|
||||
@@ -788,12 +753,46 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const retainTerminalOnBranchMismatch = thread.worktreePath === null;
|
||||
const pr = resolveDisplayedThreadPr({
|
||||
<<<<<<< HEAD
|
||||
=======
|
||||
const isHighlighted = isActive || isSelected;
|
||||
const handleOpenDiscoveredPort = useCallback(
|
||||
(event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
const port = discoveredPorts[0];
|
||||
if (!port) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
navigateToThread(threadRef);
|
||||
void (async () => {
|
||||
const result = await openDiscoveredPort({ threadRef, port, openPreview });
|
||||
if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
|
||||
return;
|
||||
}
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Unable to open preview",
|
||||
description:
|
||||
error instanceof Error ? error.message : "The preview could not be opened.",
|
||||
}),
|
||||
);
|
||||
})();
|
||||
},
|
||||
[discoveredPorts, navigateToThread, openPreview, threadRef],
|
||||
);
|
||||
const isThreadRunning =
|
||||
thread.runtime?.status === "running" && thread.runtime.activeRunId != null;
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread: {
|
||||
...thread,
|
||||
lastVisitedAt,
|
||||
},
|
||||
});
|
||||
>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover)
|
||||
const pr = resolveThreadPr({
|
||||
threadBranch: thread.branch,
|
||||
gitStatus: gitStatus.data,
|
||||
snapshot: changeRequestSnapshot,
|
||||
retainTerminalOnBranchMismatch,
|
||||
});
|
||||
const prState = pr?.state ?? null;
|
||||
|
||||
@@ -887,38 +886,17 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
activeThreadBranch: thread.branch,
|
||||
currentGitBranch: gitStatus.data?.refName ?? null,
|
||||
});
|
||||
const prProvider = resolveDisplayedThreadPrProvider({
|
||||
threadBranch: thread.branch,
|
||||
gitStatus: gitStatus.data,
|
||||
snapshot: changeRequestSnapshot,
|
||||
retainTerminalOnBranchMismatch,
|
||||
});
|
||||
const prStatus = prStatusIndicator(pr, prProvider);
|
||||
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
|
||||
const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined;
|
||||
// Report the PR state so the parent can apply the configured merge rule
|
||||
// and the always-on close rule during partitioning.
|
||||
useEffect(() => {
|
||||
const nextSnapshot = nextThreadChangeRequestSnapshot({
|
||||
threadBranch: thread.branch,
|
||||
gitStatus: gitStatus.data,
|
||||
snapshot: changeRequestSnapshot,
|
||||
retainTerminalOnBranchMismatch,
|
||||
});
|
||||
if (nextSnapshot === undefined) return;
|
||||
onChangeRequestSnapshot(threadKey, nextSnapshot);
|
||||
}, [
|
||||
changeRequestSnapshot,
|
||||
gitStatus.data,
|
||||
onChangeRequestSnapshot,
|
||||
retainTerminalOnBranchMismatch,
|
||||
thread.branch,
|
||||
threadKey,
|
||||
]);
|
||||
onChangeRequestState(threadKey, prState);
|
||||
}, [onChangeRequestState, prState, threadKey]);
|
||||
|
||||
const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;
|
||||
const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;
|
||||
const driverKind = providerEntry?.driverKind ?? null;
|
||||
const showInstanceBadge =
|
||||
providerEntry !== null &&
|
||||
shouldShowInstanceBadge(providerEntry, props.providerEntryByInstanceId.values());
|
||||
const selectedModel = providerEntry?.models.find(
|
||||
(model) => model.slug === thread.modelSelection.model,
|
||||
);
|
||||
@@ -936,8 +914,7 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
projectCwd={props.projectCwd}
|
||||
projectFaviconPath={props.projectFaviconPath}
|
||||
environmentLabel={props.environmentLabel}
|
||||
providerEntry={providerEntry}
|
||||
showInstanceBadge={showInstanceBadge}
|
||||
driverKind={driverKind}
|
||||
modelInstanceId={modelInstanceId}
|
||||
modelLabel={modelLabel}
|
||||
branchMismatch={branchMismatch}
|
||||
@@ -1372,21 +1349,15 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
)}
|
||||
{props.isPinned ? (
|
||||
props.pinningSupported ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Unpin thread"
|
||||
onClick={handleUnpinClick}
|
||||
className="inline-flex cursor-pointer items-center rounded-sm text-muted-foreground/65 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<PinIcon aria-hidden className="size-3 shrink-0" />
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup>Unpin thread</TooltipPopup>
|
||||
</Tooltip>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Unpin thread"
|
||||
title="Unpin thread"
|
||||
onClick={handleUnpinClick}
|
||||
className="inline-flex cursor-pointer items-center rounded-sm text-muted-foreground/65 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<PinIcon aria-hidden className="size-3 shrink-0" />
|
||||
</button>
|
||||
) : (
|
||||
<PinIcon
|
||||
aria-label="Pinned"
|
||||
@@ -1475,22 +1446,15 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
/>
|
||||
) : null}
|
||||
{props.settlementSupported ? (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Settle thread"
|
||||
onClick={handleSettleClick}
|
||||
className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
Settle
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup>Settle thread</TooltipPopup>
|
||||
</Tooltip>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Settle thread"
|
||||
onClick={handleSettleClick}
|
||||
className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<CheckIcon className="size-3.5" />
|
||||
Settle
|
||||
</button>
|
||||
) : null}
|
||||
</span>
|
||||
) : null}
|
||||
@@ -1534,19 +1498,11 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
|
||||
</span>
|
||||
) : null}
|
||||
{driverKind ? (
|
||||
<span className="inline-flex shrink-0 items-center">
|
||||
<span className="inline-flex shrink-0 items-center opacity-60">
|
||||
<ProviderInstanceIcon
|
||||
driverKind={driverKind}
|
||||
displayName={
|
||||
providerEntry?.displayName ??
|
||||
thread.session?.providerName ??
|
||||
modelInstanceId
|
||||
}
|
||||
accentColor={providerEntry?.accentColor}
|
||||
showBadge={showInstanceBadge}
|
||||
// Glyph dims, badge stays saturated; offset matches the composer trigger.
|
||||
iconClassName="size-3.5 opacity-60"
|
||||
badgeClassName="right-[-0.1875rem] bottom-[-0.1875rem] h-3 min-w-3 px-0.5 text-[7px]"
|
||||
displayName={thread.session?.providerName ?? modelInstanceId}
|
||||
iconClassName="size-3.5"
|
||||
/>
|
||||
</span>
|
||||
) : null}
|
||||
@@ -1603,9 +1559,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
|
||||
});
|
||||
const modelInstanceId = thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;
|
||||
const providerEntry = props.providerEntryByInstanceId.get(modelInstanceId) ?? null;
|
||||
const showInstanceBadge =
|
||||
providerEntry !== null &&
|
||||
shouldShowInstanceBadge(providerEntry, props.providerEntryByInstanceId.values());
|
||||
const driverKind = providerEntry?.driverKind ?? null;
|
||||
const selectedModel = providerEntry?.models.find(
|
||||
(model) => model.slug === thread.modelSelection.model,
|
||||
);
|
||||
@@ -1663,8 +1617,7 @@ const SidebarSearchResultRow = memo(function SidebarSearchResultRow(props: {
|
||||
projectCwd={props.projectCwd}
|
||||
projectFaviconPath={props.projectFaviconPath}
|
||||
environmentLabel={props.environmentLabel}
|
||||
providerEntry={providerEntry}
|
||||
showInstanceBadge={showInstanceBadge}
|
||||
driverKind={driverKind}
|
||||
modelInstanceId={modelInstanceId}
|
||||
modelLabel={modelLabel}
|
||||
branchMismatch={branchMismatch}
|
||||
@@ -1686,7 +1639,6 @@ export default function Sidebar() {
|
||||
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
|
||||
const autoSettleOnMerge = useClientSettings((s) => s.sidebarAutoSettleOnMerge);
|
||||
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
|
||||
const confirmThreadArchive = useClientSettings((s) => s.confirmThreadArchive);
|
||||
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
|
||||
const timestampFormat = useClientSettings((s) => s.timestampFormat);
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
@@ -1698,7 +1650,6 @@ export default function Sidebar() {
|
||||
pinThread,
|
||||
unpinThread,
|
||||
reorderPinnedThread,
|
||||
archiveThread,
|
||||
deleteThread,
|
||||
} = useThreadActions();
|
||||
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
|
||||
@@ -1889,7 +1840,26 @@ export default function Sidebar() {
|
||||
// fresh clock whenever it recomputes.
|
||||
const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);
|
||||
|
||||
const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom);
|
||||
// PR states stream in per-row. The next partition applies the configured
|
||||
// merge rule and the always-on close rule.
|
||||
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
|
||||
ReadonlyMap<string, "open" | "closed" | "merged">
|
||||
>(() => new Map());
|
||||
const handleChangeRequestState = useCallback(
|
||||
(threadKey: string, state: "open" | "closed" | "merged" | null) => {
|
||||
setChangeRequestStateByKey((current) => {
|
||||
if ((current.get(threadKey) ?? null) === state) return current;
|
||||
const next = new Map(current);
|
||||
if (state === null) {
|
||||
next.delete(threadKey);
|
||||
} else {
|
||||
next.set(threadKey, state);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
// Project scope: one menu above the list. Scoping filters the list without
|
||||
// making the header width depend on the number or length of project names.
|
||||
@@ -2005,11 +1975,7 @@ export default function Sidebar() {
|
||||
const supportsSnooze =
|
||||
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
|
||||
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
|
||||
const snapshot = changeRequestSnapshotByKey.get(threadKey);
|
||||
const changeRequestState =
|
||||
snapshot != null && (thread.worktreePath === null || snapshot.branch === thread.branch)
|
||||
? snapshot.pr.state
|
||||
: null;
|
||||
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
|
||||
// Snooze outranks everything, including a pin: "hide until Tuesday"
|
||||
// temporarily suspends "keep on top". The pin survives underneath —
|
||||
// and so does its pinOrderKey, so on wake the thread reappears at
|
||||
@@ -2067,7 +2033,7 @@ export default function Sidebar() {
|
||||
}, [
|
||||
autoSettleAfterDays,
|
||||
autoSettleOnMerge,
|
||||
changeRequestSnapshotByKey,
|
||||
changeRequestStateByKey,
|
||||
nowMinute,
|
||||
scopedProjectKeys,
|
||||
serverConfigs,
|
||||
@@ -2447,6 +2413,7 @@ export default function Sidebar() {
|
||||
[navigateToThread, router],
|
||||
);
|
||||
|
||||
<<<<<<< HEAD
|
||||
const attemptSettle = useCallback(
|
||||
(threadRef: ScopedThreadRef, opts: { coSettlingKeys?: ReadonlySet<string> } = {}) => {
|
||||
void (async () => {
|
||||
@@ -2477,6 +2444,17 @@ export default function Sidebar() {
|
||||
}
|
||||
} finally {
|
||||
settlingThreadKeysRef.current.delete(threadKey);
|
||||
=======
|
||||
const clicked = await api.contextMenu.show(
|
||||
buildMultiSelectThreadContextMenuItems({ count, hasRunningThread }),
|
||||
position,
|
||||
);
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
for (const threadKey of threadKeys) {
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey);
|
||||
markThreadUnread(threadKey, thread?.latestRun?.completedAt);
|
||||
>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover)
|
||||
}
|
||||
})();
|
||||
},
|
||||
@@ -2996,6 +2974,7 @@ export default function Sidebar() {
|
||||
);
|
||||
|
||||
const handleThreadContextMenu = useCallback(
|
||||
<<<<<<< HEAD
|
||||
(threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
|
||||
void (async () => {
|
||||
const api = readLocalApi();
|
||||
@@ -3004,6 +2983,75 @@ export default function Sidebar() {
|
||||
const selectionState = useThreadSelectionStore.getState();
|
||||
if (selectionState.hasSelection() && selectionState.selectedThreadKeys.has(threadKey)) {
|
||||
await handleMultiSelectContextMenu(position);
|
||||
=======
|
||||
async (threadRef: ScopedThreadRef, position: { x: number; y: number }) => {
|
||||
const api = readLocalApi();
|
||||
if (!api) return;
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
const thread = sidebarThreadByKeyRef.current.get(threadKey) ?? null;
|
||||
if (!thread) return;
|
||||
const threadProject = memberProjectByScopedKey.get(
|
||||
scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)),
|
||||
);
|
||||
const threadWorkspacePath =
|
||||
thread.worktreePath ?? threadProject?.workspaceRoot ?? project.workspaceRoot ?? null;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
...(thread.branch
|
||||
? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }]
|
||||
: []),
|
||||
{ id: "rename", label: "Rename thread" },
|
||||
{ id: "mark-unread", label: "Mark unread" },
|
||||
{ id: "copy-path", label: "Copy Path" },
|
||||
{ id: "copy-thread-id", label: "Copy Thread ID" },
|
||||
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
|
||||
],
|
||||
position,
|
||||
);
|
||||
|
||||
if (clicked === "new-thread-on-branch") {
|
||||
// Explicit branch carry-over: reuse the thread's worktree when it
|
||||
// has one, otherwise its branch on the local checkout.
|
||||
const result = await settlePromise(() =>
|
||||
handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId), {
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
envMode: thread.worktreePath ? "worktree" : "local",
|
||||
startFromOrigin: false,
|
||||
}),
|
||||
);
|
||||
if (result._tag === "Failure") {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Could not create thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "rename") {
|
||||
startThreadRename(threadKey, thread.title);
|
||||
return;
|
||||
}
|
||||
|
||||
if (clicked === "mark-unread") {
|
||||
markThreadUnread(threadKey, thread.latestRun?.completedAt);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-path") {
|
||||
if (!threadWorkspacePath) {
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: "Path unavailable",
|
||||
description: "This thread does not have a workspace path to copy.",
|
||||
}),
|
||||
);
|
||||
>>>>>>> 8f521e516e (Complete orchestration V2 frontend cutover)
|
||||
return;
|
||||
}
|
||||
const thread = threadByKeyRef.current.get(threadKey);
|
||||
@@ -3041,8 +3089,6 @@ export default function Sidebar() {
|
||||
isSnoozed,
|
||||
canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }),
|
||||
isRegeneratingTitle,
|
||||
isRunning:
|
||||
thread.session?.status === "running" && thread.session.activeTurnId != null,
|
||||
supports: {
|
||||
settlement: supportsSettlement,
|
||||
snooze: supportsSnooze,
|
||||
@@ -3146,34 +3192,6 @@ export default function Sidebar() {
|
||||
case "copy-thread-id":
|
||||
copyThreadIdToClipboard(thread.id, { threadId: thread.id });
|
||||
return;
|
||||
case "archive": {
|
||||
if (confirmThreadArchive) {
|
||||
const confirmed = await settlePromise(() =>
|
||||
api.dialogs.confirm(`Archive thread "${thread.title}"?`),
|
||||
);
|
||||
if (confirmed._tag === "Failure" || !confirmed.value) return;
|
||||
}
|
||||
let didArchive = false;
|
||||
const result = await archiveThread(threadRef, {
|
||||
onArchived: () => {
|
||||
didArchive = true;
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
|
||||
const error = squashAtomCommandFailure(result);
|
||||
toastManager.add(
|
||||
stackedThreadToast({
|
||||
type: "error",
|
||||
title: didArchive
|
||||
? "Thread archived, but navigation failed"
|
||||
: "Failed to archive thread",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "delete": {
|
||||
if (confirmThreadDelete) {
|
||||
const confirmed = await settlePromise(() =>
|
||||
@@ -3207,14 +3225,12 @@ export default function Sidebar() {
|
||||
})();
|
||||
},
|
||||
[
|
||||
archiveThread,
|
||||
attemptPin,
|
||||
attemptSettle,
|
||||
attemptSnooze,
|
||||
attemptUnpin,
|
||||
attemptUnsettle,
|
||||
attemptUnsnooze,
|
||||
confirmThreadArchive,
|
||||
confirmThreadDelete,
|
||||
copyBranchToClipboard,
|
||||
copyPathToClipboard,
|
||||
@@ -3381,9 +3397,9 @@ export default function Sidebar() {
|
||||
{isSearchingThreads ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="icon-micro"
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="shrink-0 text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
|
||||
className="size-5 shrink-0 rounded-sm text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"
|
||||
aria-label="Clear thread search"
|
||||
onClick={() => {
|
||||
clearThreadSearch();
|
||||
@@ -3495,19 +3511,18 @@ export default function Sidebar() {
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
<span className="min-w-0 truncate text-sm">{project.displayName}</span>
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost-muted"
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Project settings for ${project.displayName}`}
|
||||
title={`Project settings for ${project.displayName}`}
|
||||
className="ml-auto size-6 [--control-icon-color:currentColor] text-icon-muted focus-visible:bg-accent focus-visible:text-foreground"
|
||||
className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-icon-muted outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
void handleProjectSettings(event, project);
|
||||
}}
|
||||
>
|
||||
<SettingsIcon className="size-3.5" />
|
||||
</Button>
|
||||
</button>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
})}
|
||||
@@ -3702,8 +3717,7 @@ export default function Sidebar() {
|
||||
onUnsnooze={attemptUnsnooze}
|
||||
onUnpin={attemptUnpin}
|
||||
onAcknowledgeWoke={acknowledgeWoke}
|
||||
changeRequestSnapshot={changeRequestSnapshotByKey.get(threadKey) ?? null}
|
||||
onChangeRequestSnapshot={setThreadChangeRequestSnapshot}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { TurnId } from "@t3tools/contracts";
|
||||
import { RunId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
@@ -150,7 +150,7 @@ describe("ChangedFilesTree", () => {
|
||||
({ files, visibleLabels, hiddenLabels }) => {
|
||||
const markup = renderToStaticMarkup(
|
||||
<ChangedFilesTree
|
||||
turnId={TurnId.make("turn-1")}
|
||||
runId={RunId.make("turn-1")}
|
||||
files={files}
|
||||
allDirectoriesExpanded={false}
|
||||
resolvedTheme="light"
|
||||
@@ -226,7 +226,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 {
|
||||
@@ -28,7 +28,7 @@ import {
|
||||
const EMPTY_DIRECTORY_OVERRIDES: Record<string, boolean> = {};
|
||||
|
||||
export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
expanded: boolean;
|
||||
showCompactPreview: boolean;
|
||||
@@ -36,10 +36,10 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
resolvedTheme: "light" | "dark";
|
||||
onExpandedChange: (expanded: boolean) => void;
|
||||
onToggleAllDirectories: () => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
const {
|
||||
turnId,
|
||||
runId,
|
||||
files,
|
||||
expanded,
|
||||
showCompactPreview,
|
||||
@@ -152,8 +152,8 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
|
||||
</div>
|
||||
{expanded ? (
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnId}`}
|
||||
turnId={turnId}
|
||||
key={`changed-files-tree:${runId}`}
|
||||
runId={runId}
|
||||
files={files}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
@@ -205,13 +205,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"),
|
||||
@@ -296,7 +296,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
type="button"
|
||||
className="group flex w-full items-center gap-1.5 rounded-xl py-1 pr-3 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => onOpenTurnDiff(turnId, node.path)}
|
||||
onClick={() => onOpenTurnDiff(runId, node.path)}
|
||||
>
|
||||
{hasDirectoryNodes || depth > 0 ? (
|
||||
<span aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
ModelSelection,
|
||||
PreviewAnnotationPayload,
|
||||
@@ -10,9 +9,13 @@ import type {
|
||||
ScopedThreadRef,
|
||||
ServerProvider,
|
||||
ThreadId,
|
||||
<<<<<<< HEAD
|
||||
=======
|
||||
RunId,
|
||||
RuntimeRequestId,
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
isProviderSendTurnSupportedImageMimeType,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
@@ -103,17 +106,10 @@ import {
|
||||
renderProviderTraitsPicker,
|
||||
} from "./composerProviderState";
|
||||
import { ContextWindowMeter } from "./ContextWindowMeter";
|
||||
import { resolveContextWindowModelDisplayName } from "./ContextWindowMeter.logic";
|
||||
import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { basenameOfPath } from "../../pierre-icons";
|
||||
import { cn, randomUUID } from "~/lib/utils";
|
||||
import { Separator } from "../ui/separator";
|
||||
import {
|
||||
getComposerPromptLengthValidationMessage,
|
||||
getComposerSubmissionValidationMessage,
|
||||
submitComposerDraft,
|
||||
} from "./composerSubmission";
|
||||
import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation";
|
||||
|
||||
type ComposerCommandMenuPosition = {
|
||||
bottom: number;
|
||||
@@ -211,7 +207,7 @@ import {
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import { proposedPlanTitle } from "../../proposedPlan";
|
||||
import { getProviderInteractionModeToggle } from "../../providerModels";
|
||||
import { getProviderDisplayName, getProviderInteractionModeToggle } from "../../providerModels";
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
deriveProviderInstanceEntries,
|
||||
@@ -226,7 +222,10 @@ import type { UnifiedSettings } from "@t3tools/contracts/settings";
|
||||
import type { SessionPhase, Thread } from "../../types";
|
||||
import type { PendingUserInputDraftAnswer } from "../../pendingUserInput";
|
||||
import type { PendingApproval, PendingUserInput } from "../../session-logic";
|
||||
import { deriveLatestContextWindowSnapshot } from "../../lib/contextWindow";
|
||||
import {
|
||||
deriveLatestContextWindowSnapshot,
|
||||
formatProviderDisplayName,
|
||||
} from "../../lib/contextWindow";
|
||||
import { formatProviderSkillDisplayName } from "../../providerSkillPresentation";
|
||||
import { searchProviderSkills } from "../../providerSkillSearch";
|
||||
import { useMediaQuery } from "../../hooks/useMediaQuery";
|
||||
@@ -394,7 +393,7 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: {
|
||||
compact: boolean;
|
||||
activeContextWindow: ReturnType<typeof deriveLatestContextWindowSnapshot>;
|
||||
activeThreadModelDisplayName: string | null;
|
||||
activeThreadProviderDisplayName: string | null;
|
||||
isPreparingWorktree: boolean;
|
||||
pendingAction: {
|
||||
questionIndex: number;
|
||||
@@ -412,7 +411,6 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
|
||||
isEnvironmentUnavailable: boolean;
|
||||
hasSendableContent: boolean;
|
||||
preserveComposerFocusOnPointerDown?: boolean;
|
||||
showSendWhileRunning?: boolean;
|
||||
onPreviousPendingQuestion: () => void;
|
||||
onInterrupt: () => void;
|
||||
onImplementPlanInNewThread: () => void;
|
||||
@@ -422,7 +420,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
|
||||
{props.activeContextWindow ? (
|
||||
<ContextWindowMeter
|
||||
usage={props.activeContextWindow}
|
||||
modelDisplayName={props.activeThreadModelDisplayName}
|
||||
providerDisplayName={props.activeThreadProviderDisplayName}
|
||||
/>
|
||||
) : null}
|
||||
{props.isPreparingWorktree ? (
|
||||
@@ -441,7 +439,6 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
|
||||
isPreparingWorktree={props.isPreparingWorktree}
|
||||
hasSendableContent={props.hasSendableContent}
|
||||
preserveComposerFocusOnPointerDown={props.preserveComposerFocusOnPointerDown ?? false}
|
||||
showSendWhileRunning={props.showSendWhileRunning ?? false}
|
||||
onPreviousPendingQuestion={props.onPreviousPendingQuestion}
|
||||
onInterrupt={props.onInterrupt}
|
||||
onImplementPlanInNewThread={props.onImplementPlanInNewThread}
|
||||
@@ -457,7 +454,6 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
|
||||
export interface ChatComposerHandle {
|
||||
focusAtEnd: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
addDroppedFiles: (files: File[]) => void;
|
||||
insertTextAtEnd: (text: string, options?: { ensureLeadingBoundary?: boolean }) => boolean;
|
||||
openModelPicker: () => void;
|
||||
toggleModelPicker: () => void;
|
||||
@@ -492,8 +488,6 @@ export interface ChatComposerHandle {
|
||||
selectedModel: string;
|
||||
selectedProviderModels: ReadonlyArray<ServerProvider["models"][number]>;
|
||||
};
|
||||
/** Validate the fully composed text immediately before a provider turn starts. */
|
||||
validateProviderInput: (providerInput: string) => boolean;
|
||||
}
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
@@ -542,11 +536,18 @@ export interface ChatComposerProps {
|
||||
activePendingIsResponding: boolean;
|
||||
activePendingDraftAnswers: Record<string, PendingUserInputDraftAnswer>;
|
||||
activePendingQuestionIndex: number;
|
||||
respondingRequestIds: ApprovalRequestId[];
|
||||
respondingRequestIds: RuntimeRequestId[];
|
||||
|
||||
// Plan
|
||||
showPlanFollowUpPrompt: boolean;
|
||||
activeProposedPlan: Thread["proposedPlans"][number] | null;
|
||||
<<<<<<< HEAD
|
||||
=======
|
||||
activePlan: { runId?: RunId | null } | null;
|
||||
sidebarProposedPlan: { runId?: RunId | null } | null;
|
||||
planSidebarLabel: string;
|
||||
planSidebarOpen: boolean;
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
|
||||
// Mode
|
||||
runtimeMode: RuntimeMode;
|
||||
@@ -559,7 +560,7 @@ export interface ChatComposerProps {
|
||||
activeThreadModelSelection: ModelSelection | null | undefined;
|
||||
|
||||
// Context window
|
||||
activeThreadActivities: Thread["activities"] | undefined;
|
||||
activeThreadWorkEntries: Thread["workEntries"] | undefined;
|
||||
|
||||
// Misc
|
||||
resolvedTheme: "light" | "dark";
|
||||
@@ -575,12 +576,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;
|
||||
@@ -647,7 +652,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
providerStatuses,
|
||||
activeProjectDefaultModelSelection,
|
||||
activeThreadModelSelection,
|
||||
activeThreadActivities,
|
||||
activeThreadWorkEntries,
|
||||
resolvedTheme,
|
||||
settings,
|
||||
keybindings,
|
||||
@@ -658,6 +663,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerImagesRef,
|
||||
composerTerminalContextsRef,
|
||||
composerElementContextsRef,
|
||||
shouldAutoScrollRef,
|
||||
scheduleStickToBottom,
|
||||
onSend,
|
||||
onInterrupt,
|
||||
onImplementPlanInNewThread,
|
||||
@@ -738,7 +745,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;
|
||||
@@ -756,7 +763,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)
|
||||
@@ -782,7 +789,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,
|
||||
];
|
||||
@@ -819,7 +826,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
);
|
||||
}, [
|
||||
activeProjectDefaultModelSelection?.instanceId,
|
||||
activeThread?.session?.providerInstanceId,
|
||||
activeThread?.runtime?.providerInstanceId,
|
||||
activeThreadModelSelection?.instanceId,
|
||||
composerDraft.activeProvider,
|
||||
lockedContinuationGroupKey,
|
||||
@@ -925,13 +932,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// Context window
|
||||
// ------------------------------------------------------------------
|
||||
const activeContextWindow = useMemo(
|
||||
() => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []),
|
||||
[activeThreadActivities],
|
||||
);
|
||||
const activeThreadModelDisplayName = useMemo(
|
||||
() => resolveContextWindowModelDisplayName(activeThreadModelSelection, modelOptionsByInstance),
|
||||
[activeThreadModelSelection, modelOptionsByInstance],
|
||||
() => deriveLatestContextWindowSnapshot(activeThreadWorkEntries ?? []),
|
||||
[activeThreadWorkEntries],
|
||||
);
|
||||
const activeThreadProviderDisplayName = useMemo(() => {
|
||||
if (!activeThreadModelSelection) return null;
|
||||
const entry = providerStatuses.find(
|
||||
(p) => p.instanceId === activeThreadModelSelection.instanceId,
|
||||
);
|
||||
if (entry) {
|
||||
return getProviderDisplayName(providerStatuses, entry.driver);
|
||||
}
|
||||
return formatProviderDisplayName(activeThreadModelSelection.instanceId);
|
||||
}, [providerStatuses, activeThreadModelSelection]);
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Composer-local state
|
||||
@@ -951,10 +964,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
|
||||
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
|
||||
const [isComposerFocused, setIsComposerFocused] = useState(false);
|
||||
const [composerSubmissionError, setComposerSubmissionError] = useState<string | null>(null);
|
||||
const [providerInputSubmissionError, setProviderInputSubmissionError] = useState<string | null>(
|
||||
null,
|
||||
);
|
||||
const [composerMenuAnchor, setComposerMenuAnchor] = useState<HTMLDivElement | null>(null);
|
||||
const [isStashMenuOpen, setIsStashMenuOpen] = useState(false);
|
||||
const [stashPulse, setStashPulse] = useState<{ key: number; active: boolean }>({
|
||||
@@ -971,7 +980,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 providerInputRejectedRef = useRef(false);
|
||||
const composerFormHeightRef = useRef(0);
|
||||
const composerSelectLockRef = useRef(false);
|
||||
const composerMenuOpenRef = useRef(false);
|
||||
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
|
||||
@@ -980,6 +989,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
const mobileComposerExpandFrameRef = useRef<number | null>(null);
|
||||
const mobileComposerExpandReleaseFrameRef = useRef<number | null>(null);
|
||||
const mobileComposerExpandInFlightRef = useRef(false);
|
||||
const dragDepthRef = useRef(0);
|
||||
const stashPulseKeyRef = useRef(0);
|
||||
const stashPulseTimeoutRef = useRef<number | null>(null);
|
||||
/**
|
||||
@@ -1314,27 +1324,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
setComposerCursor((existing) => clampCollapsedComposerCursor(prompt, existing));
|
||||
}, [prompt, promptRef]);
|
||||
|
||||
useEffect(() => {
|
||||
if (composerSubmissionError === null) return;
|
||||
const nextError = getComposerPromptLengthValidationMessage(prompt);
|
||||
if (nextError !== composerSubmissionError) {
|
||||
setComposerSubmissionError(nextError);
|
||||
}
|
||||
}, [composerSubmissionError, prompt]);
|
||||
|
||||
useEffect(() => {
|
||||
setProviderInputSubmissionError(null);
|
||||
}, [
|
||||
composerElementContexts,
|
||||
composerPreviewAnnotations,
|
||||
composerReviewComments,
|
||||
composerTerminalContexts,
|
||||
prompt,
|
||||
selectedModel,
|
||||
selectedPromptEffort,
|
||||
selectedProvider,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
composerImagesRef.current = composerImages;
|
||||
}, [composerImages, composerImagesRef]);
|
||||
@@ -1426,10 +1415,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
// ------------------------------------------------------------------
|
||||
useEffect(() => {
|
||||
setComposerHighlightedItemId(null);
|
||||
setComposerSubmissionError(null);
|
||||
setProviderInputSubmissionError(null);
|
||||
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
|
||||
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOverComposer(false);
|
||||
}, [draftId, activeThreadId, promptRef]);
|
||||
|
||||
@@ -1456,12 +1444,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
|
||||
@@ -1471,13 +1462,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
|
||||
@@ -1854,32 +1857,17 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
});
|
||||
return;
|
||||
}
|
||||
const submission = submitComposerDraft({
|
||||
prompt: promptRef.current,
|
||||
submissionTarget: activePendingProgress ? "pending-user-input" : "provider-turn",
|
||||
event,
|
||||
onSend: (sendEvent) => {
|
||||
// ChatView reports its final composed-input preflight through the
|
||||
// composer handle before its first asynchronous send step.
|
||||
providerInputRejectedRef.current = false;
|
||||
onSend(sendEvent);
|
||||
return !providerInputRejectedRef.current;
|
||||
},
|
||||
});
|
||||
setComposerSubmissionError(submission.validationMessage);
|
||||
if (!submission.didDispatch) return;
|
||||
onSend(event);
|
||||
if (shouldBlurMobileComposerOnSubmit()) {
|
||||
blurMobileComposerAfterSend();
|
||||
}
|
||||
},
|
||||
[
|
||||
activeThreadId,
|
||||
activePendingProgress,
|
||||
blurMobileComposerAfterSend,
|
||||
isSendDisabled,
|
||||
noProviderAvailable,
|
||||
onSend,
|
||||
promptRef,
|
||||
shouldBlurMobileComposerOnSubmit,
|
||||
],
|
||||
);
|
||||
@@ -2349,10 +2337,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
error = `Unsupported file type for '${file.name}'. Please attach image files only.`;
|
||||
continue;
|
||||
}
|
||||
if (!isProviderSendTurnSupportedImageMimeType(file.type)) {
|
||||
error = `'${file.name}' is not a supported image type. Attach GIF, JPEG, PNG, or WebP images.`;
|
||||
continue;
|
||||
}
|
||||
if (reservedCount >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
|
||||
error = `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} images per message.`;
|
||||
break;
|
||||
@@ -2429,6 +2413,41 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
void addComposerImages(imageFiles);
|
||||
};
|
||||
|
||||
const onComposerDragEnter = (event: React.DragEvent<HTMLDivElement>) => {
|
||||
if (!event.dataTransfer.types.includes("Files")) return;
|
||||
event.preventDefault();
|
||||
dragDepthRef.current += 1;
|
||||
setIsDragOverComposer(true);
|
||||
};
|
||||
|
||||
const onComposerDragOver = (event: React.DragEvent<HTMLDivElement>) => {
|
||||
if (!event.dataTransfer.types.includes("Files")) return;
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
setIsDragOverComposer(true);
|
||||
};
|
||||
|
||||
const onComposerDragLeave = (event: React.DragEvent<HTMLDivElement>) => {
|
||||
if (!event.dataTransfer.types.includes("Files")) return;
|
||||
event.preventDefault();
|
||||
const nextTarget = event.relatedTarget;
|
||||
if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return;
|
||||
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
|
||||
if (dragDepthRef.current === 0) {
|
||||
setIsDragOverComposer(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onComposerDrop = (event: React.DragEvent<HTMLDivElement>) => {
|
||||
if (!event.dataTransfer.types.includes("Files")) return;
|
||||
event.preventDefault();
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOverComposer(false);
|
||||
const files = Array.from(event.dataTransfer.files);
|
||||
void addComposerImages(files);
|
||||
focusComposer();
|
||||
};
|
||||
|
||||
const insertComposerTextAtEnd = (
|
||||
text: string,
|
||||
options?: { ensureLeadingBoundary?: boolean },
|
||||
@@ -2482,6 +2501,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
useEffect(() => {
|
||||
if (!isDragOverComposer) return;
|
||||
const onWindowDragEnd = () => {
|
||||
dragDepthRef.current = 0;
|
||||
setIsDragOverComposer(false);
|
||||
};
|
||||
window.addEventListener("dragend", onWindowDragEnd);
|
||||
@@ -2550,10 +2570,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
focusAt: (cursor: number) => {
|
||||
composerEditorRef.current?.focusAt(cursor);
|
||||
},
|
||||
addDroppedFiles: (files: File[]) => {
|
||||
void addComposerImages(files);
|
||||
focusComposer();
|
||||
},
|
||||
insertTextAtEnd: insertComposerTextAtEnd,
|
||||
openModelPicker: () => {
|
||||
setIsComposerModelPickerOpen(true);
|
||||
@@ -2633,20 +2649,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
selectedModel,
|
||||
selectedProviderModels,
|
||||
}),
|
||||
validateProviderInput: (providerInput: string) => {
|
||||
const validationMessage = getComposerSubmissionValidationMessage({
|
||||
prompt: promptRef.current,
|
||||
providerInput,
|
||||
submissionTarget: "provider-turn",
|
||||
});
|
||||
providerInputRejectedRef.current = validationMessage !== null;
|
||||
setProviderInputSubmissionError(validationMessage);
|
||||
return validationMessage === null;
|
||||
},
|
||||
}),
|
||||
[
|
||||
activeThread,
|
||||
addComposerImages,
|
||||
composerDraftTarget,
|
||||
composerCursor,
|
||||
composerTerminalContexts,
|
||||
@@ -2657,7 +2662,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
composerElementContextsRef,
|
||||
composerPreviewAnnotations,
|
||||
composerReviewComments,
|
||||
focusComposer,
|
||||
isConnecting,
|
||||
isComposerApprovalState,
|
||||
pendingUserInputs.length,
|
||||
@@ -2689,6 +2693,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
"group rounded-[22px] p-px transition-colors duration-200",
|
||||
composerProviderState.composerFrameClassName,
|
||||
)}
|
||||
onDragEnter={onComposerDragEnter}
|
||||
onDragOver={onComposerDragOver}
|
||||
onDragLeave={onComposerDragLeave}
|
||||
onDrop={onComposerDrop}
|
||||
onDragEnterCapture={composerMentionDragHandlers.onDragEnter}
|
||||
onDragOverCapture={composerMentionDragHandlers.onDragOver}
|
||||
onDragLeaveCapture={onComposerMentionDragLeaveCapture}
|
||||
@@ -2763,6 +2771,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>
|
||||
@@ -3111,16 +3120,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ComposerPromptLengthValidation
|
||||
message={providerInputSubmissionError ?? composerSubmissionError}
|
||||
/>
|
||||
|
||||
{/* Bottom toolbar */}
|
||||
{isComposerCollapsedMobile ? null : activePendingApproval ? (
|
||||
<div className="flex flex-wrap items-center justify-end gap-2 px-3 pb-3 sm:px-4 sm:pb-4">
|
||||
<div className="flex items-center justify-end gap-2 px-3 pb-3 sm:px-4 sm:pb-4">
|
||||
<ComposerPendingApprovalActions
|
||||
requestId={activePendingApproval.requestId}
|
||||
isResponding={respondingRequestIds.includes(activePendingApproval.requestId)}
|
||||
canRespond={activePendingApproval.responseCapability === "live"}
|
||||
onRespondToApproval={onRespondToApproval}
|
||||
/>
|
||||
</div>
|
||||
@@ -3214,7 +3220,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
<ComposerFooterPrimaryActions
|
||||
compact={isComposerPrimaryActionsCompact}
|
||||
activeContextWindow={activeContextWindow}
|
||||
activeThreadModelDisplayName={activeThreadModelDisplayName}
|
||||
activeThreadProviderDisplayName={activeThreadProviderDisplayName}
|
||||
pendingAction={pendingPrimaryAction}
|
||||
isRunning={phase === "running"}
|
||||
showPlanFollowUpPrompt={pendingUserInputs.length === 0 && showPlanFollowUpPrompt}
|
||||
@@ -3230,7 +3236,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
hasSendableContent={composerSendState.hasSendableContent}
|
||||
preserveComposerFocusOnPointerDown={isMobileViewport}
|
||||
showSendWhileRunning={isMobileViewport}
|
||||
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
|
||||
onInterrupt={handleInterruptPrimaryAction}
|
||||
onImplementPlanInNewThread={handleImplementPlanInNewThreadPrimaryAction}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -24,7 +24,7 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
|
||||
: "File change";
|
||||
|
||||
return (
|
||||
<div className="min-w-0 px-4 py-3.5 sm:px-5 sm:py-4">
|
||||
<div className="px-4 py-3.5 sm:px-5 sm:py-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="uppercase text-sm tracking-[0.2em]">PENDING APPROVAL</span>
|
||||
<span className="text-sm font-medium">{approvalSummary}</span>
|
||||
@@ -32,17 +32,11 @@ export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprova
|
||||
<span className="text-xs text-muted-foreground">1/{pendingCount}</span>
|
||||
) : null}
|
||||
</div>
|
||||
{approval.detail ? (
|
||||
<div className="mt-3 min-w-0 max-w-full rounded-lg border border-border/65 bg-background/70 p-3">
|
||||
<p className="text-xs font-medium text-muted-foreground">{detailLabel}</p>
|
||||
<pre
|
||||
aria-label={detailLabel}
|
||||
className="mt-2 min-w-0 max-w-full max-h-40 overflow-auto whitespace-pre-wrap [overflow-wrap:anywhere] font-mono text-xs leading-relaxed text-foreground"
|
||||
data-approval-detail="complete"
|
||||
>
|
||||
{approval.detail}
|
||||
</pre>
|
||||
</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,17 +1,16 @@
|
||||
import { type ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { memo, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { type RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { memo, useEffect, useEffectEvent, useRef, useState } from "react";
|
||||
import { type PendingUserInput } from "../../session-logic";
|
||||
import {
|
||||
derivePendingUserInputProgress,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../../pendingUserInput";
|
||||
import { CheckIcon, ChevronDownIcon } from "lucide-react";
|
||||
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
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;
|
||||
@@ -60,20 +59,14 @@ 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<{
|
||||
questionId: string;
|
||||
optionLabel: string;
|
||||
} | null>(null);
|
||||
// Collapsing hides everything but the header so a tall prompt stops covering
|
||||
// the thread the user is trying to read. Scoped to a single question: the card
|
||||
// is keyed by request id so the next prompt starts expanded, and storing the
|
||||
// collapsed question's id (rather than a bare flag) reopens the card when the
|
||||
// prompt advances to its next question, which can happen without a click —
|
||||
// sending from the composer advances the active question.
|
||||
const [collapsedQuestionId, setCollapsedQuestionId] = useState<string | null>(null);
|
||||
const isCollapsed = collapsedQuestionId !== null && collapsedQuestionId === activeQuestion?.id;
|
||||
|
||||
useEffect(() => {
|
||||
onAdvanceRef.current = onAdvance;
|
||||
@@ -109,31 +102,27 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
};
|
||||
}, []);
|
||||
|
||||
const handleOptionSelection = useCallback(
|
||||
(questionId: string, optionLabel: string) => {
|
||||
if (activeQuestion?.multiSelect) {
|
||||
onToggleOption(questionId, optionLabel);
|
||||
return;
|
||||
}
|
||||
setOptimisticSingleSelect({ questionId, optionLabel });
|
||||
const handleOptionSelection = useEffectEvent((questionId: string, optionLabel: string) => {
|
||||
if (activeQuestion?.multiSelect) {
|
||||
onToggleOption(questionId, optionLabel);
|
||||
if (autoAdvanceTimerRef.current !== null) {
|
||||
window.clearTimeout(autoAdvanceTimerRef.current);
|
||||
}
|
||||
autoAdvanceTimerRef.current = window.setTimeout(() => {
|
||||
autoAdvanceTimerRef.current = null;
|
||||
onAdvanceRef.current();
|
||||
}, 200);
|
||||
},
|
||||
[activeQuestion, onToggleOption],
|
||||
);
|
||||
return;
|
||||
}
|
||||
setOptimisticSingleSelect({ questionId, optionLabel });
|
||||
onToggleOption(questionId, optionLabel);
|
||||
if (autoAdvanceTimerRef.current !== null) {
|
||||
window.clearTimeout(autoAdvanceTimerRef.current);
|
||||
}
|
||||
autoAdvanceTimerRef.current = window.setTimeout(() => {
|
||||
autoAdvanceTimerRef.current = null;
|
||||
onAdvanceRef.current();
|
||||
}, 200);
|
||||
});
|
||||
|
||||
// Keyboard shortcut: number keys 1-9 select corresponding options when focus is
|
||||
// outside editable fields. Multi-select prompts toggle options in place; single-
|
||||
// select prompts keep the existing auto-advance behavior. Collapsed prompts opt
|
||||
// out, since the numbers they refer to are not on screen.
|
||||
// select prompts keep the existing auto-advance behavior.
|
||||
useEffect(() => {
|
||||
if (!activeQuestion || isResponding || isCollapsed) return;
|
||||
if (!activeQuestion || responseDisabled) return;
|
||||
const handler = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
const target = event.target;
|
||||
@@ -157,7 +146,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
};
|
||||
document.addEventListener("keydown", handler);
|
||||
return () => document.removeEventListener("keydown", handler);
|
||||
}, [activeQuestion, handleOptionSelection, isCollapsed, isResponding]);
|
||||
}, [activeQuestion, responseDisabled]);
|
||||
|
||||
if (!activeQuestion) {
|
||||
return null;
|
||||
@@ -166,119 +155,83 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
|
||||
const customAnswerActive = progress.customAnswer.trim().length > 0;
|
||||
|
||||
return (
|
||||
<Collapsible
|
||||
className="py-3"
|
||||
open={!isCollapsed}
|
||||
onOpenChange={(open) => {
|
||||
setCollapsedQuestionId(open ? null : activeQuestion.id);
|
||||
}}
|
||||
>
|
||||
{/* The trigger's wrapper is inset less than the card's text column, and
|
||||
the trigger pays the difference back as padding: the hover background
|
||||
and focus ring bleed 10px past that column on both sides, while the
|
||||
header label and the chevron still line up with the left and right
|
||||
edges of the question text below. The negative block margin keeps the
|
||||
taller hit area from pushing the panel down. */}
|
||||
<div className="px-1.5 sm:px-2.5">
|
||||
<CollapsibleTrigger
|
||||
title={
|
||||
isCollapsed ? "Show the question and its options" : "Hide the question and its options"
|
||||
}
|
||||
data-pending-user-input-toggle={isCollapsed ? "collapsed" : "expanded"}
|
||||
className="group -my-1 flex w-full items-center gap-3 rounded-md px-2.5 py-1.5 text-left outline-none transition-colors duration-150 hover:bg-muted/40 focus-visible:ring-1 focus-visible:ring-primary/25"
|
||||
>
|
||||
<span className="text-secondary-label text-[11px] font-semibold tracking-widest uppercase group-hover:text-foreground">
|
||||
{activeQuestion.header}
|
||||
<div className="px-4 py-3 sm:px-5">
|
||||
<div className="mb-2 flex items-center gap-3">
|
||||
<span className="text-secondary-label text-[11px] font-semibold tracking-widest uppercase">
|
||||
{activeQuestion.header}
|
||||
</span>
|
||||
{prompt.questions.length > 1 ? (
|
||||
<span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-secondary-label text-[10px] font-medium tabular-nums">
|
||||
{questionIndex + 1}/{prompt.questions.length}
|
||||
</span>
|
||||
{prompt.questions.length > 1 ? (
|
||||
<span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-secondary-label text-[10px] font-medium tabular-nums">
|
||||
{questionIndex + 1}/{prompt.questions.length}
|
||||
</span>
|
||||
) : null}
|
||||
{/* Collapsed, the header is otherwise just a section label and a
|
||||
counter, so the question itself is echoed here as a one-line
|
||||
reminder of what is being asked. */}
|
||||
{isCollapsed ? (
|
||||
<span className="min-w-0 flex-1 truncate text-secondary-label text-xs">
|
||||
{activeQuestion.question}
|
||||
</span>
|
||||
) : null}
|
||||
{/* The chevron points at the body: down while it is open below the
|
||||
header, up while it is collapsed into it. */}
|
||||
<ChevronDownIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"ml-auto size-3.5 shrink-0 text-secondary-label transition-transform duration-150 group-hover:text-foreground",
|
||||
isCollapsed && "rotate-180",
|
||||
)}
|
||||
/>
|
||||
</CollapsibleTrigger>
|
||||
) : null}
|
||||
</div>
|
||||
{/* The panel carries the horizontal padding itself: it clips its content
|
||||
while the height animates, so the option buttons have to sit inside
|
||||
that padding or their focus rings get shaved off at the edges. */}
|
||||
<CollapsiblePanel className="px-4 sm:px-5">
|
||||
<div className="pt-2 pb-0.5">
|
||||
<p className="text-sm text-foreground/90">{activeQuestion.question}</p>
|
||||
{activeQuestion.multiSelect ? (
|
||||
<p className="mt-1 text-secondary-label text-xs">Select one or more options.</p>
|
||||
) : null}
|
||||
<div className="mt-3 space-y-1.5">
|
||||
{activeQuestion.options.map((option, index) => {
|
||||
const isOptimisticallySelected =
|
||||
optimisticSingleSelect?.questionId === activeQuestion.id &&
|
||||
optimisticSingleSelect.optionLabel === option.label;
|
||||
const isSelected =
|
||||
isOptimisticallySelected ||
|
||||
(!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
|
||||
const shortcutKey = index < 9 ? index + 1 : null;
|
||||
const className = cn(
|
||||
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-all duration-150 focus-visible:border-primary/40 focus-visible:ring-1 focus-visible:ring-primary/25",
|
||||
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",
|
||||
);
|
||||
const content = (
|
||||
<>
|
||||
<div className="min-w-0 flex-1 flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium">{option.label}</span>
|
||||
{option.description && option.description !== option.label ? (
|
||||
<span className="text-secondary-label text-xs">{option.description}</span>
|
||||
) : null}
|
||||
</div>
|
||||
{isSelected ? (
|
||||
<CheckIcon className="size-3.5 shrink-0 text-primary" />
|
||||
) : shortcutKey !== null ? (
|
||||
<kbd
|
||||
className={cn(
|
||||
"flex size-5 shrink-0 items-center justify-center rounded border border-border/50 text-[11px] font-medium tabular-nums transition-colors duration-150",
|
||||
"bg-background/35 text-secondary-label group-hover:border-border/70 group-hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{shortcutKey}
|
||||
</kbd>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<button
|
||||
key={`${activeQuestion.id}:${option.label}`}
|
||||
type="button"
|
||||
disabled={isResponding}
|
||||
onClick={() => {
|
||||
handleOptionSelection(activeQuestion.id, option.label);
|
||||
}}
|
||||
className={className}
|
||||
<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-secondary-label text-xs">Select one or more options.</p>
|
||||
) : null}
|
||||
<div className="mt-3 space-y-1.5">
|
||||
{activeQuestion.options.map((option, index) => {
|
||||
const isOptimisticallySelected =
|
||||
optimisticSingleSelect?.questionId === activeQuestion.id &&
|
||||
optimisticSingleSelect.optionLabel === option.label;
|
||||
const isSelected =
|
||||
isOptimisticallySelected ||
|
||||
(!customAnswerActive && progress.selectedOptionLabels.includes(option.label));
|
||||
const shortcutKey = index < 9 ? index + 1 : null;
|
||||
const className = cn(
|
||||
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left outline-none transition-all duration-150 focus-visible:border-primary/40 focus-visible:ring-1 focus-visible:ring-primary/25",
|
||||
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",
|
||||
responseDisabled && "opacity-50 cursor-not-allowed",
|
||||
!responseDisabled && "cursor-pointer",
|
||||
);
|
||||
const content = (
|
||||
<>
|
||||
<div className="min-w-0 flex-1 flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium">{option.label}</span>
|
||||
{option.description && option.description !== option.label ? (
|
||||
<span className="text-secondary-label text-xs">{option.description}</span>
|
||||
) : null}
|
||||
</div>
|
||||
{isSelected ? (
|
||||
<CheckIcon className="size-3.5 shrink-0 text-primary" />
|
||||
) : shortcutKey !== null ? (
|
||||
<kbd
|
||||
className={cn(
|
||||
"flex size-5 shrink-0 items-center justify-center rounded border border-border/50 text-[11px] font-medium tabular-nums transition-colors duration-150",
|
||||
"bg-background/35 text-secondary-label group-hover:border-border/70 group-hover:text-foreground",
|
||||
)}
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</CollapsiblePanel>
|
||||
</Collapsible>
|
||||
{shortcutKey}
|
||||
</kbd>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
return (
|
||||
<button
|
||||
key={`${activeQuestion.id}:${option.label}`}
|
||||
type="button"
|
||||
disabled={responseDisabled}
|
||||
aria-disabled={responseDisabled}
|
||||
onClick={() => {
|
||||
if (responseDisabled) return;
|
||||
handleOptionSelection(activeQuestion.id, option.label);
|
||||
}}
|
||||
className={className}
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -284,7 +284,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user",
|
||||
text: "Write a poem",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -298,7 +298,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "I should ground this first.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
@@ -312,14 +312,14 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Here is the poem.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
expandedRunIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
@@ -347,7 +347,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-one" as never,
|
||||
role: "assistant",
|
||||
text: "Earlier response.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
@@ -361,16 +361,16 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-two" as never,
|
||||
role: "assistant",
|
||||
text: "Active response.",
|
||||
turnId: "turn-2" as never,
|
||||
runId: "turn-2" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "running",
|
||||
latestRun: {
|
||||
runId: "turn-2" as never,
|
||||
status: "running",
|
||||
startedAt: "2026-01-01T00:00:19Z",
|
||||
completedAt: null,
|
||||
},
|
||||
@@ -391,7 +391,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
|
||||
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
|
||||
const assistantTurnDiffSummary = {
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
assistantMessageId: "assistant-1" as never,
|
||||
checkpointTurnCount: 2,
|
||||
@@ -410,7 +410,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user",
|
||||
text: "Do the thing",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -424,7 +424,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-1" as never,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
@@ -462,7 +462,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "Build it",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -476,7 +476,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Looking around first.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
updatedAt: "2026-01-01T00:00:06Z",
|
||||
streaming: false,
|
||||
@@ -489,7 +489,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
@@ -502,7 +502,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:22Z",
|
||||
streaming: false,
|
||||
@@ -522,7 +522,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
(row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> =>
|
||||
row.kind === "turn-fold",
|
||||
);
|
||||
expect(foldRow?.turnId).toBe("turn-1");
|
||||
expect(foldRow?.runId).toBe("turn-1");
|
||||
expect(foldRow?.expanded).toBe(false);
|
||||
// User message boundary (00:00:00) → terminal message updatedAt (00:00:22).
|
||||
expect(foldRow?.label).toBe("Worked for 22s");
|
||||
@@ -534,7 +534,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
|
||||
const expandedRows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
expandedRunIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
@@ -568,7 +568,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "do it once more",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -582,7 +582,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-commentary" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Kicking off call 1.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:09Z",
|
||||
updatedAt: "2026-01-01T00:00:09Z",
|
||||
streaming: false,
|
||||
@@ -595,7 +595,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
@@ -608,7 +608,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "actually do 15",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:14Z",
|
||||
updatedAt: "2026-01-01T00:00:14Z",
|
||||
streaming: false,
|
||||
@@ -622,16 +622,16 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-next" as never,
|
||||
role: "assistant" as const,
|
||||
text: "One down — adjusting.",
|
||||
turnId: "turn-2" as never,
|
||||
runId: "turn-2" as never,
|
||||
createdAt: "2026-01-01T00:00:17Z",
|
||||
updatedAt: "2026-01-01T00:00:17Z",
|
||||
streaming: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "running",
|
||||
latestRun: {
|
||||
runId: "turn-2" as never,
|
||||
status: "running",
|
||||
startedAt: "2026-01-01T00:00:14Z",
|
||||
completedAt: null,
|
||||
},
|
||||
@@ -646,7 +646,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
row.kind === "turn-fold",
|
||||
);
|
||||
// User message (00:00:00) → trailing work entry (00:00:12).
|
||||
expect(foldRow?.turnId).toBe("turn-1");
|
||||
expect(foldRow?.runId).toBe("turn-1");
|
||||
expect(foldRow?.label).toBe("Worked for 12s");
|
||||
});
|
||||
|
||||
@@ -660,15 +660,15 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "interrupted",
|
||||
latestRun: {
|
||||
runId: "turn-1" as never,
|
||||
status: "interrupted",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:47Z",
|
||||
},
|
||||
@@ -681,15 +681,88 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(rows).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: "turn-fold",
|
||||
turnId: "turn-1",
|
||||
runId: "turn-1",
|
||||
label: "You stopped after 47s",
|
||||
expanded: false,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps interruption request, intervening work, and result visible in order", () => {
|
||||
const runId = "turn-1" as never;
|
||||
const interruptEvent = (type: "run_interrupt_request" | "run_interrupt_result") => ({
|
||||
position: type === "run_interrupt_request" ? 0 : 2,
|
||||
visibility: "local" as const,
|
||||
sourceThreadId: "thread-1" as never,
|
||||
sourceItemId: `item-${type}` as never,
|
||||
item: {
|
||||
id: `item-${type}`,
|
||||
threadId: "thread-1",
|
||||
runId,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: type === "run_interrupt_request" ? 0 : 2,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
updatedAt: {},
|
||||
type,
|
||||
message: type === "run_interrupt_request" ? "Stopping" : "Stopped",
|
||||
},
|
||||
});
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "interrupt-request",
|
||||
kind: "event",
|
||||
createdAt: "2026-01-01T00:00:01Z",
|
||||
projectedItem: interruptEvent("run_interrupt_request") as never,
|
||||
},
|
||||
{
|
||||
id: "work-entry",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:00:02Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:02Z",
|
||||
runId,
|
||||
label: "Finishing tool output",
|
||||
tone: "tool",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "interrupt-result",
|
||||
kind: "event",
|
||||
createdAt: "2026-01-01T00:00:03Z",
|
||||
projectedItem: interruptEvent("run_interrupt_result") as never,
|
||||
},
|
||||
],
|
||||
latestRun: {
|
||||
runId,
|
||||
status: "interrupted",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:03Z",
|
||||
},
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([
|
||||
"interrupt-request",
|
||||
"work-entry",
|
||||
"interrupt-result",
|
||||
]);
|
||||
expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps the previous turn folded while a newly sent message awaits its turn", () => {
|
||||
// Right after send, isWorking is true but latestTurn still points at the
|
||||
// Right after send, isWorking is true but latestRun still points at the
|
||||
// previous, settled turn — it must stay folded through that window.
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
@@ -700,7 +773,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
@@ -713,7 +786,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:22Z",
|
||||
streaming: false,
|
||||
@@ -727,16 +800,16 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "user-followup" as never,
|
||||
role: "user",
|
||||
text: "yooo",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:01:00Z",
|
||||
updatedAt: "2026-01-01T00:01:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "completed",
|
||||
latestRun: {
|
||||
runId: "turn-1" as never,
|
||||
status: "completed",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:22Z",
|
||||
},
|
||||
@@ -767,7 +840,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "Working on it.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
updatedAt: "2026-01-01T00:00:06Z",
|
||||
streaming: false,
|
||||
@@ -780,15 +853,15 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "running",
|
||||
latestRun: {
|
||||
runId: "turn-1" as never,
|
||||
status: "running",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: null,
|
||||
},
|
||||
@@ -878,7 +951,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "Checking first.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
@@ -892,14 +965,14 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Done.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
updatedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
expandedRunIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
@@ -925,16 +998,16 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "Working on it.",
|
||||
turnId: "turn-1" as never,
|
||||
runId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "running",
|
||||
latestRun: {
|
||||
runId: "turn-1" as never,
|
||||
status: "running",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: null,
|
||||
},
|
||||
@@ -1031,7 +1104,7 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "First",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -1040,7 +1113,7 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "Second",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:10Z",
|
||||
streaming: false,
|
||||
@@ -1136,7 +1209,7 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "First",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
updatedAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
@@ -1145,7 +1218,7 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "Second",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
updatedAt: "2026-01-01T00:00:10Z",
|
||||
streaming: false,
|
||||
|
||||
@@ -8,7 +8,12 @@ import {
|
||||
type WorkLogEntry,
|
||||
} from "../../session-logic";
|
||||
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
|
||||
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
type MessageId,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ThreadRunSummary } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
export const TIMELINE_MINIMAP_ITEM_SPACING = 8;
|
||||
@@ -159,9 +164,9 @@ export interface TimelineDurationMessage {
|
||||
streaming: boolean;
|
||||
}
|
||||
|
||||
export type TimelineLatestTurn = Pick<
|
||||
OrchestrationLatestTurn,
|
||||
"turnId" | "state" | "startedAt" | "completedAt"
|
||||
export type TimelineLatestRun = Pick<
|
||||
ThreadRunSummary,
|
||||
"runId" | "status" | "startedAt" | "completedAt"
|
||||
>;
|
||||
|
||||
export type MessagesTimelineRow =
|
||||
@@ -184,7 +189,7 @@ export type MessagesTimelineRow =
|
||||
kind: "turn-fold";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
label: string;
|
||||
expanded: boolean;
|
||||
}
|
||||
@@ -200,6 +205,12 @@ export type MessagesTimelineRow =
|
||||
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
|
||||
revertTurnCount?: number | undefined;
|
||||
}
|
||||
| {
|
||||
kind: "event";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
projectedItem: OrchestrationV2ProjectedTurnItem;
|
||||
}
|
||||
| {
|
||||
kind: "proposed-plan";
|
||||
id: string;
|
||||
@@ -275,8 +286,8 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
continue;
|
||||
}
|
||||
|
||||
const responseKey = message.turnId
|
||||
? `turn:${message.turnId}`
|
||||
const responseKey = message.runId
|
||||
? `turn:${message.runId}`
|
||||
: `unkeyed:${nullTurnResponseIndex}`;
|
||||
lastAssistantMessageIdByResponseKey.set(responseKey, message.id);
|
||||
}
|
||||
@@ -285,7 +296,7 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
}
|
||||
|
||||
interface TurnFold {
|
||||
turnId: TurnId;
|
||||
runId: RunId;
|
||||
anchorEntryId: string;
|
||||
createdAt: string;
|
||||
hiddenEntryIds: ReadonlySet<string>;
|
||||
@@ -300,18 +311,16 @@ interface TurnFold {
|
||||
* user sends a message, the previous turn is still the "active" one until the
|
||||
* server creates the new turn, and folding must not flicker through that window.
|
||||
*/
|
||||
function deriveUnsettledTurnId(
|
||||
latestTurn: TimelineLatestTurn | null,
|
||||
runningTurnId: TurnId | null,
|
||||
): TurnId | null {
|
||||
if (runningTurnId !== null) {
|
||||
return runningTurnId;
|
||||
}
|
||||
if (!latestTurn) {
|
||||
function deriveUnsettledRunId(latestRun: TimelineLatestRun | null): RunId | null {
|
||||
if (!latestRun) {
|
||||
return null;
|
||||
}
|
||||
const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
|
||||
return isSettled ? null : latestTurn.turnId;
|
||||
const isSettled =
|
||||
latestRun.completedAt !== null &&
|
||||
latestRun.status !== "running" &&
|
||||
latestRun.status !== "starting" &&
|
||||
latestRun.status !== "waiting";
|
||||
return isSettled ? null : latestRun.runId;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -322,9 +331,21 @@ function deriveUnsettledTurnId(
|
||||
function deriveTurnFolds(input: {
|
||||
timelineEntries: ReadonlyArray<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;
|
||||
@@ -337,7 +358,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) {
|
||||
@@ -345,16 +366,16 @@ function deriveTurnFolds(input: {
|
||||
pendingUserBoundary = entry.message.createdAt;
|
||||
continue;
|
||||
}
|
||||
const turnId =
|
||||
const runId =
|
||||
entry.kind === "message" && entry.message.role === "assistant"
|
||||
? (entry.message.turnId ?? null)
|
||||
? (entry.message.runId ?? null)
|
||||
: entry.kind === "work"
|
||||
? (entry.entry.turnId ?? null)
|
||||
? (entry.entry.runId ?? null)
|
||||
: null;
|
||||
if (!turnId) {
|
||||
if (!runId) {
|
||||
continue;
|
||||
}
|
||||
let group = groupsByTurnId.get(turnId);
|
||||
let group = groupsByRunId.get(runId);
|
||||
if (!group) {
|
||||
group = {
|
||||
entries: [],
|
||||
@@ -366,7 +387,7 @@ function deriveTurnFolds(input: {
|
||||
startBoundary: pendingUserBoundary,
|
||||
};
|
||||
pendingUserBoundary = null;
|
||||
groupsByTurnId.set(turnId, group);
|
||||
groupsByRunId.set(runId, group);
|
||||
}
|
||||
group.entries.push(entry);
|
||||
if (entry.kind === "message") {
|
||||
@@ -380,8 +401,8 @@ function deriveTurnFolds(input: {
|
||||
}
|
||||
|
||||
const foldsByAnchorEntryId = new Map<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) {
|
||||
@@ -411,16 +432,14 @@ function deriveTurnFolds(input: {
|
||||
}
|
||||
|
||||
const isLatestInterruptedTurn =
|
||||
input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
|
||||
input.latestRun?.runId === runId && input.latestRun.status === "interrupted";
|
||||
// A turn cut short by a steer leaves trailing work entries behind its
|
||||
// terminal message — take whichever ended last.
|
||||
const lastEntryEnd =
|
||||
lastEntry.kind === "message" ? lastEntry.message.updatedAt : lastEntry.createdAt;
|
||||
const elapsedMs =
|
||||
input.latestTurn?.turnId === turnId &&
|
||||
input.latestTurn.startedAt &&
|
||||
input.latestTurn.completedAt
|
||||
? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
|
||||
input.latestRun?.runId === runId && input.latestRun.startedAt && input.latestRun.completedAt
|
||||
? computeElapsedMs(input.latestRun.startedAt, input.latestRun.completedAt)
|
||||
: computeElapsedMs(
|
||||
group.startBoundary ?? firstEntry.createdAt,
|
||||
maxIsoTimestamp(group.terminalEntry?.message.updatedAt ?? null, lastEntryEnd) ??
|
||||
@@ -436,7 +455,7 @@ function deriveTurnFolds(input: {
|
||||
: "Worked";
|
||||
|
||||
foldsByAnchorEntryId.set(firstEntry.id, {
|
||||
turnId,
|
||||
runId,
|
||||
anchorEntryId: firstEntry.id,
|
||||
createdAt: firstEntry.createdAt,
|
||||
hiddenEntryIds,
|
||||
@@ -448,10 +467,8 @@ function deriveTurnFolds(input: {
|
||||
|
||||
export function deriveMessagesTimelineRows(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
latestTurn?: TimelineLatestTurn | null;
|
||||
runningTurnId?: TurnId | null;
|
||||
expandedTurnIds?: ReadonlySet<TurnId>;
|
||||
expandedWorkGroupIds?: ReadonlySet<string>;
|
||||
latestRun?: TimelineLatestRun | null;
|
||||
expandedRunIds?: ReadonlySet<RunId>;
|
||||
isWorking: boolean;
|
||||
activeTurnStartedAt: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
@@ -462,19 +479,16 @@ export function deriveMessagesTimelineRows(input: {
|
||||
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
|
||||
);
|
||||
const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
|
||||
const unsettledTurnId = deriveUnsettledTurnId(
|
||||
input.latestTurn ?? null,
|
||||
input.runningTurnId ?? null,
|
||||
);
|
||||
const unsettledRunId = deriveUnsettledRunId(input.latestRun ?? null);
|
||||
const foldsByAnchorEntryId = deriveTurnFolds({
|
||||
timelineEntries: input.timelineEntries,
|
||||
terminalAssistantMessageIds,
|
||||
latestTurn: input.latestTurn ?? null,
|
||||
unsettledTurnId,
|
||||
latestRun: input.latestRun ?? null,
|
||||
unsettledRunId,
|
||||
});
|
||||
const collapsedEntryIds = new Set<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);
|
||||
}
|
||||
@@ -491,11 +505,11 @@ export function deriveMessagesTimelineRows(input: {
|
||||
if (turnFold) {
|
||||
nextRows.push({
|
||||
kind: "turn-fold",
|
||||
id: `turn-fold:${turnFold.turnId}`,
|
||||
id: `turn-fold:${turnFold.runId}`,
|
||||
createdAt: turnFold.createdAt,
|
||||
turnId: turnFold.turnId,
|
||||
runId: turnFold.runId,
|
||||
label: turnFold.label,
|
||||
expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false,
|
||||
expanded: input.expandedRunIds?.has(turnFold.runId) ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -587,20 +601,29 @@ export function deriveMessagesTimelineRows(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
if (timelineEntry.kind === "turn-plan") {
|
||||
nextRows.push({
|
||||
kind: "turn-plan",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
turnPlan: timelineEntry.turnPlan,
|
||||
=======
|
||||
if (timelineEntry.kind === "event") {
|
||||
nextRows.push({
|
||||
kind: "event",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
projectedItem: timelineEntry.projectedItem,
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const assistantTurnStillInProgress =
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
unsettledTurnId !== null &&
|
||||
timelineEntry.message.turnId === unsettledTurnId;
|
||||
unsettledRunId !== null &&
|
||||
timelineEntry.message.runId === unsettledRunId;
|
||||
|
||||
const durationStart =
|
||||
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
|
||||
@@ -680,12 +703,17 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
case "proposed-plan":
|
||||
return a.proposedPlan === (b as typeof a).proposedPlan;
|
||||
|
||||
<<<<<<< HEAD
|
||||
case "turn-plan": {
|
||||
const bp = b as typeof a;
|
||||
// Plans rewrite in place: compare the snapshot's identity fields so an
|
||||
// unchanged plan keeps its row reference (virtualization stability).
|
||||
return a.createdAt === bp.createdAt && a.turnPlan.plan === bp.turnPlan.plan;
|
||||
}
|
||||
=======
|
||||
case "event":
|
||||
return a.projectedItem === (b as typeof a).projectedItem;
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
|
||||
case "work":
|
||||
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
|
||||
|
||||
@@ -180,8 +180,7 @@ function buildProps() {
|
||||
activeTurnInProgress: false,
|
||||
activeTurnStartedAt: null,
|
||||
listRef: createRef<LegendListRef | null>(),
|
||||
latestTurn: null,
|
||||
runningTurnId: null,
|
||||
latestRun: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
routeThreadKey: "environment-local:thread-1",
|
||||
onOpenTurnDiff: () => {},
|
||||
@@ -218,7 +217,7 @@ function buildUserTimelineEntry(text: string) {
|
||||
id: MessageId.make("message-1"),
|
||||
role: "user" as const,
|
||||
text,
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: MESSAGE_CREATED_AT,
|
||||
updatedAt: MESSAGE_CREATED_AT,
|
||||
streaming: false,
|
||||
@@ -706,7 +705,116 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("Work Log");
|
||||
});
|
||||
|
||||
it("formats changed file paths from the workspace root", () => {
|
||||
it("renders V2 interruption lifecycle entries as standalone rows", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<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(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
@@ -720,6 +828,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"],
|
||||
},
|
||||
},
|
||||
@@ -754,7 +864,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,
|
||||
@@ -793,7 +903,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 type { AgentPanelModel } from "@t3tools/client-runtime/state/subagentRuntime";
|
||||
@@ -86,8 +87,7 @@ import {
|
||||
shouldPreserveAssistantLineBreaks,
|
||||
type StableMessagesTimelineRowsState,
|
||||
type MessagesTimelineRow,
|
||||
TIMELINE_MINIMAP_MIN_ITEMS,
|
||||
type TimelineLatestTurn,
|
||||
type TimelineLatestRun,
|
||||
} from "./MessagesTimeline.logic";
|
||||
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
@@ -140,11 +140,16 @@ interface TimelineRowSharedState {
|
||||
activeThreadEnvironmentId: EnvironmentId;
|
||||
onRevertUserMessage: (messageId: MessageId) => void;
|
||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||
<<<<<<< HEAD
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onToggleTurnFold: (turnId: TurnId) => void;
|
||||
onToggleWorkGroup: (groupId: string, anchorKey: string) => void;
|
||||
agentPanelModel: AgentPanelModel;
|
||||
onOpenAgents: () => void;
|
||||
=======
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
onToggleTurnFold: (runId: RunId) => void;
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
}
|
||||
|
||||
interface TimelineRowActivityState {
|
||||
@@ -211,11 +216,10 @@ interface MessagesTimelineProps {
|
||||
activeTurnStartedAt: string | null;
|
||||
listRef: React.RefObject<LegendListRef | null>;
|
||||
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
|
||||
latestTurn: TimelineLatestTurn | null;
|
||||
runningTurnId: TurnId | 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;
|
||||
@@ -257,8 +261,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onOpenAgents = NOOP_OPEN_AGENTS,
|
||||
listRef,
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
runningTurnId,
|
||||
latestRun,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
routeThreadKey,
|
||||
onOpenTurnDiff,
|
||||
@@ -282,6 +285,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
topFadeEnabled = false,
|
||||
loadEarlier = null,
|
||||
}: MessagesTimelineProps) {
|
||||
<<<<<<< HEAD
|
||||
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
|
||||
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
@@ -294,6 +298,25 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
return () => {
|
||||
if (disclosureSettleFrameRef.current !== null) {
|
||||
cancelAnimationFrame(disclosureSettleFrameRef.current);
|
||||
=======
|
||||
const [expandedRunIds, setExpandedRunIds] = useState<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
|
||||
// put as long as the list doesn't re-anchor. maintainScrollAtEnd would do
|
||||
// exactly that (pin the bottom content when row data changes while scrolled
|
||||
// to the end), yanking the trigger out of view. Suppress it for the frames
|
||||
// in which the toggle's data change and item measurements settle.
|
||||
const [foldToggleSettling, setFoldToggleSettling] = useState(false);
|
||||
const onToggleTurnFold = useCallback((runId: RunId) => {
|
||||
setFoldToggleSettling(true);
|
||||
setExpandedRunIds((existing) => {
|
||||
const next = new Set(existing);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
} else {
|
||||
next.add(runId);
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
}
|
||||
if (disclosureSettleSecondFrameRef.current !== null) {
|
||||
cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
|
||||
@@ -367,41 +390,39 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
|
||||
// An in-session interrupt leaves its turn expanded so the user keeps their
|
||||
// place; the next turn (or a reload, since this is local state) folds it.
|
||||
const previousLatestTurnRef = useRef(latestTurn);
|
||||
const previousLatestRunRef = useRef(latestRun);
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = latestTurn;
|
||||
if (!latestTurn || previous?.turnId === undefined) {
|
||||
const previous = previousLatestRunRef.current;
|
||||
previousLatestRunRef.current = latestRun;
|
||||
if (!latestRun || previous?.runId === undefined) {
|
||||
return;
|
||||
}
|
||||
if (latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && latestTurn.state === "interrupted") {
|
||||
setExpandedTurnIds((existing) => {
|
||||
if (latestRun.runId === previous.runId) {
|
||||
if (previous.status === "running" && latestRun.status === "interrupted") {
|
||||
setExpandedRunIds((existing) => {
|
||||
const next = new Set(existing);
|
||||
next.add(latestTurn.turnId);
|
||||
next.add(latestRun.runId);
|
||||
return next;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
setExpandedTurnIds((existing) => {
|
||||
if (!existing.has(previous.turnId)) {
|
||||
setExpandedRunIds((existing) => {
|
||||
if (!existing.has(previous.runId)) {
|
||||
return existing;
|
||||
}
|
||||
const next = new Set(existing);
|
||||
next.delete(previous.turnId);
|
||||
next.delete(previous.runId);
|
||||
return next;
|
||||
});
|
||||
}, [latestTurn]);
|
||||
}, [latestRun]);
|
||||
|
||||
const rawRows = useMemo(
|
||||
() =>
|
||||
deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
runningTurnId,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
latestRun,
|
||||
expandedRunIds,
|
||||
isWorking,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
@@ -409,10 +430,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
}),
|
||||
[
|
||||
timelineEntries,
|
||||
latestTurn,
|
||||
runningTurnId,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
latestRun,
|
||||
expandedRunIds,
|
||||
isWorking,
|
||||
activeTurnStartedAt,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
@@ -928,8 +947,12 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
// they sit closer to the work that follows them.
|
||||
(row.kind === "message" && row.message.role === "assistant" && !row.showAssistantMeta) ||
|
||||
row.kind === "work" ||
|
||||
<<<<<<< HEAD
|
||||
row.kind === "work-toggle" ||
|
||||
row.kind === "turn-plan"
|
||||
=======
|
||||
row.kind === "event"
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
? "pb-2"
|
||||
: "pb-4",
|
||||
row.kind === "message" && row.message.role === "assistant" ? "group/assistant" : null,
|
||||
@@ -947,7 +970,11 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
<AssistantTimelineRow row={row} />
|
||||
) : null}
|
||||
{row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
|
||||
<<<<<<< HEAD
|
||||
{row.kind === "turn-plan" ? <TurnPlanTimelineRow row={row} /> : null}
|
||||
=======
|
||||
{row.kind === "event" ? <V2EventTimelineRow row={row} /> : null}
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
{row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
|
||||
</div>
|
||||
);
|
||||
@@ -1092,7 +1119,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>
|
||||
@@ -1179,6 +1206,7 @@ function ProposedPlanTimelineRow({
|
||||
);
|
||||
}
|
||||
|
||||
<<<<<<< HEAD
|
||||
/**
|
||||
* Inline folded plan chip: one row per turn that produced plan/todo steps.
|
||||
* Collapsed by default — a segment bar plus the in-progress step label —
|
||||
@@ -1278,6 +1306,174 @@ const TurnPlanTimelineRow = memo(function TurnPlanTimelineRow({
|
||||
</div>
|
||||
);
|
||||
});
|
||||
=======
|
||||
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>
|
||||
);
|
||||
}
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
|
||||
function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
|
||||
const { workingStepLabel } = use(TimelineRowActivityCtx);
|
||||
@@ -1430,7 +1626,7 @@ const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection(
|
||||
turnSummary: TurnDiffSummary | undefined;
|
||||
routeThreadKey: string;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
if (!turnSummary) return null;
|
||||
const checkpointFiles = turnSummary.files;
|
||||
@@ -1460,12 +1656,10 @@ function AssistantChangedFilesSectionInner({
|
||||
checkpointFiles: TurnDiffSummary["files"];
|
||||
routeThreadKey: string;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
|
||||
}) {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const isLatestTurn = activity.latestTurnId === turnSummary.turnId;
|
||||
const persistedExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.turnId],
|
||||
const allDirectoriesExpanded = useUiStateStore(
|
||||
(store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId] ?? true,
|
||||
);
|
||||
const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
|
||||
const [autoExpanded] = useState(() =>
|
||||
@@ -1475,19 +1669,46 @@ function AssistantChangedFilesSectionInner({
|
||||
const expanded = persistedExpanded ?? (isLatestTurn && autoExpanded);
|
||||
|
||||
return (
|
||||
<ChangedFilesCard
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
expanded={expanded}
|
||||
showCompactPreview={isLatestTurn}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onExpandedChange={(nextExpanded) =>
|
||||
setExpanded(routeThreadKey, turnSummary.turnId, nextExpanded)
|
||||
}
|
||||
onToggleAllDirectories={() => setAllDirectoriesExpanded((current) => !current)}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="sticky top-2 z-10 mb-1.5 flex items-center justify-between gap-2 bg-[color-mix(in_srgb,var(--card)_45%,var(--background))] before:absolute before:inset-x-0 before:-top-2 before:h-2 before:bg-[color-mix(in_srgb,var(--card)_45%,var(--background))] before:content-['']">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
<span>Changed files ({changedFileCountLabel})</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<>
|
||||
<span className="mx-1">•</span>
|
||||
<DiffStatLabel additions={summaryStat.additions} deletions={summaryStat.deletions} />
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() => setExpanded(routeThreadKey, turnSummary.runId, !allDirectoriesExpanded)}
|
||||
>
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onOpenTurnDiff(turnSummary.runId, checkpointFiles[0]?.path)}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.runId}`}
|
||||
runId={turnSummary.runId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2040,8 +2261,8 @@ function buildToolCallExpandedBody(
|
||||
workspaceRoot: string | undefined,
|
||||
): string | null {
|
||||
const blocks: string[] = [];
|
||||
if (workEntry.itemType === "mcp_tool_call" && workEntry.toolData !== undefined) {
|
||||
blocks.push(`MCP call\n${JSON.stringify(workEntry.toolData, null, 2)}`);
|
||||
if (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) {
|
||||
blocks.push(`Tool call\n${JSON.stringify(workEntry.toolData, null, 2)}`);
|
||||
}
|
||||
const raw = workEntryRawCommand(workEntry);
|
||||
if (raw?.trim()) {
|
||||
@@ -2060,6 +2281,20 @@ function buildToolCallExpandedBody(
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
if (workEntry.structuredPayload !== undefined) {
|
||||
const structured = JSON.stringify(workEntry.structuredPayload, null, 2);
|
||||
if (structured && !blocks.includes(structured)) {
|
||||
blocks.push(structured);
|
||||
}
|
||||
}
|
||||
if (workEntry.projectedItem?.visibility !== undefined) {
|
||||
const { visibility, sourceThreadId } = workEntry.projectedItem;
|
||||
if (visibility !== "local") {
|
||||
blocks.push(
|
||||
`${visibility === "inherited" ? "Inherited" : "Synthetic"} from ${sourceThreadId}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return blocks.length > 0 ? blocks.join("\n\n") : null;
|
||||
}
|
||||
|
||||
@@ -2067,10 +2302,7 @@ export const toolCallExpandedBodyClassName =
|
||||
"max-h-64 cursor-text overflow-auto whitespace-pre-wrap break-words font-mono text-secondary-label text-[length:var(--font-size-code,0.6875rem)] leading-relaxed select-text";
|
||||
|
||||
function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
|
||||
if (
|
||||
workEntry.sourceActivityKind === "user-input.requested" ||
|
||||
workEntry.sourceActivityKind === "user-input.resolved"
|
||||
) {
|
||||
if (workEntry.itemType === "user_input_request") {
|
||||
return "message-circle";
|
||||
}
|
||||
if (workEntry.requestKind === "command") return "terminal";
|
||||
@@ -2084,12 +2316,16 @@ function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
|
||||
return "square-pen";
|
||||
}
|
||||
if (workEntry.itemType === "web_search") return "globe";
|
||||
if (workEntry.itemType === "image_view") return "eye";
|
||||
if (workEntry.itemType === "file_search") return "eye";
|
||||
|
||||
switch (workEntry.itemType) {
|
||||
case "mcp_tool_call":
|
||||
case "dynamic_tool":
|
||||
return "wrench";
|
||||
<<<<<<< HEAD
|
||||
case "dynamic_tool_call":
|
||||
=======
|
||||
case "subagent":
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
return "hammer";
|
||||
case "collab_agent_tool_call":
|
||||
return "bot";
|
||||
@@ -2234,7 +2470,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
|
||||
const activity = use(TimelineRowActivityCtx);
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const iconConfig = workToneIcon(workEntry.tone);
|
||||
const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
|
||||
const showWarningIndicator = false;
|
||||
const entryIconName = showWarningIndicator ? "x" : workEntryIconName(workEntry);
|
||||
const heading = toolWorkEntryHeading(workEntry);
|
||||
const rawPreview = workEntryPreview(workEntry, workspaceRoot);
|
||||
@@ -2248,9 +2484,7 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
|
||||
const expandedBody = buildToolCallExpandedBody(workEntry, workspaceRoot);
|
||||
const canExpand = expandedBody !== null;
|
||||
const showFailedIndicator = workEntryIndicatesToolFailure(workEntry);
|
||||
const showDestructiveRowStyle =
|
||||
showFailedIndicator &&
|
||||
(workEntry.sourceActivityKind === "runtime.error" || !workLogEntryIsToolLike(workEntry));
|
||||
const showDestructiveRowStyle = showFailedIndicator && !workLogEntryIsToolLike(workEntry);
|
||||
const iconWrapperClass = cn(
|
||||
"flex size-5 shrink-0 items-center justify-center",
|
||||
showWarningIndicator
|
||||
@@ -2293,6 +2527,8 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
|
||||
canExpand &&
|
||||
"cursor-pointer hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70",
|
||||
)}
|
||||
data-v2-item-type={workEntry.projectedItem?.item.type}
|
||||
data-v2-item-visibility={workEntry.projectedItem?.visibility}
|
||||
{...rowToggleProps}
|
||||
>
|
||||
<div className="flex select-none items-center gap-1.5 transition-[opacity,translate] duration-200">
|
||||
@@ -2306,6 +2542,12 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(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-secondary-label">{preview}</span>
|
||||
)}
|
||||
|
||||
@@ -11,6 +11,11 @@ import {
|
||||
type SidebarProjectGroupingMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
<<<<<<< HEAD
|
||||
=======
|
||||
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
import {
|
||||
isAtomCommandInterrupted,
|
||||
settlePromise,
|
||||
@@ -3018,10 +3023,7 @@ export function ArchivedThreadsPanel() {
|
||||
),
|
||||
);
|
||||
const threads = archivedSnapshots.flatMap(({ environmentId, snapshot }) =>
|
||||
snapshot.threads.map((thread) => ({
|
||||
...thread,
|
||||
environmentId,
|
||||
})),
|
||||
snapshot.threads.map((thread) => presentThreadShell(environmentId, thread)),
|
||||
);
|
||||
|
||||
const archivedProjects = Array.from(projectsByEnvironmentAndId.values());
|
||||
|
||||
@@ -6,6 +6,10 @@ import {
|
||||
ConnectionTargetStore,
|
||||
EMPTY_CONNECTION_CATALOG_DOCUMENT,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
decodeOrDiscardOrchestrationCache,
|
||||
registerConnectionInCatalog,
|
||||
removeCatalogValue,
|
||||
removeConnectionFromCatalog,
|
||||
@@ -17,14 +21,7 @@ import {
|
||||
CredentialStore,
|
||||
ProfileStore,
|
||||
} from "@t3tools/client-runtime/connection";
|
||||
import {
|
||||
EnvironmentId,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ServerConfig,
|
||||
ThreadId,
|
||||
VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -41,14 +38,9 @@ const THREAD_STORE_NAME = "thread";
|
||||
const SERVER_CONFIG_STORE_NAME = "server-config";
|
||||
const VCS_REFS_STORE_NAME = "vcs-refs";
|
||||
const CATALOG_KEY = "document";
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: EnvironmentId,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
const StoredShellSnapshot = StoredOrchestrationShellSnapshot;
|
||||
const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
|
||||
<<<<<<< HEAD
|
||||
// v2 stores the snapshot sequence alongside the thread so a warm cache can
|
||||
// resume via `afterSequence` instead of re-downloading the full thread body.
|
||||
// v3 adds windowed (paginated) snapshots carrying `page` metadata. The bump
|
||||
@@ -61,6 +53,9 @@ const StoredThreadSnapshot = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
});
|
||||
=======
|
||||
const StoredThreadSnapshot = StoredOrchestrationThreadSnapshot;
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
const StoredThreadSnapshotJson = Schema.fromJsonString(StoredThreadSnapshot);
|
||||
const StoredServerConfig = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(1),
|
||||
@@ -472,25 +467,24 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (typeof raw !== "string") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredShellSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none(),
|
||||
return decodeOrDiscardOrchestrationCache(
|
||||
decodeStoredShellSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none(),
|
||||
),
|
||||
),
|
||||
removeDatabaseValue(database, SHELL_STORE_NAME, environmentId),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("load-shell", cause),
|
||||
),
|
||||
Effect.mapError((cause) => persistenceError("load-shell", cause)),
|
||||
),
|
||||
saveShell: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeStoredShellSnapshot({
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
|
||||
@@ -546,33 +540,40 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
if (typeof raw !== "string") {
|
||||
return Effect.succeed(Option.none());
|
||||
}
|
||||
return decodeStoredThreadSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.snapshot)
|
||||
: Option.none(),
|
||||
return decodeOrDiscardOrchestrationCache(
|
||||
decodeStoredThreadSnapshot(raw).pipe(
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
Effect.map((stored) =>
|
||||
stored.environmentId === environmentId && stored.threadId === threadId
|
||||
? Option.some(stored.thread)
|
||||
: Option.none(),
|
||||
),
|
||||
),
|
||||
removeDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, threadId),
|
||||
),
|
||||
);
|
||||
}),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ConnectionPersistenceError"
|
||||
? cause
|
||||
: persistenceError("load-thread", cause),
|
||||
),
|
||||
Effect.mapError((cause) => persistenceError("load-thread", cause)),
|
||||
),
|
||||
saveThread: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeStoredThreadSnapshot({
|
||||
<<<<<<< HEAD
|
||||
schemaVersion: 3,
|
||||
=======
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
|
||||
environmentId,
|
||||
threadId: snapshot.thread.id,
|
||||
snapshot,
|
||||
threadId: thread.thread.id,
|
||||
thread,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
yield* writeDatabaseValue(
|
||||
database,
|
||||
THREAD_STORE_NAME,
|
||||
threadCacheKey(environmentId, snapshot.thread.id),
|
||||
threadCacheKey(environmentId, thread.thread.id),
|
||||
encoded,
|
||||
);
|
||||
}).pipe(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { EnvironmentId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ThreadId, RunId } from "@t3tools/contracts";
|
||||
import { beforeEach, describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { selectThreadDiffPanelSelection, useDiffPanelStore } from "./diffPanelStore";
|
||||
@@ -57,7 +57,7 @@ describe("diffPanelStore", () => {
|
||||
|
||||
it("clears incompatible selection fields when changing scopes", () => {
|
||||
const store = useDiffPanelStore.getState();
|
||||
store.selectTurn(THREAD_REF, TurnId.make("turn-1"), "src/app.ts");
|
||||
store.selectTurn(THREAD_REF, RunId.make("turn-1"), "src/app.ts");
|
||||
store.selectGitScope(THREAD_REF, "unstaged");
|
||||
|
||||
expect(
|
||||
@@ -71,7 +71,7 @@ describe("diffPanelStore", () => {
|
||||
});
|
||||
|
||||
it("increments the reveal request when opening the same turn file again", () => {
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const turnId = RunId.make("turn-1");
|
||||
useDiffPanelStore.getState().selectTurn(THREAD_REF, turnId, "src/app.ts");
|
||||
useDiffPanelStore.getState().selectTurn(THREAD_REF, turnId, "src/app.ts");
|
||||
|
||||
@@ -91,8 +91,8 @@ describe("diffPanelStore", () => {
|
||||
});
|
||||
|
||||
it("reconciles a missing turn selection to the latest available turn", () => {
|
||||
const missingTurnId = TurnId.make("turn-missing");
|
||||
const latestTurnId = TurnId.make("turn-latest");
|
||||
const missingTurnId = RunId.make("turn-missing");
|
||||
const latestTurnId = RunId.make("turn-latest");
|
||||
useDiffPanelStore.getState().selectTurn(THREAD_REF, missingTurnId, "src/app.ts");
|
||||
useDiffPanelStore.getState().reconcileTurnSelection(THREAD_REF, [latestTurnId]);
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import type { ScopedThreadRef, TurnId } from "@t3tools/contracts";
|
||||
import type { RunId, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
|
||||
@@ -8,7 +8,7 @@ import { resolveStorage } from "./lib/storage";
|
||||
export type DiffPanelSelection =
|
||||
| { kind: "branch"; baseRef: string | null }
|
||||
| { kind: "unstaged" }
|
||||
| { kind: "turn"; turnId: TurnId; filePath: string | null; revealRequestId: number };
|
||||
| { kind: "turn"; turnId: RunId; filePath: string | null; revealRequestId: number };
|
||||
|
||||
export type DiffRenderMode = "stacked" | "split";
|
||||
|
||||
@@ -22,8 +22,8 @@ interface DiffPanelStoreState {
|
||||
setDiffRenderMode: (mode: DiffRenderMode) => void;
|
||||
selectGitScope: (ref: ScopedThreadRef, scope: "branch" | "unstaged") => void;
|
||||
selectBranchBaseRef: (ref: ScopedThreadRef, baseRef: string | null) => void;
|
||||
selectTurn: (ref: ScopedThreadRef, turnId: TurnId, filePath?: string) => void;
|
||||
reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray<TurnId>) => void;
|
||||
selectTurn: (ref: ScopedThreadRef, turnId: RunId, filePath?: string) => void;
|
||||
reconcileTurnSelection: (ref: ScopedThreadRef, availableTurnIds: ReadonlyArray<RunId>) => void;
|
||||
removeThread: (ref: ScopedThreadRef) => void;
|
||||
}
|
||||
|
||||
@@ -125,7 +125,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,
|
||||
},
|
||||
|
||||
@@ -211,7 +211,7 @@ export function useThreadActions() {
|
||||
const resolved = resolveThreadTarget(target);
|
||||
if (!resolved) return AsyncResult.success(undefined);
|
||||
const { thread, threadRef } = resolved;
|
||||
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
|
||||
if (thread.runtime?.status === "running" && thread.runtime.activeRunId != null) {
|
||||
return AsyncResult.failure(
|
||||
Cause.fail(
|
||||
new ThreadArchiveBlockedError({
|
||||
@@ -333,7 +333,7 @@ export function useThreadActions() {
|
||||
shouldDeleteWorktree = confirmationResult.value;
|
||||
}
|
||||
|
||||
if (thread.session && thread.session.status !== "stopped") {
|
||||
if (thread.runtime !== null) {
|
||||
await stopThreadSession({
|
||||
environmentId: threadRef.environmentId,
|
||||
input: { threadId: threadRef.threadId },
|
||||
|
||||
@@ -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,7 +22,7 @@ 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",
|
||||
@@ -30,13 +31,11 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
latestRun: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
checkpoints: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
describe("sortThreads", () => {
|
||||
@@ -51,7 +50,7 @@ describe("sortThreads", () => {
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
@@ -67,7 +66,7 @@ describe("sortThreads", () => {
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:06:00.000Z",
|
||||
updatedAt: "2026-03-09T10:06:00.000Z",
|
||||
streaming: false,
|
||||
@@ -95,7 +94,7 @@ describe("sortThreads", () => {
|
||||
id: "message-1" as never,
|
||||
role: "assistant",
|
||||
text: "assistant only",
|
||||
turnId: null,
|
||||
runId: null,
|
||||
createdAt: "2026-03-09T10:02:00.000Z",
|
||||
updatedAt: "2026-03-09T10:02:00.000Z",
|
||||
streaming: false,
|
||||
|
||||
+123
-1683
File diff suppressed because it is too large.
Load diff
+409
-1523
File diff suppressed because it is too large.
Load diff
@@ -3,21 +3,14 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThread,
|
||||
EnvironmentThreadShell,
|
||||
ThreadConversationMessage,
|
||||
ThreadProposedPlan,
|
||||
ThreadRuntimeSummary,
|
||||
ThreadWorkEntry,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
type EnvironmentThreadStatus,
|
||||
mergeEnvironmentThread,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import type {
|
||||
OrchestrationMessage,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationSession,
|
||||
OrchestrationThreadActivity,
|
||||
ScopedProjectRef,
|
||||
ScopedThreadRef,
|
||||
ServerConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { mergeEnvironmentThread } from "@t3tools/client-runtime/state/threads";
|
||||
import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts";
|
||||
import type { EnvironmentId, OrchestrationV2ProjectedTurnItem, ThreadId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
import { useMemo } from "react";
|
||||
import { appAtomRegistry } from "../rpc/atomRegistry";
|
||||
@@ -28,9 +21,10 @@ import { environmentThreadDetails, environmentThreadShells } from "./threads";
|
||||
|
||||
const EMPTY_PROJECT_REFS: ReadonlyArray<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"),
|
||||
@@ -53,14 +47,17 @@ const EMPTY_THREAD_STATUS_ATOM = Atom.make<EnvironmentThreadStatus>("empty").pip
|
||||
const EMPTY_MESSAGES_ATOM = Atom.make(EMPTY_MESSAGES).pipe(
|
||||
Atom.withLabel("web-thread-messages:empty"),
|
||||
);
|
||||
const EMPTY_ACTIVITIES_ATOM = Atom.make(EMPTY_ACTIVITIES).pipe(
|
||||
Atom.withLabel("web-thread-activities:empty"),
|
||||
const EMPTY_WORK_ENTRIES_ATOM = Atom.make(EMPTY_WORK_ENTRIES).pipe(
|
||||
Atom.withLabel("web-thread-work-entries:empty"),
|
||||
);
|
||||
const EMPTY_PROPOSED_PLANS_ATOM = Atom.make(EMPTY_PROPOSED_PLANS).pipe(
|
||||
Atom.withLabel("web-thread-proposed-plans:empty"),
|
||||
);
|
||||
const EMPTY_SESSION_ATOM = Atom.make<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(
|
||||
@@ -186,31 +183,39 @@ export function useThread(
|
||||
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,15 +9,8 @@ import {
|
||||
type EnvironmentThreadSearchMatch,
|
||||
} from "@t3tools/client-runtime/state/thread-search";
|
||||
import { type VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
ProjectContentMatch,
|
||||
ProjectEntryKind,
|
||||
ThreadId,
|
||||
VcsListRefsResult,
|
||||
VcsRef,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ThreadId, VcsListRefsResult, VcsRef } from "@t3tools/contracts";
|
||||
import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
@@ -56,7 +49,7 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
|
||||
});
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: OrchestrationThread | null;
|
||||
readonly data: EnvironmentThread | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly isDeleted: boolean;
|
||||
|
||||
@@ -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,10 +19,8 @@ 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",
|
||||
@@ -29,11 +28,11 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
settledOverride: null,
|
||||
settledAt: 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,13 +30,8 @@ import {
|
||||
import * as EnvironmentSupervisor from "../connection/supervisor.ts";
|
||||
import * as RpcSession from "../rpc/session.ts";
|
||||
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
|
||||
import {
|
||||
archiveThread,
|
||||
createProject,
|
||||
settleThread,
|
||||
stopThreadSession,
|
||||
unsettleThread,
|
||||
} from "./commands.ts";
|
||||
import { v2Projection, v2ThreadId } from "../state/orchestrationV2TestFixtures.ts";
|
||||
import { archiveThread, createProject, startThreadTurn } from "./commands.ts";
|
||||
|
||||
const TEST_CRYPTO_LAYER = Layer.succeed(
|
||||
Crypto.Crypto,
|
||||
@@ -44,14 +48,45 @@ const TARGET = new PrimaryConnectionTarget({
|
||||
wsBaseUrl: "wss://environment.example.test",
|
||||
});
|
||||
|
||||
const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (
|
||||
dispatched: ClientOrchestrationCommand[],
|
||||
) {
|
||||
const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(function* (input: {
|
||||
readonly commands: OrchestrationV2Command[];
|
||||
readonly projects: ProjectMutation[];
|
||||
readonly launches?: OrchestrationV2ThreadLaunchInput[];
|
||||
readonly projection?: OrchestrationV2ThreadProjection;
|
||||
}) {
|
||||
const client = {
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: (command: ClientOrchestrationCommand) =>
|
||||
[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
|
||||
Effect.sync(() => {
|
||||
dispatched.push(command);
|
||||
return { sequence: dispatched.length };
|
||||
input.commands.push(command);
|
||||
return { sequence: input.commands.length };
|
||||
}),
|
||||
[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: () =>
|
||||
Effect.succeed(input.projection ?? v2Projection),
|
||||
[ORCHESTRATION_V2_WS_METHODS.launchThread]: (launchInput: OrchestrationV2ThreadLaunchInput) =>
|
||||
Effect.sync(() => {
|
||||
input.launches?.push(launchInput);
|
||||
return {
|
||||
threadId: launchInput.threadId ?? v2ThreadId,
|
||||
projection: input.projection ?? v2Projection,
|
||||
resumed: false,
|
||||
};
|
||||
}),
|
||||
[WS_METHODS.projectsMutate]: (mutation: ProjectMutation) =>
|
||||
Effect.sync(() => {
|
||||
input.projects.push(mutation);
|
||||
return {
|
||||
id: mutation.projectId,
|
||||
title: mutation.type === "project.create" ? mutation.title : "Project",
|
||||
workspaceRoot:
|
||||
mutation.type === "project.create" ? mutation.workspaceRoot : "/workspace/project",
|
||||
repositoryIdentity: null,
|
||||
faviconPath: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-06T00:00:00.000Z",
|
||||
updatedAt: "2026-06-06T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
};
|
||||
}),
|
||||
} as unknown as WsRpcProtocolClient;
|
||||
const session: RpcSession.RpcSession = {
|
||||
@@ -72,103 +107,222 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
|
||||
} satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);
|
||||
});
|
||||
|
||||
describe("environment commands", () => {
|
||||
it.effect("adds generated command metadata", () =>
|
||||
describe("V2 environment commands", () => {
|
||||
it.effect("routes projects through the event-sourced project transport", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatched: ClientOrchestrationCommand[] = [];
|
||||
const supervisor = yield* makeSupervisor(dispatched);
|
||||
const projects: ProjectMutation[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands: [], projects });
|
||||
|
||||
const result = yield* createProject({
|
||||
yield* createProject({
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/workspace/project",
|
||||
createdAt: "2026-06-06T00:00:00.000Z",
|
||||
createWorkspaceRootIfMissing: true,
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(result).toEqual({ sequence: 1 });
|
||||
expect(dispatched).toEqual([
|
||||
expect(projects).toEqual([
|
||||
{
|
||||
type: "project.create",
|
||||
commandId: "00000000-0000-4000-8000-000000000000",
|
||||
projectId: "project-1",
|
||||
title: "Project",
|
||||
workspaceRoot: "/workspace/project",
|
||||
createdAt: "2026-06-06T00:00:00.000Z",
|
||||
createWorkspaceRootIfMissing: true,
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("preserves caller metadata for idempotent queued commands", () =>
|
||||
it.effect("preserves caller command ids for idempotent V2 commands", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatched: ClientOrchestrationCommand[] = [];
|
||||
const supervisor = yield* makeSupervisor(dispatched);
|
||||
|
||||
yield* stopThreadSession({
|
||||
commandId: CommandId.make("queued-command"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
createdAt: "2026-06-06T00:01:00.000Z",
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(dispatched).toEqual([
|
||||
{
|
||||
type: "thread.session.stop",
|
||||
commandId: "queued-command",
|
||||
threadId: "thread-1",
|
||||
createdAt: "2026-06-06T00:01:00.000Z",
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("does not add timestamps to commands without createdAt", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatched: ClientOrchestrationCommand[] = [];
|
||||
const supervisor = yield* makeSupervisor(dispatched);
|
||||
const commands: OrchestrationV2Command[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands, projects: [] });
|
||||
|
||||
yield* archiveThread({
|
||||
commandId: CommandId.make("archive-command"),
|
||||
commandId: CommandId.make("queued-command"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(dispatched).toEqual([
|
||||
{
|
||||
type: "thread.archive",
|
||||
commandId: "archive-command",
|
||||
threadId: "thread-1",
|
||||
},
|
||||
expect(commands).toEqual([
|
||||
{ type: "thread.archive", commandId: "queued-command", threadId: "thread-1" },
|
||||
]);
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("dispatches settle and unsettle commands without timestamps", () =>
|
||||
it.effect("preserves plan implementation provenance on V2 runs", () =>
|
||||
Effect.gen(function* () {
|
||||
const dispatched: ClientOrchestrationCommand[] = [];
|
||||
const supervisor = yield* makeSupervisor(dispatched);
|
||||
const commands: OrchestrationV2Command[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands, projects: [] });
|
||||
|
||||
yield* settleThread({
|
||||
commandId: CommandId.make("settle-command"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
yield* unsettleThread({
|
||||
commandId: CommandId.make("unsettle-command"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
reason: "user",
|
||||
yield* startThreadTurn({
|
||||
commandId: CommandId.make("implement-plan"),
|
||||
threadId: v2ThreadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-implementation"),
|
||||
role: "user",
|
||||
text: "Implement the plan",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
sourceProposedPlan: {
|
||||
threadId: ThreadId.make("thread-plan"),
|
||||
planId: PlanId.make("plan-1"),
|
||||
},
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(dispatched).toEqual([
|
||||
{
|
||||
type: "thread.settle",
|
||||
commandId: "settle-command",
|
||||
threadId: "thread-1",
|
||||
expect(commands).toHaveLength(1);
|
||||
expect(commands[0]).toMatchObject({
|
||||
type: "message.dispatch",
|
||||
commandId: "implement-plan",
|
||||
threadId: v2ThreadId,
|
||||
sourcePlanRef: { threadId: "thread-plan", planId: "plan-1" },
|
||||
dispatchMode: { type: "start_immediately" },
|
||||
});
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("preserves an existing worktree and branch during first-message launch", () =>
|
||||
Effect.gen(function* () {
|
||||
const launches: OrchestrationV2ThreadLaunchInput[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
|
||||
|
||||
yield* startThreadTurn({
|
||||
commandId: CommandId.make("launch-existing-worktree"),
|
||||
threadId: v2ThreadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-existing-worktree"),
|
||||
role: "user",
|
||||
text: "Continue here",
|
||||
attachments: [],
|
||||
},
|
||||
{
|
||||
type: "thread.unsettle",
|
||||
commandId: "unsettle-command",
|
||||
threadId: "thread-1",
|
||||
reason: "user",
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
createThread: {
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: v2Projection.thread.modelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature",
|
||||
worktreePath: "/workspace/project-worktrees/feature",
|
||||
createdAt: "2026-06-20T00:00:00.000Z",
|
||||
},
|
||||
},
|
||||
]);
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(launches[0]).toMatchObject({
|
||||
threadId: v2ThreadId,
|
||||
workspaceStrategy: {
|
||||
type: "existing_worktree",
|
||||
worktreePath: "/workspace/project-worktrees/feature",
|
||||
branch: "feature",
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("provisions an origin-based worktree for an existing empty thread", () =>
|
||||
Effect.gen(function* () {
|
||||
const launches: OrchestrationV2ThreadLaunchInput[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches });
|
||||
|
||||
yield* startThreadTurn({
|
||||
commandId: CommandId.make("launch-existing-thread-worktree"),
|
||||
threadId: v2ThreadId,
|
||||
message: {
|
||||
messageId: MessageId.make("message-existing-thread-worktree"),
|
||||
role: "user",
|
||||
text: "Move to a worktree",
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
bootstrap: {
|
||||
prepareWorktree: {
|
||||
projectCwd: "/workspace/project",
|
||||
baseBranch: "main",
|
||||
branch: "feature",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
},
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(launches[0]).toMatchObject({
|
||||
threadId: v2ThreadId,
|
||||
reuseExistingThread: true,
|
||||
projectId: v2Projection.thread.projectId,
|
||||
workspaceStrategy: {
|
||||
type: "worktree",
|
||||
baseRef: "main",
|
||||
branch: "feature",
|
||||
startFromOrigin: true,
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
|
||||
it.effect("maps explicit active-run delivery modes to V2 dispatch semantics", () =>
|
||||
Effect.gen(function* () {
|
||||
const activeRunId = RunId.make("run-active");
|
||||
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
|
||||
const projection: OrchestrationV2ThreadProjection = {
|
||||
...v2Projection,
|
||||
runs: [
|
||||
{
|
||||
id: activeRunId,
|
||||
threadId: v2ThreadId,
|
||||
ordinal: 1,
|
||||
providerInstanceId: v2Projection.thread.providerInstanceId,
|
||||
modelSelection: v2Projection.thread.modelSelection,
|
||||
providerThreadId: null,
|
||||
userMessageId: MessageId.make("message-active"),
|
||||
rootNodeId: null,
|
||||
activeAttemptId: null,
|
||||
status: "running",
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
const commands: OrchestrationV2Command[] = [];
|
||||
const supervisor = yield* makeSupervisor({ commands, projects: [], projection });
|
||||
|
||||
for (const [mode, expectedType] of [
|
||||
["queue", "queue_after_active"],
|
||||
["steer", "steer_active"],
|
||||
["restart", "restart_active"],
|
||||
] as const) {
|
||||
yield* startThreadTurn({
|
||||
commandId: CommandId.make(`command-${mode}`),
|
||||
threadId: v2ThreadId,
|
||||
message: {
|
||||
messageId: MessageId.make(`message-${mode}`),
|
||||
role: "user",
|
||||
text: mode,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
dispatchMode: mode,
|
||||
}).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
|
||||
|
||||
expect(commands.at(-1)).toMatchObject({
|
||||
type: "message.dispatch",
|
||||
dispatchMode: {
|
||||
type: expectedType,
|
||||
...(mode === "queue" ? {} : { targetRunId: activeRunId }),
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
|
||||
);
|
||||
});
|
||||
@@ -1,333 +1,548 @@
|
||||
import {
|
||||
CommandId,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type ClientOrchestrationCommand,
|
||||
ORCHESTRATION_V2_WS_METHODS,
|
||||
WS_METHODS,
|
||||
type ChatAttachment,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type OrchestrationV2Command,
|
||||
type OrchestrationV2CreationSource,
|
||||
type PlanId,
|
||||
type ProjectId,
|
||||
type ProjectScript,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderInteractionMode,
|
||||
type ProviderUserInputAnswers,
|
||||
type RunId,
|
||||
type RuntimeMode,
|
||||
type RuntimeRequestId,
|
||||
type ThreadId,
|
||||
type UploadChatAttachment,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import type { EnvironmentSupervisor } from "../connection/supervisor.ts";
|
||||
import {
|
||||
type EnvironmentRpcFailure,
|
||||
type EnvironmentRpcSuccess,
|
||||
type EnvironmentRpcUnavailableError,
|
||||
request,
|
||||
} from "../rpc/client.ts";
|
||||
import { request } from "../rpc/client.ts";
|
||||
|
||||
type CommandType = ClientOrchestrationCommand["type"];
|
||||
type CommandOf<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 SettleThreadInput = CommandInput<"thread.settle">;
|
||||
export type UnsettleThreadInput = CommandInput<"thread.unsettle">;
|
||||
export type SnoozeThreadInput = CommandInput<"thread.snooze">;
|
||||
export type UnsnoozeThreadInput = CommandInput<"thread.unsnooze">;
|
||||
export type PinThreadInput = CommandInput<"thread.pin">;
|
||||
export type UnpinThreadInput = CommandInput<"thread.unpin">;
|
||||
export type ReorderPinnedThreadInput = CommandInput<"thread.pin.reorder">;
|
||||
export type UpdateThreadMetadataInput = CommandInput<"thread.meta.update">;
|
||||
export type SetThreadRuntimeModeInput = CommandInput<"thread.runtime-mode.set">;
|
||||
export type SetThreadInteractionModeInput = CommandInput<"thread.interaction-mode.set">;
|
||||
export type StartThreadTurnInput = CommandInput<"thread.turn.start">;
|
||||
export type InterruptThreadTurnInput = CommandInput<"thread.turn.interrupt">;
|
||||
export type RespondToThreadApprovalInput = CommandInput<"thread.approval.respond">;
|
||||
export type RespondToThreadUserInputInput = CommandInput<"thread.user-input.respond">;
|
||||
export type RevertThreadCheckpointInput = CommandInput<"thread.checkpoint.revert">;
|
||||
export type StopThreadSessionInput = CommandInput<"thread.session.stop">;
|
||||
|
||||
type DispatchTag = typeof ORCHESTRATION_WS_METHODS.dispatchCommand;
|
||||
type CommandEffect = Effect.Effect<
|
||||
EnvironmentRpcSuccess<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 settleThread: (input: SettleThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.settleThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.settle",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
|
||||
function* (input: UpdateThreadMetadataInput) {
|
||||
const commandId = yield* allocateCommandId(input);
|
||||
let result = null;
|
||||
if (
|
||||
input.title !== undefined ||
|
||||
input.branch !== undefined ||
|
||||
input.worktreePath !== undefined
|
||||
) {
|
||||
result = yield* dispatch({
|
||||
type: "thread.metadata.update",
|
||||
commandId,
|
||||
threadId: input.threadId,
|
||||
...(input.title === undefined ? {} : { title: input.title }),
|
||||
...(input.branch === undefined ? {} : { branch: input.branch }),
|
||||
...(input.worktreePath === undefined ? {} : { worktreePath: input.worktreePath }),
|
||||
});
|
||||
}
|
||||
if (input.modelSelection !== undefined) {
|
||||
result = yield* dispatch({
|
||||
type: "thread.model-selection.set",
|
||||
commandId: result === null ? commandId : CommandId.make(`${commandId}:model-selection`),
|
||||
threadId: input.threadId,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
}
|
||||
return result ?? { sequence: 0 };
|
||||
},
|
||||
);
|
||||
|
||||
export const unsettleThread: (input: UnsettleThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.unsettleThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.unsettle",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const snoozeThread: (input: SnoozeThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.snoozeThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.snooze",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const unsnoozeThread: (input: UnsnoozeThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.unsnoozeThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.unsnooze",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const pinThread: (input: PinThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.pinThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.pin",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const unpinThread: (input: UnpinThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.unpinThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.unpin",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const reorderPinnedThread: (input: ReorderPinnedThreadInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.reorderPinnedThread",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.pin.reorder",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const updateThreadMetadata: (input: UpdateThreadMetadataInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.updateThreadMetadata",
|
||||
)(function* (input) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.meta.update",
|
||||
commandId: yield* commandId(input),
|
||||
});
|
||||
});
|
||||
|
||||
export const setThreadRuntimeMode: (input: SetThreadRuntimeModeInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.setThreadRuntimeMode",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
});
|
||||
|
||||
export const setThreadInteractionMode: (input: SetThreadInteractionModeInput) => CommandEffect =
|
||||
Effect.fn("EnvironmentCommands.setThreadInteractionMode")(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const setThreadRuntimeMode = Effect.fn("EnvironmentCommands.setThreadRuntimeMode")(
|
||||
function* (input: SetThreadRuntimeModeInput) {
|
||||
return yield* dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
runtimeMode: input.runtimeMode,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const setThreadInteractionMode = Effect.fn("EnvironmentCommands.setThreadInteractionMode")(
|
||||
function* (input: SetThreadInteractionModeInput) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
interactionMode: input.interactionMode,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const startThreadTurn: (input: StartThreadTurnInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.startThreadTurn",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(function* (
|
||||
input: StartThreadTurnInput,
|
||||
) {
|
||||
const commandId = yield* allocateCommandId(input);
|
||||
const attachments = yield* persistAttachments(
|
||||
input.threadId,
|
||||
input.message.messageId,
|
||||
input.message.attachments,
|
||||
);
|
||||
const bootstrap = input.bootstrap?.createThread;
|
||||
const prepareWorktree = input.bootstrap?.prepareWorktree;
|
||||
if (bootstrap !== undefined || prepareWorktree !== undefined) {
|
||||
const existingProjection =
|
||||
bootstrap === undefined ? yield* getProjection(input.threadId) : null;
|
||||
const thread = bootstrap ?? existingProjection!.thread;
|
||||
const workspaceStrategy =
|
||||
prepareWorktree !== undefined
|
||||
? {
|
||||
type: "worktree" as const,
|
||||
baseRef: prepareWorktree.baseBranch,
|
||||
...(prepareWorktree.branch === undefined ? {} : { branch: prepareWorktree.branch }),
|
||||
...(prepareWorktree.startFromOrigin === undefined
|
||||
? {}
|
||||
: { startFromOrigin: prepareWorktree.startFromOrigin }),
|
||||
}
|
||||
: bootstrap?.worktreePath
|
||||
? {
|
||||
type: "existing_worktree" as const,
|
||||
worktreePath: bootstrap.worktreePath,
|
||||
...(bootstrap.branch === null ? {} : { branch: bootstrap.branch }),
|
||||
}
|
||||
: {
|
||||
type: "root" as const,
|
||||
...(bootstrap?.branch === null || bootstrap?.branch === undefined
|
||||
? {}
|
||||
: { branch: bootstrap.branch }),
|
||||
};
|
||||
return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
|
||||
commandId,
|
||||
creationSource: input.creationSource ?? "web",
|
||||
threadId: input.threadId,
|
||||
...(bootstrap === undefined ? { reuseExistingThread: true } : {}),
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: input.modelSelection ?? thread.modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
workspaceStrategy,
|
||||
initialMessage: {
|
||||
messageId: input.message.messageId,
|
||||
text: input.message.text,
|
||||
attachments,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const projection = yield* getProjection(input.threadId);
|
||||
const activeRun = projection.runs.findLast(
|
||||
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
|
||||
);
|
||||
const requestedMode = input.dispatchMode ?? "auto";
|
||||
const activeProviderThread =
|
||||
activeRun === undefined
|
||||
? undefined
|
||||
: projection.providerThreads.find((thread) => thread.id === activeRun.providerThreadId);
|
||||
const activeProviderSession =
|
||||
activeProviderThread?.providerSessionId === null ||
|
||||
activeProviderThread?.providerSessionId === undefined
|
||||
? undefined
|
||||
: projection.providerSessions.find(
|
||||
(session) => session.id === activeProviderThread.providerSessionId,
|
||||
);
|
||||
const turnCapabilities = activeProviderSession?.capabilities.turns;
|
||||
const dispatchMode =
|
||||
activeRun === undefined
|
||||
? ({ type: "start_immediately" } as const)
|
||||
: requestedMode === "steer"
|
||||
? ({ type: "steer_active", targetRunId: activeRun.id } as const)
|
||||
: requestedMode === "restart"
|
||||
? ({ type: "restart_active", targetRunId: activeRun.id } as const)
|
||||
: requestedMode === "queue"
|
||||
? ({ type: "queue_after_active" } as const)
|
||||
: turnCapabilities?.supportsActiveSteering === true
|
||||
? ({ type: "steer_active", targetRunId: activeRun.id } as const)
|
||||
: turnCapabilities?.supportsQueuedMessages === true
|
||||
? ({ type: "queue_after_active" } as const)
|
||||
: turnCapabilities?.supportsSteeringByInterruptRestart === true
|
||||
? ({ type: "restart_active", targetRunId: activeRun.id } as const)
|
||||
: ({ type: "queue_after_active" } as const);
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.turn.start",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "message.dispatch",
|
||||
commandId,
|
||||
createdBy: "user",
|
||||
creationSource: input.creationSource ?? "web",
|
||||
threadId: input.threadId,
|
||||
messageId: input.message.messageId,
|
||||
text: input.message.text,
|
||||
attachments,
|
||||
...(input.modelSelection === undefined ? {} : { modelSelection: input.modelSelection }),
|
||||
...(input.sourceProposedPlan === undefined ? {} : { sourcePlanRef: input.sourceProposedPlan }),
|
||||
dispatchMode,
|
||||
});
|
||||
});
|
||||
|
||||
export const interruptThreadTurn: (input: InterruptThreadTurnInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.interruptThreadTurn",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
|
||||
input: InterruptThreadTurnInput,
|
||||
) {
|
||||
const projection = yield* getProjection(input.threadId);
|
||||
const runId =
|
||||
input.runId ??
|
||||
(input.turnId as RunId | undefined) ??
|
||||
projection.runs.findLast(
|
||||
(run) => run.status === "starting" || run.status === "running" || run.status === "waiting",
|
||||
)?.id;
|
||||
if (runId === undefined) return { sequence: 0 };
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "run.interrupt",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
runId,
|
||||
});
|
||||
});
|
||||
|
||||
export const respondToThreadApproval: (input: RespondToThreadApprovalInput) => CommandEffect =
|
||||
Effect.fn("EnvironmentCommands.respondToThreadApproval")(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const respondToThreadApproval = Effect.fn("EnvironmentCommands.respondToThreadApproval")(
|
||||
function* (input: RespondToThreadApprovalInput) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.approval.respond",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "runtime-request.respond",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
requestId: input.requestId,
|
||||
decision: input.decision,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const respondToThreadUserInput: (input: RespondToThreadUserInputInput) => CommandEffect =
|
||||
Effect.fn("EnvironmentCommands.respondToThreadUserInput")(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const respondToThreadUserInput = Effect.fn("EnvironmentCommands.respondToThreadUserInput")(
|
||||
function* (input: RespondToThreadUserInputInput) {
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.user-input.respond",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "runtime-request.respond",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
requestId: input.requestId,
|
||||
answers: input.answers,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const revertThreadCheckpoint: (input: RevertThreadCheckpointInput) => CommandEffect =
|
||||
Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThreadCheckpoint")(
|
||||
function* (input: RevertThreadCheckpointInput) {
|
||||
const projection = yield* getProjection(input.threadId);
|
||||
const checkpoint =
|
||||
projection.checkpoints.find(
|
||||
(candidate) => candidate.id === input.checkpointId && candidate.scopeId === input.scopeId,
|
||||
) ??
|
||||
projection.checkpoints.findLast((candidate) => candidate.appRunOrdinal === input.turnCount);
|
||||
if (checkpoint === undefined) return { sequence: 0 };
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
type: "checkpoint.rollback",
|
||||
commandId: yield* allocateCommandId(input),
|
||||
threadId: input.threadId,
|
||||
scopeId: checkpoint.scopeId,
|
||||
checkpointId: checkpoint.id,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
export const stopThreadSession: (input: StopThreadSessionInput) => CommandEffect = Effect.fn(
|
||||
"EnvironmentCommands.stopThreadSession",
|
||||
)(function* (input) {
|
||||
const metadata = yield* timestampedCommandMetadata(input);
|
||||
return yield* dispatch({
|
||||
...input,
|
||||
type: "thread.session.stop",
|
||||
commandId: metadata.commandId,
|
||||
createdAt: metadata.createdAt,
|
||||
});
|
||||
export const stopThreadSession = Effect.fn("EnvironmentCommands.stopThreadSession")(function* (
|
||||
input: StopThreadSessionInput,
|
||||
) {
|
||||
const projection = yield* getProjection(input.threadId);
|
||||
const commandId = yield* allocateCommandId(input);
|
||||
let result = { sequence: 0 };
|
||||
for (const session of projection.providerSessions) {
|
||||
result = yield* dispatch({
|
||||
type: "provider-session.detach",
|
||||
commandId: CommandId.make(`${commandId}:detach:${session.id}`),
|
||||
threadId: input.threadId,
|
||||
providerSessionId: session.id,
|
||||
reason: "client-requested",
|
||||
});
|
||||
}
|
||||
return result;
|
||||
});
|
||||
@@ -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,8 +1,7 @@
|
||||
import {
|
||||
type EnvironmentId,
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationThreadDetailSnapshot,
|
||||
type ServerConfig,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type ThreadId,
|
||||
type VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -60,21 +59,18 @@ export class EnvironmentCacheStore extends Context.Service<
|
||||
{
|
||||
readonly loadShell: (
|
||||
environmentId: EnvironmentId,
|
||||
) => Effect.Effect<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<OrchestrationThreadDetailSnapshot>,
|
||||
ConnectionPersistenceError
|
||||
>;
|
||||
) => Effect.Effect<Option.Option<OrchestrationV2ThreadProjection>, ConnectionPersistenceError>;
|
||||
readonly saveThread: (
|
||||
environmentId: EnvironmentId,
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
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";
|
||||
@@ -44,8 +40,8 @@ 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
|
||||
| typeof WS_METHODS.subscribeServerConfig
|
||||
| typeof WS_METHODS.subscribeServerLifecycle
|
||||
|
||||
@@ -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,372 +1,115 @@
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationShellSnapshot,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";
|
||||
import { EnvironmentId, MessageId, RunId, TurnItemId } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { PrimaryConnectionTarget } from "../connection/model.ts";
|
||||
import {
|
||||
InvalidScopedProjectKeyError,
|
||||
InvalidScopedProjectRefCollectionKeyError,
|
||||
InvalidScopedThreadKeyError,
|
||||
parseProjectKey,
|
||||
parseProjectRefCollectionKey,
|
||||
parseThreadKey,
|
||||
} from "./entities.ts";
|
||||
import type { EnvironmentShellState } from "./shell.ts";
|
||||
import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts";
|
||||
import { createEnvironmentProjectAtoms } from "./projectEntities.ts";
|
||||
import { createEnvironmentSnapshotAtom } from "./snapshots.ts";
|
||||
import { createEnvironmentThreadDetailAtoms } from "./threadDetail.ts";
|
||||
import { mergeEnvironmentThread } from "./threadDetail.ts";
|
||||
import { createEnvironmentThreadShellAtoms } from "./threadShell.ts";
|
||||
import { presentThread, presentThreadShell } from "./models.ts";
|
||||
import { v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
|
||||
|
||||
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
const OTHER_PROJECT_ID = ProjectId.make("project-2");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const OTHER_THREAD_ID = ThreadId.make("thread-2");
|
||||
const environmentId = EnvironmentId.make("environment-v2");
|
||||
|
||||
describe("scoped entity keys", () => {
|
||||
it("preserves an invalid project key as structured error data", () => {
|
||||
const key = "missing-project-key-separator";
|
||||
let error: unknown;
|
||||
|
||||
try {
|
||||
parseProjectKey(key);
|
||||
} catch (cause) {
|
||||
error = cause;
|
||||
}
|
||||
|
||||
expect(error).toEqual(new InvalidScopedProjectKeyError({ key }));
|
||||
describe("V2 client presentation", () => {
|
||||
it("presents shell timestamps and status without constructing V1 state", () => {
|
||||
const shell = presentThreadShell(environmentId, v2ThreadShell);
|
||||
expect(shell.environmentId).toBe(environmentId);
|
||||
expect(shell.createdAt).toBe("2026-06-20T00:00:00.000Z");
|
||||
expect(shell.runtime).toBeNull();
|
||||
expect(shell.source).toBe(v2ThreadShell);
|
||||
});
|
||||
|
||||
it("preserves an invalid thread key as structured error data", () => {
|
||||
const key = "missing-thread-key-separator";
|
||||
let error: unknown;
|
||||
|
||||
try {
|
||||
parseThreadKey(key);
|
||||
} catch (cause) {
|
||||
error = cause;
|
||||
}
|
||||
|
||||
expect(error).toEqual(new InvalidScopedThreadKeyError({ key }));
|
||||
});
|
||||
|
||||
it("preserves malformed project reference collection input and its cause", () => {
|
||||
const key = "not-json";
|
||||
let error: unknown;
|
||||
|
||||
try {
|
||||
parseProjectRefCollectionKey(key);
|
||||
} catch (cause) {
|
||||
error = cause;
|
||||
}
|
||||
|
||||
expect(error).toBeInstanceOf(InvalidScopedProjectRefCollectionKeyError);
|
||||
expect(error).toMatchObject({ key, cause: expect.anything() });
|
||||
});
|
||||
|
||||
it("rejects invalid project reference collection shapes", () => {
|
||||
const key = JSON.stringify([["environment-1"]]);
|
||||
|
||||
expect(() => parseProjectRefCollectionKey(key)).toThrowError(
|
||||
InvalidScopedProjectRefCollectionKeyError,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const THREAD_SHELL = {
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
} as const;
|
||||
|
||||
const SNAPSHOT: OrchestrationShellSnapshot = {
|
||||
snapshotSequence: 1,
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
projects: [
|
||||
{
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: OTHER_PROJECT_ID,
|
||||
title: "Other project",
|
||||
workspaceRoot: "/other-repo",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
THREAD_SHELL,
|
||||
{
|
||||
...THREAD_SHELL,
|
||||
id: OTHER_THREAD_ID,
|
||||
projectId: OTHER_PROJECT_ID,
|
||||
title: "Other thread",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function shellState(snapshot: OrchestrationShellSnapshot): EnvironmentShellState {
|
||||
return {
|
||||
snapshot: Option.some(snapshot),
|
||||
status: "live",
|
||||
error: Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
function makeHarness() {
|
||||
const shellStateAtoms = Atom.family((_environmentId: EnvironmentId) =>
|
||||
Atom.make(AsyncResult.success(shellState(SNAPSHOT))),
|
||||
);
|
||||
const threadStateAtoms = Atom.family((_key: string) =>
|
||||
Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)),
|
||||
);
|
||||
const catalogValueAtom = Atom.make({
|
||||
isReady: true,
|
||||
entries: new Map([
|
||||
[
|
||||
ENVIRONMENT_ID,
|
||||
it("retains the complete projection while deriving conversation parity", () => {
|
||||
const runId = RunId.make("run-1");
|
||||
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
|
||||
const projection = {
|
||||
...v2Projection,
|
||||
runs: [
|
||||
{
|
||||
target: new PrimaryConnectionTarget({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
label: "Environment",
|
||||
httpBaseUrl: "https://example.test",
|
||||
wsBaseUrl: "wss://example.test",
|
||||
}),
|
||||
profile: Option.none(),
|
||||
id: runId,
|
||||
threadId: v2Projection.thread.id,
|
||||
ordinal: 1,
|
||||
providerInstanceId: v2Projection.thread.providerInstanceId,
|
||||
modelSelection: v2Projection.thread.modelSelection,
|
||||
providerThreadId: null,
|
||||
userMessageId: MessageId.make("message-user"),
|
||||
rootNodeId: null,
|
||||
activeAttemptId: null,
|
||||
status: "running" as const,
|
||||
requestedAt: now,
|
||||
startedAt: now,
|
||||
completedAt: null,
|
||||
checkpointId: null,
|
||||
contextHandoffId: null,
|
||||
},
|
||||
],
|
||||
]),
|
||||
});
|
||||
const snapshotAtom = createEnvironmentSnapshotAtom(shellStateAtoms);
|
||||
const projects = createEnvironmentProjectAtoms({
|
||||
catalogValueAtom,
|
||||
snapshotAtom,
|
||||
});
|
||||
const threadShells = createEnvironmentThreadShellAtoms({
|
||||
catalogValueAtom,
|
||||
snapshotAtom,
|
||||
});
|
||||
const threadDetails = createEnvironmentThreadDetailAtoms((environmentId, threadId) =>
|
||||
threadStateAtoms(`${environmentId}\u0000${threadId}`),
|
||||
);
|
||||
|
||||
return {
|
||||
registry: AtomRegistry.make(),
|
||||
shellStateAtom: shellStateAtoms(ENVIRONMENT_ID),
|
||||
threadStateAtom: (threadId: ThreadId) => threadStateAtoms(`${ENVIRONMENT_ID}\u0000${threadId}`),
|
||||
projects,
|
||||
threadShells,
|
||||
threadDetails,
|
||||
};
|
||||
}
|
||||
|
||||
describe("environment entity projections", () => {
|
||||
it("composes detail collections with authoritative shell workspace metadata", () => {
|
||||
const messages: OrchestrationThread["messages"] = [];
|
||||
const detail = {
|
||||
...THREAD_SHELL,
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
title: "Cached thread",
|
||||
branch: "stale-branch",
|
||||
worktreePath: "/repo/stale-worktree",
|
||||
deletedAt: null,
|
||||
messages,
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
} satisfies OrchestrationThread & { readonly environmentId: EnvironmentId };
|
||||
const shell = {
|
||||
...THREAD_SHELL,
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
title: "Current thread",
|
||||
branch: "current-branch",
|
||||
worktreePath: "/repo/current-worktree",
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("message-user"),
|
||||
threadId: v2Projection.thread.id,
|
||||
runId,
|
||||
nodeId: null,
|
||||
role: "user" as const,
|
||||
text: "Hello",
|
||||
attachments: [],
|
||||
streaming: false,
|
||||
createdBy: "user" as const,
|
||||
creationSource: "web" as const,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const merged = mergeEnvironmentThread(detail, shell);
|
||||
const thread = presentThread(environmentId, projection);
|
||||
expect(thread.projection).toBe(projection);
|
||||
expect(thread.latestRun?.runId).toBe(runId);
|
||||
expect(thread.runtime?.status).toBe("running");
|
||||
expect(thread.runs).toHaveLength(1);
|
||||
expect(thread.availableActions.canInterrupt).toBe(true);
|
||||
expect(thread.messages[0]).toMatchObject({ text: "Hello", runId });
|
||||
});
|
||||
|
||||
expect(merged).toMatchObject({
|
||||
title: "Current thread",
|
||||
branch: "current-branch",
|
||||
worktreePath: "/repo/current-worktree",
|
||||
it("keeps the complete payload for generic V2 work-item rendering", () => {
|
||||
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
|
||||
const item = {
|
||||
id: TurnItemId.make("item-dynamic"),
|
||||
threadId: v2Projection.thread.id,
|
||||
runId: null,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed" as const,
|
||||
title: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "dynamic_tool" as const,
|
||||
toolName: "custom_tool",
|
||||
input: { nested: { value: 1 } },
|
||||
output: { ok: true },
|
||||
};
|
||||
const projection = {
|
||||
...v2Projection,
|
||||
turnItems: [item],
|
||||
visibleTurnItems: [
|
||||
{
|
||||
position: 0,
|
||||
visibility: "local" as const,
|
||||
sourceThreadId: v2Projection.thread.id,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
},
|
||||
],
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const thread = presentThread(environmentId, projection);
|
||||
expect(thread.workEntries[0]).toMatchObject({
|
||||
itemType: "dynamic_tool",
|
||||
label: "custom_tool",
|
||||
structuredPayload: item,
|
||||
});
|
||||
expect(merged?.messages).toBe(messages);
|
||||
});
|
||||
|
||||
it("preserves untouched project and thread identities across unrelated shell updates", () => {
|
||||
const harness = makeHarness();
|
||||
const projectRefsAtom = harness.projects.environmentProjectRefsAtom(ENVIRONMENT_ID);
|
||||
const threadRefsAtom = harness.threadShells.environmentThreadRefsAtom(ENVIRONMENT_ID);
|
||||
const projectsAtom = harness.projects.projectsAtom;
|
||||
const projectAtom = harness.projects.projectAtom({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
});
|
||||
const threadAtom = harness.threadShells.threadShellAtom({
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
threadId: THREAD_ID,
|
||||
});
|
||||
const projectRefs = harness.registry.get(projectRefsAtom);
|
||||
const threadRefs = harness.registry.get(threadRefsAtom);
|
||||
const projects = harness.registry.get(projectsAtom);
|
||||
const project = harness.registry.get(projectAtom);
|
||||
const thread = harness.registry.get(threadAtom);
|
||||
|
||||
harness.registry.set(
|
||||
harness.shellStateAtom,
|
||||
AsyncResult.success(
|
||||
shellState({
|
||||
...SNAPSHOT,
|
||||
snapshotSequence: 2,
|
||||
threads: SNAPSHOT.threads.map((candidate) =>
|
||||
candidate.id === OTHER_THREAD_ID
|
||||
? { ...candidate, title: "Renamed other thread" }
|
||||
: candidate,
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(harness.registry.get(projectRefsAtom)).toBe(projectRefs);
|
||||
expect(harness.registry.get(threadRefsAtom)).toBe(threadRefs);
|
||||
expect(harness.registry.get(projectsAtom)).toBe(projects);
|
||||
expect(harness.registry.get(projectAtom)).toBe(project);
|
||||
expect(harness.registry.get(threadAtom)).toBe(thread);
|
||||
});
|
||||
|
||||
it("preserves project-scoped thread collections across unrelated project updates", () => {
|
||||
const harness = makeHarness();
|
||||
const projectRef = {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
projectId: PROJECT_ID,
|
||||
};
|
||||
const refsByProjectAtom =
|
||||
harness.threadShells.environmentThreadRefsByProjectAtom(ENVIRONMENT_ID);
|
||||
const threadsAtom = harness.threadShells.threadShellsForProjectRefsAtom([projectRef]);
|
||||
const refs = harness.registry.get(refsByProjectAtom).get(PROJECT_ID);
|
||||
const threads = harness.registry.get(threadsAtom);
|
||||
|
||||
expect(threads).toHaveLength(1);
|
||||
expect(threads[0]?.id).toBe(THREAD_ID);
|
||||
|
||||
harness.registry.set(
|
||||
harness.shellStateAtom,
|
||||
AsyncResult.success(
|
||||
shellState({
|
||||
...SNAPSHOT,
|
||||
snapshotSequence: 2,
|
||||
threads: SNAPSHOT.threads.map((thread) =>
|
||||
thread.id === OTHER_THREAD_ID ? { ...thread, title: "Updated elsewhere" } : thread,
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(harness.registry.get(refsByProjectAtom).get(PROJECT_ID)).toBe(refs);
|
||||
expect(harness.registry.get(threadsAtom)).toBe(threads);
|
||||
});
|
||||
|
||||
it("updates only the requested thread detail and preserves untouched field identities", () => {
|
||||
const harness = makeHarness();
|
||||
const threadRef = {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
threadId: THREAD_ID,
|
||||
};
|
||||
const otherThreadRef = {
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
threadId: OTHER_THREAD_ID,
|
||||
};
|
||||
const threadDetailAtom = harness.threadDetails.detailAtom(threadRef);
|
||||
const messagesAtom = harness.threadDetails.messagesAtom(threadRef);
|
||||
const activitiesAtom = harness.threadDetails.activitiesAtom(threadRef);
|
||||
const statusAtom = harness.threadDetails.statusAtom(threadRef);
|
||||
const otherThreadDetailAtom = harness.threadDetails.detailAtom(otherThreadRef);
|
||||
const otherValue = harness.registry.get(otherThreadDetailAtom);
|
||||
const detail = {
|
||||
...THREAD_SHELL,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
} satisfies OrchestrationThread;
|
||||
|
||||
harness.registry.set(
|
||||
harness.threadStateAtom(THREAD_ID),
|
||||
AsyncResult.success<EnvironmentThreadState>({
|
||||
data: Option.some(detail),
|
||||
status: "live",
|
||||
error: Option.none(),
|
||||
page: Option.none(),
|
||||
}),
|
||||
);
|
||||
|
||||
const scopedDetail = harness.registry.get(threadDetailAtom);
|
||||
const messages = harness.registry.get(messagesAtom);
|
||||
const activities = harness.registry.get(activitiesAtom);
|
||||
|
||||
expect(scopedDetail).toEqual({ ...detail, environmentId: ENVIRONMENT_ID });
|
||||
expect(harness.registry.get(statusAtom)).toBe("live");
|
||||
expect(harness.registry.get(otherThreadDetailAtom)).toBe(otherValue);
|
||||
|
||||
harness.registry.set(
|
||||
harness.threadStateAtom(THREAD_ID),
|
||||
AsyncResult.success<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(),
|
||||
page: 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_WS_METHODS } from "@t3tools/contracts";
|
||||
import { ORCHESTRATION_V2_WS_METHODS } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { createEnvironmentRpcQueryAtomFamily } from "./runtime.ts";
|
||||
@@ -10,7 +10,7 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
|
||||
return {
|
||||
turnDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:orchestration:turn-diff",
|
||||
tag: ORCHESTRATION_WS_METHODS.getTurnDiff,
|
||||
tag: ORCHESTRATION_V2_WS_METHODS.getTurnDiff,
|
||||
}),
|
||||
workflowScript: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:orchestration:workflow-script",
|
||||
@@ -21,7 +21,7 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
|
||||
}),
|
||||
fullThreadDiff: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:orchestration:full-thread-diff",
|
||||
tag: ORCHESTRATION_WS_METHODS.getFullThreadDiff,
|
||||
tag: ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff,
|
||||
}),
|
||||
threadSearch: createEnvironmentRpcQueryAtomFamily(runtime, {
|
||||
label: "environment-data:orchestration:thread-search",
|
||||
@@ -31,7 +31,7 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
|
||||
}),
|
||||
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";
|
||||
@@ -22,7 +22,8 @@ import * as ConnectionWakeups from "../connection/wakeups.ts";
|
||||
import * as Persistence from "../platform/persistence.ts";
|
||||
import * as RpcSession from "../rpc/session.ts";
|
||||
import type { WsRpcProtocolClient } from "../rpc/protocol.ts";
|
||||
import { makeEnvironmentShellState, ShellSnapshotLoader } from "./shell.ts";
|
||||
import { makeEnvironmentShellState } from "./shell.ts";
|
||||
import { v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts";
|
||||
|
||||
const TARGET = new PrimaryConnectionTarget({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
@@ -31,20 +32,9 @@ const TARGET = new PrimaryConnectionTarget({
|
||||
wsBaseUrl: "wss://environment.example.test",
|
||||
});
|
||||
|
||||
const PREPARED: PreparedConnection = {
|
||||
environmentId: TARGET.environmentId,
|
||||
label: TARGET.label,
|
||||
httpBaseUrl: TARGET.httpBaseUrl,
|
||||
socketUrl: TARGET.wsBaseUrl,
|
||||
httpAuthorization: null,
|
||||
target: TARGET,
|
||||
};
|
||||
|
||||
const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = {
|
||||
const LIVE_SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
|
||||
...v2ShellSnapshot,
|
||||
snapshotSequence: 1,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: "2026-06-06T00:00:00.000Z",
|
||||
};
|
||||
|
||||
function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
|
||||
@@ -60,9 +50,9 @@ function session(client: WsRpcProtocolClient): RpcSession.RpcSession {
|
||||
describe("environment shell synchronization", () => {
|
||||
it.effect("publishes live state before persistence and preserves it when ready", () =>
|
||||
Effect.gen(function* () {
|
||||
const events = yield* Queue.unbounded<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";
|
||||
@@ -30,7 +31,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>;
|
||||
}
|
||||
@@ -42,7 +43,7 @@ const EMPTY_SHELL_STATE: EnvironmentShellState = {
|
||||
};
|
||||
|
||||
function shellStatusForSnapshot(
|
||||
snapshot: Option.Option<OrchestrationShellSnapshot>,
|
||||
snapshot: Option.Option<OrchestrationV2ShellSnapshot>,
|
||||
): EnvironmentShellStatus {
|
||||
return Option.isSome(snapshot) ? "cached" : "empty";
|
||||
}
|
||||
@@ -62,7 +63,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
|
||||
environmentId,
|
||||
...safeErrorLogAttributes(error),
|
||||
}),
|
||||
Effect.as(Option.none<OrchestrationShellSnapshot>()),
|
||||
Effect.as(Option.none<OrchestrationV2ShellSnapshot>()),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -71,13 +72,10 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
|
||||
status: shellStatusForSnapshot(cachedSnapshot),
|
||||
error: Option.none(),
|
||||
});
|
||||
const awaitingCompletion = yield* Ref.make(false);
|
||||
const lastAuthoritativeSession = yield* Ref.make<RpcSession | null>(null);
|
||||
const activeSubscriptionSession = yield* Ref.make<RpcSession | null>(null);
|
||||
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) =>
|
||||
@@ -136,7 +134,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
|
||||
);
|
||||
|
||||
const applyItem = Effect.fn("EnvironmentShellState.applyItem")(function* (
|
||||
item: OrchestrationShellStreamItem,
|
||||
item: OrchestrationV2ShellStreamItem,
|
||||
) {
|
||||
if (item.kind === "synchronized") {
|
||||
yield* Ref.set(awaitingCompletion, false);
|
||||
@@ -178,80 +176,13 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")
|
||||
yield* Queue.offer(persistence, nextSnapshot);
|
||||
});
|
||||
|
||||
const foregroundResubscriptions = Option.match(wakeups, {
|
||||
onNone: () => Stream.never,
|
||||
onSome: (service) =>
|
||||
service.changes.pipe(Stream.filter(ConnectionWakeups.shouldResubscribeAfterWakeup)),
|
||||
});
|
||||
|
||||
yield* setSynchronizing;
|
||||
yield* Effect.forkScoped(
|
||||
subscribeDynamic(
|
||||
ORCHESTRATION_WS_METHODS.subscribeShell,
|
||||
Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {
|
||||
yield* Ref.set(activeSubscriptionSession, session);
|
||||
const supportsCompletionMarker = yield* session.initialConfig.pipe(
|
||||
Effect.map((config) => config.shellResumeCompletionMarker === true),
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
|
||||
yield* setSynchronizing;
|
||||
|
||||
// Foreground resubscriptions on the same live session can resume from
|
||||
// the in-memory cursor. A new session reloads the authoritative HTTP
|
||||
// snapshot so a valid cursor cannot preserve incomplete cached data.
|
||||
const hasAuthoritativeSnapshot = (yield* Ref.get(lastAuthoritativeSession)) === session;
|
||||
let canResume = hasAuthoritativeSnapshot;
|
||||
let current = yield* SubscriptionRef.get(state);
|
||||
if (!hasAuthoritativeSnapshot || Option.isNone(current.snapshot)) {
|
||||
const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe(
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onSome: Effect.succeed,
|
||||
onNone: () =>
|
||||
SubscriptionRef.changes(supervisor.prepared).pipe(
|
||||
Stream.filter(Option.isSome),
|
||||
Stream.map((value) => value.value),
|
||||
Stream.runHead,
|
||||
Effect.map(Option.getOrThrow),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
const httpSnapshot = yield* snapshotLoader.load(prepared);
|
||||
if (Option.isSome(httpSnapshot)) {
|
||||
yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
|
||||
canResume = true;
|
||||
current = yield* SubscriptionRef.get(state);
|
||||
}
|
||||
}
|
||||
|
||||
// If the authoritative refresh failed, omit the cached cursor so the
|
||||
// socket fallback sends a complete snapshot for this new session.
|
||||
if (!canResume || Option.isNone(current.snapshot)) {
|
||||
return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};
|
||||
}
|
||||
if (!supportsCompletionMarker) {
|
||||
// Without a completion marker there is no synchronized signal for a
|
||||
// resumed subscription, so report live immediately, like threads.
|
||||
yield* SubscriptionRef.update(state, (value) => ({
|
||||
...value,
|
||||
status: "live" as const,
|
||||
error: Option.none(),
|
||||
}));
|
||||
}
|
||||
return {
|
||||
afterSequence: current.snapshot.value.snapshotSequence,
|
||||
...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
|
||||
};
|
||||
}),
|
||||
{
|
||||
onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
|
||||
retryExpectedFailureAfter: "250 millis",
|
||||
resubscribe: foregroundResubscriptions,
|
||||
},
|
||||
).pipe(Stream.runForEach(applyItem)),
|
||||
);
|
||||
yield* subscribe(
|
||||
ORCHESTRATION_V2_WS_METHODS.subscribeShell,
|
||||
{},
|
||||
{
|
||||
onExpectedFailure: (cause) => setStreamError(Cause.squash(cause)),
|
||||
},
|
||||
).pipe(Stream.runForEach(applyItem), Effect.forkScoped);
|
||||
yield* SubscriptionRef.changes(supervisor.state).pipe(
|
||||
Stream.runForEach((connectionState) => {
|
||||
switch (connectionProjectionPhase(connectionState)) {
|
||||
@@ -347,8 +278,20 @@ export function createEnvironmentShellSummaryAtom(input: {
|
||||
continue;
|
||||
}
|
||||
hasSnapshot = true;
|
||||
const updatedAt = state.snapshot.value.updatedAt;
|
||||
if (latestSnapshotUpdatedAt === null || updatedAt > latestSnapshotUpdatedAt) {
|
||||
const snapshot = state.snapshot.value;
|
||||
const updatedAt = snapshot.threads.concat(snapshot.archivedThreads).reduce<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,185 +1,84 @@
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
|
||||
|
||||
import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
|
||||
import { applyShellStreamEvent } from "./shellReducer.ts";
|
||||
|
||||
const baseSnapshot: OrchestrationShellSnapshot = {
|
||||
snapshotSequence: 0,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
const stubProject = {
|
||||
id: ProjectId.make("project-1"),
|
||||
title: "Test Project",
|
||||
workspaceRoot: "/workspace/test",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
} as const;
|
||||
|
||||
const stubThread = {
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Test Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access" as const,
|
||||
interactionMode: "default" as const,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
session: null,
|
||||
} as const;
|
||||
|
||||
describe("applyShellStreamEvent", () => {
|
||||
it("ignores stale project upserts without mutating the snapshot", () => {
|
||||
const snapshotWithProject: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
it("ignores stale project updates without mutating the snapshot", () => {
|
||||
const snapshotWithProject = {
|
||||
...v2ShellSnapshot,
|
||||
snapshotSequence: 4,
|
||||
projects: [stubProject],
|
||||
projects: [v2Project],
|
||||
};
|
||||
|
||||
for (const sequence of [3, 4]) {
|
||||
const next = applyShellStreamEvent(snapshotWithProject, {
|
||||
kind: "project-upserted",
|
||||
kind: "project.updated",
|
||||
sequence,
|
||||
project: { ...stubProject, title: "Stale Title" },
|
||||
project: { ...v2Project, title: "Stale Title" },
|
||||
});
|
||||
|
||||
expect(next).toBe(snapshotWithProject);
|
||||
expect(next.snapshotSequence).toBe(4);
|
||||
expect(next.projects[0]?.title).toBe("Test Project");
|
||||
expect(next.projects[0]?.title).toBe(v2Project.title);
|
||||
}
|
||||
});
|
||||
|
||||
describe("project-upserted", () => {
|
||||
it("adds a new project", () => {
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "project-upserted",
|
||||
sequence: 1,
|
||||
project: stubProject,
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(baseSnapshot, event);
|
||||
|
||||
expect(next.projects).toHaveLength(1);
|
||||
expect(next.projects[0]?.id).toBe("project-1");
|
||||
expect(next.snapshotSequence).toBe(1);
|
||||
it("applies project updates and removals", () => {
|
||||
const updated = applyShellStreamEvent(v2ShellSnapshot, {
|
||||
kind: "project.updated",
|
||||
sequence: 1,
|
||||
project: { ...v2Project, title: "Updated" },
|
||||
});
|
||||
expect(updated.projects[0]?.title).toBe("Updated");
|
||||
expect(updated.snapshotSequence).toBe(1);
|
||||
|
||||
it("updates an existing project", () => {
|
||||
const snapshotWithProject: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
projects: [stubProject],
|
||||
};
|
||||
|
||||
const updatedProject = { ...stubProject, title: "Updated Title" };
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "project-upserted",
|
||||
sequence: 2,
|
||||
project: updatedProject,
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(snapshotWithProject, event);
|
||||
|
||||
expect(next.projects).toHaveLength(1);
|
||||
expect(next.projects[0]?.title).toBe("Updated Title");
|
||||
expect(next.snapshotSequence).toBe(2);
|
||||
const removed = applyShellStreamEvent(updated, {
|
||||
kind: "project.removed",
|
||||
sequence: 2,
|
||||
projectId: ProjectId.make(v2Project.id),
|
||||
});
|
||||
expect(removed.projects).toEqual([]);
|
||||
});
|
||||
|
||||
describe("project-removed", () => {
|
||||
it("removes a project by id", () => {
|
||||
const snapshotWithProject: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
projects: [stubProject],
|
||||
};
|
||||
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "project-removed",
|
||||
sequence: 3,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(snapshotWithProject, event);
|
||||
|
||||
expect(next.projects).toHaveLength(0);
|
||||
expect(next.snapshotSequence).toBe(3);
|
||||
it("moves a thread between active and archive without duplicating it", () => {
|
||||
const archived = applyShellStreamEvent(v2ShellSnapshot, {
|
||||
kind: "thread.updated",
|
||||
sequence: 3,
|
||||
location: "archive",
|
||||
thread: { ...v2ThreadShell, archivedAt: v2ThreadShell.updatedAt },
|
||||
});
|
||||
expect(archived.threads).toEqual([]);
|
||||
expect(archived.archivedThreads).toHaveLength(1);
|
||||
|
||||
const active = applyShellStreamEvent(archived, {
|
||||
kind: "thread.updated",
|
||||
sequence: 4,
|
||||
location: "active",
|
||||
thread: v2ThreadShell,
|
||||
});
|
||||
expect(active.threads).toHaveLength(1);
|
||||
expect(active.archivedThreads).toEqual([]);
|
||||
});
|
||||
|
||||
describe("thread-upserted", () => {
|
||||
it("adds a new thread", () => {
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "thread-upserted",
|
||||
sequence: 4,
|
||||
thread: stubThread,
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(baseSnapshot, event);
|
||||
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.id).toBe("thread-1");
|
||||
expect(next.snapshotSequence).toBe(4);
|
||||
});
|
||||
|
||||
it("updates an existing thread", () => {
|
||||
const snapshotWithThread: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
threads: [stubThread],
|
||||
};
|
||||
|
||||
const updatedThread = { ...stubThread, title: "Updated Thread" };
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "thread-upserted",
|
||||
sequence: 5,
|
||||
thread: updatedThread,
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(snapshotWithThread, event);
|
||||
|
||||
expect(next.threads).toHaveLength(1);
|
||||
expect(next.threads[0]?.title).toBe("Updated Thread");
|
||||
it("removes a thread from either collection", () => {
|
||||
const next = applyShellStreamEvent(v2ShellSnapshot, {
|
||||
kind: "thread.removed",
|
||||
sequence: 5,
|
||||
location: "active",
|
||||
threadId: ThreadId.make(v2ThreadShell.id),
|
||||
});
|
||||
expect(next.threads).toEqual([]);
|
||||
expect(next.snapshotSequence).toBe(5);
|
||||
});
|
||||
|
||||
describe("thread-removed", () => {
|
||||
it("removes a thread by id", () => {
|
||||
const snapshotWithThread: OrchestrationShellSnapshot = {
|
||||
...baseSnapshot,
|
||||
threads: [stubThread],
|
||||
};
|
||||
it("leaves unknown future events unchanged", () => {
|
||||
const next = applyShellStreamEvent(
|
||||
v2ShellSnapshot,
|
||||
{ kind: "future.event", sequence: 99 } as never,
|
||||
);
|
||||
|
||||
const event: OrchestrationShellStreamEvent = {
|
||||
kind: "thread-removed",
|
||||
sequence: 6,
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
};
|
||||
|
||||
const next = applyShellStreamEvent(snapshotWithThread, event);
|
||||
|
||||
expect(next.threads).toHaveLength(0);
|
||||
expect(next.snapshotSequence).toBe(6);
|
||||
});
|
||||
});
|
||||
|
||||
it("returns original snapshot for unrecognized event kinds", () => {
|
||||
const unknownEvent = { kind: "unknown-future-event", sequence: 99 } as any;
|
||||
const next = applyShellStreamEvent(baseSnapshot, unknownEvent);
|
||||
expect(next).toBe(baseSnapshot);
|
||||
expect(next).toBe(v2ShellSnapshot);
|
||||
});
|
||||
});
|
||||
@@ -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),
|
||||
|
||||
@@ -62,6 +62,7 @@ export type {
|
||||
SnoozeThreadInput,
|
||||
StartThreadTurnInput,
|
||||
StopThreadSessionInput,
|
||||
ThreadCommandInput,
|
||||
UnarchiveThreadInput,
|
||||
UnpinThreadInput,
|
||||
UnsettleThreadInput,
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -1,69 +1,48 @@
|
||||
import type {
|
||||
OrchestrationCheckpointSummary,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationMessage,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationSession,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
ScopedThreadRef,
|
||||
} from "@t3tools/contracts";
|
||||
import type { OrchestrationV2ThreadProjection, ScopedThreadRef } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { AsyncResult, Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import type { EnvironmentThread, EnvironmentThreadShell } from "./models.ts";
|
||||
import { scopeThread } from "./models.ts";
|
||||
import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threadState.ts";
|
||||
import type {
|
||||
EnvironmentThread,
|
||||
EnvironmentThreadShell,
|
||||
ThreadCheckpointSummary,
|
||||
ThreadConversationMessage,
|
||||
ThreadPendingApproval,
|
||||
ThreadPendingUserInput,
|
||||
ThreadProposedPlan,
|
||||
ThreadRunSummary,
|
||||
ThreadRuntimeSummary,
|
||||
ScopedThreadProjection,
|
||||
ThreadWorkEntry,
|
||||
} from "./models.ts";
|
||||
import { presentThread } from "./models.ts";
|
||||
import { EMPTY_ENVIRONMENT_THREAD_STATE, type EnvironmentThreadState } from "./threads.ts";
|
||||
import { parseThreadKey, threadKey } from "./entities.ts";
|
||||
import { THREAD_STATE_IDLE_TTL_MS } from "./threadRetention.ts";
|
||||
|
||||
const EMPTY_MESSAGES: ReadonlyArray<OrchestrationMessage> = Object.freeze([]);
|
||||
const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = Object.freeze([]);
|
||||
const EMPTY_PROPOSED_PLANS: ReadonlyArray<OrchestrationProposedPlan> = Object.freeze([]);
|
||||
const EMPTY_CHECKPOINTS: ReadonlyArray<OrchestrationCheckpointSummary> = 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_CHECKPOINTS: ReadonlyArray<ThreadCheckpointSummary> = Object.freeze([]);
|
||||
const EMPTY_APPROVALS: ReadonlyArray<ThreadPendingApproval> = Object.freeze([]);
|
||||
const EMPTY_USER_INPUTS: ReadonlyArray<ThreadPendingUserInput> = Object.freeze([]);
|
||||
const EMPTY_VISIBLE_TURN_ITEMS: OrchestrationV2ThreadProjection["visibleTurnItems"] = Object.freeze(
|
||||
[],
|
||||
);
|
||||
|
||||
/**
|
||||
* Combine detail-only collections with the shell's authoritative thread metadata.
|
||||
*
|
||||
* Shell and detail subscriptions are intentionally independent. A cached detail can
|
||||
* therefore briefly outlive a newer shell snapshot after reconnecting. Workspace
|
||||
* consumers must use the shell branch/worktree/project fields so they do not target
|
||||
* a stale checkout while retaining messages, activities, plans, and checkpoints
|
||||
* from the detail subscription.
|
||||
*/
|
||||
/** Shell metadata wins over an independently cached detail projection. */
|
||||
export function mergeEnvironmentThread(
|
||||
detail: EnvironmentThread | null,
|
||||
shell: EnvironmentThreadShell | null,
|
||||
): EnvironmentThread | null {
|
||||
if (detail === null || shell === null) {
|
||||
return detail;
|
||||
}
|
||||
if (detail.environmentId !== shell.environmentId || detail.id !== shell.id) {
|
||||
return detail;
|
||||
}
|
||||
|
||||
if (detail === null || shell === null) return detail;
|
||||
if (detail.environmentId !== shell.environmentId || detail.id !== shell.id) return detail;
|
||||
return {
|
||||
...detail,
|
||||
environmentId: shell.environmentId,
|
||||
id: shell.id,
|
||||
projectId: shell.projectId,
|
||||
title: shell.title,
|
||||
modelSelection: shell.modelSelection,
|
||||
runtimeMode: shell.runtimeMode,
|
||||
interactionMode: shell.interactionMode,
|
||||
branch: shell.branch,
|
||||
worktreePath: shell.worktreePath,
|
||||
latestTurn: shell.latestTurn,
|
||||
createdAt: shell.createdAt,
|
||||
updatedAt: shell.updatedAt,
|
||||
archivedAt: shell.archivedAt,
|
||||
settledOverride: shell.settledOverride,
|
||||
settledAt: shell.settledAt,
|
||||
snoozedUntil: shell.snoozedUntil,
|
||||
snoozedAt: shell.snoozedAt,
|
||||
pinnedAt: shell.pinnedAt,
|
||||
pinOrderKey: shell.pinOrderKey,
|
||||
session: shell.session,
|
||||
...shell,
|
||||
latestRun: detail.latestRun,
|
||||
runtime: detail.runtime,
|
||||
source: shell.source,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -88,15 +67,13 @@ export function createEnvironmentThreadDetailAtoms<E>(
|
||||
|
||||
const threadDetailAtomFamily = Atom.family((key: string) => {
|
||||
const ref = parseThreadKey(key);
|
||||
let previousSource: OrchestrationThread | null = null;
|
||||
let previousSource: OrchestrationV2ThreadProjection | null = null;
|
||||
let previousValue: EnvironmentThread | null = null;
|
||||
return Atom.make((get) => {
|
||||
const source = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
|
||||
if (source === previousSource) {
|
||||
return previousValue;
|
||||
}
|
||||
if (source === previousSource) return previousValue;
|
||||
previousSource = source;
|
||||
previousValue = source === null ? null : scopeThread(ref.environmentId, source);
|
||||
previousValue = source === null ? null : presentThread(ref.environmentId, source);
|
||||
return previousValue;
|
||||
}).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
@@ -104,88 +81,96 @@ export function createEnvironmentThreadDetailAtoms<E>(
|
||||
);
|
||||
});
|
||||
|
||||
const threadStatusAtomFamily = Atom.family((key: string) =>
|
||||
const scopedThreadProjectionAtomFamily = Atom.family((key: string) => {
|
||||
const ref = parseThreadKey(key);
|
||||
let previousProjection: OrchestrationV2ThreadProjection | null = null;
|
||||
let previousValue: ScopedThreadProjection | null = null;
|
||||
return Atom.make((get) => {
|
||||
const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
|
||||
if (projection === previousProjection) return previousValue;
|
||||
previousProjection = projection;
|
||||
previousValue = projection === null ? null : { environmentId: ref.environmentId, projection };
|
||||
return previousValue;
|
||||
}).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`scoped-thread-projection:${key}`),
|
||||
);
|
||||
});
|
||||
|
||||
const visibleTurnItemsAtomFamily = Atom.family((key: string) =>
|
||||
Atom.make(
|
||||
(get): OrchestrationV2ThreadProjection["visibleTurnItems"] =>
|
||||
Option.getOrNull(get(threadStateValueAtomFamily(key)).data)?.visibleTurnItems ??
|
||||
EMPTY_VISIBLE_TURN_ITEMS,
|
||||
).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-visible-turn-items:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const family = <A>(label: string, select: (thread: EnvironmentThread) => A, empty: A) =>
|
||||
Atom.family((key: string) =>
|
||||
Atom.make((get): A => {
|
||||
const thread = get(threadDetailAtomFamily(key));
|
||||
return thread === null ? empty : select(thread);
|
||||
}).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-${label}:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const messages = family("messages", (thread) => thread.messages, EMPTY_MESSAGES);
|
||||
const workEntries = family("work-entries", (thread) => thread.workEntries, EMPTY_WORK_ENTRIES);
|
||||
const proposedPlans = family(
|
||||
"proposed-plans",
|
||||
(thread) => thread.proposedPlans,
|
||||
EMPTY_PROPOSED_PLANS,
|
||||
);
|
||||
const checkpoints = family("checkpoints", (thread) => thread.checkpoints, EMPTY_CHECKPOINTS);
|
||||
const pendingApprovals = family(
|
||||
"pending-approvals",
|
||||
(thread) => thread.pendingApprovals,
|
||||
EMPTY_APPROVALS,
|
||||
);
|
||||
const pendingUserInputs = family(
|
||||
"pending-user-inputs",
|
||||
(thread) => thread.pendingUserInputs,
|
||||
EMPTY_USER_INPUTS,
|
||||
);
|
||||
const runtime = family<ThreadRuntimeSummary | null>("runtime", (thread) => thread.runtime, null);
|
||||
const latestRun = family<ThreadRunSummary | null>(
|
||||
"latest-run",
|
||||
(thread) => thread.latestRun,
|
||||
null,
|
||||
);
|
||||
|
||||
const status = Atom.family((key: string) =>
|
||||
Atom.make((get) => get(threadStateValueAtomFamily(key)).status).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-status:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const threadErrorAtomFamily = Atom.family((key: string) =>
|
||||
const error = Atom.family((key: string) =>
|
||||
Atom.make((get) => Option.getOrNull(get(threadStateValueAtomFamily(key)).error)).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-error:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const threadMessagesAtomFamily = Atom.family((key: string) =>
|
||||
Atom.make(
|
||||
(get): ReadonlyArray<OrchestrationMessage> =>
|
||||
get(threadDetailAtomFamily(key))?.messages ?? EMPTY_MESSAGES,
|
||||
).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-messages:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const threadActivitiesAtomFamily = Atom.family((key: string) =>
|
||||
Atom.make(
|
||||
(get): ReadonlyArray<OrchestrationThreadActivity> =>
|
||||
get(threadDetailAtomFamily(key))?.activities ?? EMPTY_ACTIVITIES,
|
||||
).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-activities:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const threadProposedPlansAtomFamily = Atom.family((key: string) =>
|
||||
Atom.make(
|
||||
(get): ReadonlyArray<OrchestrationProposedPlan> =>
|
||||
get(threadDetailAtomFamily(key))?.proposedPlans ?? EMPTY_PROPOSED_PLANS,
|
||||
).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-proposed-plans:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const threadCheckpointsAtomFamily = Atom.family((key: string) =>
|
||||
Atom.make(
|
||||
(get): ReadonlyArray<OrchestrationCheckpointSummary> =>
|
||||
get(threadDetailAtomFamily(key))?.checkpoints ?? EMPTY_CHECKPOINTS,
|
||||
).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-checkpoints:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const threadSessionAtomFamily = Atom.family((key: string) =>
|
||||
Atom.make(
|
||||
(get): OrchestrationSession | null => get(threadDetailAtomFamily(key))?.session ?? null,
|
||||
).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-session:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
const threadLatestTurnAtomFamily = Atom.family((key: string) =>
|
||||
Atom.make(
|
||||
(get): OrchestrationLatestTurn | null => get(threadDetailAtomFamily(key))?.latestTurn ?? null,
|
||||
).pipe(
|
||||
Atom.setIdleTTL(THREAD_STATE_IDLE_TTL_MS),
|
||||
Atom.withLabel(`environment-thread-latest-turn:${key}`),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
stateAtom: (ref: ScopedThreadRef) => threadStateValueAtomFamily(threadKey(ref)),
|
||||
threadAtom: (ref: ScopedThreadRef) => scopedThreadProjectionAtomFamily(threadKey(ref)),
|
||||
visibleTurnItemsAtom: (ref: ScopedThreadRef) => visibleTurnItemsAtomFamily(threadKey(ref)),
|
||||
detailAtom: (ref: ScopedThreadRef) => threadDetailAtomFamily(threadKey(ref)),
|
||||
statusAtom: (ref: ScopedThreadRef) => threadStatusAtomFamily(threadKey(ref)),
|
||||
errorAtom: (ref: ScopedThreadRef) => threadErrorAtomFamily(threadKey(ref)),
|
||||
messagesAtom: (ref: ScopedThreadRef) => threadMessagesAtomFamily(threadKey(ref)),
|
||||
activitiesAtom: (ref: ScopedThreadRef) => threadActivitiesAtomFamily(threadKey(ref)),
|
||||
proposedPlansAtom: (ref: ScopedThreadRef) => threadProposedPlansAtomFamily(threadKey(ref)),
|
||||
checkpointsAtom: (ref: ScopedThreadRef) => threadCheckpointsAtomFamily(threadKey(ref)),
|
||||
sessionAtom: (ref: ScopedThreadRef) => threadSessionAtomFamily(threadKey(ref)),
|
||||
latestTurnAtom: (ref: ScopedThreadRef) => threadLatestTurnAtomFamily(threadKey(ref)),
|
||||
statusAtom: (ref: ScopedThreadRef) => status(threadKey(ref)),
|
||||
errorAtom: (ref: ScopedThreadRef) => error(threadKey(ref)),
|
||||
messagesAtom: (ref: ScopedThreadRef) => messages(threadKey(ref)),
|
||||
workEntriesAtom: (ref: ScopedThreadRef) => workEntries(threadKey(ref)),
|
||||
proposedPlansAtom: (ref: ScopedThreadRef) => proposedPlans(threadKey(ref)),
|
||||
checkpointsAtom: (ref: ScopedThreadRef) => checkpoints(threadKey(ref)),
|
||||
pendingApprovalsAtom: (ref: ScopedThreadRef) => pendingApprovals(threadKey(ref)),
|
||||
pendingUserInputsAtom: (ref: ScopedThreadRef) => pendingUserInputs(threadKey(ref)),
|
||||
runtimeAtom: (ref: ScopedThreadRef) => runtime(threadKey(ref)),
|
||||
latestRunAtom: (ref: ScopedThreadRef) => latestRun(threadKey(ref)),
|
||||
};
|
||||
}
|
||||
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user