Compare commits

..
Author SHA1 Message Date
Julius Marminge c8e866813d Migrate projection pins to pinned_at timestamps
- Drop legacy pinned columns from projection tables
- Consolidate pin timestamp migration and update projection writes
- Fix sidebar pin icon hover state
2026-03-30 18:22:32 -07:00
Julius Marminge 3a199bc719 Track pin timestamps for projects and threads
- replace boolean pin state with pinnedAt timestamps
- update orchestration, persistence, and sidebar sorting
2026-03-30 18:12:43 -07:00
Julius Marminge f48fcb8afe Move pinned threads into a global sidebar section
- Render pinned threads above projects
- Remove pin indicators from project rows
- Keep archive and status actions working in the shared row renderer
2026-03-30 17:56:06 -07:00
Julius Marminge 6723507c00 Use boolean bit schema for pinned flags
- Replace manual bit transforms with `Schema.BooleanFromBit`
- Keep project and thread projection mapping consistent
2026-03-30 15:53:43 -07:00
Julius Marminge c09e21da38 Prioritize pinned projects in sidebar
- Include project pin state in projection snapshots
- Show the pin indicator before project names in the sidebar
2026-03-30 15:43:43 -07:00
Julius Marminge 3083d30b1c Add pin support to orchestration and persistence
- Thread and project pin state now flows through decider, projector, snapshots, and SQL persistence
- Updates UI, contracts, and tests to cover pinned read models and mutations
2026-03-30 14:13:22 -07:00
Julius Marminge d32da3cb9a Prioritize pinned threads in sidebar sorting
- Sort pinned threads ahead of unpinned ones in auto-sort modes
- Persist thread pin state and surface pin/unpin actions in the sidebar
- Keep delete fallback selection aware of pinned threads
2026-03-30 13:30:06 -07:00
Julius Marminge 835d693a92 Prioritize pinned projects in sidebar sorting
- Add project pin state persistence and toggle actions
- Show pin affordance in the sidebar and keep pinned projects first
2026-03-30 13:04:14 -07:00
0ea639196a Refactor web orchestration sync to incremental events and isolated recovery (#1560)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-03-30 12:51:49 -07:00
Utkarsh Patil 6f51725732 refactor(web): remove redundant add-project cancel button (#1302) 2026-03-30 10:31:38 -07:00
Julius Marminge 8622b952ca Refactor terminal manager onto Effect runtime (#1525) 2026-03-30 10:19:11 -07:00
Julius Marminge f47c1f1046 Update README.md (#1565) 2026-03-30 05:37:28 +00:00
Julius Marminge 145ddfc408 Document T3 Code install methods (#1564) 2026-03-29 22:33:05 -07:00
Ivor 0bb787b90d Clarify provider setup in README (#1406) 2026-03-29 22:09:23 -07:00
67 changed files with 7094 additions and 2985 deletions

No files matched your search

+28 -4
View File
@@ -2,18 +2,42 @@
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
## How to use
## Installation
> [!WARNING]
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
> T3 Code currently supports Codex and Claude.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
### Run without installing
```bash
npx t3
```
You can also just install the desktop app. It's cooler.
### Desktop app
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
#### Windows (`winget`)
```bash
winget install T3Tools.T3Code
```
#### macOS (Homebrew)
```bash
brew install --cask t3-code
```
#### Arch Linux (AUR)
```bash
yay -S t3code-bin
```
## Some notes
@@ -116,6 +116,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
pinned: false,
defaultModelSelection: {
provider,
model: defaultModel,
@@ -129,6 +130,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
pinned: false,
modelSelection: {
provider,
model: defaultModel,
@@ -265,6 +267,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -278,6 +281,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -31,6 +31,7 @@ function makeSnapshot(input: {
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
@@ -43,6 +44,7 @@ function makeSnapshot(input: {
id: input.threadId,
projectId: input.projectId,
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -282,6 +282,7 @@ describe("CheckpointReactor", () => {
projectId: asProjectId("project-1"),
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -296,6 +297,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -72,6 +72,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -86,6 +87,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -132,6 +134,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-archive"),
title: "Project Archive",
workspaceRoot: "/tmp/project-archive",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -146,6 +149,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-archive"),
projectId: asProjectId("project-archive"),
title: "Archive me",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -199,6 +203,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-replay"),
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -213,6 +218,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-replay"),
projectId: asProjectId("project-replay"),
title: "replay",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -257,6 +263,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-stream"),
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -281,6 +288,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-stream"),
projectId: asProjectId("project-stream"),
title: "domain-stream",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -318,6 +326,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-turn-diff"),
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -332,6 +341,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -435,6 +445,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -451,6 +462,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -471,6 +483,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -528,6 +541,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-atomic"),
title: "Atomic Project",
workspaceRoot: "/tmp/project-atomic",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -542,6 +556,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-atomic"),
projectId: asProjectId("project-atomic"),
title: "atomic",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -669,6 +684,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-sync"),
title: "Sync Project",
workspaceRoot: "/tmp/project-sync",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -683,6 +699,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-sync"),
projectId: asProjectId("project-sync"),
title: "sync-before",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -754,6 +771,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -769,6 +787,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -789,6 +808,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1867,6 +1867,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
projectId: ProjectId.makeUnsafe("project-live"),
title: "Live Project",
workspaceRoot: "/tmp/project-live",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1905,6 +1906,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
projectId: ProjectId.makeUnsafe("project-scripts"),
title: "Scripts Project",
workspaceRoot: "/tmp/project-scripts",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -383,6 +383,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
projectId: event.payload.projectId,
title: event.payload.title,
workspaceRoot: event.payload.workspaceRoot,
pinnedAt: event.payload.pinnedAt,
defaultModelSelection: event.payload.defaultModelSelection,
scripts: event.payload.scripts,
createdAt: event.payload.createdAt,
@@ -404,6 +405,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.workspaceRoot !== undefined
? { workspaceRoot: event.payload.workspaceRoot }
: {}),
...(event.payload.pinnedAt !== undefined ? { pinnedAt: event.payload.pinnedAt } : {}),
...(event.payload.defaultModelSelection !== undefined
? { defaultModelSelection: event.payload.defaultModelSelection }
: {}),
@@ -442,6 +444,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
threadId: event.payload.threadId,
projectId: event.payload.projectId,
title: event.payload.title,
pinnedAt: event.payload.pinnedAt,
modelSelection: event.payload.modelSelection,
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
@@ -495,6 +498,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.pinnedAt !== undefined ? { pinnedAt: event.payload.pinnedAt } : {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
@@ -234,6 +234,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
id: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -257,6 +258,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
id: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread 1",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -46,6 +46,7 @@ import {
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
Struct.assign({
pinnedAt: Schema.NullOr(IsoDateTime),
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
@@ -59,6 +60,7 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
Struct.assign({
pinnedAt: Schema.NullOr(IsoDateTime),
modelSelection: Schema.fromJsonString(ModelSelection),
}),
);
@@ -147,6 +149,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
pinned_at AS "pinnedAt",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -166,6 +169,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
project_id AS "projectId",
title,
pinned_at AS "pinnedAt",
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
@@ -542,6 +546,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
pinnedAt: row.pinnedAt,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
@@ -553,6 +558,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
id: row.threadId,
projectId: row.projectId,
title: row.title,
pinnedAt: row.pinnedAt,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
@@ -245,6 +245,7 @@ describe("ProviderCommandReactor", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
pinned: false,
defaultModelSelection: modelSelection,
createdAt: now,
}),
@@ -256,6 +257,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinned: false,
modelSelection: modelSelection,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
@@ -225,6 +225,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -239,6 +240,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -768,6 +770,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -803,6 +806,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -955,6 +959,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1108,6 +1113,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1143,6 +1149,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -28,6 +28,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-a"),
title: "Project A",
workspaceRoot: "/tmp/project-a",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -41,6 +42,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-b"),
title: "Project B",
workspaceRoot: "/tmp/project-b",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -56,6 +58,7 @@ const readModel: OrchestrationReadModel = {
id: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "Thread A",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -79,6 +82,7 @@ const readModel: OrchestrationReadModel = {
id: ThreadId.makeUnsafe("thread-2"),
projectId: ProjectId.makeUnsafe("project-b"),
title: "Thread B",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -158,6 +162,7 @@ describe("commandInvariants", () => {
threadId: ThreadId.makeUnsafe("thread-3"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "new",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -182,6 +187,7 @@ describe("commandInvariants", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "dup",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -29,6 +29,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-scripts"),
title: "Scripts",
workspaceRoot: "/tmp/scripts",
pinned: false,
createdAt: now,
},
readModel,
@@ -37,7 +38,10 @@ describe("decider project scripts", () => {
const event = Array.isArray(result) ? result[0] : result;
expect(event.type).toBe("project.created");
expect((event.payload as { scripts: unknown[] }).scripts).toEqual([]);
expect(event.payload).toMatchObject({
pinnedAt: null,
scripts: [],
});
});
it("propagates scripts in project.meta.update payload", async () => {
@@ -59,6 +63,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-scripts"),
title: "Scripts",
workspaceRoot: "/tmp/scripts",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
@@ -94,6 +99,82 @@ describe("decider project scripts", () => {
expect((event.payload as { scripts?: unknown[] }).scripts).toEqual(scripts);
});
it("propagates pin state through thread create and meta update", async () => {
const now = new Date().toISOString();
const initial = createEmptyReadModel(now);
const withProject = await Effect.runPromise(
projectEvent(initial, {
sequence: 1,
eventId: asEventId("evt-project-create-pin"),
aggregateKind: "project",
aggregateId: asProjectId("project-pin"),
type: "project.created",
occurredAt: now,
commandId: CommandId.makeUnsafe("cmd-project-create-pin"),
causationEventId: null,
correlationId: CommandId.makeUnsafe("cmd-project-create-pin"),
metadata: {},
payload: {
projectId: asProjectId("project-pin"),
title: "Project",
workspaceRoot: "/tmp/project-pin",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
}),
);
const created = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-pin"),
threadId: ThreadId.makeUnsafe("thread-pin"),
projectId: asProjectId("project-pin"),
title: "Pinned thread",
pinned: true,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
branch: null,
worktreePath: null,
createdAt: now,
},
readModel: withProject,
}),
);
const createdEvent = Array.isArray(created) ? created[0] : created;
expect(createdEvent.type).toBe("thread.created");
expect(createdEvent.payload).toMatchObject({ pinnedAt: now });
const withThread = await Effect.runPromise(
projectEvent(withProject, {
...createdEvent,
sequence: 2,
}),
);
const updated = await Effect.runPromise(
decideOrchestrationCommand({
command: {
type: "thread.meta.update",
commandId: CommandId.makeUnsafe("cmd-thread-update-pin"),
threadId: ThreadId.makeUnsafe("thread-pin"),
pinned: false,
},
readModel: withThread,
}),
);
const updatedEvent = Array.isArray(updated) ? updated[0] : updated;
expect(updatedEvent.type).toBe("thread.meta-updated");
expect(updatedEvent.payload).toMatchObject({ pinnedAt: null });
});
it("emits user message and turn-start-requested events for thread.turn.start", async () => {
const now = new Date().toISOString();
const initial = createEmptyReadModel(now);
@@ -113,6 +194,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
@@ -136,6 +218,7 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -222,6 +305,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
@@ -245,6 +329,7 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -304,6 +389,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: now,
@@ -327,6 +413,7 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
+4
View File
@@ -77,6 +77,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
projectId: command.projectId,
title: command.title,
workspaceRoot: command.workspaceRoot,
pinnedAt: command.pinned ? command.createdAt : null,
defaultModelSelection: command.defaultModelSelection ?? null,
scripts: [],
createdAt: command.createdAt,
@@ -104,6 +105,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
projectId: command.projectId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
...(command.pinned !== undefined ? { pinnedAt: command.pinned ? occurredAt : null } : {}),
...(command.defaultModelSelection !== undefined
? { defaultModelSelection: command.defaultModelSelection }
: {}),
@@ -158,6 +160,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
projectId: command.projectId,
title: command.title,
pinnedAt: command.pinned ? command.createdAt : null,
modelSelection: command.modelSelection,
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
@@ -254,6 +257,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.pinned !== undefined ? { pinnedAt: command.pinned ? occurredAt : null } : {}),
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
@@ -76,6 +76,7 @@ describe("orchestration projector", () => {
id: "thread-1",
projectId: "project-1",
title: "demo",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -98,6 +99,99 @@ describe("orchestration projector", () => {
]);
});
it("applies pin updates for projects and threads", async () => {
const now = new Date().toISOString();
const later = new Date(Date.parse(now) + 1_000).toISOString();
const withProject = await Effect.runPromise(
projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "project.created",
aggregateKind: "project",
aggregateId: "project-1",
occurredAt: now,
commandId: "cmd-project-create",
payload: {
projectId: "project-1",
title: "demo",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: null,
scripts: [],
createdAt: now,
updatedAt: now,
},
}),
),
);
const withPinnedProject = await Effect.runPromise(
projectEvent(
withProject,
makeEvent({
sequence: 2,
type: "project.meta-updated",
aggregateKind: "project",
aggregateId: "project-1",
occurredAt: later,
commandId: "cmd-project-pin",
payload: {
projectId: "project-1",
pinnedAt: later,
updatedAt: later,
},
}),
),
);
expect(withPinnedProject.projects[0]?.pinnedAt).toBe(later);
const withThread = await Effect.runPromise(
projectEvent(
withPinnedProject,
makeEvent({
sequence: 3,
type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-thread-create",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
),
);
const withPinnedThread = await Effect.runPromise(
projectEvent(
withThread,
makeEvent({
sequence: 4,
type: "thread.meta-updated",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: later,
commandId: "cmd-thread-pin",
payload: {
threadId: "thread-1",
pinnedAt: later,
updatedAt: later,
},
}),
),
);
expect(withPinnedThread.threads[0]?.pinnedAt).toBe(later);
});
it("fails when event payload cannot be decoded by runtime schema", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
@@ -183,6 +183,7 @@ export function projectEvent(
id: payload.projectId,
title: payload.title,
workspaceRoot: payload.workspaceRoot,
pinnedAt: payload.pinnedAt,
defaultModelSelection: payload.defaultModelSelection,
scripts: payload.scripts,
createdAt: payload.createdAt,
@@ -213,6 +214,7 @@ export function projectEvent(
...(payload.workspaceRoot !== undefined
? { workspaceRoot: payload.workspaceRoot }
: {}),
...(payload.pinnedAt !== undefined ? { pinnedAt: payload.pinnedAt } : {}),
...(payload.defaultModelSelection !== undefined
? { defaultModelSelection: payload.defaultModelSelection }
: {}),
@@ -254,6 +256,7 @@ export function projectEvent(
id: payload.threadId,
projectId: payload.projectId,
title: payload.title,
pinnedAt: payload.pinnedAt,
modelSelection: payload.modelSelection,
runtimeMode: payload.runtimeMode,
interactionMode: payload.interactionMode,
@@ -320,6 +323,7 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...(payload.title !== undefined ? { title: payload.title } : {}),
...(payload.pinnedAt !== undefined ? { pinnedAt: payload.pinnedAt } : {}),
...(payload.modelSelection !== undefined
? { modelSelection: payload.modelSelection }
: {}),
@@ -14,6 +14,7 @@ import {
const ProjectionProjectDbRow = ProjectionProject.mapFields(
Struct.assign({
pinnedAt: Schema.NullOr(Schema.String),
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
@@ -31,6 +32,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
project_id,
title,
workspace_root,
pinned_at,
default_model_selection_json,
scripts_json,
created_at,
@@ -41,6 +43,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
${row.projectId},
${row.title},
${row.workspaceRoot},
${row.pinnedAt},
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
${JSON.stringify(row.scripts)},
${row.createdAt},
@@ -51,6 +54,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
DO UPDATE SET
title = excluded.title,
workspace_root = excluded.workspace_root,
pinned_at = excluded.pinned_at,
default_model_selection_json = excluded.default_model_selection_json,
scripts_json = excluded.scripts_json,
created_at = excluded.created_at,
@@ -68,6 +72,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
pinned_at AS "pinnedAt",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -87,6 +92,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
pinned_at AS "pinnedAt",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
created_at AS "createdAt",
@@ -27,6 +27,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options project",
workspaceRoot: "/tmp/project-null-options",
pinnedAt: "2026-03-24T00:00:00.000Z",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
@@ -60,6 +61,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
const persisted = yield* projects.getById({
projectId: ProjectId.makeUnsafe("project-null-options"),
});
assert.strictEqual(Option.getOrNull(persisted)?.pinnedAt, "2026-03-24T00:00:00.000Z");
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
provider: "codex",
model: "gpt-5.4",
@@ -76,6 +78,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
threadId: ThreadId.makeUnsafe("thread-null-options"),
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options thread",
pinnedAt: "2026-03-24T00:00:00.000Z",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
@@ -114,6 +117,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
const persisted = yield* threads.getById({
threadId: ThreadId.makeUnsafe("thread-null-options"),
});
assert.strictEqual(Option.getOrNull(persisted)?.pinnedAt, "2026-03-24T00:00:00.000Z");
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
@@ -15,6 +15,7 @@ import { ModelSelection } from "@t3tools/contracts";
const ProjectionThreadDbRow = ProjectionThread.mapFields(
Struct.assign({
pinnedAt: Schema.NullOr(Schema.String),
modelSelection: Schema.fromJsonString(ModelSelection),
}),
);
@@ -31,6 +32,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
thread_id,
project_id,
title,
pinned_at,
model_selection_json,
runtime_mode,
interaction_mode,
@@ -46,6 +48,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.threadId},
${row.projectId},
${row.title},
${row.pinnedAt},
${JSON.stringify(row.modelSelection)},
${row.runtimeMode},
${row.interactionMode},
@@ -61,6 +64,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
DO UPDATE SET
project_id = excluded.project_id,
title = excluded.title,
pinned_at = excluded.pinned_at,
model_selection_json = excluded.model_selection_json,
runtime_mode = excluded.runtime_mode,
interaction_mode = excluded.interaction_mode,
@@ -83,6 +87,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
thread_id AS "threadId",
project_id AS "projectId",
title,
pinned_at AS "pinnedAt",
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
@@ -107,6 +112,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
thread_id AS "threadId",
project_id AS "projectId",
title,
pinned_at AS "pinnedAt",
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
@@ -31,6 +31,7 @@ import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
import Migration0019 from "./Migrations/019_ProjectionPins.ts";
/**
* Migration loader with all migrations defined inline.
@@ -61,6 +62,7 @@ export const migrationEntries = [
[16, "CanonicalizeModelSelections", Migration0016],
[17, "ProjectionThreadsArchivedAt", Migration0017],
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
[19, "ProjectionPins", Migration0019],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,26 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const projectColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_projects)
`;
if (!projectColumns.some((column) => column.name === "pinned_at")) {
yield* sql`
ALTER TABLE projection_projects
ADD COLUMN pinned_at TEXT
`;
}
const threadColumns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!threadColumns.some((column) => column.name === "pinned_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN pinned_at TEXT
`;
}
});
@@ -16,6 +16,7 @@ export const ProjectionProject = Schema.Struct({
projectId: ProjectId,
title: Schema.String,
workspaceRoot: Schema.String,
pinnedAt: Schema.NullOr(IsoDateTime),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -24,6 +24,7 @@ export const ProjectionThread = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
title: Schema.String,
pinnedAt: Schema.NullOr(IsoDateTime),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+71 -38
View File
@@ -14,47 +14,81 @@ import {
TerminalResizeInput,
TerminalRestartInput,
TerminalSessionSnapshot,
TerminalSessionStatus,
TerminalWriteInput,
} from "@t3tools/contracts";
import { PtyProcess } from "./PTY";
import { Effect, Schema, ServiceMap } from "effect";
export class TerminalError extends Schema.TaggedErrorClass<TerminalError>()("TerminalError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
export interface TerminalSessionState {
threadId: string;
terminalId: string;
cwd: string;
status: TerminalSessionStatus;
pid: number | null;
history: string;
pendingHistoryControlSequence: string;
exitCode: number | null;
exitSignal: number | null;
updatedAt: string;
cols: number;
rows: number;
process: PtyProcess | null;
unsubscribeData: (() => void) | null;
unsubscribeExit: (() => void) | null;
hasRunningSubprocess: boolean;
runtimeEnv: Record<string, string> | null;
export class TerminalCwdError extends Schema.TaggedErrorClass<TerminalCwdError>()(
"TerminalCwdError",
{
cwd: Schema.String,
reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]),
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
if (this.reason === "notDirectory") {
return `Terminal cwd is not a directory: ${this.cwd}`;
}
if (this.reason === "notFound") {
return `Terminal cwd does not exist: ${this.cwd}`;
}
const causeMessage =
this.cause && typeof this.cause === "object" && "message" in this.cause
? this.cause.message
: undefined;
return causeMessage
? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})`
: `Failed to access terminal cwd: ${this.cwd}`;
}
}
export interface ShellCandidate {
shell: string;
args?: string[];
export class TerminalHistoryError extends Schema.TaggedErrorClass<TerminalHistoryError>()(
"TerminalHistoryError",
{
operation: Schema.Literals(["read", "truncate", "migrate"]),
threadId: Schema.String,
terminalId: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message() {
return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;
}
}
export interface TerminalStartInput extends TerminalOpenInput {
cols: number;
rows: number;
export class TerminalSessionLookupError extends Schema.TaggedErrorClass<TerminalSessionLookupError>()(
"TerminalSessionLookupError",
{
threadId: Schema.String,
terminalId: Schema.String,
},
) {
override get message() {
return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;
}
}
export class TerminalNotRunningError extends Schema.TaggedErrorClass<TerminalNotRunningError>()(
"TerminalNotRunningError",
{
threadId: Schema.String,
terminalId: Schema.String,
},
) {
override get message() {
return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;
}
}
export const TerminalError = Schema.Union([
TerminalCwdError,
TerminalHistoryError,
TerminalSessionLookupError,
TerminalNotRunningError,
]);
export type TerminalError = typeof TerminalError.Type;
/**
* TerminalManagerShape - Service API for terminal session lifecycle operations.
*/
@@ -101,14 +135,13 @@ export interface TerminalManagerShape {
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
/**
* Subscribe to terminal runtime events.
* Subscribe to terminal runtime events with a direct callback.
*
* Returns an unsubscribe function.
*/
readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>;
/**
* Dispose all managed terminal resources.
*/
readonly dispose: Effect.Effect<void>;
readonly subscribe: (
listener: (event: TerminalEvent) => Effect.Effect<void>,
) => Effect.Effect<() => void>;
}
/**
+25 -14
View File
@@ -4,7 +4,7 @@ import os from "node:os";
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
@@ -90,20 +90,19 @@ const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
class MockTerminalManager implements TerminalManagerShape {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private readonly listeners = new Set<(event: TerminalEvent) => void>();
private readonly eventPubSub = Effect.runSync(PubSub.unbounded<TerminalEvent>());
private activeSubscriptions = 0;
private key(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
emitEvent(event: TerminalEvent): void {
for (const listener of this.listeners) {
listener(event);
}
Effect.runSync(PubSub.publish(this.eventPubSub, event));
}
subscriptionCount(): number {
return this.listeners.size;
return this.activeSubscriptions;
}
readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) =>
@@ -210,13 +209,15 @@ class MockTerminalManager implements TerminalManagerShape {
readonly subscribe: TerminalManagerShape["subscribe"] = (listener) =>
Effect.sync(() => {
this.listeners.add(listener);
this.activeSubscriptions += 1;
const fiber = Effect.runFork(
Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)),
);
return () => {
this.listeners.delete(listener);
this.activeSubscriptions -= 1;
Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore));
};
});
readonly dispose: TerminalManagerShape["dispose"] = Effect.void;
}
// ---------------------------------------------------------------------------
@@ -1220,6 +1221,7 @@ describe("WebSocket Server", () => {
projectId: "project-diff",
title: "Diff Project",
workspaceRoot,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1233,6 +1235,7 @@ describe("WebSocket Server", () => {
threadId: "thread-diff",
projectId: "project-diff",
title: "Diff Thread",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1305,6 +1308,7 @@ describe("WebSocket Server", () => {
projectId: "project-1",
title: "WS Project",
workspaceRoot,
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1318,6 +1322,7 @@ describe("WebSocket Server", () => {
threadId: "thread-1",
projectId: "project-1",
title: "Thread 1",
pinned: false,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -1454,19 +1459,25 @@ describe("WebSocket Server", () => {
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
});
it("detaches terminal event listener on stop for injected manager", async () => {
it("shuts down cleanly for injected terminal managers", async () => {
const terminalManager = new MockTerminalManager();
server = await createTestServer({
cwd: "/test",
terminalManager,
});
expect(terminalManager.subscriptionCount()).toBe(1);
await closeTestServer();
server = null;
expect(terminalManager.subscriptionCount()).toBe(0);
expect(() =>
terminalManager.emitEvent({
type: "output",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
data: "after shutdown\n",
}),
).not.toThrow();
});
it("returns validation errors for invalid terminal open params", async () => {
+4 -2
View File
@@ -675,6 +675,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
projectId: bootstrapProjectId,
title: bootstrapProjectTitle,
workspaceRoot: cwd,
pinned: false,
defaultModelSelection: bootstrapProjectDefaultModelSelection,
createdAt,
});
@@ -698,6 +699,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
threadId,
projectId: bootstrapProjectId,
title: "New thread",
pinned: false,
modelSelection: bootstrapProjectDefaultModelSelection,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
@@ -719,9 +721,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
}
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
);
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
yield* readiness.markTerminalSubscriptionsReady;
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
+92 -45
View File
@@ -2,8 +2,11 @@
import "../index.css";
import {
EventId,
ORCHESTRATION_WS_METHODS,
ORCHESTRATION_WS_CHANNELS,
type MessageId,
type OrchestrationEvent,
type OrchestrationReadModel,
type ProjectId,
type ServerConfig,
@@ -57,6 +60,8 @@ interface TestFixture {
let fixture: TestFixture;
const wsRequests: WsRequestEnvelope["body"][] = [];
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
let wsClient: { send: (message: string) => void } | null = null;
let pushSequence = 1;
const wsLink = ws.link(/ws(s)?:\/\/.*/);
interface ViewportSpec {
@@ -232,6 +237,7 @@ function createSnapshotForTargetUser(options: {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
@@ -247,6 +253,7 @@ function createSnapshotForTargetUser(options: {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Browser test thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5",
@@ -305,6 +312,7 @@ function addThreadToSnapshot(
id: threadId,
projectId: PROJECT_ID,
title: "New thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5",
@@ -336,6 +344,80 @@ function addThreadToSnapshot(
};
}
function createThreadCreatedEvent(threadId: ThreadId, sequence: number): OrchestrationEvent {
return {
sequence,
eventId: EventId.makeUnsafe(`event-thread-created-${sequence}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: NOW_ISO,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.created",
payload: {
threadId,
projectId: PROJECT_ID,
title: "New thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
},
};
}
function sendOrchestrationDomainEvent(event: OrchestrationEvent): void {
if (!wsClient) {
throw new Error("WebSocket client not connected");
}
wsClient.send(
JSON.stringify({
type: "push",
sequence: pushSequence++,
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
data: event,
}),
);
}
async function waitForWsClient(): Promise<{ send: (message: string) => void }> {
let client: { send: (message: string) => void } | null = null;
await vi.waitFor(
() => {
client = wsClient;
expect(client).toBeTruthy();
},
{ timeout: 8_000, interval: 16 },
);
if (!client) {
throw new Error("WebSocket client not connected");
}
return client;
}
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
await waitForWsClient();
fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId);
sendOrchestrationDomainEvent(
createThreadCreatedEvent(threadId, fixture.snapshot.snapshotSequence),
);
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftThreadsByThreadId[threadId]).toBeUndefined();
},
{ timeout: 8_000, interval: 16 },
);
}
function createDraftOnlySnapshot(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-draft-target" as MessageId,
@@ -500,10 +582,12 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
const worker = setupWorker(
wsLink.addEventListener("connection", ({ client }) => {
wsClient = client;
pushSequence = 1;
client.send(
JSON.stringify({
type: "push",
sequence: 1,
sequence: pushSequence++,
channel: WS_CHANNELS.serverWelcome,
data: fixture.welcome,
}),
@@ -875,7 +959,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
useStore.setState({
projects: [],
threads: [],
threadsHydrated: false,
bootstrapComplete: false,
});
});
@@ -1773,36 +1857,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("restores the connecting composer state without showing the stop button", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-connecting-state" as MessageId,
targetText: "connecting state target",
sessionStatus: "starting",
}),
});
try {
const connectingButton = await waitForElement(
() => document.querySelector<HTMLButtonElement>('button[aria-label="Connecting"]'),
"Unable to find connecting send button.",
);
expect(connectingButton.disabled).toBe(true);
expect(
document.querySelector<HTMLButtonElement>('button[aria-label="Stop generation"]'),
).toBeNull();
const composerEditor = await waitForElement(
() => document.querySelector<HTMLElement>('[contenteditable="false"]'),
"Unable to find disabled composer editor.",
);
expect(composerEditor).toBeTruthy();
} finally {
await mounted.cleanup();
}
});
it("hides the archive action when the pointer leaves a thread row", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
@@ -1911,21 +1965,16 @@ describe("ChatView timeline estimator parity (full app)", () => {
// The composer editor should be present for the new draft thread.
await waitForComposerEditor();
// Simulate the snapshot sync arriving from the server after the draft
// thread has been promoted to a server thread (thread.create + turn.start
// succeeded). The snapshot now includes the new thread, and the sync
// should clear the draft without disrupting the route.
const { syncServerReadModel } = useStore.getState();
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, newThreadId));
// Clear the draft now that the server thread exists (mirrors EventRouter behavior).
useComposerDraftStore.getState().clearDraftThread(newThreadId);
// Simulate the steady-state promotion path: the server emits
// `thread.created`, the client materializes the thread incrementally,
// and the draft is cleared by live batch effects.
await promoteDraftThreadViaDomainEvent(newThreadId);
// The route should still be on the new thread — not redirected away.
await waitForURL(
mounted.router,
(path) => path === newThreadPath,
"New thread should remain selected after snapshot sync clears the draft.",
"New thread should remain selected after server thread promotion clears the draft.",
);
// The empty thread view and composer should still be visible.
@@ -2247,9 +2296,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
const { syncServerReadModel } = useStore.getState();
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
await promoteDraftThreadViaDomainEvent(promotedThreadId);
const freshThreadPath = await triggerChatNewShortcutUntilPath(
mounted.router,
+301 -3
View File
@@ -1,7 +1,14 @@
import { ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useStore } from "../store";
import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic";
import {
buildExpiredTerminalContextToastCopy,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
waitForStartedServerThread,
} from "./ChatView.logic";
describe("deriveComposerSendState", () => {
it("treats expired terminal pills as non-sendable content", () => {
@@ -67,3 +74,294 @@ describe("buildExpiredTerminalContextToastCopy", () => {
});
});
});
const makeThread = (input?: {
id?: ThreadId;
latestTurn?: {
turnId: TurnId;
state: "running" | "completed";
requestedAt: string;
startedAt: string | null;
completedAt: string | null;
} | null;
}) => ({
id: input?.id ?? ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: { provider: "codex" as const, model: "gpt-5.4" },
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
session: null,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:00.000Z",
latestTurn: input?.latestTurn
? {
...input.latestTurn,
assistantMessageId: null,
}
: null,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
useStore.setState((state) => ({
...state,
projects: [],
threads: [],
bootstrapComplete: true,
}));
});
describe("waitForStartedServerThread", () => {
it("resolves immediately when the thread is already started", async () => {
const threadId = ThreadId.makeUnsafe("thread-started");
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
await expect(waitForStartedServerThread(threadId)).resolves.toBe(true);
});
it("waits for the thread to start via subscription updates", async () => {
const threadId = ThreadId.makeUnsafe("thread-wait");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
const promise = waitForStartedServerThread(threadId, 500);
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
await expect(promise).resolves.toBe(true);
});
it("handles the thread starting between the initial read and subscription setup", async () => {
const threadId = ThreadId.makeUnsafe("thread-race");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
const originalSubscribe = useStore.subscribe.bind(useStore);
let raced = false;
vi.spyOn(useStore, "subscribe").mockImplementation((listener) => {
if (!raced) {
raced = true;
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-race"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
}
return originalSubscribe(listener);
});
await expect(waitForStartedServerThread(threadId, 500)).resolves.toBe(true);
});
it("returns false after the timeout when the thread never starts", async () => {
vi.useFakeTimers();
const threadId = ThreadId.makeUnsafe("thread-timeout");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
const promise = waitForStartedServerThread(threadId, 500);
await vi.advanceTimersByTimeAsync(500);
await expect(promise).resolves.toBe(false);
});
});
describe("hasServerAcknowledgedLocalDispatch", () => {
const projectId = ProjectId.makeUnsafe("project-1");
const previousLatestTurn = {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed" as const,
requestedAt: "2026-03-29T00:00:00.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: "2026-03-29T00:00:10.000Z",
assistantMessageId: null,
};
const previousSession = {
provider: "codex" as const,
status: "ready" as const,
createdAt: "2026-03-29T00:00:00.000Z",
updatedAt: "2026-03-29T00:00:10.000Z",
orchestrationStatus: "idle" as const,
};
it("does not clear local dispatch before server state changes", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId,
title: "Thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: previousSession,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:10.000Z",
latestTurn: previousLatestTurn,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "ready",
latestTurn: previousLatestTurn,
session: previousSession,
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(false);
});
it("clears local dispatch when a new turn is already settled", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId,
title: "Thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: previousSession,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:10.000Z",
latestTurn: previousLatestTurn,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "ready",
latestTurn: {
...previousLatestTurn,
turnId: TurnId.makeUnsafe("turn-2"),
requestedAt: "2026-03-29T00:01:00.000Z",
startedAt: "2026-03-29T00:01:01.000Z",
completedAt: "2026-03-29T00:01:30.000Z",
},
session: {
...previousSession,
updatedAt: "2026-03-29T00:01:30.000Z",
},
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(true);
});
it("clears local dispatch when the session changes without an observed running phase", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId,
title: "Thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: previousSession,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:10.000Z",
latestTurn: previousLatestTurn,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "ready",
latestTurn: previousLatestTurn,
session: {
...previousSession,
updatedAt: "2026-03-29T00:00:11.000Z",
},
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(true);
});
});
+117 -3
View File
@@ -1,8 +1,9 @@
import { ProjectId, type ModelSelection, type ThreadId } from "@t3tools/contracts";
import { type ChatMessage, type Thread } from "../types";
import { ProjectId, type ModelSelection, type ThreadId, type TurnId } from "@t3tools/contracts";
import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
import { randomUUID } from "~/lib/utils";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { Schema } from "effect";
import { useStore } from "../store";
import {
filterTerminalContextsWithText,
stripInlineTerminalContextPlaceholders,
@@ -25,6 +26,7 @@ export function buildLocalDraftThread(
codexThreadId: null,
projectId: draftThread.projectId,
title: "New thread",
pinnedAt: null,
modelSelection: fallbackModelSelection,
runtimeMode: draftThread.runtimeMode,
interactionMode: draftThread.interactionMode,
@@ -34,7 +36,6 @@ export function buildLocalDraftThread(
createdAt: draftThread.createdAt,
archivedAt: null,
latestTurn: null,
lastVisitedAt: draftThread.createdAt,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
turnDiffSummaries: [],
@@ -159,3 +160,116 @@ export function buildExpiredTerminalContextToastCopy(
description: "Re-add it if you want that terminal output included.",
};
}
export function threadHasStarted(thread: Thread | null | undefined): boolean {
return Boolean(
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
);
}
export async function waitForStartedServerThread(
threadId: ThreadId,
timeoutMs = 1_000,
): Promise<boolean> {
const getThread = () => useStore.getState().threads.find((thread) => thread.id === threadId);
const thread = getThread();
if (threadHasStarted(thread)) {
return true;
}
return await new Promise<boolean>((resolve) => {
let settled = false;
let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
const finish = (result: boolean) => {
if (settled) {
return;
}
settled = true;
if (timeoutId !== null) {
globalThis.clearTimeout(timeoutId);
}
unsubscribe();
resolve(result);
};
const unsubscribe = useStore.subscribe((state) => {
if (!threadHasStarted(state.threads.find((thread) => thread.id === threadId))) {
return;
}
finish(true);
});
if (threadHasStarted(getThread())) {
finish(true);
return;
}
timeoutId = globalThis.setTimeout(() => {
finish(false);
}, timeoutMs);
});
}
export interface LocalDispatchSnapshot {
startedAt: string;
preparingWorktree: boolean;
latestTurnTurnId: TurnId | null;
latestTurnRequestedAt: string | null;
latestTurnStartedAt: string | null;
latestTurnCompletedAt: string | null;
sessionOrchestrationStatus: ThreadSession["orchestrationStatus"] | null;
sessionUpdatedAt: string | null;
}
export function createLocalDispatchSnapshot(
activeThread: Thread | undefined,
options?: { preparingWorktree?: boolean },
): LocalDispatchSnapshot {
const latestTurn = activeThread?.latestTurn ?? null;
const session = activeThread?.session ?? null;
return {
startedAt: new Date().toISOString(),
preparingWorktree: Boolean(options?.preparingWorktree),
latestTurnTurnId: latestTurn?.turnId ?? null,
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
latestTurnStartedAt: latestTurn?.startedAt ?? null,
latestTurnCompletedAt: latestTurn?.completedAt ?? null,
sessionOrchestrationStatus: session?.orchestrationStatus ?? null,
sessionUpdatedAt: session?.updatedAt ?? null,
};
}
export function hasServerAcknowledgedLocalDispatch(input: {
localDispatch: LocalDispatchSnapshot | null;
phase: SessionPhase;
latestTurn: Thread["latestTurn"] | null;
session: Thread["session"] | null;
hasPendingApproval: boolean;
hasPendingUserInput: boolean;
threadError: string | null | undefined;
}): boolean {
if (!input.localDispatch) {
return false;
}
if (
input.phase === "running" ||
input.hasPendingApproval ||
input.hasPendingUserInput ||
Boolean(input.threadError)
) {
return true;
}
const latestTurn = input.latestTurn ?? null;
const session = input.session ?? null;
return (
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) ||
input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) ||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
);
}
+319 -193
View File
@@ -20,6 +20,7 @@ import {
OrchestrationThreadActivity,
ProviderInteractionMode,
RuntimeMode,
TerminalOpenInput,
} from "@t3tools/contracts";
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
import { truncate } from "@t3tools/shared/String";
@@ -42,6 +43,7 @@ import {
replaceTextRange,
} from "../composer-logic";
import {
deriveCompletionDividerBeforeEntryId,
derivePendingApprovals,
derivePendingUserInputs,
derivePhase,
@@ -64,6 +66,8 @@ import {
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { useStore } from "../store";
import { useProjectById, useThreadById } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
@@ -76,8 +80,12 @@ import {
DEFAULT_THREAD_TERMINAL_ID,
MAX_TERMINALS_PER_GROUP,
type ChatMessage,
type SessionPhase,
type Thread,
type TurnDiffSummary,
} from "../types";
import { LRUCache } from "../lib/lruCache";
import { basenameOfPath } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
@@ -168,13 +176,18 @@ import {
buildTemporaryWorktreeBranchName,
cloneComposerImageForRetry,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
type LocalDispatchSnapshot,
PullRequestDialogState,
readFileAsDataUrl,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
threadHasStarted,
waitForStartedServerThread,
} from "./ChatView.logic";
import { useLocalStorage } from "~/hooks/useLocalStorage";
@@ -189,6 +202,81 @@ const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
const MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES = 500;
const MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES = 512 * 1024;
const threadPlanCatalogCache = new LRUCache<{
proposedPlans: Thread["proposedPlans"];
entry: ThreadPlanCatalogEntry;
}>(MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES, MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES);
function estimateThreadPlanCatalogEntrySize(thread: Thread): number {
return Math.max(
64,
thread.id.length +
thread.proposedPlans.reduce(
(total, plan) =>
total +
plan.id.length +
plan.planMarkdown.length +
plan.updatedAt.length +
(plan.turnId?.length ?? 0),
0,
),
);
}
function toThreadPlanCatalogEntry(thread: Thread): ThreadPlanCatalogEntry {
const cached = threadPlanCatalogCache.get(thread.id);
if (cached && cached.proposedPlans === thread.proposedPlans) {
return cached.entry;
}
const entry: ThreadPlanCatalogEntry = {
id: thread.id,
proposedPlans: thread.proposedPlans,
};
threadPlanCatalogCache.set(
thread.id,
{
proposedPlans: thread.proposedPlans,
entry,
},
estimateThreadPlanCatalogEntrySize(thread),
);
return entry;
}
function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] {
const selector = useMemo(() => {
let previousThreads: Array<Thread | undefined> | null = null;
let previousEntries: ThreadPlanCatalogEntry[] = [];
return (state: { threads: Thread[] }): ThreadPlanCatalogEntry[] => {
const nextThreads = threadIds.map((threadId) =>
state.threads.find((thread) => thread.id === threadId),
);
const cachedThreads = previousThreads;
if (
cachedThreads &&
nextThreads.length === cachedThreads.length &&
nextThreads.every((thread, index) => thread === cachedThreads[index])
) {
return previousEntries;
}
previousThreads = nextThreads;
previousEntries = nextThreads.flatMap((thread) =>
thread ? [toThreadPlanCatalogEntry(thread)] : [],
);
return previousEntries;
};
}, [threadIds]);
return useStore(selector);
}
function formatOutgoingPrompt(params: {
provider: ProviderKind;
model: string | null;
@@ -244,19 +332,81 @@ interface PendingPullRequestSetupRequest {
scriptId: string;
}
function useLocalDispatchState(input: {
activeThread: Thread | undefined;
activeLatestTurn: Thread["latestTurn"] | null;
phase: SessionPhase;
activePendingApproval: ApprovalRequestId | null;
activePendingUserInput: ApprovalRequestId | null;
threadError: string | null | undefined;
}) {
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
const beginLocalDispatch = useCallback(
(options?: { preparingWorktree?: boolean }) => {
const preparingWorktree = Boolean(options?.preparingWorktree);
setLocalDispatch((current) => {
if (current) {
return current.preparingWorktree === preparingWorktree
? current
: { ...current, preparingWorktree };
}
return createLocalDispatchSnapshot(input.activeThread, options);
});
},
[input.activeThread],
);
const resetLocalDispatch = useCallback(() => {
setLocalDispatch(null);
}, []);
const serverAcknowledgedLocalDispatch = useMemo(
() =>
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: input.phase,
latestTurn: input.activeLatestTurn,
session: input.activeThread?.session ?? null,
hasPendingApproval: input.activePendingApproval !== null,
hasPendingUserInput: input.activePendingUserInput !== null,
threadError: input.threadError,
}),
[
input.activeLatestTurn,
input.activePendingApproval,
input.activePendingUserInput,
input.activeThread?.session,
input.phase,
input.threadError,
localDispatch,
],
);
useEffect(() => {
if (!serverAcknowledgedLocalDispatch) {
return;
}
resetLocalDispatch();
}, [resetLocalDispatch, serverAcknowledgedLocalDispatch]);
return {
beginLocalDispatch,
resetLocalDispatch,
localDispatchStartedAt: localDispatch?.startedAt ?? null,
isPreparingWorktree: localDispatch?.preparingWorktree ?? false,
isSendBusy: localDispatch !== null && !serverAcknowledgedLocalDispatch,
};
}
export default function ChatView({ threadId }: ChatViewProps) {
const beginThreadSend = useStore((store) => store.beginThreadSend);
const clearThreadSend = useStore((store) => store.clearThreadSend);
const markThreadSendSettled = useStore((store) => store.markThreadSendSettled);
const moveThreadSend = useStore((store) => store.moveThreadSend);
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const markThreadVisited = useStore((store) => store.markThreadVisited);
const pendingThreadSend = useStore((store) => store.pendingThreadSendById[threadId] ?? null);
const setThreadSendPhase = useStore((store) => store.setThreadSendPhase);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const serverThread = useThreadById(threadId);
const setStoreThreadError = useStore((store) => store.setError);
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore(
(store) => store.threadLastVisitedAtById[threadId],
);
const settings = useSettings();
const setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
@@ -330,10 +480,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
optimisticUserMessagesRef.current = optimisticUserMessages;
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>(composerTerminalContexts);
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
Record<ThreadId, string | null>
>({});
const [isConnecting, _setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
@@ -467,8 +619,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
[composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId],
);
const serverThread = threads.find((t) => t.id === threadId);
const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId);
const fallbackDraftProject = useProjectById(draftThread?.projectId);
const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null);
const localDraftThread = useMemo(
() =>
@@ -496,12 +647,25 @@ export default function ChatView({ threadId }: ChatViewProps) {
const diffOpen = rawSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
const threadIds: ThreadId[] = [];
if (activeThread?.id) {
threadIds.push(activeThread.id);
}
const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId;
if (sourceThreadId && sourceThreadId !== activeThread?.id) {
threadIds.push(sourceThreadId);
}
return threadIds;
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]),
);
const activeContextWindow = useMemo(
() => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []),
[activeThread?.activities],
);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
const activeProject = useProjectById(activeThread?.projectId);
const openPullRequestDialog = useCallback(
(reference?: string) => {
@@ -596,33 +760,28 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
useEffect(() => {
if (!activeThread?.id) return;
if (!serverThread?.id) return;
if (!latestTurnSettled) return;
if (!activeLatestTurn?.completedAt) return;
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
if (Number.isNaN(turnCompletedAt)) return;
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
markThreadVisited(activeThread.id);
markThreadVisited(serverThread.id);
}, [
activeThread?.id,
activeThread?.lastVisitedAt,
activeLatestTurn?.completedAt,
activeThreadLastVisitedAt,
latestTurnSettled,
markThreadVisited,
serverThread?.id,
]);
const sessionProvider = activeThread?.session?.provider ?? null;
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
const threadProvider =
activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null;
const hasThreadStarted = Boolean(
activeThread &&
(activeThread.latestTurn !== null ||
activeThread.messages.length > 0 ||
activeThread.session !== null),
);
const hasThreadStarted = threadHasStarted(activeThread);
const lockedProvider: ProviderKind | null = hasThreadStarted
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
: null;
@@ -665,19 +824,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const selectedModelForPicker = selectedModel;
const phase = derivePhase(activeThread?.session ?? null);
const activeSendStartedAt = pendingThreadSend?.startedAt ?? null;
const isSendBusy = pendingThreadSend !== null;
const isPreparingWorktree =
pendingThreadSend?.phase === "preparing-worktree" && createWorktreeMutation.isPending;
const isConnecting = phase === "connecting";
const showConnectingState = isConnecting && !isSendBusy;
const isWorking = phase === "running" || isSendBusy || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
activeSendStartedAt,
);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
@@ -740,12 +886,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const sidebarProposedPlan = useMemo(
() =>
findSidebarProposedPlan({
threads,
threads: threadPlanCatalog,
latestTurn: activeLatestTurn,
latestTurnSettled,
threadId: activeThread?.id ?? null,
}),
[activeLatestTurn, activeThread?.id, latestTurnSettled, threads],
[activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog],
);
const activePlan = useMemo(
() => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),
@@ -757,6 +903,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
latestTurnSettled &&
hasActionableProposedPlan(activeProposedPlan);
const activePendingApproval = pendingApprovals[0] ?? null;
const {
beginLocalDispatch,
resetLocalDispatch,
localDispatchStartedAt,
isPreparingWorktree,
isSendBusy,
} = useLocalDispatchState({
activeThread,
activeLatestTurn,
phase,
activePendingApproval: activePendingApproval?.requestId ?? null,
activePendingUserInput: activePendingUserInput?.requestId ?? null,
threadError: activeThread?.error,
});
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
localDispatchStartedAt,
);
const isComposerApprovalState = activePendingApproval !== null;
const hasComposerHeader =
isComposerApprovalState ||
@@ -985,35 +1152,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
]);
const completionDividerBeforeEntryId = useMemo(() => {
if (!latestTurnSettled) return null;
if (!activeLatestTurn?.startedAt) return null;
if (!activeLatestTurn.completedAt) return null;
if (!completionSummary) return null;
const turnStartedAt = Date.parse(activeLatestTurn.startedAt);
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
if (Number.isNaN(turnStartedAt)) return null;
if (Number.isNaN(turnCompletedAt)) return null;
let inRangeMatch: string | null = null;
let fallbackMatch: string | null = null;
for (const timelineEntry of timelineEntries) {
if (timelineEntry.kind !== "message") continue;
if (timelineEntry.message.role !== "assistant") continue;
const messageAt = Date.parse(timelineEntry.message.createdAt);
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) continue;
fallbackMatch = timelineEntry.id;
if (messageAt <= turnCompletedAt) {
inRangeMatch = timelineEntry.id;
}
}
return inRangeMatch ?? fallbackMatch;
}, [
activeLatestTurn?.completedAt,
activeLatestTurn?.startedAt,
completionSummary,
latestTurnSettled,
timelineEntries,
]);
return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn);
}, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]);
const gitCwd = activeProject
? projectScriptCwd({
project: { cwd: activeProject.cwd },
@@ -1143,6 +1284,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
null,
[composerHighlightedItemId, composerMenuItems],
);
composerMenuOpenRef.current = composerMenuOpen;
composerMenuItemsRef.current = composerMenuItems;
activeComposerMenuItemRef.current = activeComposerMenuItem;
const nonPersistedComposerImageIdSet = useMemo(
() => new Set(nonPersistedComposerImageIds),
[nonPersistedComposerImageIds],
@@ -1232,7 +1376,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setThreadError = useCallback(
(targetThreadId: ThreadId | null, error: string | null) => {
if (!targetThreadId) return;
if (threads.some((thread) => thread.id === targetThreadId)) {
if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) {
setStoreThreadError(targetThreadId, error);
return;
}
@@ -1246,7 +1390,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
});
},
[setStoreThreadError, threads],
[setStoreThreadError],
);
const focusComposer = useCallback(() => {
@@ -1413,7 +1557,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
...(options?.env ? { extraEnv: options.env } : {}),
});
const openTerminalInput: Parameters<typeof api.terminal.open>[0] = shouldCreateNewTerminal
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
? {
threadId: activeThreadId,
terminalId: targetTerminalId,
@@ -1982,16 +2126,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
composerTerminalContextsRef.current = composerTerminalContexts;
}, [composerTerminalContexts]);
useEffect(() => {
optimisticUserMessagesRef.current = optimisticUserMessages;
}, [optimisticUserMessages]);
useEffect(() => {
composerMenuOpenRef.current = composerMenuOpen;
composerMenuItemsRef.current = composerMenuItems;
activeComposerMenuItemRef.current = activeComposerMenuItem;
}, [activeComposerMenuItem, composerMenuItems, composerMenuOpen]);
useEffect(() => {
if (!activeThread?.id) return;
if (activeThread.messages.length === 0) {
@@ -2032,14 +2166,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
return [];
});
sendInFlightRef.current = false;
resetLocalDispatch();
setComposerHighlightedItemId(null);
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
}, [threadId]);
}, [resetLocalDispatch, threadId]);
useEffect(() => {
let cancelled = false;
@@ -2163,14 +2297,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
: "local";
useEffect(() => {
if (phase !== "running" && !isSendBusy) return;
if (phase !== "running") return;
const timer = window.setInterval(() => {
setNowTick(Date.now());
}, 1000);
return () => {
window.clearInterval(timer);
};
}, [isSendBusy, phase]);
}, [phase]);
useEffect(() => {
if (!activeThreadId) return;
@@ -2390,7 +2524,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const api = readNativeApi();
if (!api || !activeThread || isRevertingCheckpoint) return;
if (phase === "running" || isSendBusy) {
if (phase === "running" || isSendBusy || isConnecting) {
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
return;
}
@@ -2423,13 +2557,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
setIsRevertingCheckpoint(false);
},
[activeThread, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
);
const onSend = async (e?: { preventDefault: () => void }) => {
e?.preventDefault();
const api = readNativeApi();
if (!api || !activeThread || isSendBusy || sendInFlightRef.current) return;
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
if (activePendingProgress) {
onAdvanceActivePendingUserInput();
return;
@@ -2508,13 +2642,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
return;
}
const sendStartedAt = new Date().toISOString();
sendInFlightRef.current = true;
beginThreadSend(
threadIdForSend,
baseBranchForWorktree ? "preparing-worktree" : "sending-turn",
sendStartedAt,
);
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
const composerImagesSnapshot = [...composerImages];
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
@@ -2585,9 +2714,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
let turnStartSucceeded = false;
let nextThreadBranch = activeThread.branch;
let nextThreadWorktreePath = activeThread.worktreePath;
try {
await (async () => {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
beginLocalDispatch({ preparingWorktree: true });
const newBranch = buildTemporaryWorktreeBranchName();
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
@@ -2644,6 +2774,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: threadIdForSend,
projectId: activeProject.id,
title,
pinned: false,
modelSelection: threadCreateModelSelection,
runtimeMode,
interactionMode,
@@ -2662,8 +2793,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
let shouldRunSetupScript = false;
if (isServerThread) {
shouldRunSetupScript = true;
} else if (createdServerThreadForLocalDraft) {
shouldRunSetupScript = true;
} else {
if (createdServerThreadForLocalDraft) {
shouldRunSetupScript = true;
}
}
if (shouldRunSetupScript) {
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
@@ -2697,9 +2830,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
if (baseBranchForWorktree) {
setThreadSendPhase(threadIdForSend, "sending-turn");
}
beginLocalDispatch({ preparingWorktree: false });
const turnAttachments = await turnAttachmentsPromise;
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
@@ -2718,8 +2849,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt: messageCreatedAt,
});
turnStartSucceeded = true;
markThreadSendSettled(threadIdForSend);
} catch (err: unknown) {
})().catch(async (err: unknown) => {
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
await api.orchestration
.dispatchCommand({
@@ -2754,9 +2884,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadIdForSend,
err instanceof Error ? err.message : "Failed to send message.",
);
clearThreadSend(threadIdForSend);
}
});
sendInFlightRef.current = false;
if (!turnStartSucceeded) {
resetLocalDispatch();
}
};
const onInterrupt = async () => {
@@ -2926,7 +3058,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
interactionMode: "default" | "plan";
}) => {
const api = readNativeApi();
if (!api || !activeThread || !isServerThread || isSendBusy || sendInFlightRef.current) {
if (
!api ||
!activeThread ||
!isServerThread ||
isSendBusy ||
isConnecting ||
sendInFlightRef.current
) {
return;
}
@@ -2947,7 +3086,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
sendInFlightRef.current = true;
beginThreadSend(threadIdForSend, "sending-turn", new Date().toISOString());
beginLocalDispatch({ preparingWorktree: false });
setThreadError(threadIdForSend, null);
setOptimisticUserMessages((existing) => [
...existing,
@@ -2999,7 +3138,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
: {}),
createdAt: messageCreatedAt,
});
markThreadSendSettled(threadIdForSend);
// Optimistically open the plan sidebar when implementing (not refining).
// "default" mode here means the agent is executing the plan, which produces
// step-tracking activities that the sidebar will display.
@@ -3007,33 +3145,34 @@ export default function ChatView({ threadId }: ChatViewProps) {
planSidebarDismissedForTurnRef.current = null;
setPlanSidebarOpen(true);
}
sendInFlightRef.current = false;
} catch (err) {
setOptimisticUserMessages((existing) =>
existing.filter((message) => message.id !== messageIdForSend),
);
clearThreadSend(threadIdForSend);
setThreadError(
threadIdForSend,
err instanceof Error ? err.message : "Failed to send plan follow-up.",
);
sendInFlightRef.current = false;
resetLocalDispatch();
}
sendInFlightRef.current = false;
},
[
activeThread,
activeProposedPlan,
beginLocalDispatch,
forceStickToBottom,
isConnecting,
isSendBusy,
isServerThread,
persistThreadSettingsForNextTurn,
resetLocalDispatch,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
beginThreadSend,
clearThreadSend,
markThreadSendSettled,
setComposerDraftInteractionMode,
setThreadError,
selectedModel,
@@ -3049,6 +3188,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
!activeProposedPlan ||
!isServerThread ||
isSendBusy ||
isConnecting ||
sendInFlightRef.current
) {
return;
@@ -3069,91 +3209,87 @@ export default function ChatView({ threadId }: ChatViewProps) {
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
sendInFlightRef.current = true;
beginThreadSend(activeThread.id, "sending-turn", createdAt);
beginLocalDispatch({ preparingWorktree: false });
const finish = () => {
sendInFlightRef.current = false;
resetLocalDispatch();
};
try {
await api.orchestration.dispatchCommand({
await api.orchestration
.dispatchCommand({
type: "thread.create",
commandId: newCommandId(),
threadId: nextThreadId,
projectId: activeProject.id,
title: nextThreadTitle,
pinned: false,
modelSelection: nextThreadModelSelection,
runtimeMode,
interactionMode: "default",
branch: activeThread.branch,
worktreePath: activeThread.worktreePath,
createdAt,
});
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
threadId: nextThreadId,
message: {
messageId: newMessageId(),
role: "user",
text: outgoingImplementationPrompt,
attachments: [],
},
modelSelection: selectedModelSelection,
titleSeed: nextThreadTitle,
runtimeMode,
interactionMode: "default",
createdAt,
});
moveThreadSend(activeThread.id, nextThreadId);
markThreadSendSettled(nextThreadId);
const snapshot = await api.orchestration.getSnapshot();
syncServerReadModel(snapshot);
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
await navigate({
to: "/$threadId",
params: { threadId: nextThreadId },
});
} catch (err) {
clearThreadSend(activeThread.id);
clearThreadSend(nextThreadId);
await api.orchestration
.dispatchCommand({
type: "thread.delete",
})
.then(() => {
return api.orchestration.dispatchCommand({
type: "thread.turn.start",
commandId: newCommandId(),
threadId: nextThreadId,
})
.catch(() => undefined);
await api.orchestration
.getSnapshot()
.then((snapshot) => {
syncServerReadModel(snapshot);
})
.catch(() => undefined);
toastManager.add({
type: "error",
title: "Could not start implementation thread",
description:
err instanceof Error ? err.message : "An error occurred while creating the new thread.",
});
}
sendInFlightRef.current = false;
message: {
messageId: newMessageId(),
role: "user",
text: outgoingImplementationPrompt,
attachments: [],
},
modelSelection: selectedModelSelection,
titleSeed: nextThreadTitle,
runtimeMode,
interactionMode: "default",
createdAt,
});
})
.then(() => {
return waitForStartedServerThread(nextThreadId);
})
.then(() => {
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
return navigate({
to: "/$threadId",
params: { threadId: nextThreadId },
});
})
.catch(async (err) => {
await api.orchestration
.dispatchCommand({
type: "thread.delete",
commandId: newCommandId(),
threadId: nextThreadId,
})
.catch(() => undefined);
toastManager.add({
type: "error",
title: "Could not start implementation thread",
description:
err instanceof Error ? err.message : "An error occurred while creating the new thread.",
});
})
.then(finish, finish);
}, [
activeProject,
activeProposedPlan,
activeThread,
beginLocalDispatch,
isConnecting,
isSendBusy,
isServerThread,
navigate,
resetLocalDispatch,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
beginThreadSend,
clearThreadSend,
markThreadSendSettled,
moveThreadSend,
syncServerReadModel,
selectedModel,
]);
@@ -3820,7 +3956,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, or use / to show available commands"
}
disabled={showConnectingState || isComposerApprovalState}
disabled={isConnecting || isComposerApprovalState}
/>
</div>
@@ -4045,13 +4181,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
size="sm"
className="h-9 rounded-full px-4 sm:h-8"
disabled={isSendBusy || showConnectingState}
disabled={isSendBusy || isConnecting}
>
{showConnectingState
? "Connecting..."
: isSendBusy
? "Sending..."
: "Refine"}
{isConnecting || isSendBusy ? "Sending..." : "Refine"}
</Button>
) : (
<div className="flex items-center">
@@ -4059,13 +4191,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
size="sm"
className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8"
disabled={isSendBusy || showConnectingState}
disabled={isSendBusy || isConnecting}
>
{showConnectingState
? "Connecting..."
: isSendBusy
? "Sending..."
: "Implement"}
{isConnecting || isSendBusy ? "Sending..." : "Implement"}
</Button>
<Menu>
<MenuTrigger
@@ -4075,7 +4203,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
variant="default"
className="h-9 rounded-l-none rounded-r-full border-l-white/12 px-2 sm:h-8"
aria-label="Implementation actions"
disabled={isSendBusy || showConnectingState}
disabled={isSendBusy || isConnecting}
/>
}
>
@@ -4083,7 +4211,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
</MenuTrigger>
<MenuPopup align="end" side="top">
<MenuItem
disabled={isSendBusy || showConnectingState}
disabled={isSendBusy || isConnecting}
onClick={() => void onImplementPlanInNewThread()}
>
Implement in a new thread
@@ -4097,21 +4225,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
type="submit"
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
disabled={
isSendBusy ||
showConnectingState ||
!composerSendState.hasSendableContent
isSendBusy || isConnecting || !composerSendState.hasSendableContent
}
aria-label={
isPreparingWorktree
? "Preparing worktree"
: showConnectingState
? "Connecting"
isConnecting
? "Connecting"
: isPreparingWorktree
? "Preparing worktree"
: isSendBusy
? "Sending"
: "Send message"
}
>
{showConnectingState || isSendBusy ? (
{isConnecting || isSendBusy ? (
<svg
width="14"
height="14"
@@ -76,6 +76,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5",
@@ -91,6 +92,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Test thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5",
@@ -323,7 +325,7 @@ describe("Keybindings update toast", () => {
useStore.setState({
projects: [],
threads: [],
threadsHydrated: false,
bootstrapComplete: false,
});
});
+210 -3
View File
@@ -9,6 +9,7 @@ import {
getProjectSortTimestamp,
hasUnseenCompletion,
isContextMenuPointerDown,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
@@ -18,7 +19,7 @@ import {
sortThreadsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -29,7 +30,7 @@ import {
function makeLatestTurn(overrides?: {
completedAt?: string | null;
startedAt?: string | null;
}): Parameters<typeof hasUnseenCompletion>[0]["latestTurn"] {
}): OrchestrationLatestTurn {
return {
turnId: "turn-1" as never,
state: "completed",
@@ -163,6 +164,50 @@ describe("resolveSidebarNewThreadEnvMode", () => {
});
});
describe("orderItemsByPreferredIds", () => {
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
const ordered = orderItemsByPreferredIds({
items: [
{ id: ProjectId.makeUnsafe("project-1"), name: "One" },
{ id: ProjectId.makeUnsafe("project-2"), name: "Two" },
{ id: ProjectId.makeUnsafe("project-3"), name: "Three" },
],
preferredIds: [
ProjectId.makeUnsafe("project-3"),
ProjectId.makeUnsafe("project-missing"),
ProjectId.makeUnsafe("project-1"),
],
getId: (project) => project.id,
});
expect(ordered.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-3"),
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
]);
});
it("does not duplicate items when preferred ids repeat", () => {
const ordered = orderItemsByPreferredIds({
items: [
{ id: ProjectId.makeUnsafe("project-1"), name: "One" },
{ id: ProjectId.makeUnsafe("project-2"), name: "Two" },
],
preferredIds: [
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
],
getId: (project) => project.id,
});
expect(ordered.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
});
});
describe("resolveAdjacentThreadId", () => {
it("resolves adjacent thread ids in ordered sidebar traversal", () => {
const threads = [
@@ -547,12 +592,12 @@ function makeProject(overrides: Partial<Project> = {}): Project {
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
...defaultModelSelection,
},
expanded: true,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
scripts: [],
@@ -566,6 +611,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5.4",
@@ -714,6 +760,73 @@ describe("sortThreadsForSidebar", () => {
ThreadId.makeUnsafe("thread-2"),
]);
});
it("puts pinned threads ahead of unpinned threads in auto-sort modes", () => {
const sorted = sortThreadsForSidebar(
[
{
...makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
pinnedAt: "2026-03-09T10:20:00.000Z",
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
pinnedAt: null,
},
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-2"),
]);
});
it("sorts pinned threads by latest pin timestamp before activity recency", () => {
const sorted = sortThreadsForSidebar(
[
{
...makeThread({
id: ThreadId.makeUnsafe("thread-1"),
createdAt: "2026-03-09T10:01:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
pinnedAt: "2026-03-09T10:10:00.000Z",
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-2"),
createdAt: "2026-03-09T10:05:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
pinnedAt: "2026-03-09T10:20:00.000Z",
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-3"),
createdAt: "2026-03-09T10:10:00.000Z",
updatedAt: "2026-03-09T10:10:00.000Z",
}),
pinnedAt: null,
},
],
"updated_at",
);
expect(sorted.map((thread) => thread.id)).toEqual([
ThreadId.makeUnsafe("thread-2"),
ThreadId.makeUnsafe("thread-1"),
ThreadId.makeUnsafe("thread-3"),
]);
});
});
describe("getFallbackThreadIdAfterDelete", () => {
@@ -752,6 +865,41 @@ describe("getFallbackThreadIdAfterDelete", () => {
expect(fallbackThreadId).toBe(ThreadId.makeUnsafe("thread-newest"));
});
it("respects pinning when choosing the fallback thread after delete", () => {
const fallbackThreadId = getFallbackThreadIdAfterDelete({
threads: [
{
...makeThread({
id: ThreadId.makeUnsafe("thread-active"),
projectId: ProjectId.makeUnsafe("project-1"),
updatedAt: "2026-03-09T10:05:00.000Z",
}),
pinnedAt: null,
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-pinned"),
projectId: ProjectId.makeUnsafe("project-1"),
updatedAt: "2026-03-09T10:03:00.000Z",
}),
pinnedAt: "2026-03-09T10:20:00.000Z",
},
{
...makeThread({
id: ThreadId.makeUnsafe("thread-newer"),
projectId: ProjectId.makeUnsafe("project-1"),
updatedAt: "2026-03-09T10:10:00.000Z",
}),
pinnedAt: null,
},
],
deletedThreadId: ThreadId.makeUnsafe("thread-active"),
sortOrder: "updated_at",
});
expect(fallbackThreadId).toBe(ThreadId.makeUnsafe("thread-pinned"));
});
it("skips other threads being deleted in the same action", () => {
const fallbackThreadId = getFallbackThreadIdAfterDelete({
threads: [
@@ -856,6 +1004,65 @@ describe("sortProjectsForSidebar", () => {
]);
});
it("puts pinned projects ahead of unpinned projects in auto-sort modes", () => {
const sorted = sortProjectsForSidebar(
[
makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "Pinned older project",
pinnedAt: "2026-03-09T10:20:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Unpinned newer project",
pinnedAt: null,
updatedAt: "2026-03-09T10:05:00.000Z",
}),
],
[],
"updated_at",
);
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
]);
});
it("sorts pinned projects by latest pin timestamp before project recency", () => {
const sorted = sortProjectsForSidebar(
[
makeProject({
id: ProjectId.makeUnsafe("project-1"),
name: "Pinned older project",
pinnedAt: "2026-03-09T10:10:00.000Z",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
makeProject({
id: ProjectId.makeUnsafe("project-2"),
name: "Pinned newer project",
pinnedAt: "2026-03-09T10:20:00.000Z",
updatedAt: "2026-03-09T10:05:00.000Z",
}),
makeProject({
id: ProjectId.makeUnsafe("project-3"),
name: "Unpinned project",
pinnedAt: null,
updatedAt: "2026-03-09T10:10:00.000Z",
}),
],
[],
"updated_at",
);
expect(sorted.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-3"),
]);
});
it("falls back to name and id ordering when projects have no sortable timestamps", () => {
const sorted = sortProjectsForSidebar(
[
+78 -12
View File
@@ -16,8 +16,13 @@ type SidebarProject = {
name: string;
createdAt?: string | undefined;
updatedAt?: string | undefined;
pinnedAt?: string | null | undefined;
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
latestUserMessageAt?: string | null;
messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
pinnedAt?: string | null | undefined;
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt" | "messages">;
export type ThreadTraversalDirection = "previous" | "next";
@@ -45,8 +50,10 @@ const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
>;
"interactionMode" | "latestTurn" | "proposedPlans" | "session"
> & {
lastVisitedAt?: string | undefined;
};
export interface ThreadJumpHintVisibilityController {
sync: (shouldShow: boolean) => void;
@@ -156,6 +163,34 @@ export function resolveSidebarNewThreadEnvMode(input: {
return input.requestedEnvMode ?? input.defaultEnvMode;
}
export function orderItemsByPreferredIds<TItem, TId>(input: {
items: readonly TItem[];
preferredIds: readonly TId[];
getId: (item: TItem) => TId;
}): TItem[] {
const { getId, items, preferredIds } = input;
if (preferredIds.length === 0) {
return [...items];
}
const itemsById = new Map(items.map((item) => [getId(item), item] as const));
const preferredIdSet = new Set(preferredIds);
const emittedPreferredIds = new Set<TId>();
const ordered = preferredIds.flatMap((id) => {
if (emittedPreferredIds.has(id)) {
return [];
}
const item = itemsById.get(id);
if (!item) {
return [];
}
emittedPreferredIds.add(id);
return [item];
});
const remaining = items.filter((item) => !preferredIdSet.has(getId(item)));
return [...ordered, ...remaining];
}
export function getVisibleSidebarThreadIds<TThreadId>(
renderedProjects: readonly {
shouldShowThreadPanel?: boolean;
@@ -327,15 +362,15 @@ export function resolveProjectStatusIndicator(
return highestPriorityStatus;
}
export function getVisibleThreadsForProject(input: {
threads: readonly Thread[];
activeThreadId: Thread["id"] | undefined;
export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
threads: readonly T[];
activeThreadId: T["id"] | undefined;
isThreadListExpanded: boolean;
previewLimit: number;
}): {
hasHiddenThreads: boolean;
hiddenThreads: Thread[];
visibleThreads: Thread[];
visibleThreads: T[];
hiddenThreads: T[];
} {
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
const hasHiddenThreads = threads.length > previewLimit;
@@ -382,9 +417,13 @@ function toSortableTimestamp(iso: string | undefined): number | null {
}
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
if (thread.latestUserMessageAt) {
return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
}
let latestUserMessageTimestamp: number | null = null;
for (const message of thread.messages) {
for (const message of thread.messages ?? []) {
if (message.role !== "user") continue;
const messageTimestamp = toSortableTimestamp(message.createdAt);
if (messageTimestamp === null) continue;
@@ -411,10 +450,24 @@ function getThreadSortTimestamp(
return getLatestUserMessageTimestamp(thread);
}
function getPinnedSortTimestamp(input: { pinnedAt?: string | null | undefined }): number | null {
return toSortableTimestamp(input.pinnedAt ?? undefined);
}
export function sortThreadsForSidebar<
T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,
T extends Pick<Thread, "id" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
return threads.toSorted((left, right) => {
const leftPinnedAt = getPinnedSortTimestamp(left);
const rightPinnedAt = getPinnedSortTimestamp(right);
const leftPinned = leftPinnedAt !== null;
const rightPinned = rightPinnedAt !== null;
if (leftPinned !== rightPinned) {
return rightPinned ? 1 : -1;
}
if (leftPinnedAt !== null && rightPinnedAt !== null && leftPinnedAt !== rightPinnedAt) {
return rightPinnedAt > leftPinnedAt ? 1 : -1;
}
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
const byTimestamp =
@@ -425,7 +478,7 @@ export function sortThreadsForSidebar<
}
export function getFallbackThreadIdAfterDelete<
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt" | "messages">,
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
>(input: {
threads: readonly T[];
deletedThreadId: T["id"];
@@ -469,7 +522,10 @@ export function getProjectSortTimestamp(
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
}
export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(
export function sortProjectsForSidebar<
TProject extends SidebarProject,
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
>(
projects: readonly TProject[],
threads: readonly TThread[],
sortOrder: SidebarProjectSortOrder,
@@ -486,6 +542,16 @@ export function sortProjectsForSidebar<TProject extends SidebarProject, TThread
}
return [...projects].toSorted((left, right) => {
const leftPinnedAt = getPinnedSortTimestamp(left);
const rightPinnedAt = getPinnedSortTimestamp(right);
const leftPinned = leftPinnedAt !== null;
const rightPinned = rightPinnedAt !== null;
if (leftPinned !== rightPinned) {
return rightPinned ? 1 : -1;
}
if (leftPinnedAt !== null && rightPinnedAt !== null && leftPinnedAt !== rightPinnedAt) {
return rightPinnedAt > leftPinnedAt ? 1 : -1;
}
const rightTimestamp = getProjectSortTimestamp(
right,
threadsByProjectId.get(right.id) ?? [],
File diff suppressed because it is too large. Load diff
@@ -549,10 +549,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
</span>
<span>
{(() => {
const elapsed = row.createdAt ? formatWorkingTimer(row.createdAt, nowIso) : null;
return elapsed ? `Working for ${elapsed}` : "Working...";
})()}
{row.createdAt
? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
: "Working..."}
</span>
</div>
</div>
@@ -644,9 +643,6 @@ function formatWorkingTimer(startIso: string, endIso: string): string | null {
}
const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
if (elapsedSeconds < 1) {
return null;
}
if (elapsedSeconds < 60) {
return `${elapsedSeconds}s`;
}
+53
View File
@@ -9,6 +9,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
COMPOSER_DRAFT_STORAGE_KEY,
clearPromotedDraftThread,
clearPromotedDraftThreads,
type ComposerImageAttachment,
useComposerDraftStore,
} from "./composerDraftStore";
@@ -549,6 +551,57 @@ describe("composerDraftStore project draft thread mapping", () => {
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("clears a promoted draft by thread id", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "promote me");
clearPromotedDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("does not clear composer drafts for existing server threads during promotion cleanup", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(threadId, "keep me");
clearPromotedDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
it("clears promoted drafts from an iterable of server thread ids", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "promote me");
store.setProjectDraftThreadId(otherProjectId, otherThreadId);
store.setPrompt(otherThreadId, "keep me");
clearPromotedDraftThreads([threadId]);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
expect(
useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId,
).toBe(otherThreadId);
expect(useComposerDraftStore.getState().draftsByThreadId[otherThreadId]?.prompt).toBe(
"keep me",
);
});
it("keeps existing server-thread composer drafts during iterable promotion cleanup", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(threadId, "keep me");
clearPromotedDraftThreads([threadId]);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
it("updates branch context on an existing draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
+14 -11
View File
@@ -2195,18 +2195,21 @@ export function useEffectiveComposerModelState(input: {
}
/**
* Clear draft threads that have been promoted to server threads.
* Clear a draft thread once the server has materialized the same thread id.
*
* Call this after a snapshot sync so the route guard in `_chat.$threadId`
* sees the server thread before the draft is removed — avoids a redirect
* to `/` caused by a gap where neither draft nor server thread exists.
* Use the single-thread helper for live `thread.created` events and the
* iterable helper for bootstrap/recovery paths that discover multiple server
* threads at once.
*/
export function clearPromotedDraftThreads(serverThreadIds: ReadonlySet<ThreadId>): void {
const store = useComposerDraftStore.getState();
const draftThreadIds = Object.keys(store.draftThreadsByThreadId) as ThreadId[];
for (const draftId of draftThreadIds) {
if (serverThreadIds.has(draftId)) {
store.clearDraftThread(draftId);
}
export function clearPromotedDraftThread(threadId: ThreadId): void {
if (!useComposerDraftStore.getState().getDraftThread(threadId)) {
return;
}
useComposerDraftStore.getState().clearDraftThread(threadId);
}
export function clearPromotedDraftThreads(serverThreadIds: Iterable<ThreadId>): void {
for (const threadId of serverThreadIds) {
clearPromotedDraftThread(threadId);
}
}
+16 -8
View File
@@ -1,29 +1,37 @@
import { DEFAULT_RUNTIME_MODE, type ProjectId, ThreadId } from "@t3tools/contracts";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useCallback } from "react";
import { useCallback, useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import {
type DraftThreadEnvMode,
type DraftThreadState,
useComposerDraftStore,
} from "../composerDraftStore";
import { newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { useStore } from "../store";
import { useThreadById } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
export function useHandleNewThread() {
const projects = useStore((store) => store.projects);
const threads = useStore((store) => store.threads);
const projectIds = useStore(useShallow((store) => store.projects.map((project) => project.id)));
const projectOrder = useUiStateStore((store) => store.projectOrder);
const navigate = useNavigate();
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const activeThread = useThreadById(routeThreadId);
const activeDraftThread = useComposerDraftStore((store) =>
routeThreadId ? (store.draftThreadsByThreadId[routeThreadId] ?? null) : null,
);
const activeThread = routeThreadId
? threads.find((thread) => thread.id === routeThreadId)
: undefined;
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projectIds,
preferredIds: projectOrder,
getId: (projectId) => projectId,
});
}, [projectIds, projectOrder]);
const handleNewThread = useCallback(
(
@@ -111,8 +119,8 @@ export function useHandleNewThread() {
return {
activeDraftThread,
activeThread,
defaultProjectId: orderedProjects[0] ?? null,
handleNewThread,
projects,
routeThreadId,
};
}
+5 -8
View File
@@ -16,8 +16,6 @@ import { toastManager } from "../components/ui/toast";
import { useSettings } from "./useSettings";
export function useThreadActions() {
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const appSettings = useSettings();
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const clearProjectDraftThreadById = useComposerDraftStore(
@@ -37,7 +35,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = threads.find((entry) => entry.id === threadId);
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
if (!thread) return;
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
throw new Error("Cannot archive a running thread.");
@@ -53,7 +51,7 @@ export function useThreadActions() {
await handleNewThread(thread.projectId);
}
},
[handleNewThread, routeThreadId, threads],
[handleNewThread, routeThreadId],
);
const unarchiveThread = useCallback(async (threadId: ThreadId) => {
@@ -70,6 +68,7 @@ export function useThreadActions() {
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
const api = readNativeApi();
if (!api) return;
const { projects, threads } = useStore.getState();
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
const threadProject = projects.find((project) => project.id === thread.projectId);
@@ -171,10 +170,8 @@ export function useThreadActions() {
clearTerminalState,
appSettings.sidebarThreadSortOrder,
navigate,
projects,
removeWorktreeMutation,
routeThreadId,
threads,
],
);
@@ -182,7 +179,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = threads.find((entry) => entry.id === threadId);
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
if (!thread) return;
if (appSettings.confirmThreadDelete) {
@@ -199,7 +196,7 @@ export function useThreadActions() {
await deleteThread(threadId);
},
[appSettings.confirmThreadDelete, deleteThread, threads],
[appSettings.confirmThreadDelete, deleteThread],
);
return {
@@ -0,0 +1,110 @@
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveOrchestrationBatchEffects } from "./orchestrationEventEffects";
function makeEvent<T extends OrchestrationEvent["type"]>(
type: T,
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
): Extract<OrchestrationEvent, { type: T }> {
const sequence = overrides.sequence ?? 1;
return {
sequence,
eventId: EventId.makeUnsafe(`event-${sequence}`),
aggregateKind: "thread",
aggregateId:
"threadId" in payload
? payload.threadId
: "projectId" in payload
? payload.projectId
: ProjectId.makeUnsafe("project-1"),
occurredAt: "2026-02-27T00:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type,
payload,
...overrides,
} as Extract<OrchestrationEvent, { type: T }>;
}
describe("deriveOrchestrationBatchEffects", () => {
it("targets draft promotion and terminal cleanup from thread lifecycle events", () => {
const createdThreadId = ThreadId.makeUnsafe("thread-created");
const deletedThreadId = ThreadId.makeUnsafe("thread-deleted");
const effects = deriveOrchestrationBatchEffects([
makeEvent("thread.created", {
threadId: createdThreadId,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Created thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5-codex" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
}),
makeEvent("thread.deleted", {
threadId: deletedThreadId,
deletedAt: "2026-02-27T00:00:01.000Z",
}),
]);
expect(effects.clearPromotedDraftThreadIds).toEqual([createdThreadId]);
expect(effects.clearDeletedThreadIds).toEqual([deletedThreadId]);
expect(effects.removeTerminalStateThreadIds).toEqual([deletedThreadId]);
expect(effects.needsProviderInvalidation).toBe(false);
});
it("keeps only the final lifecycle outcome for a thread within one batch", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const effects = deriveOrchestrationBatchEffects([
makeEvent("thread.deleted", {
threadId,
deletedAt: "2026-02-27T00:00:01.000Z",
}),
makeEvent("thread.created", {
threadId,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Recreated thread",
pinnedAt: null,
modelSelection: { provider: "codex", model: "gpt-5-codex" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-27T00:00:02.000Z",
updatedAt: "2026-02-27T00:00:02.000Z",
}),
makeEvent("thread.turn-diff-completed", {
threadId,
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("assistant-1"),
completedAt: "2026-02-27T00:00:03.000Z",
}),
]);
expect(effects.clearPromotedDraftThreadIds).toEqual([threadId]);
expect(effects.clearDeletedThreadIds).toEqual([]);
expect(effects.removeTerminalStateThreadIds).toEqual([]);
expect(effects.needsProviderInvalidation).toBe(true);
});
});
+76
View File
@@ -0,0 +1,76 @@
import type { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
export interface OrchestrationBatchEffects {
clearPromotedDraftThreadIds: ThreadId[];
clearDeletedThreadIds: ThreadId[];
removeTerminalStateThreadIds: ThreadId[];
needsProviderInvalidation: boolean;
}
export function deriveOrchestrationBatchEffects(
events: readonly OrchestrationEvent[],
): OrchestrationBatchEffects {
const threadLifecycleEffects = new Map<
ThreadId,
{
clearPromotedDraft: boolean;
clearDeletedThread: boolean;
removeTerminalState: boolean;
}
>();
let needsProviderInvalidation = false;
for (const event of events) {
switch (event.type) {
case "thread.turn-diff-completed":
case "thread.reverted": {
needsProviderInvalidation = true;
break;
}
case "thread.created": {
threadLifecycleEffects.set(event.payload.threadId, {
clearPromotedDraft: true,
clearDeletedThread: false,
removeTerminalState: false,
});
break;
}
case "thread.deleted": {
threadLifecycleEffects.set(event.payload.threadId, {
clearPromotedDraft: false,
clearDeletedThread: true,
removeTerminalState: true,
});
break;
}
default: {
break;
}
}
}
const clearPromotedDraftThreadIds: ThreadId[] = [];
const clearDeletedThreadIds: ThreadId[] = [];
const removeTerminalStateThreadIds: ThreadId[] = [];
for (const [threadId, effect] of threadLifecycleEffects) {
if (effect.clearPromotedDraft) {
clearPromotedDraftThreadIds.push(threadId);
}
if (effect.clearDeletedThread) {
clearDeletedThreadIds.push(threadId);
}
if (effect.removeTerminalState) {
removeTerminalStateThreadIds.push(threadId);
}
}
return {
clearPromotedDraftThreadIds,
clearDeletedThreadIds,
removeTerminalStateThreadIds,
needsProviderInvalidation,
};
}
+100
View File
@@ -0,0 +1,100 @@
import { describe, expect, it } from "vitest";
import { createOrchestrationRecoveryCoordinator } from "./orchestrationRecovery";
describe("createOrchestrationRecoveryCoordinator", () => {
it("defers live events until bootstrap completes and then requests replay", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
expect(coordinator.beginSnapshotRecovery("bootstrap")).toBe(true);
expect(coordinator.classifyDomainEvent(4)).toBe("defer");
expect(coordinator.completeSnapshotRecovery(2)).toBe(true);
expect(coordinator.getState()).toMatchObject({
latestSequence: 2,
highestObservedSequence: 4,
bootstrapped: true,
pendingReplay: false,
inFlight: null,
});
});
it("classifies sequence gaps as recovery-only replay work", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
expect(coordinator.classifyDomainEvent(5)).toBe("recover");
expect(coordinator.beginReplayRecovery("sequence-gap")).toBe(true);
expect(coordinator.getState().inFlight).toEqual({
kind: "replay",
reason: "sequence-gap",
});
});
it("tracks live event batches without entering recovery", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
expect(coordinator.classifyDomainEvent(4)).toBe("apply");
expect(coordinator.markEventBatchApplied([{ sequence: 4 }])).toEqual([{ sequence: 4 }]);
expect(coordinator.getState()).toMatchObject({
latestSequence: 4,
highestObservedSequence: 4,
bootstrapped: true,
inFlight: null,
});
});
it("requests another replay when deferred events arrive during replay recovery", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.classifyDomainEvent(5);
coordinator.beginReplayRecovery("sequence-gap");
coordinator.classifyDomainEvent(7);
coordinator.markEventBatchApplied([{ sequence: 4 }, { sequence: 5 }, { sequence: 6 }]);
expect(coordinator.completeReplayRecovery()).toBe(true);
});
it("does not immediately replay again when replay returns no new events", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.classifyDomainEvent(5);
coordinator.beginReplayRecovery("sequence-gap");
expect(coordinator.completeReplayRecovery()).toBe(false);
expect(coordinator.getState()).toMatchObject({
latestSequence: 3,
highestObservedSequence: 5,
pendingReplay: false,
inFlight: null,
});
});
it("marks replay failure as unbootstrapped so snapshot fallback is recovery-only", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.beginReplayRecovery("sequence-gap");
coordinator.failReplayRecovery();
expect(coordinator.getState()).toMatchObject({
bootstrapped: false,
inFlight: null,
});
expect(coordinator.beginSnapshotRecovery("replay-failed")).toBe(true);
expect(coordinator.getState().inFlight).toEqual({
kind: "snapshot",
reason: "replay-failed",
});
});
});
+136
View File
@@ -0,0 +1,136 @@
export type OrchestrationRecoveryReason = "bootstrap" | "sequence-gap" | "replay-failed";
export interface OrchestrationRecoveryPhase {
kind: "snapshot" | "replay";
reason: OrchestrationRecoveryReason;
}
export interface OrchestrationRecoveryState {
latestSequence: number;
highestObservedSequence: number;
bootstrapped: boolean;
pendingReplay: boolean;
inFlight: OrchestrationRecoveryPhase | null;
}
type SequencedEvent = Readonly<{ sequence: number }>;
export function createOrchestrationRecoveryCoordinator() {
let state: OrchestrationRecoveryState = {
latestSequence: 0,
highestObservedSequence: 0,
bootstrapped: false,
pendingReplay: false,
inFlight: null,
};
let replayStartSequence: number | null = null;
const snapshotState = (): OrchestrationRecoveryState => ({
...state,
...(state.inFlight ? { inFlight: { ...state.inFlight } } : {}),
});
const observeSequence = (sequence: number) => {
state.highestObservedSequence = Math.max(state.highestObservedSequence, sequence);
};
const shouldReplayAfterRecovery = (): boolean => {
const shouldReplay =
state.pendingReplay || state.highestObservedSequence > state.latestSequence;
state.pendingReplay = false;
return shouldReplay;
};
return {
getState(): OrchestrationRecoveryState {
return snapshotState();
},
classifyDomainEvent(sequence: number): "ignore" | "defer" | "recover" | "apply" {
observeSequence(sequence);
if (sequence <= state.latestSequence) {
return "ignore";
}
if (!state.bootstrapped || state.inFlight) {
state.pendingReplay = true;
return "defer";
}
if (sequence !== state.latestSequence + 1) {
state.pendingReplay = true;
return "recover";
}
return "apply";
},
markEventBatchApplied<T extends SequencedEvent>(events: ReadonlyArray<T>): ReadonlyArray<T> {
const nextEvents = events
.filter((event) => event.sequence > state.latestSequence)
.toSorted((left, right) => left.sequence - right.sequence);
if (nextEvents.length === 0) {
return [];
}
state.latestSequence = nextEvents.at(-1)?.sequence ?? state.latestSequence;
state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);
return nextEvents;
},
beginSnapshotRecovery(reason: OrchestrationRecoveryReason): boolean {
if (state.inFlight?.kind === "snapshot") {
state.pendingReplay = true;
return false;
}
if (state.inFlight?.kind === "replay") {
state.pendingReplay = true;
return false;
}
state.inFlight = { kind: "snapshot", reason };
return true;
},
completeSnapshotRecovery(snapshotSequence: number): boolean {
state.latestSequence = Math.max(state.latestSequence, snapshotSequence);
state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);
state.bootstrapped = true;
state.inFlight = null;
return shouldReplayAfterRecovery();
},
failSnapshotRecovery(): void {
state.inFlight = null;
},
beginReplayRecovery(reason: OrchestrationRecoveryReason): boolean {
if (!state.bootstrapped || state.inFlight?.kind === "snapshot") {
state.pendingReplay = true;
return false;
}
if (state.inFlight?.kind === "replay") {
state.pendingReplay = true;
return false;
}
state.pendingReplay = false;
replayStartSequence = state.latestSequence;
state.inFlight = { kind: "replay", reason };
return true;
},
completeReplayRecovery(): boolean {
const replayMadeProgress =
replayStartSequence !== null && state.latestSequence > replayStartSequence;
replayStartSequence = null;
state.inFlight = null;
if (!replayMadeProgress) {
state.pendingReplay = false;
return false;
}
return shouldReplayAfterRecovery();
},
failReplayRecovery(): void {
replayStartSequence = null;
state.bootstrapped = false;
state.inFlight = null;
},
};
}
+2 -10
View File
@@ -1,11 +1,8 @@
import { createElement } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRouter } from "@tanstack/react-router";
import { createRouter, RouterHistory } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
import { StoreProvider } from "./store";
type RouterHistory = NonNullable<Parameters<typeof createRouter>[0]["history"]>;
export function getRouter(history: RouterHistory) {
const queryClient = new QueryClient();
@@ -16,12 +13,7 @@ export function getRouter(history: RouterHistory) {
context: {
queryClient,
},
Wrap: ({ children }) =>
createElement(
QueryClientProvider,
{ client: queryClient },
createElement(StoreProvider, null, children),
),
Wrap: ({ children }) => createElement(QueryClientProvider, { client: queryClient }, children),
});
}
+146 -47
View File
@@ -1,4 +1,4 @@
import { ThreadId } from "@t3tools/contracts";
import { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
import {
Outlet,
createRootRouteWithContext,
@@ -17,8 +17,13 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDraftStore";
import {
clearPromotedDraftThread,
clearPromotedDraftThreads,
useComposerDraftStore,
} from "../composerDraftStore";
import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
import { useTerminalStateStore } from "../terminalStateStore";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi";
@@ -26,6 +31,8 @@ import { migrateLocalSettingsToServer } from "../hooks/useSettings";
import { providerQueryKeys } from "../lib/providerReactQuery";
import { projectQueryKeys } from "../lib/projectReactQuery";
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects";
import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
@@ -135,8 +142,13 @@ function errorDetails(error: unknown): string {
}
function EventRouter() {
const applyOrchestrationEvents = useStore((store) => store.applyOrchestrationEvents);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded);
const syncProjects = useUiStateStore((store) => store.syncProjects);
const syncThreads = useUiStateStore((store) => store.syncThreads);
const clearThreadUi = useUiStateStore((store) => store.clearThreadUi);
const removeTerminalState = useTerminalStateStore((store) => store.removeTerminalState);
const removeOrphanedTerminalStates = useTerminalStateStore(
(store) => store.removeOrphanedTerminalStates,
);
@@ -152,56 +164,40 @@ function EventRouter() {
const api = readNativeApi();
if (!api) return;
let disposed = false;
let latestSequence = 0;
let syncing = false;
let pending = false;
const recovery = createOrchestrationRecoveryCoordinator();
let needsProviderInvalidation = false;
const flushSnapshotSync = async (): Promise<void> => {
const snapshot = await api.orchestration.getSnapshot();
if (disposed) return;
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
syncServerReadModel(snapshot);
clearPromotedDraftThreads(new Set(snapshot.threads.map((t) => t.id)));
const reconcileSnapshotDerivedState = () => {
const threads = useStore.getState().threads;
const projects = useStore.getState().projects;
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
syncThreads(
threads.map((thread) => ({
id: thread.id,
seedVisitedAt: thread.updatedAt ?? thread.createdAt,
})),
);
clearPromotedDraftThreads(threads.map((thread) => thread.id));
const draftThreadIds = Object.keys(
useComposerDraftStore.getState().draftThreadsByThreadId,
) as ThreadId[];
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: snapshot.threads,
snapshotThreads: threads.map((thread) => ({ id: thread.id, deletedAt: null })),
draftThreadIds,
});
removeOrphanedTerminalStates(activeThreadIds);
if (pending) {
pending = false;
await flushSnapshotSync();
}
};
const syncSnapshot = async () => {
if (syncing) {
pending = true;
return;
}
syncing = true;
pending = false;
try {
await flushSnapshotSync();
} catch {
// Keep prior state and wait for next domain event to trigger a resync.
}
syncing = false;
};
const domainEventFlushThrottler = new Throttler(
const queryInvalidationThrottler = new Throttler(
() => {
if (needsProviderInvalidation) {
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
// Invalidate workspace entry queries so the @-mention file picker
// reflects files created, deleted, or restored during this turn.
void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
if (!needsProviderInvalidation) {
return;
}
void syncSnapshot();
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
// Invalidate workspace entry queries so the @-mention file picker
// reflects files created, deleted, or restored during this turn.
void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
},
{
wait: 100,
@@ -210,15 +206,113 @@ function EventRouter() {
},
);
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
if (event.sequence <= latestSequence) {
const applyEventBatch = (events: ReadonlyArray<OrchestrationEvent>) => {
const nextEvents = recovery.markEventBatchApplied(events);
if (nextEvents.length === 0) {
return;
}
latestSequence = event.sequence;
if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") {
const batchEffects = deriveOrchestrationBatchEffects(nextEvents);
const needsProjectUiSync = nextEvents.some(
(event) =>
event.type === "project.created" ||
event.type === "project.meta-updated" ||
event.type === "project.deleted",
);
if (batchEffects.needsProviderInvalidation) {
needsProviderInvalidation = true;
void queryInvalidationThrottler.maybeExecute();
}
applyOrchestrationEvents(nextEvents);
if (needsProjectUiSync) {
const projects = useStore.getState().projects;
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
}
const needsThreadUiSync = nextEvents.some(
(event) => event.type === "thread.created" || event.type === "thread.deleted",
);
if (needsThreadUiSync) {
const threads = useStore.getState().threads;
syncThreads(
threads.map((thread) => ({
id: thread.id,
seedVisitedAt: thread.updatedAt ?? thread.createdAt,
})),
);
}
const draftStore = useComposerDraftStore.getState();
for (const threadId of batchEffects.clearPromotedDraftThreadIds) {
clearPromotedDraftThread(threadId);
}
for (const threadId of batchEffects.clearDeletedThreadIds) {
draftStore.clearDraftThread(threadId);
clearThreadUi(threadId);
}
for (const threadId of batchEffects.removeTerminalStateThreadIds) {
removeTerminalState(threadId);
}
};
const recoverFromSequenceGap = async (): Promise<void> => {
if (!recovery.beginReplayRecovery("sequence-gap")) {
return;
}
try {
const events = await api.orchestration.replayEvents(recovery.getState().latestSequence);
if (!disposed) {
applyEventBatch(events);
}
} catch {
recovery.failReplayRecovery();
void fallbackToSnapshotRecovery();
return;
}
if (!disposed && recovery.completeReplayRecovery()) {
void recoverFromSequenceGap();
}
};
const runSnapshotRecovery = async (reason: "bootstrap" | "replay-failed"): Promise<void> => {
if (!recovery.beginSnapshotRecovery(reason)) {
return;
}
try {
const snapshot = await api.orchestration.getSnapshot();
if (!disposed) {
syncServerReadModel(snapshot);
reconcileSnapshotDerivedState();
if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
void recoverFromSequenceGap();
}
}
} catch {
// Keep prior state and wait for welcome or a later replay attempt.
recovery.failSnapshotRecovery();
}
};
const bootstrapFromSnapshot = async (): Promise<void> => {
await runSnapshotRecovery("bootstrap");
};
const fallbackToSnapshotRecovery = async (): Promise<void> => {
await runSnapshotRecovery("replay-failed");
};
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
const action = recovery.classifyDomainEvent(event.sequence);
if (action === "apply") {
applyEventBatch([event]);
return;
}
if (action === "recover") {
void recoverFromSequenceGap();
}
domainEventFlushThrottler.maybeExecute();
});
const unsubTerminalEvent = api.terminal.onEvent((event) => {
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
@@ -237,7 +331,7 @@ function EventRouter() {
// Migrate old localStorage settings to server on first connect
migrateLocalSettingsToServer();
void (async () => {
await syncSnapshot();
await bootstrapFromSnapshot();
if (disposed) {
return;
}
@@ -319,7 +413,7 @@ function EventRouter() {
return () => {
disposed = true;
needsProviderInvalidation = false;
domainEventFlushThrottler.cancel();
queryInvalidationThrottler.cancel();
unsubDomainEvent();
unsubTerminalEvent();
unsubWelcome();
@@ -327,11 +421,16 @@ function EventRouter() {
unsubProvidersUpdated();
};
}, [
applyOrchestrationEvents,
navigate,
queryClient,
removeTerminalState,
removeOrphanedTerminalStates,
clearThreadUi,
setProjectExpanded,
syncProjects,
syncServerReadModel,
syncThreads,
]);
return null;
+4 -4
View File
@@ -161,7 +161,7 @@ const DiffPanelInlineSidebar = (props: {
};
function ChatThreadRouteView() {
const threadsHydrated = useStore((store) => store.threadsHydrated);
const bootstrapComplete = useStore((store) => store.bootstrapComplete);
const navigate = useNavigate();
const threadId = Route.useParams({
select: (params) => ThreadId.makeUnsafe(params.threadId),
@@ -202,7 +202,7 @@ function ChatThreadRouteView() {
}, [diffOpen]);
useEffect(() => {
if (!threadsHydrated) {
if (!bootstrapComplete) {
return;
}
@@ -210,9 +210,9 @@ function ChatThreadRouteView() {
void navigate({ to: "/", replace: true });
return;
}
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
}, [bootstrapComplete, navigate, routeThreadExists, threadId]);
if (!threadsHydrated || !routeThreadExists) {
if (!bootstrapComplete || !routeThreadExists) {
return null;
}
+14 -11
View File
@@ -17,7 +17,7 @@ const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
function ChatRouteGlobalShortcuts() {
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
const selectedThreadIdsSize = useThreadSelectionStore((state) => state.selectedThreadIds.size);
const { activeDraftThread, activeThread, handleNewThread, projects, routeThreadId } =
const { activeDraftThread, activeThread, defaultProjectId, handleNewThread, routeThreadId } =
useHandleNewThread();
const serverConfigQuery = useQuery(serverConfigQueryOptions());
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
@@ -38,7 +38,7 @@ function ChatRouteGlobalShortcuts() {
return;
}
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? defaultProjectId;
if (!projectId) return;
const command = resolveShortcutCommand(event, keybindings, {
@@ -59,14 +59,17 @@ function ChatRouteGlobalShortcuts() {
return;
}
if (command !== "chat.new") return;
event.preventDefault();
event.stopPropagation();
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
});
if (command === "chat.new") {
event.preventDefault();
event.stopPropagation();
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode:
activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
});
return;
}
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -79,7 +82,7 @@ function ChatRouteGlobalShortcuts() {
clearSelection,
handleNewThread,
keybindings,
projects,
defaultProjectId,
selectedThreadIdsSize,
terminalOpen,
appSettings.defaultThreadEnvMode,
+32
View File
@@ -8,6 +8,7 @@ import {
import { describe, expect, it } from "vitest";
import {
deriveCompletionDividerBeforeEntryId,
deriveActiveWorkStartedAt,
deriveActivePlanState,
PROVIDER_OPTIONS,
@@ -964,6 +965,37 @@ describe("deriveTimelineEntries", () => {
},
});
});
it("anchors the completion divider to latestTurn.assistantMessageId before timestamp fallback", () => {
const entries = deriveTimelineEntries(
[
{
id: MessageId.makeUnsafe("assistant-earlier"),
role: "assistant",
text: "progress update",
createdAt: "2026-02-23T00:00:01.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("assistant-final"),
role: "assistant",
text: "final answer",
createdAt: "2026-02-23T00:00:01.000Z",
streaming: false,
},
],
[],
[],
);
expect(
deriveCompletionDividerBeforeEntryId(entries, {
assistantMessageId: MessageId.makeUnsafe("assistant-final"),
startedAt: "2026-02-23T00:00:00.000Z",
completedAt: "2026-02-23T00:00:02.000Z",
}),
).toBe("assistant-final");
});
});
describe("deriveWorkLogEntries context window handling", () => {
+47
View File
@@ -852,6 +852,53 @@ export function deriveTimelineEntries(
);
}
export function deriveCompletionDividerBeforeEntryId(
timelineEntries: ReadonlyArray<TimelineEntry>,
latestTurn: Pick<
OrchestrationLatestTurn,
"assistantMessageId" | "startedAt" | "completedAt"
> | null,
): string | null {
if (!latestTurn?.startedAt || !latestTurn.completedAt) {
return null;
}
if (latestTurn.assistantMessageId) {
const exactMatch = timelineEntries.find(
(timelineEntry) =>
timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
timelineEntry.message.id === latestTurn.assistantMessageId,
);
if (exactMatch) {
return exactMatch.id;
}
}
const turnStartedAt = Date.parse(latestTurn.startedAt);
const turnCompletedAt = Date.parse(latestTurn.completedAt);
if (Number.isNaN(turnStartedAt) || Number.isNaN(turnCompletedAt)) {
return null;
}
let inRangeMatch: string | null = null;
let fallbackMatch: string | null = null;
for (const timelineEntry of timelineEntries) {
if (timelineEntry.kind !== "message" || timelineEntry.message.role !== "assistant") {
continue;
}
const messageAt = Date.parse(timelineEntry.message.createdAt);
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) {
continue;
}
fallbackMatch = timelineEntry.id;
if (messageAt <= turnCompletedAt) {
inRangeMatch = timelineEntry.id;
}
}
return inRangeMatch ?? fallbackMatch;
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<TurnId, number> {
+461 -215
View File
@@ -1,19 +1,19 @@
import {
CheckpointRef,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
type OrchestrationEvent,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
beginThreadSend,
clearThreadSend,
markThreadUnread,
markThreadSendSettled,
reorderProjects,
setThreadSendPhase,
applyOrchestrationEvent,
applyOrchestrationEvents,
syncServerReadModel,
type AppState,
} from "./store";
@@ -25,6 +25,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -48,30 +49,57 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
function makeState(thread: Thread): AppState {
return {
pendingThreadSendById: {},
projects: [
{
id: ProjectId.makeUnsafe("project-1"),
name: "Project",
cwd: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
expanded: true,
scripts: [],
},
],
threads: [thread],
threadsHydrated: true,
bootstrapComplete: true,
};
}
function makeEvent<T extends OrchestrationEvent["type"]>(
type: T,
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
): Extract<OrchestrationEvent, { type: T }> {
const sequence = overrides.sequence ?? 1;
return {
sequence,
eventId: EventId.makeUnsafe(`event-${sequence}`),
aggregateKind: "thread",
aggregateId:
"threadId" in payload
? payload.threadId
: "projectId" in payload
? payload.projectId
: ProjectId.makeUnsafe("project-1"),
occurredAt: "2026-02-27T00:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type,
payload,
...overrides,
} as Extract<OrchestrationEvent, { type: T }>;
}
function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"][number]>) {
return {
id: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -103,6 +131,7 @@ function makeReadModel(thread: OrchestrationReadModel["threads"][number]): Orche
id: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -124,6 +153,7 @@ function makeReadModelProject(
id: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
@@ -136,98 +166,18 @@ function makeReadModelProject(
};
}
describe("store pure functions", () => {
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeState(
makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-25T12:28:00.000Z",
startedAt: "2026-02-25T12:28:30.000Z",
completedAt: latestTurnCompletedAt,
assistantMessageId: null,
},
lastVisitedAt: "2026-02-25T12:35:00.000Z",
}),
);
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
const updatedThread = next.threads[0];
expect(updatedThread).toBeDefined();
expect(updatedThread?.lastVisitedAt).toBe("2026-02-25T12:29:59.999Z");
expect(Date.parse(updatedThread?.lastVisitedAt ?? "")).toBeLessThan(
Date.parse(latestTurnCompletedAt),
);
});
it("markThreadUnread does not change a thread without a completed turn", () => {
const initialState = makeState(
makeThread({
latestTurn: null,
lastVisitedAt: "2026-02-25T12:35:00.000Z",
}),
);
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
expect(next).toEqual(initialState);
});
it("reorderProjects moves a project to a target index", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const state: AppState = {
pendingThreadSendById: {},
projects: [
{
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project3,
name: "Project 3",
cwd: "/tmp/project-3",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
],
threads: [],
threadsHydrated: true,
describe("store read model sync", () => {
it("marks bootstrap complete after snapshot sync", () => {
const initialState: AppState = {
...makeState(makeThread()),
bootstrapComplete: false,
};
const next = reorderProjects(state, project1, project3);
const next = syncServerReadModel(initialState, makeReadModel(makeReadModelThread({})));
expect(next.projects.map((project) => project.id)).toEqual([project2, project3, project1]);
expect(next.bootstrapComplete).toBe(true);
});
});
describe("store read model sync", () => {
it("preserves claude model slugs without an active session", () => {
const initialState = makeState(makeThread());
const readModel = makeReadModel(
@@ -298,38 +248,37 @@ describe("store read model sync", () => {
expect(next.threads[0]?.archivedAt).toBe(archivedAt);
});
it("preserves the current project order when syncing incoming read model updates", () => {
it("replaces projects using snapshot order during recovery", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState: AppState = {
pendingThreadSendById: {},
projects: [
{
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
],
threads: [],
threadsHydrated: true,
bootstrapComplete: true,
};
const readModel: OrchestrationReadModel = {
snapshotSequence: 2,
@@ -356,151 +305,448 @@ describe("store read model sync", () => {
const next = syncServerReadModel(initialState, readModel);
expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]);
expect(next.projects.map((project) => project.id)).toEqual([project1, project2, project3]);
});
});
it("keeps pending sends until the server catches up to the send", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
describe("incremental orchestration updates", () => {
it("does not mark bootstrap complete for incremental events", () => {
const state: AppState = {
...makeState(makeThread()),
bootstrapComplete: false,
};
const next = applyOrchestrationEvent(
state,
makeEvent("thread.meta-updated", {
threadId: ThreadId.makeUnsafe("thread-1"),
title: "Updated title",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-27T00:00:59.000Z",
startedAt: "2026-02-27T00:01:01.000Z",
completedAt: "2026-02-27T00:01:03.000Z",
assistantMessageId: null,
expect(next.bootstrapComplete).toBe(false);
});
it("preserves state identity for no-op project and thread deletes", () => {
const thread = makeThread();
const state = makeState(thread);
const nextAfterProjectDelete = applyOrchestrationEvent(
state,
makeEvent("project.deleted", {
projectId: ProjectId.makeUnsafe("project-missing"),
deletedAt: "2026-02-27T00:00:01.000Z",
}),
);
const nextAfterThreadDelete = applyOrchestrationEvent(
state,
makeEvent("thread.deleted", {
threadId: ThreadId.makeUnsafe("thread-missing"),
deletedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(nextAfterProjectDelete).toBe(state);
expect(nextAfterThreadDelete).toBe(state);
});
it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => {
const originalProjectId = ProjectId.makeUnsafe("project-1");
const recreatedProjectId = ProjectId.makeUnsafe("project-2");
const state: AppState = {
projects: [
{
id: originalProjectId,
name: "Project",
cwd: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
}),
),
scripts: [],
},
],
threads: [],
bootstrapComplete: true,
};
const next = applyOrchestrationEvent(
state,
makeEvent("project.created", {
projectId: recreatedProjectId,
title: "Project Recreated",
workspaceRoot: "/tmp/project",
pinnedAt: null,
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
scripts: [],
createdAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.pendingThreadSendById[threadId]).toEqual({
phase: "sending-turn",
startedAt: "2026-02-27T00:01:00.000Z",
requestSettled: false,
});
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe(recreatedProjectId);
expect(next.projects[0]?.cwd).toBe("/tmp/project");
expect(next.projects[0]?.name).toBe("Project Recreated");
});
it("does not clear pending sends when the turn appears before the request settles", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-27T00:01:01.000Z",
startedAt: "2026-02-27T00:01:02.000Z",
completedAt: "2026-02-27T00:01:03.000Z",
assistantMessageId: null,
},
}),
),
);
expect(next.pendingThreadSendById[threadId]).toEqual({
phase: "sending-turn",
startedAt: "2026-02-27T00:01:00.000Z",
requestSettled: false,
it("updates only the affected thread for message events", () => {
const thread1 = makeThread({
id: ThreadId.makeUnsafe("thread-1"),
messages: [
{
id: MessageId.makeUnsafe("message-1"),
role: "assistant",
text: "hello",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:00.000Z",
streaming: false,
},
],
});
const thread2 = makeThread({ id: ThreadId.makeUnsafe("thread-2") });
const state: AppState = {
...makeState(thread1),
threads: [thread1, thread2],
};
const next = applyOrchestrationEvent(
state,
makeEvent("thread.message-sent", {
threadId: thread1.id,
messageId: MessageId.makeUnsafe("message-1"),
role: "assistant",
text: " world",
turnId: TurnId.makeUnsafe("turn-1"),
streaming: true,
createdAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.threads[0]?.messages[0]?.text).toBe("hello world");
expect(next.threads[0]?.latestTurn?.state).toBe("running");
expect(next.threads[1]).toBe(thread2);
});
it("clears pending sends once the server session starts running", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
);
it("applies replay batches in sequence and updates session state", () => {
const thread = makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "running",
requestedAt: "2026-02-27T00:00:00.000Z",
startedAt: "2026-02-27T00:00:00.000Z",
completedAt: null,
assistantMessageId: null,
},
});
const state = makeState(thread);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
const next = applyOrchestrationEvents(state, [
makeEvent(
"thread.session-set",
{
threadId: thread.id,
session: {
threadId,
threadId: thread.id,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-1"),
lastError: null,
updatedAt: "2026-02-27T00:01:02.000Z",
updatedAt: "2026-02-27T00:00:02.000Z",
},
}),
},
{ sequence: 2 },
),
);
makeEvent(
"thread.message-sent",
{
threadId: thread.id,
messageId: MessageId.makeUnsafe("assistant-1"),
role: "assistant",
text: "done",
turnId: TurnId.makeUnsafe("turn-1"),
streaming: false,
createdAt: "2026-02-27T00:00:03.000Z",
updatedAt: "2026-02-27T00:00:03.000Z",
},
{ sequence: 3 },
),
]);
expect(next.pendingThreadSendById[threadId]).toBeUndefined();
expect(next.threads[0]?.session?.status).toBe("running");
expect(next.threads[0]?.latestTurn?.state).toBe("completed");
expect(next.threads[0]?.messages).toHaveLength(1);
});
it("clears settled pending sends once the turn has caught up", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = markThreadSendSettled(
beginThreadSend(
makeState(makeThread()),
threadId,
"sending-turn",
"2026-02-27T00:01:00.000Z",
),
threadId,
it("does not regress latestTurn when an older turn diff completes late", () => {
const state = makeState(
makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-2"),
state: "running",
requestedAt: "2026-02-27T00:00:02.000Z",
startedAt: "2026-02-27T00:00:03.000Z",
completedAt: null,
assistantMessageId: null,
},
}),
);
const next = syncServerReadModel(
initialState,
makeReadModel(
makeReadModelThread({
latestTurn: {
const next = applyOrchestrationEvent(
state,
makeEvent("thread.turn-diff-completed", {
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("assistant-1"),
completedAt: "2026-02-27T00:00:04.000Z",
}),
);
expect(next.threads[0]?.turnDiffSummaries).toHaveLength(1);
expect(next.threads[0]?.latestTurn).toEqual(state.threads[0]?.latestTurn);
});
it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => {
const turnId = TurnId.makeUnsafe("turn-1");
const state = makeState(
makeThread({
latestTurn: {
turnId,
state: "completed",
requestedAt: "2026-02-27T00:00:00.000Z",
startedAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:02.000Z",
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
},
turnDiffSummaries: [
{
turnId,
completedAt: "2026-02-27T00:00:02.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
files: [{ path: "src/app.ts", additions: 1, deletions: 0 }],
},
],
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.message-sent", {
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: MessageId.makeUnsafe("assistant-real"),
role: "assistant",
text: "final answer",
turnId,
streaming: false,
createdAt: "2026-02-27T00:00:03.000Z",
updatedAt: "2026-02-27T00:00:03.000Z",
}),
);
expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
expect(next.threads[0]?.latestTurn?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
});
it("reverts messages, plans, activities, and checkpoints by retained turns", () => {
const state = makeState(
makeThread({
messages: [
{
id: MessageId.makeUnsafe("user-1"),
role: "user",
text: "first",
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-27T00:01:01.000Z",
startedAt: "2026-02-27T00:01:02.000Z",
completedAt: "2026-02-27T00:01:03.000Z",
assistantMessageId: null,
createdAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:00.000Z",
streaming: false,
},
}),
),
{
id: MessageId.makeUnsafe("assistant-1"),
role: "assistant",
text: "first reply",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:01.000Z",
completedAt: "2026-02-27T00:00:01.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("user-2"),
role: "user",
text: "second",
turnId: TurnId.makeUnsafe("turn-2"),
createdAt: "2026-02-27T00:00:02.000Z",
completedAt: "2026-02-27T00:00:02.000Z",
streaming: false,
},
],
proposedPlans: [
{
id: "plan-1",
turnId: TurnId.makeUnsafe("turn-1"),
planMarkdown: "plan 1",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
},
{
id: "plan-2",
turnId: TurnId.makeUnsafe("turn-2"),
planMarkdown: "plan 2",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-02-27T00:00:02.000Z",
updatedAt: "2026-02-27T00:00:02.000Z",
},
],
activities: [
{
id: EventId.makeUnsafe("activity-1"),
tone: "info",
kind: "step",
summary: "one",
payload: {},
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
},
{
id: EventId.makeUnsafe("activity-2"),
tone: "info",
kind: "step",
summary: "two",
payload: {},
turnId: TurnId.makeUnsafe("turn-2"),
createdAt: "2026-02-27T00:00:02.000Z",
},
],
turnDiffSummaries: [
{
turnId: TurnId.makeUnsafe("turn-1"),
completedAt: "2026-02-27T00:00:01.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
files: [],
},
{
turnId: TurnId.makeUnsafe("turn-2"),
completedAt: "2026-02-27T00:00:03.000Z",
status: "ready",
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
files: [],
},
],
}),
);
expect(next.pendingThreadSendById[threadId]).toBeUndefined();
});
});
describe("store pending thread send helpers", () => {
it("updates and clears pending thread send state", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const startedState = beginThreadSend(
makeState(makeThread()),
threadId,
"preparing-worktree",
"2026-02-27T00:01:00.000Z",
const next = applyOrchestrationEvent(
state,
makeEvent("thread.reverted", {
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
}),
);
const sendingState = setThreadSendPhase(startedState, threadId, "sending-turn");
const settledState = markThreadSendSettled(sendingState, threadId);
const clearedState = clearThreadSend(settledState, threadId);
expect(startedState.pendingThreadSendById[threadId]?.phase).toBe("preparing-worktree");
expect(startedState.pendingThreadSendById[threadId]?.requestSettled).toBe(false);
expect(sendingState.pendingThreadSendById[threadId]?.phase).toBe("sending-turn");
expect(settledState.pendingThreadSendById[threadId]?.requestSettled).toBe(true);
expect(clearedState.pendingThreadSendById[threadId]).toBeUndefined();
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual([
"user-1",
"assistant-1",
]);
expect(next.threads[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]);
expect(next.threads[0]?.activities.map((activity) => activity.id)).toEqual([
EventId.makeUnsafe("activity-1"),
]);
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
TurnId.makeUnsafe("turn-1"),
]);
});
it("clears pending source proposed plans after revert before a new session-set event", () => {
const thread = makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-2"),
state: "completed",
requestedAt: "2026-02-27T00:00:02.000Z",
startedAt: "2026-02-27T00:00:02.000Z",
completedAt: "2026-02-27T00:00:03.000Z",
assistantMessageId: MessageId.makeUnsafe("assistant-2"),
sourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-source"),
planId: "plan-2" as never,
},
},
pendingSourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-source"),
planId: "plan-2" as never,
},
turnDiffSummaries: [
{
turnId: TurnId.makeUnsafe("turn-1"),
completedAt: "2026-02-27T00:00:01.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
files: [],
},
{
turnId: TurnId.makeUnsafe("turn-2"),
completedAt: "2026-02-27T00:00:03.000Z",
status: "ready",
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
files: [],
},
],
});
const reverted = applyOrchestrationEvent(
makeState(thread),
makeEvent("thread.reverted", {
threadId: thread.id,
turnCount: 1,
}),
);
expect(reverted.threads[0]?.pendingSourceProposedPlan).toBeUndefined();
const next = applyOrchestrationEvent(
reverted,
makeEvent("thread.session-set", {
threadId: thread.id,
session: {
threadId: thread.id,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-3"),
lastError: null,
updatedAt: "2026-02-27T00:00:04.000Z",
},
}),
);
expect(next.threads[0]?.latestTurn).toMatchObject({
turnId: TurnId.makeUnsafe("turn-3"),
state: "running",
});
expect(next.threads[0]?.latestTurn?.sourceProposedPlan).toBeUndefined();
});
});
+795 -504
View File
File diff suppressed because it is too large. Load diff
+14
View File
@@ -0,0 +1,14 @@
import { type ThreadId } from "@t3tools/contracts";
import { useMemo } from "react";
import { selectProjectById, selectThreadById, useStore } from "./store";
import { type Project, type Thread } from "./types";
export function useProjectById(projectId: Project["id"] | null | undefined): Project | undefined {
const selector = useMemo(() => selectProjectById(projectId), [projectId]);
return useStore(selector);
}
export function useThreadById(threadId: ThreadId | null | undefined): Thread | undefined {
const selector = useMemo(() => selectThreadById(threadId), [threadId]);
return useStore(selector);
}
+10
View File
@@ -485,6 +485,7 @@ interface TerminalStateStoreState {
hasRunningSubprocess: boolean,
) => void;
clearTerminalState: (threadId: ThreadId) => void;
removeTerminalState: (threadId: ThreadId) => void;
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
}
@@ -530,6 +531,15 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
),
clearTerminalState: (threadId) =>
updateTerminal(threadId, () => createDefaultThreadTerminalState()),
removeTerminalState: (threadId) =>
set((state) => {
if (state.terminalStateByThreadId[threadId] === undefined) {
return state;
}
const next = { ...state.terminalStateByThreadId };
delete next[threadId];
return { terminalStateByThreadId: next };
}),
removeOrphanedTerminalStates: (activeThreadIds) =>
set((state) => {
const orphanedIds = Object.keys(state.terminalStateByThreadId).filter(
+4 -9
View File
@@ -16,7 +16,6 @@ import type {
} from "@t3tools/contracts";
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
export type PendingThreadSendPhase = "preparing-worktree" | "sending-turn";
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
export const DEFAULT_INTERACTION_MODE: ProviderInteractionMode = "default";
@@ -46,6 +45,7 @@ export interface ChatMessage {
role: "user" | "assistant" | "system";
text: string;
attachments?: ChatAttachment[];
turnId?: TurnId | null;
createdAt: string;
completedAt?: string | undefined;
streaming: boolean;
@@ -82,8 +82,8 @@ export interface Project {
id: ProjectId;
name: string;
cwd: string;
pinnedAt: string | null;
defaultModelSelection: ModelSelection | null;
expanded: boolean;
createdAt?: string | undefined;
updatedAt?: string | undefined;
scripts: ProjectScript[];
@@ -94,6 +94,7 @@ export interface Thread {
codexThreadId: string | null;
projectId: ProjectId;
title: string;
pinnedAt: string | null;
modelSelection: ModelSelection;
runtimeMode: RuntimeMode;
interactionMode: ProviderInteractionMode;
@@ -105,7 +106,7 @@ export interface Thread {
archivedAt: string | null;
updatedAt?: string | undefined;
latestTurn: OrchestrationLatestTurn | null;
lastVisitedAt?: string | undefined;
pendingSourceProposedPlan?: OrchestrationLatestTurn["sourceProposedPlan"];
branch: string | null;
worktreePath: string | null;
turnDiffSummaries: TurnDiffSummary[];
@@ -121,9 +122,3 @@ export interface ThreadSession {
lastError?: string;
orchestrationStatus: OrchestrationSessionStatus;
}
export interface PendingThreadSend {
phase: PendingThreadSendPhase;
startedAt: string;
requestSettled: boolean;
}
+192
View File
@@ -0,0 +1,192 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
clearThreadUi,
markThreadUnread,
reorderProjects,
setProjectExpanded,
syncProjects,
syncThreads,
type UiState,
} from "./uiStateStore";
function makeUiState(overrides: Partial<UiState> = {}): UiState {
return {
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
...overrides,
};
}
describe("uiStateStore pure functions", () => {
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeUiState({
threadLastVisitedAtById: {
[threadId]: "2026-02-25T12:35:00.000Z",
},
});
const next = markThreadUnread(initialState, threadId, latestTurnCompletedAt);
expect(next.threadLastVisitedAtById[threadId]).toBe("2026-02-25T12:29:59.999Z");
});
it("markThreadUnread does not change a thread without a completed turn", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = makeUiState({
threadLastVisitedAtById: {
[threadId]: "2026-02-25T12:35:00.000Z",
},
});
const next = markThreadUnread(initialState, threadId, null);
expect(next).toBe(initialState);
});
it("reorderProjects moves a project to a target index", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState = makeUiState({
projectOrder: [project1, project2, project3],
});
const next = reorderProjects(initialState, project1, project3);
expect(next.projectOrder).toEqual([project2, project3, project1]);
});
it("syncProjects preserves current project order during snapshot recovery", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState = makeUiState({
projectExpandedById: {
[project1]: true,
[project2]: false,
},
projectOrder: [project2, project1],
});
const next = syncProjects(initialState, [
{ id: project1, cwd: "/tmp/project-1" },
{ id: project2, cwd: "/tmp/project-2" },
{ id: project3, cwd: "/tmp/project-3" },
]);
expect(next.projectOrder).toEqual([project2, project1, project3]);
expect(next.projectExpandedById[project2]).toBe(false);
});
it("syncProjects preserves manual order when a project is recreated with the same cwd", () => {
const oldProject1 = ProjectId.makeUnsafe("project-1");
const oldProject2 = ProjectId.makeUnsafe("project-2");
const recreatedProject2 = ProjectId.makeUnsafe("project-2b");
const initialState = syncProjects(
makeUiState({
projectExpandedById: {
[oldProject1]: true,
[oldProject2]: false,
},
projectOrder: [oldProject2, oldProject1],
}),
[
{ id: oldProject1, cwd: "/tmp/project-1" },
{ id: oldProject2, cwd: "/tmp/project-2" },
],
);
const next = syncProjects(initialState, [
{ id: oldProject1, cwd: "/tmp/project-1" },
{ id: recreatedProject2, cwd: "/tmp/project-2" },
]);
expect(next.projectOrder).toEqual([recreatedProject2, oldProject1]);
expect(next.projectExpandedById[recreatedProject2]).toBe(false);
});
it("syncProjects returns a new state when only project cwd changes", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const initialState = syncProjects(
makeUiState({
projectExpandedById: {
[project1]: false,
},
projectOrder: [project1],
}),
[{ id: project1, cwd: "/tmp/project-1" }],
);
const next = syncProjects(initialState, [{ id: project1, cwd: "/tmp/project-1-renamed" }]);
expect(next).not.toBe(initialState);
expect(next.projectOrder).toEqual([project1]);
expect(next.projectExpandedById[project1]).toBe(false);
});
it("syncThreads prunes missing thread UI state", () => {
const thread1 = ThreadId.makeUnsafe("thread-1");
const thread2 = ThreadId.makeUnsafe("thread-2");
const initialState = makeUiState({
threadLastVisitedAtById: {
[thread1]: "2026-02-25T12:35:00.000Z",
[thread2]: "2026-02-25T12:36:00.000Z",
},
});
const next = syncThreads(initialState, [{ id: thread1 }]);
expect(next.threadLastVisitedAtById).toEqual({
[thread1]: "2026-02-25T12:35:00.000Z",
});
});
it("syncThreads seeds visit state for unseen snapshot threads", () => {
const thread1 = ThreadId.makeUnsafe("thread-1");
const initialState = makeUiState();
const next = syncThreads(initialState, [
{
id: thread1,
seedVisitedAt: "2026-02-25T12:35:00.000Z",
},
]);
expect(next.threadLastVisitedAtById).toEqual({
[thread1]: "2026-02-25T12:35:00.000Z",
});
});
it("setProjectExpanded updates expansion without touching order", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const initialState = makeUiState({
projectExpandedById: {
[project1]: true,
},
projectOrder: [project1],
});
const next = setProjectExpanded(initialState, project1, false);
expect(next.projectExpandedById[project1]).toBe(false);
expect(next.projectOrder).toEqual([project1]);
});
it("clearThreadUi removes visit state for deleted threads", () => {
const thread1 = ThreadId.makeUnsafe("thread-1");
const initialState = makeUiState({
threadLastVisitedAtById: {
[thread1]: "2026-02-25T12:35:00.000Z",
},
});
const next = clearThreadUi(initialState, thread1);
expect(next.threadLastVisitedAtById).toEqual({});
});
});
+417
View File
@@ -0,0 +1,417 @@
import { Debouncer } from "@tanstack/react-pacer";
import { type ProjectId, type ThreadId } from "@t3tools/contracts";
import { create } from "zustand";
const PERSISTED_STATE_KEY = "t3code:ui-state:v1";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v8",
"t3code:renderer-state:v7",
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
"t3code:renderer-state:v3",
"codething:renderer-state:v4",
"codething:renderer-state:v3",
"codething:renderer-state:v2",
"codething:renderer-state:v1",
] as const;
interface PersistedUiState {
expandedProjectCwds?: string[];
projectOrderCwds?: string[];
}
export interface UiProjectState {
projectExpandedById: Record<string, boolean>;
projectOrder: ProjectId[];
}
export interface UiThreadState {
threadLastVisitedAtById: Record<string, string>;
}
export interface UiState extends UiProjectState, UiThreadState {}
export interface SyncProjectInput {
id: ProjectId;
cwd: string;
}
export interface SyncThreadInput {
id: ThreadId;
seedVisitedAt?: string | undefined;
}
const initialState: UiState = {
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
};
const persistedExpandedProjectCwds = new Set<string>();
const persistedProjectOrderCwds: string[] = [];
const currentProjectCwdById = new Map<ProjectId, string>();
let legacyKeysCleanedUp = false;
function readPersistedState(): UiState {
if (typeof window === "undefined") {
return initialState;
}
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
if (!raw) {
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
const legacyRaw = window.localStorage.getItem(legacyKey);
if (!legacyRaw) {
continue;
}
hydratePersistedProjectState(JSON.parse(legacyRaw) as PersistedUiState);
return initialState;
}
return initialState;
}
hydratePersistedProjectState(JSON.parse(raw) as PersistedUiState);
return initialState;
} catch {
return initialState;
}
}
function hydratePersistedProjectState(parsed: PersistedUiState): void {
persistedExpandedProjectCwds.clear();
persistedProjectOrderCwds.length = 0;
for (const cwd of parsed.expandedProjectCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0) {
persistedExpandedProjectCwds.add(cwd);
}
}
for (const cwd of parsed.projectOrderCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) {
persistedProjectOrderCwds.push(cwd);
}
}
}
function persistState(state: UiState): void {
if (typeof window === "undefined") {
return;
}
try {
const expandedProjectCwds = Object.entries(state.projectExpandedById)
.filter(([, expanded]) => expanded)
.flatMap(([projectId]) => {
const cwd = currentProjectCwdById.get(projectId as ProjectId);
return cwd ? [cwd] : [];
});
const projectOrderCwds = state.projectOrder.flatMap((projectId) => {
const cwd = currentProjectCwdById.get(projectId);
return cwd ? [cwd] : [];
});
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify({
expandedProjectCwds,
projectOrderCwds,
} satisfies PersistedUiState),
);
if (!legacyKeysCleanedUp) {
legacyKeysCleanedUp = true;
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
const debouncedPersistState = new Debouncer(persistState, { wait: 500 });
function recordsEqual<T>(left: Record<string, T>, right: Record<string, T>): boolean {
const leftEntries = Object.entries(left);
const rightEntries = Object.entries(right);
if (leftEntries.length !== rightEntries.length) {
return false;
}
for (const [key, value] of leftEntries) {
if (right[key] !== value) {
return false;
}
}
return true;
}
function projectOrdersEqual(left: readonly ProjectId[], right: readonly ProjectId[]): boolean {
return (
left.length === right.length && left.every((projectId, index) => projectId === right[index])
);
}
export function syncProjects(state: UiState, projects: readonly SyncProjectInput[]): UiState {
const previousProjectCwdById = new Map(currentProjectCwdById);
const previousProjectIdByCwd = new Map(
[...previousProjectCwdById.entries()].map(([projectId, cwd]) => [cwd, projectId] as const),
);
currentProjectCwdById.clear();
for (const project of projects) {
currentProjectCwdById.set(project.id, project.cwd);
}
const cwdMappingChanged =
previousProjectCwdById.size !== currentProjectCwdById.size ||
projects.some((project) => previousProjectCwdById.get(project.id) !== project.cwd);
const nextExpandedById: Record<string, boolean> = {};
const previousExpandedById = state.projectExpandedById;
const persistedOrderByCwd = new Map(
persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const),
);
const mappedProjects = projects.map((project, index) => {
const previousProjectIdForCwd = previousProjectIdByCwd.get(project.cwd);
const expanded =
previousExpandedById[project.id] ??
(previousProjectIdForCwd ? previousExpandedById[previousProjectIdForCwd] : undefined) ??
(persistedExpandedProjectCwds.size > 0
? persistedExpandedProjectCwds.has(project.cwd)
: true);
nextExpandedById[project.id] = expanded;
return {
id: project.id,
cwd: project.cwd,
incomingIndex: index,
};
});
const nextProjectOrder =
state.projectOrder.length > 0
? (() => {
const nextProjectIdByCwd = new Map(
mappedProjects.map((project) => [project.cwd, project.id] as const),
);
const usedProjectIds = new Set<ProjectId>();
const orderedProjectIds: ProjectId[] = [];
for (const projectId of state.projectOrder) {
const matchedProjectId =
(projectId in nextExpandedById ? projectId : undefined) ??
(() => {
const previousCwd = previousProjectCwdById.get(projectId);
return previousCwd ? nextProjectIdByCwd.get(previousCwd) : undefined;
})();
if (!matchedProjectId || usedProjectIds.has(matchedProjectId)) {
continue;
}
usedProjectIds.add(matchedProjectId);
orderedProjectIds.push(matchedProjectId);
}
for (const project of mappedProjects) {
if (usedProjectIds.has(project.id)) {
continue;
}
orderedProjectIds.push(project.id);
}
return orderedProjectIds;
})()
: mappedProjects
.map((project) => ({
id: project.id,
incomingIndex: project.incomingIndex,
orderIndex:
persistedOrderByCwd.get(project.cwd) ??
persistedProjectOrderCwds.length + project.incomingIndex,
}))
.toSorted((left, right) => {
const byOrder = left.orderIndex - right.orderIndex;
if (byOrder !== 0) {
return byOrder;
}
return left.incomingIndex - right.incomingIndex;
})
.map((project) => project.id);
if (
recordsEqual(state.projectExpandedById, nextExpandedById) &&
projectOrdersEqual(state.projectOrder, nextProjectOrder) &&
!cwdMappingChanged
) {
return state;
}
return {
...state,
projectExpandedById: nextExpandedById,
projectOrder: nextProjectOrder,
};
}
export function syncThreads(state: UiState, threads: readonly SyncThreadInput[]): UiState {
const retainedThreadIds = new Set(threads.map((thread) => thread.id));
const nextThreadLastVisitedAtById = Object.fromEntries(
Object.entries(state.threadLastVisitedAtById).filter(([threadId]) =>
retainedThreadIds.has(threadId as ThreadId),
),
);
for (const thread of threads) {
if (
nextThreadLastVisitedAtById[thread.id] === undefined &&
thread.seedVisitedAt !== undefined &&
thread.seedVisitedAt.length > 0
) {
nextThreadLastVisitedAtById[thread.id] = thread.seedVisitedAt;
}
}
if (recordsEqual(state.threadLastVisitedAtById, nextThreadLastVisitedAtById)) {
return state;
}
return {
...state,
threadLastVisitedAtById: nextThreadLastVisitedAtById,
};
}
export function markThreadVisited(state: UiState, threadId: ThreadId, visitedAt?: string): UiState {
const at = visitedAt ?? new Date().toISOString();
const visitedAtMs = Date.parse(at);
const previousVisitedAt = state.threadLastVisitedAtById[threadId];
const previousVisitedAtMs = previousVisitedAt ? Date.parse(previousVisitedAt) : NaN;
if (
Number.isFinite(previousVisitedAtMs) &&
Number.isFinite(visitedAtMs) &&
previousVisitedAtMs >= visitedAtMs
) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: at,
},
};
}
export function markThreadUnread(
state: UiState,
threadId: ThreadId,
latestTurnCompletedAt: string | null | undefined,
): UiState {
if (!latestTurnCompletedAt) {
return state;
}
const latestTurnCompletedAtMs = Date.parse(latestTurnCompletedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) {
return state;
}
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
if (state.threadLastVisitedAtById[threadId] === unreadVisitedAt) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: unreadVisitedAt,
},
};
}
export function clearThreadUi(state: UiState, threadId: ThreadId): UiState {
if (!(threadId in state.threadLastVisitedAtById)) {
return state;
}
const nextThreadLastVisitedAtById = { ...state.threadLastVisitedAtById };
delete nextThreadLastVisitedAtById[threadId];
return {
...state,
threadLastVisitedAtById: nextThreadLastVisitedAtById,
};
}
export function toggleProject(state: UiState, projectId: ProjectId): UiState {
const expanded = state.projectExpandedById[projectId] ?? true;
return {
...state,
projectExpandedById: {
...state.projectExpandedById,
[projectId]: !expanded,
},
};
}
export function setProjectExpanded(
state: UiState,
projectId: ProjectId,
expanded: boolean,
): UiState {
if ((state.projectExpandedById[projectId] ?? true) === expanded) {
return state;
}
return {
...state,
projectExpandedById: {
...state.projectExpandedById,
[projectId]: expanded,
},
};
}
export function reorderProjects(
state: UiState,
draggedProjectId: ProjectId,
targetProjectId: ProjectId,
): UiState {
if (draggedProjectId === targetProjectId) {
return state;
}
const draggedIndex = state.projectOrder.findIndex((projectId) => projectId === draggedProjectId);
const targetIndex = state.projectOrder.findIndex((projectId) => projectId === targetProjectId);
if (draggedIndex < 0 || targetIndex < 0) {
return state;
}
const projectOrder = [...state.projectOrder];
const [draggedProject] = projectOrder.splice(draggedIndex, 1);
if (!draggedProject) {
return state;
}
projectOrder.splice(targetIndex, 0, draggedProject);
return {
...state,
projectOrder,
};
}
interface UiStateStore extends UiState {
syncProjects: (projects: readonly SyncProjectInput[]) => void;
syncThreads: (threads: readonly SyncThreadInput[]) => void;
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
markThreadUnread: (threadId: ThreadId, latestTurnCompletedAt: string | null | undefined) => void;
clearThreadUi: (threadId: ThreadId) => void;
toggleProject: (projectId: ProjectId) => void;
setProjectExpanded: (projectId: ProjectId, expanded: boolean) => void;
reorderProjects: (draggedProjectId: ProjectId, targetProjectId: ProjectId) => void;
}
export const useUiStateStore = create<UiStateStore>((set) => ({
...readPersistedState(),
syncProjects: (projects) => set((state) => syncProjects(state, projects)),
syncThreads: (threads) => set((state) => syncThreads(state, threads)),
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
markThreadUnread: (threadId, latestTurnCompletedAt) =>
set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)),
clearThreadUi: (threadId) => set((state) => clearThreadUi(state, threadId)),
toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
setProjectExpanded: (projectId, expanded) =>
set((state) => setProjectExpanded(state, projectId, expanded)),
reorderProjects: (draggedProjectId, targetProjectId) =>
set((state) => reorderProjects(state, draggedProjectId, targetProjectId)),
}));
useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
debouncedPersistState.flush();
});
}
+1
View File
@@ -10,6 +10,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
pinnedAt: null,
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
+2
View File
@@ -289,6 +289,7 @@ describe("wsNativeApi", () => {
projectId: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/workspace",
pinnedAt: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-02-24T00:00:00.000Z",
@@ -331,6 +332,7 @@ describe("wsNativeApi", () => {
projectId: ProjectId.makeUnsafe("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
pinned: false,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
+6 -6
View File
@@ -130,12 +130,12 @@ export interface NativeApi {
confirm: (message: string) => Promise<boolean>;
};
terminal: {
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
write: (input: TerminalWriteInput) => Promise<void>;
resize: (input: TerminalResizeInput) => Promise<void>;
clear: (input: TerminalClearInput) => Promise<void>;
restart: (input: TerminalRestartInput) => Promise<TerminalSessionSnapshot>;
close: (input: TerminalCloseInput) => Promise<void>;
open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;
write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;
resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;
clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;
restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;
close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
};
projects: {
@@ -95,6 +95,7 @@ it.effect("trims branded ids and command string fields at decode boundaries", ()
assert.strictEqual(parsed.projectId, "project-1");
assert.strictEqual(parsed.title, "Project Title");
assert.strictEqual(parsed.workspaceRoot, "/tmp/workspace");
assert.strictEqual(parsed.pinned, false);
assert.deepStrictEqual(parsed.defaultModelSelection, {
provider: "codex",
model: "gpt-5.2",
@@ -117,6 +118,7 @@ it.effect("decodes historical project.created payloads with a default provider",
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.strictEqual(parsed.defaultModelSelection?.provider, "codex");
assert.strictEqual(parsed.pinnedAt, null);
}),
);
@@ -214,6 +216,7 @@ it.effect("decodes thread.created runtime mode for historical events", () =>
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
assert.strictEqual(parsed.modelSelection.provider, "codex");
assert.strictEqual(parsed.pinnedAt, null);
}),
);
+10
View File
@@ -145,6 +145,7 @@ export const OrchestrationProject = Schema.Struct({
id: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
pinnedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -274,6 +275,7 @@ export const OrchestrationThread = Schema.Struct({
id: ThreadId,
projectId: ProjectId,
title: TrimmedNonEmptyString,
pinnedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode.pipe(
@@ -308,6 +310,7 @@ export const ProjectCreateCommand = Schema.Struct({
projectId: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
pinned: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
createdAt: IsoDateTime,
});
@@ -318,6 +321,7 @@ const ProjectMetaUpdateCommand = Schema.Struct({
projectId: ProjectId,
title: Schema.optional(TrimmedNonEmptyString),
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
pinned: Schema.optional(Schema.Boolean),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
});
@@ -334,6 +338,7 @@ const ThreadCreateCommand = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
title: TrimmedNonEmptyString,
pinned: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode.pipe(
@@ -367,6 +372,7 @@ const ThreadMetaUpdateCommand = Schema.Struct({
commandId: CommandId,
threadId: ThreadId,
title: Schema.optional(TrimmedNonEmptyString),
pinned: Schema.optional(Schema.Boolean),
modelSelection: Schema.optional(ModelSelection),
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
@@ -624,6 +630,7 @@ export const ProjectCreatedPayload = Schema.Struct({
projectId: ProjectId,
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
pinnedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
defaultModelSelection: Schema.NullOr(ModelSelection),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
@@ -634,6 +641,7 @@ export const ProjectMetaUpdatedPayload = Schema.Struct({
projectId: ProjectId,
title: Schema.optional(TrimmedNonEmptyString),
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
scripts: Schema.optional(Schema.Array(ProjectScript)),
updatedAt: IsoDateTime,
@@ -648,6 +656,7 @@ export const ThreadCreatedPayload = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
title: TrimmedNonEmptyString,
pinnedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)),
modelSelection: ModelSelection,
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
interactionMode: ProviderInteractionMode.pipe(
@@ -678,6 +687,7 @@ export const ThreadUnarchivedPayload = Schema.Struct({
export const ThreadMetaUpdatedPayload = Schema.Struct({
threadId: ThreadId,
title: Schema.optional(TrimmedNonEmptyString),
pinnedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
modelSelection: Schema.optional(ModelSelection),
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
+2 -2
View File
@@ -26,7 +26,7 @@ const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe(
export const TerminalThreadInput = Schema.Struct({
threadId: TrimmedNonEmptyStringSchema,
});
export type TerminalThreadInput = Schema.Codec.Encoded<typeof TerminalThreadInput>;
export type TerminalThreadInput = typeof TerminalThreadInput.Type;
const TerminalSessionInput = Schema.Struct({
...TerminalThreadInput.fields,
@@ -73,7 +73,7 @@ export const TerminalCloseInput = Schema.Struct({
terminalId: Schema.optional(TerminalIdSchema),
deleteHistory: Schema.optional(Schema.Boolean),
});
export type TerminalCloseInput = Schema.Codec.Encoded<typeof TerminalCloseInput>;
export type TerminalCloseInput = typeof TerminalCloseInput.Type;
export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]);
export type TerminalSessionStatus = typeof TerminalSessionStatus.Type;
+4
View File
@@ -28,6 +28,10 @@
"types": "./src/DrainableWorker.ts",
"import": "./src/DrainableWorker.ts"
},
"./KeyedCoalescingWorker": {
"types": "./src/KeyedCoalescingWorker.ts",
"import": "./src/KeyedCoalescingWorker.ts"
},
"./schemaJson": {
"types": "./src/schemaJson.ts",
"import": "./src/schemaJson.ts"
@@ -0,0 +1,96 @@
import { it } from "@effect/vitest";
import { describe, expect } from "vitest";
import { Deferred, Effect } from "effect";
import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker";
describe("makeKeyedCoalescingWorker", () => {
it.live("waits for latest work enqueued during active processing before draining the key", () =>
Effect.scoped(
Effect.gen(function* () {
const processed: string[] = [];
const firstStarted = yield* Deferred.make<void>();
const releaseFirst = yield* Deferred.make<void>();
const secondStarted = yield* Deferred.make<void>();
const releaseSecond = yield* Deferred.make<void>();
const worker = yield* makeKeyedCoalescingWorker<string, string, never, never>({
merge: (_current, next) => next,
process: (key, value) =>
Effect.gen(function* () {
processed.push(`${key}:${value}`);
if (value === "first") {
yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
yield* Deferred.await(releaseFirst);
}
if (value === "second") {
yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie);
yield* Deferred.await(releaseSecond);
}
}),
});
yield* worker.enqueue("terminal-1", "first");
yield* Deferred.await(firstStarted);
const drained = yield* Deferred.make<void>();
yield* Effect.forkChild(
worker
.drainKey("terminal-1")
.pipe(Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie))),
);
yield* worker.enqueue("terminal-1", "second");
yield* Deferred.succeed(releaseFirst, undefined);
yield* Deferred.await(secondStarted);
expect(yield* Deferred.isDone(drained)).toBe(false);
yield* Deferred.succeed(releaseSecond, undefined);
yield* Deferred.await(drained);
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
}),
),
);
it.live("requeues pending work for a key after a processor failure and keeps draining", () =>
Effect.scoped(
Effect.gen(function* () {
const processed: string[] = [];
const firstStarted = yield* Deferred.make<void>();
const releaseFailure = yield* Deferred.make<void>();
const secondProcessed = yield* Deferred.make<void>();
const worker = yield* makeKeyedCoalescingWorker<string, string, string, never>({
merge: (_current, next) => next,
process: (key, value) =>
Effect.gen(function* () {
processed.push(`${key}:${value}`);
if (value === "first") {
yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
yield* Deferred.await(releaseFailure);
yield* Effect.fail("boom");
}
if (value === "second") {
yield* Deferred.succeed(secondProcessed, undefined).pipe(Effect.orDie);
}
}),
});
yield* worker.enqueue("terminal-1", "first");
yield* Deferred.await(firstStarted);
yield* worker.enqueue("terminal-1", "second");
yield* Deferred.succeed(releaseFailure, undefined);
yield* Deferred.await(secondProcessed);
yield* worker.drainKey("terminal-1");
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
}),
),
);
});
@@ -0,0 +1,140 @@
/**
* KeyedCoalescingWorker - A keyed worker that keeps only the latest value per key.
*
* Enqueues for an active or already-queued key are merged atomically instead of
* creating duplicate queued items. `drainKey()` resolves only when that key has
* no queued, pending, or active work left.
*
* @module KeyedCoalescingWorker
*/
import type { Scope } from "effect";
import { Effect, TxQueue, TxRef } from "effect";
export interface KeyedCoalescingWorker<K, V> {
readonly enqueue: (key: K, value: V) => Effect.Effect<void>;
readonly drainKey: (key: K) => Effect.Effect<void>;
}
interface KeyedCoalescingWorkerState<K, V> {
readonly latestByKey: Map<K, V>;
readonly queuedKeys: Set<K>;
readonly activeKeys: Set<K>;
}
export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
readonly merge: (current: V, next: V) => V;
readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;
}): Effect.Effect<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> =>
Effect.gen(function* () {
const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);
const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({
latestByKey: new Map(),
queuedKeys: new Set(),
activeKeys: new Set(),
});
const processKey = (key: K, value: V): Effect.Effect<void, E, R> =>
options.process(key, value).pipe(
Effect.flatMap(() =>
TxRef.modify(stateRef, (state) => {
const nextValue = state.latestByKey.get(key);
if (nextValue === undefined) {
const activeKeys = new Set(state.activeKeys);
activeKeys.delete(key);
return [null, { ...state, activeKeys }] as const;
}
const latestByKey = new Map(state.latestByKey);
latestByKey.delete(key);
return [nextValue, { ...state, latestByKey }] as const;
}).pipe(Effect.tx),
),
Effect.flatMap((nextValue) =>
nextValue === null ? Effect.void : processKey(key, nextValue),
),
);
const cleanupFailedKey = (key: K): Effect.Effect<void> =>
TxRef.modify(stateRef, (state) => {
const activeKeys = new Set(state.activeKeys);
activeKeys.delete(key);
if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {
const queuedKeys = new Set(state.queuedKeys);
queuedKeys.add(key);
return [true, { ...state, activeKeys, queuedKeys }] as const;
}
return [false, { ...state, activeKeys }] as const;
}).pipe(
Effect.tx,
Effect.flatMap((shouldRequeue) =>
shouldRequeue ? TxQueue.offer(queue, key) : Effect.void,
),
);
yield* TxQueue.take(queue).pipe(
Effect.flatMap((key) =>
TxRef.modify(stateRef, (state) => {
const queuedKeys = new Set(state.queuedKeys);
queuedKeys.delete(key);
const value = state.latestByKey.get(key);
if (value === undefined) {
return [null, { ...state, queuedKeys }] as const;
}
const latestByKey = new Map(state.latestByKey);
latestByKey.delete(key);
const activeKeys = new Set(state.activeKeys);
activeKeys.add(key);
return [
{ key, value } as const,
{ ...state, latestByKey, queuedKeys, activeKeys },
] as const;
}).pipe(Effect.tx),
),
Effect.flatMap((item) =>
item === null
? Effect.void
: processKey(item.key, item.value).pipe(
Effect.catchCause(() => cleanupFailedKey(item.key)),
),
),
Effect.forever,
Effect.forkScoped,
);
const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>
TxRef.modify(stateRef, (state) => {
const latestByKey = new Map(state.latestByKey);
const existing = latestByKey.get(key);
latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
return [false, { ...state, latestByKey }] as const;
}
const queuedKeys = new Set(state.queuedKeys);
queuedKeys.add(key);
return [true, { ...state, latestByKey, queuedKeys }] as const;
}).pipe(
Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),
Effect.tx,
Effect.asVoid,
);
const drainKey: KeyedCoalescingWorker<K, V>["drainKey"] = (key) =>
TxRef.get(stateRef).pipe(
Effect.tap((state) =>
state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)
? Effect.txRetry
: Effect.void,
),
Effect.asVoid,
Effect.tx,
);
return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;
});