feat(sidebar-v2): add task tabs and context forks

This commit is contained in:
Theo Browne committed 2026-07-24 07:43:45 -07:00
1 parent a7ee3092c3
commit 0ed495a122
36 files changed
+4207 -90

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -68,6 +68,7 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(first.environmentId).toBe(second.environmentId);
expect(second.capabilities.repositoryIdentity).toBe(true);
expect(second.capabilities.connectionProbe).toBe(true);
expect(second.capabilities.workspaceTaskTabs).toBe(true);
}),
);
@@ -142,6 +142,7 @@ export const make = Effect.gen(function* () {
connectionProbe: true,
threadSettlement: true,
threadSnooze: true,
workspaceTaskTabs: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
},
};
@@ -4,6 +4,7 @@ import {
type OrchestrationEvent,
type OrchestrationSessionStatus,
ThreadId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -597,6 +598,12 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
threadId: event.payload.threadId,
projectId: event.payload.projectId,
workspaceTaskId:
event.payload.workspaceTaskId ?? WorkspaceTaskId.make(String(event.payload.threadId)),
tabLabel: event.payload.tabLabel ?? null,
tabPosition: event.payload.tabPosition ?? 0,
tabClosedAt: event.payload.tabClosedAt ?? null,
forkProvenance: event.payload.forkProvenance ?? null,
title: event.payload.title,
modelSelection: event.payload.modelSelection,
runtimeMode: event.payload.runtimeMode,
@@ -730,6 +737,13 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.worktreePath !== undefined
? { worktreePath: event.payload.worktreePath }
: {}),
...(event.payload.tabLabel !== undefined ? { tabLabel: event.payload.tabLabel } : {}),
...(event.payload.tabPosition !== undefined
? { tabPosition: event.payload.tabPosition }
: {}),
...(event.payload.tabClosedAt !== undefined
? { tabClosedAt: event.payload.tabClosedAt }
: {}),
updatedAt: event.payload.updatedAt,
});
return;
@@ -6,6 +6,7 @@ import {
ThreadId,
TurnId,
ProviderInstanceId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -284,6 +285,11 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
{
id: ThreadId.make("thread-1"),
projectId: asProjectId("project-1"),
workspaceTaskId: WorkspaceTaskId.make("thread-1"),
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
@@ -398,6 +404,11 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
{
id: ThreadId.make("thread-1"),
projectId: asProjectId("project-1"),
workspaceTaskId: WorkspaceTaskId.make("thread-1"),
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Thread 1",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
@@ -447,6 +458,23 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
if (threadDetail._tag === "Some") {
assert.deepEqual(threadDetail.value, snapshot.threads[0]);
}
yield* sql`
UPDATE projection_threads
SET tab_closed_at = '2026-02-24T00:00:09.000Z'
WHERE thread_id = 'thread-1'
`;
const closedShellSnapshot = yield* snapshotQuery.getShellSnapshot();
assert.deepEqual(closedShellSnapshot.threads, []);
const closedThreadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
assert.equal(closedThreadShell._tag, "None");
const closedThreadDetail = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-1"),
);
assert.equal(closedThreadDetail._tag, "Some");
if (closedThreadDetail._tag === "Some") {
assert.equal(closedThreadDetail.value.tabClosedAt, "2026-02-24T00:00:09.000Z");
}
}),
);
@@ -24,6 +24,7 @@ import {
ModelSelection,
ProjectId,
ThreadId,
ThreadForkProvenance,
} from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Effect from "effect/Effect";
@@ -78,6 +79,7 @@ const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
forkProvenance: Schema.NullOr(Schema.fromJsonString(ThreadForkProvenance)),
}),
);
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
@@ -117,6 +119,10 @@ const ProjectIdLookupInput = Schema.Struct({
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
const ThreadRowByIdLookupInput = Schema.Struct({
threadId: ThreadId,
includeClosed: Schema.Boolean,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
@@ -324,6 +330,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -356,6 +367,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -378,6 +394,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NULL
AND tab_closed_at IS NULL
ORDER BY project_id ASC, created_at ASC, thread_id ASC
`,
});
@@ -390,6 +407,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -748,14 +770,19 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const getActiveThreadRowById = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
const getThreadRowById = SqlSchema.findOneOption({
Request: ThreadRowByIdLookupInput,
Result: ProjectionThreadDbRowSchema,
execute: ({ threadId }) =>
execute: ({ threadId, includeClosed }) =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -779,6 +806,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
WHERE thread_id = ${threadId}
AND deleted_at IS NULL
AND archived_at IS NULL
AND (${includeClosed ? 1 : 0} = 1 OR tab_closed_at IS NULL)
LIMIT 1
`,
});
@@ -1192,6 +1220,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
id: row.threadId,
projectId: row.projectId,
workspaceTaskId: row.workspaceTaskId,
tabLabel: row.tabLabel,
tabPosition: row.tabPosition,
tabClosedAt: row.tabClosedAt,
forkProvenance: row.forkProvenance,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
@@ -1394,6 +1427,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
threads.push({
id: row.threadId,
projectId: row.projectId,
workspaceTaskId: row.workspaceTaskId,
tabLabel: row.tabLabel,
tabPosition: row.tabPosition,
tabClosedAt: row.tabClosedAt,
forkProvenance: row.forkProvenance,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
@@ -1527,6 +1565,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
? Result.succeed({
id: row.threadId,
projectId: row.projectId,
workspaceTaskId: row.workspaceTaskId,
tabLabel: row.tabLabel,
tabPosition: row.tabPosition,
tabClosedAt: row.tabClosedAt,
forkProvenance: row.forkProvenance,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
@@ -1665,6 +1708,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
(row): OrchestrationThreadShell => ({
id: row.threadId,
projectId: row.projectId,
workspaceTaskId: row.workspaceTaskId,
tabLabel: row.tabLabel,
tabPosition: row.tabPosition,
tabClosedAt: row.tabClosedAt,
forkProvenance: row.forkProvenance,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
@@ -1876,7 +1924,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
getThreadRowById({ threadId, includeClosed: false }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadShellById:getThread:query",
@@ -1909,6 +1957,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
return Option.some({
id: threadRow.value.threadId,
projectId: threadRow.value.projectId,
workspaceTaskId: threadRow.value.workspaceTaskId,
tabLabel: threadRow.value.tabLabel,
tabPosition: threadRow.value.tabPosition,
tabClosedAt: threadRow.value.tabClosedAt,
forkProvenance: threadRow.value.forkProvenance,
title: threadRow.value.title,
modelSelection: threadRow.value.modelSelection,
runtimeMode: threadRow.value.runtimeMode,
@@ -1942,7 +1995,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
latestTurnRow,
sessionRow,
] = yield* Effect.all([
getActiveThreadRowById({ threadId }).pipe(
getThreadRowById({ threadId, includeClosed: true }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:getThread:query",
@@ -2007,6 +2060,11 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const thread = {
id: threadRow.value.threadId,
projectId: threadRow.value.projectId,
workspaceTaskId: threadRow.value.workspaceTaskId,
tabLabel: threadRow.value.tabLabel,
tabPosition: threadRow.value.tabPosition,
tabClosedAt: threadRow.value.tabClosedAt,
forkProvenance: threadRow.value.forkProvenance,
title: threadRow.value.title,
modelSelection: threadRow.value.modelSelection,
runtimeMode: threadRow.value.runtimeMode,
@@ -20,6 +20,7 @@ import {
ProjectId,
ThreadId,
TurnId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Deferred from "effect/Deferred";
@@ -477,6 +478,80 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
effectIt.effect(
"injects a source transcript only into the first provider turn of a portable task fork",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() => createHarness());
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-source-turn"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("source-user-message"),
role: "user",
text: "Source tab context",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-fork-thread-create"),
threadId: ThreadId.make("thread-fork"),
projectId: asProjectId("project-1"),
workspaceTaskId: WorkspaceTaskId.make("thread-1"),
tabPosition: 1,
forkProvenance: {
mode: "portable",
sourceThreadId: ThreadId.make("thread-1"),
createdAt: now,
},
title: "Fork",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
});
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-fork-turn"),
threadId: ThreadId.make("thread-fork"),
message: {
messageId: asMessageId("fork-user-message"),
role: "user",
text: "Try another approach",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 2));
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.make("thread-fork"),
});
const forkInput = harness.sendTurn.mock.calls[1]?.[0] as { input?: string };
expect(forkInput.input).toContain("Source tab context");
expect(forkInput.input?.endsWith("Try another approach")).toBe(true);
const readModel = yield* Effect.promise(() => harness.readModel());
const fork = readModel.threads.find((thread) => thread.id === ThreadId.make("thread-fork"));
expect(fork?.messages.map((message) => message.text)).toEqual(["Try another approach"]);
}),
);
effectIt.effect("projects starting before a slow provider session finishes", () =>
Effect.gen(function* () {
const releaseStart = yield* Deferred.make<void>();
@@ -41,6 +41,7 @@ import {
import { ServerSettingsService } from "../../serverSettings.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
import { buildPortableForkProviderInput } from "../portableFork.ts";
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
const isProviderDriverKind = Schema.is(ProviderDriverKind);
@@ -629,7 +630,20 @@ const make = Effect.gen(function* () {
if (input.modelSelection !== undefined) {
threadModelSelections.set(input.threadId, input.modelSelection);
}
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const sourceThread =
thread.forkProvenance?.mode === "portable" &&
thread.forkProvenance.sourceThreadId !== null &&
thread.messages.filter((entry) => entry.role === "user").length === 1
? yield* resolveThread(thread.forkProvenance.sourceThreadId)
: undefined;
const providerInput =
sourceThread !== undefined
? buildPortableForkProviderInput({
source: sourceThread,
userInput: input.messageText,
})
: input.messageText;
const normalizedInput = toNonEmptyProviderInput(providerInput);
const normalizedAttachments = input.attachments ?? [];
const activeSession = yield* providerService
.listSessions()
@@ -0,0 +1,137 @@
import {
CommandId,
EventId,
ProjectId,
ProviderInstanceId,
ThreadId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
const now = "2026-07-24T00:00:00.000Z";
const projectId = ProjectId.make("project-1");
const taskId = WorkspaceTaskId.make("task-1");
const rootThreadId = ThreadId.make("thread-root");
const modelSelection = {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5",
} as const;
const seededReadModel = Effect.gen(function* () {
const withProject = yield* projectEvent(createEmptyReadModel(now), {
sequence: 1,
eventId: EventId.make("event-project"),
aggregateKind: "project",
aggregateId: projectId,
type: "project.created",
occurredAt: now,
commandId: CommandId.make("command-project"),
causationEventId: null,
correlationId: CommandId.make("command-project"),
metadata: {},
payload: {
projectId,
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: modelSelection,
scripts: [],
createdAt: now,
updatedAt: now,
},
});
return yield* projectEvent(withProject, {
sequence: 2,
eventId: EventId.make("event-root"),
aggregateKind: "thread",
aggregateId: rootThreadId,
type: "thread.created",
occurredAt: now,
commandId: CommandId.make("command-root"),
causationEventId: null,
correlationId: CommandId.make("command-root"),
metadata: {},
payload: {
threadId: rootThreadId,
projectId,
workspaceTaskId: taskId,
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Task",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/task",
worktreePath: "/tmp/project-task",
createdAt: now,
updatedAt: now,
},
});
});
it.layer(NodeServices.layer)("task tab invariants", (it) => {
it.effect("accepts a sibling tab on the same project and worktree", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
readModel: yield* seededReadModel,
command: {
type: "thread.create",
commandId: CommandId.make("command-child"),
threadId: ThreadId.make("thread-child"),
projectId,
workspaceTaskId: taskId,
tabPosition: 1,
forkProvenance: {
mode: "portable",
sourceThreadId: rootThreadId,
createdAt: now,
},
title: "Alternative",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/task",
worktreePath: "/tmp/project-task",
createdAt: now,
},
});
const firstEvent = Array.isArray(event) ? event[0] : event;
expect(firstEvent.type).toBe("thread.created");
expect(firstEvent.payload).toMatchObject({
workspaceTaskId: taskId,
tabPosition: 1,
});
}),
);
it.effect("rejects a sibling tab that points at another worktree", () =>
Effect.gen(function* () {
const failure = yield* Effect.flip(
decideOrchestrationCommand({
readModel: yield* seededReadModel,
command: {
type: "thread.create",
commandId: CommandId.make("command-wrong-tree"),
threadId: ThreadId.make("thread-wrong-tree"),
projectId,
workspaceTaskId: taskId,
title: "Wrong tree",
modelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "other",
worktreePath: "/tmp/other-tree",
createdAt: now,
},
}),
);
expect(failure.message).toContain("must keep project and worktree identity");
}),
);
});
+48
View File
@@ -3,6 +3,7 @@ import {
type OrchestrationCommand,
type OrchestrationEvent,
type OrchestrationReadModel,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
@@ -355,6 +356,45 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
command,
threadId: command.threadId,
});
const workspaceTaskId =
command.workspaceTaskId ?? WorkspaceTaskId.make(String(command.threadId));
const sibling = readModel.threads.find(
(thread) =>
thread.deletedAt === null &&
(thread.workspaceTaskId ?? WorkspaceTaskId.make(String(thread.id))) === workspaceTaskId,
);
if (
sibling &&
(sibling.projectId !== command.projectId || sibling.worktreePath !== command.worktreePath)
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `workspace task ${workspaceTaskId} must keep project and worktree identity from sibling thread ${sibling.id}`,
});
}
if (
command.forkProvenance?.mode === "fresh" &&
command.forkProvenance.sourceThreadId !== null
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: "a fresh task tab cannot declare a source thread",
});
}
if (command.forkProvenance?.mode === "portable") {
const source = readModel.threads.find(
(thread) => thread.id === command.forkProvenance?.sourceThreadId,
);
if (
!source ||
(source.workspaceTaskId ?? WorkspaceTaskId.make(String(source.id))) !== workspaceTaskId
) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `portable fork source must be an existing tab in workspace task ${workspaceTaskId}`,
});
}
}
return {
...(yield* withEventBase({
aggregateKind: "thread",
@@ -366,6 +406,11 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
projectId: command.projectId,
workspaceTaskId,
tabLabel: command.tabLabel ?? null,
tabPosition: command.tabPosition ?? 0,
tabClosedAt: command.tabClosedAt ?? null,
forkProvenance: command.forkProvenance ?? null,
title: command.title,
modelSelection: command.modelSelection,
runtimeMode: command.runtimeMode,
@@ -659,6 +704,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
: {}),
...(branch !== undefined ? { branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
...(command.tabLabel !== undefined ? { tabLabel: command.tabLabel } : {}),
...(command.tabPosition !== undefined ? { tabPosition: command.tabPosition } : {}),
...(command.tabClosedAt !== undefined ? { tabClosedAt: command.tabClosedAt } : {}),
updatedAt: occurredAt,
},
};
@@ -0,0 +1,100 @@
import { describe, expect, it } from "@effect/vitest";
import {
MessageId,
ProviderInstanceId,
ProjectId,
ThreadId,
WorkspaceTaskId,
type OrchestrationThread,
} from "@t3tools/contracts";
import { buildPortableForkProviderInput } from "./portableFork.ts";
function makeSource(messages: OrchestrationThread["messages"]): OrchestrationThread {
return {
id: ThreadId.make("source-thread"),
projectId: ProjectId.make("project-1"),
workspaceTaskId: WorkspaceTaskId.make("task-1"),
tabLabel: "Main",
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Investigate task tabs",
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: "feature/task-tabs",
worktreePath: "/tmp/task-tabs",
latestTurn: null,
createdAt: "2026-07-24T00:00:00.000Z",
updatedAt: "2026-07-24T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
deletedAt: null,
messages,
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
};
}
describe("buildPortableForkProviderInput", () => {
it("places the source transcript before the child tab request", () => {
const result = buildPortableForkProviderInput({
source: makeSource([
{
id: MessageId.make("message-1"),
role: "user",
text: "Inspect the architecture.",
attachments: [],
turnId: null,
streaming: false,
createdAt: "2026-07-24T00:00:00.000Z",
updatedAt: "2026-07-24T00:00:00.000Z",
},
]),
userInput: "Try a different implementation.",
});
expect(result).toContain("same T3 Code task");
expect(result).toContain("Inspect the architecture.");
expect(result).toContain("Shared worktree: /tmp/task-tabs");
expect(result.endsWith("Try a different implementation.")).toBe(true);
});
it("bounds large transcripts while retaining recent messages", () => {
const result = buildPortableForkProviderInput({
source: makeSource([
{
id: MessageId.make("message-old"),
role: "user",
text: `old-${"x".repeat(48_000)}`,
attachments: [],
turnId: null,
streaming: false,
createdAt: "2026-07-24T00:00:00.000Z",
updatedAt: "2026-07-24T00:00:00.000Z",
},
{
id: MessageId.make("message-recent"),
role: "assistant",
text: "recent-context",
attachments: [],
turnId: null,
streaming: false,
createdAt: "2026-07-24T00:01:00.000Z",
updatedAt: "2026-07-24T00:01:00.000Z",
},
]),
userInput: "Continue.",
});
expect(result).not.toContain("old-");
expect(result).toContain("recent-context");
expect(result.length).toBeLessThan(50_000);
});
});
@@ -0,0 +1,55 @@
import type { OrchestrationMessage, OrchestrationThread } from "@t3tools/contracts";
const MAX_HANDOFF_CHARACTERS = 48_000;
function renderMessage(message: OrchestrationMessage): string {
const attachmentNote =
message.attachments && message.attachments.length > 0
? `\n[${message.attachments.length} attachment${message.attachments.length === 1 ? "" : "s"} omitted from the handoff]`
: "";
return `<message role="${message.role}">\n${message.text}${attachmentNote}\n</message>`;
}
/**
* Builds a provider-neutral first-turn handoff for a context-forked task tab.
* The source transcript remains owned by its original thread; the child only
* receives this bounded snapshot as provider input.
*/
export function buildPortableForkProviderInput(input: {
readonly source: OrchestrationThread;
readonly userInput: string;
}): string {
const header = [
"<t3-task-tab-context>",
"You are continuing in a sibling tab of the same T3 Code task.",
"The sibling tabs share one worktree. Treat the source transcript below as prior context,",
"but follow the new user request after the closing tag as the current instruction.",
`Source tab: ${input.source.title}`,
`Source thread id: ${input.source.id}`,
`Source branch: ${input.source.branch ?? "(current checkout)"}`,
`Shared worktree: ${input.source.worktreePath ?? "(project workspace)"}`,
"<source-transcript>",
].join("\n");
const footer = "\n</source-transcript>\n</t3-task-tab-context>";
const fixedSize = header.length + footer.length;
const budget = Math.max(0, MAX_HANDOFF_CHARACTERS - fixedSize);
const selected: string[] = [];
let used = 0;
// Preserve the most recent context when the source conversation is larger
// than the portable handoff budget.
for (let index = input.source.messages.length - 1; index >= 0; index -= 1) {
const message = input.source.messages[index];
if (!message) continue;
const rendered = renderMessage(message);
if (used + rendered.length > budget) {
continue;
}
selected.unshift(rendered);
used += rendered.length;
}
const transcript =
selected.length > 0 ? selected.join("\n") : "[No source transcript was available.]";
return `${header}\n${transcript}${footer}\n\n${input.userInput}`;
}
@@ -280,6 +280,11 @@ export function projectEvent(
{
id: payload.threadId,
projectId: payload.projectId,
workspaceTaskId: payload.workspaceTaskId,
tabLabel: payload.tabLabel,
tabPosition: payload.tabPosition,
tabClosedAt: payload.tabClosedAt,
forkProvenance: payload.forkProvenance,
title: payload.title,
modelSelection: payload.modelSelection,
runtimeMode: payload.runtimeMode,
@@ -404,6 +409,9 @@ export function projectEvent(
: {}),
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
...(payload.tabLabel !== undefined ? { tabLabel: payload.tabLabel } : {}),
...(payload.tabPosition !== undefined ? { tabPosition: payload.tabPosition } : {}),
...(payload.tabClosedAt !== undefined ? { tabClosedAt: payload.tabClosedAt } : {}),
updatedAt: payload.updatedAt,
}),
})),
@@ -1,4 +1,4 @@
import { ProjectId, ThreadId, ProviderInstanceId } from "@t3tools/contracts";
import { ProjectId, ProviderInstanceId, ThreadId, WorkspaceTaskId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -78,6 +78,11 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
yield* threads.upsert({
threadId: ThreadId.make("thread-null-options"),
projectId: ProjectId.make("project-null-options"),
workspaceTaskId: WorkspaceTaskId.make("thread-null-options"),
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Null options thread",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
@@ -140,6 +145,11 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
yield* threads.upsert({
threadId: ThreadId.make("thread-settled"),
projectId: ProjectId.make("project-1"),
workspaceTaskId: WorkspaceTaskId.make("thread-settled"),
tabLabel: null,
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
title: "Settled thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
@@ -14,11 +14,12 @@ import {
ProjectionThreadRepository,
type ProjectionThreadRepositoryShape,
} from "../Services/ProjectionThreads.ts";
import { ModelSelection } from "@t3tools/contracts";
import { ModelSelection, ThreadForkProvenance } from "@t3tools/contracts";
const ProjectionThreadDbRow = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
forkProvenance: Schema.NullOr(Schema.fromJsonString(ThreadForkProvenance)),
}),
);
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
@@ -33,6 +34,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
INSERT INTO projection_threads (
thread_id,
project_id,
workspace_task_id,
tab_label,
tab_position,
tab_closed_at,
fork_provenance_json,
title,
model_selection_json,
runtime_mode,
@@ -56,6 +62,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
VALUES (
${row.threadId},
${row.projectId},
${row.workspaceTaskId},
${row.tabLabel},
${row.tabPosition},
${row.tabClosedAt},
${row.forkProvenance === null ? null : JSON.stringify(row.forkProvenance)},
${row.title},
${JSON.stringify(row.modelSelection)},
${row.runtimeMode},
@@ -79,6 +90,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
ON CONFLICT (thread_id)
DO UPDATE SET
project_id = excluded.project_id,
workspace_task_id = excluded.workspace_task_id,
tab_label = excluded.tab_label,
tab_position = excluded.tab_position,
tab_closed_at = excluded.tab_closed_at,
fork_provenance_json = excluded.fork_provenance_json,
title = excluded.title,
model_selection_json = excluded.model_selection_json,
runtime_mode = excluded.runtime_mode,
@@ -109,6 +125,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -141,6 +162,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
SELECT
thread_id AS "threadId",
project_id AS "projectId",
COALESCE(workspace_task_id, thread_id) AS "workspaceTaskId",
tab_label AS "tabLabel",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
@@ -47,6 +47,7 @@ import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionThreadTasks.ts";
/**
* Migration loader with all migrations defined inline.
@@ -93,6 +94,7 @@ export const migrationEntries = [
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "ProjectionThreadsSettled", Migration0033],
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionThreadTasks", Migration0035],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,97 @@
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("035_ProjectionThreadTasks", (it) => {
it.effect("backfills legacy threads as one-tab tasks and creates the lookup index", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 34 });
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
settled_override,
settled_at,
snoozed_until,
snoozed_at,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
deleted_at
)
VALUES (
'thread-legacy',
'project-1',
'Legacy thread',
'{"instanceId":"codex","model":"gpt-5"}',
'full-access',
'default',
'main',
'/tmp/worktree',
NULL,
'2026-07-24T00:00:00.000Z',
'2026-07-24T00:00:00.000Z',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
NULL
)
`;
yield* runMigrations({ toMigrationInclusive: 35 });
const rows = yield* sql<{
readonly workspaceTaskId: string;
readonly tabPosition: number;
readonly tabClosedAt: string | null;
readonly forkProvenance: string | null;
}>`
SELECT
workspace_task_id AS "workspaceTaskId",
tab_position AS "tabPosition",
tab_closed_at AS "tabClosedAt",
fork_provenance_json AS "forkProvenance"
FROM projection_threads
WHERE thread_id = 'thread-legacy'
`;
assert.deepStrictEqual(rows, [
{
workspaceTaskId: "thread-legacy",
tabPosition: 0,
tabClosedAt: null,
forkProvenance: null,
},
]);
const indexes = yield* sql<{ readonly name: string }>`
PRAGMA index_list(projection_threads)
`;
assert.ok(indexes.some((index) => index.name === "idx_projection_threads_workspace_task"));
}),
);
});
@@ -0,0 +1,53 @@
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 columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "workspace_task_id")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN workspace_task_id TEXT
`;
}
if (!columns.some((column) => column.name === "tab_label")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN tab_label TEXT
`;
}
if (!columns.some((column) => column.name === "tab_position")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN tab_position INTEGER NOT NULL DEFAULT 0
`;
}
if (!columns.some((column) => column.name === "tab_closed_at")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN tab_closed_at TEXT
`;
}
if (!columns.some((column) => column.name === "fork_provenance_json")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN fork_provenance_json TEXT
`;
}
// Every pre-task thread becomes a one-tab task. This makes the migration
// lossless and lets mixed-version clients continue using thread routes.
yield* sql`
UPDATE projection_threads
SET workspace_task_id = thread_id
WHERE workspace_task_id IS NULL
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_workspace_task
ON projection_threads (workspace_task_id, tab_closed_at, tab_position, created_at, thread_id)
`;
});
@@ -14,7 +14,9 @@ import {
ProviderInteractionMode,
RuntimeMode,
ThreadId,
ThreadForkProvenance,
TurnId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -26,6 +28,11 @@ import type { ProjectionRepositoryError } from "../Errors.ts";
export const ProjectionThread = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
workspaceTaskId: WorkspaceTaskId,
tabLabel: Schema.NullOr(Schema.String),
tabPosition: NonNegativeInt,
tabClosedAt: Schema.NullOr(IsoDateTime),
forkProvenance: Schema.NullOr(ThreadForkProvenance),
title: Schema.String,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
+15
View File
@@ -984,6 +984,21 @@ const makeWsRpcLayer = (
commandId: yield* serverCommandId("bootstrap-thread-create"),
threadId: command.threadId,
projectId: bootstrap.createThread.projectId,
...(bootstrap.createThread.workspaceTaskId !== undefined
? { workspaceTaskId: bootstrap.createThread.workspaceTaskId }
: {}),
...(bootstrap.createThread.tabLabel !== undefined
? { tabLabel: bootstrap.createThread.tabLabel }
: {}),
...(bootstrap.createThread.tabPosition !== undefined
? { tabPosition: bootstrap.createThread.tabPosition }
: {}),
...(bootstrap.createThread.tabClosedAt !== undefined
? { tabClosedAt: bootstrap.createThread.tabClosedAt }
: {}),
...(bootstrap.createThread.forkProvenance !== undefined
? { forkProvenance: bootstrap.createThread.forkProvenance }
: {}),
title: bootstrap.createThread.title,
modelSelection: bootstrap.createThread.modelSelection,
runtimeMode: bootstrap.createThread.runtimeMode,
+14
View File
@@ -115,6 +115,7 @@ import { useTheme } from "../hooks/useTheme";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { isCommandPaletteOpen } from "../commandPaletteBus";
import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";
import { WorkspaceTaskTabs } from "./WorkspaceTaskTabs";
import { useMediaQuery } from "../hooks/useMediaQuery";
import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";
import {
@@ -4725,6 +4726,18 @@ function ChatViewContent(props: ChatViewProps) {
? {
createThread: {
projectId: activeProject.id,
...(draftThread?.workspaceTaskId
? { workspaceTaskId: draftThread.workspaceTaskId }
: {}),
...(draftThread?.tabLabel !== undefined
? { tabLabel: draftThread.tabLabel }
: {}),
...(draftThread?.tabPosition !== undefined
? { tabPosition: draftThread.tabPosition }
: {}),
...(draftThread?.forkProvenance !== undefined
? { forkProvenance: draftThread.forkProvenance }
: {}),
title,
modelSelection: threadCreateModelSelection,
runtimeMode,
@@ -5655,6 +5668,7 @@ function ChatViewContent(props: ChatViewProps) {
/>
</header>
<WorkspaceTaskTabs />
<ThreadErrorBanner
error={threadError}
onDismiss={() => setThreadError(activeThread.id, null)}
+194 -79
View File
@@ -18,7 +18,6 @@ import {
AlarmClockOffIcon,
CheckIcon,
ChevronDownIcon,
ChevronRightIcon,
CircleAlertIcon,
CircleCheckIcon,
CircleDashedIcon,
@@ -101,6 +100,11 @@ import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoute
import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat";
import type { SidebarThreadSummary } from "../types";
import { cn } from "~/lib/utils";
import {
groupThreadsByWorkspaceTask,
taskPresentationThread,
workspaceTaskKey,
} from "../lib/workspaceTasks";
import {
formatWorkingDurationLabel,
firstValidTimestampMs,
@@ -365,6 +369,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
// When a snooze ended (timer or early wake); drives the Woke pill until
// the user visits the thread.
wokeAt: string | null;
tabCount: number;
isActive: boolean;
jumpLabel: string | null;
currentEnvironmentId: string | null;
@@ -766,6 +771,14 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
/>
</span>
{title}
{props.tabCount > 1 ? (
<span
className="shrink-0 rounded bg-sidebar-accent px-1.5 font-mono text-[10px] text-sidebar-muted-foreground"
aria-label={`${props.tabCount} task tabs`}
>
{props.tabCount}
</span>
) : null}
{/* The PR badge stays outside the hover-fading slot: it must
remain visible AND clickable while the row is hovered. Only
the time/jump label yields to the settle affordance. */}
@@ -941,7 +954,17 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
) : null}
</span>
</div>
<div className="mt-1 flex min-w-0">{title}</div>
<div className="mt-1 flex min-w-0 items-center gap-1.5">
{title}
{props.tabCount > 1 ? (
<span
className="shrink-0 rounded bg-sidebar-accent px-1.5 font-mono text-[10px] text-sidebar-muted-foreground"
aria-label={`${props.tabCount} task tabs`}
>
{props.tabCount}
</span>
) : null}
</div>
<div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground/75">
{thread.branch ? (
<span className="min-w-0 flex-1 truncate whitespace-nowrap">{thread.branch}</span>
@@ -1056,6 +1079,34 @@ export default function SidebarV2() {
});
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null;
const routeTaskKey = useMemo(() => {
if (routeThreadKey === null) return null;
const routeThread = threads.find(
(thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
);
return routeThread ? workspaceTaskKey(routeThread) : null;
}, [routeThreadKey, threads]);
const taskTabCountByKey = useMemo(
() =>
new Map(
groupThreadsByWorkspaceTask(threads.filter((thread) => thread.tabClosedAt == null)).map(
(task) => [task.key, task.tabs.length] as const,
),
),
[threads],
);
const taskTabsByThreadKey = useMemo(() => {
const mapping = new Map<string, ReadonlyArray<EnvironmentThreadShell>>();
for (const task of groupThreadsByWorkspaceTask(
threads.filter((thread) => thread.tabClosedAt == null),
)) {
for (const tab of task.tabs) {
mapping.set(scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id)), task.tabs);
}
}
return mapping;
}, [threads]);
const routeTargetRef = useRef(routeTarget);
routeTargetRef.current = routeTarget;
// Post-settle navigation validates against the CURRENT route, not the one
@@ -1368,13 +1419,15 @@ export default function SidebarV2() {
const visible = threads.filter(
(thread) =>
thread.archivedAt === null &&
thread.tabClosedAt == null &&
(scopedProjectKeys === null ||
scopedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`)),
);
const active: EnvironmentThreadShell[] = [];
const snoozed: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
for (const thread of visible) {
for (const task of groupThreadsByWorkspaceTask(visible)) {
const thread = taskPresentationThread(task, routeThreadKey);
// Threads on servers without the settlement capability (old server,
// or descriptor not loaded yet) never classify as settled: the user
// could neither un-settle nor pin them, so auto-settling them would
@@ -1383,17 +1436,22 @@ export default function SidebarV2() {
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSettlement === true;
const supportsSnooze =
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true;
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
const tabStates = task.tabs.map((tab) => {
const threadKey = scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id));
const changeRequestState = changeRequestStateByKey.get(threadKey) ?? null;
return {
snoozed: supportsSnooze && effectiveSnoozed(tab, { now: preciseNow }),
settled:
supportsSettlement &&
effectiveSettled(tab, { now, autoSettleAfterDays, changeRequestState }),
};
});
// Snooze outranks settled classification: an explicitly snoozed thread
// belongs to the shelf even if it would also auto-settle (the shelf's
// wake time is a stronger statement about when it matters again).
if (supportsSnooze && effectiveSnoozed(thread, { now: preciseNow })) {
if (tabStates.every((state) => state.snoozed)) {
snoozed.push(thread);
} else if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
) {
} else if (tabStates.every((state) => state.settled)) {
settled.push(thread);
} else {
active.push(thread);
@@ -1418,6 +1476,7 @@ export default function SidebarV2() {
serverConfigs,
snoozeWakeTick,
threads,
routeThreadKey,
]);
// Arm a timeout for the earliest upcoming wake so the shelf empties the
@@ -1455,17 +1514,14 @@ export default function SidebarV2() {
// The open thread must never hide under "Show more": navigating into a
// deep settled thread (search, deep link) pulls its row into the visible
// tail so the highlight and the un-settle affordance stay reachable.
if (routeThreadKey !== null) {
if (routeTaskKey !== null) {
const routeThread = settledThreads
.slice(settledVisibleCount)
.find(
(thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
);
.find((thread) => workspaceTaskKey(thread) === routeTaskKey);
if (routeThread !== undefined) visible.push(routeThread);
}
return visible;
}, [routeThreadKey, settledThreads, settledVisibleCount]);
}, [routeTaskKey, settledThreads, settledVisibleCount]);
const hiddenSettledCount = settledThreads.length - visibleSettledThreads.length;
const showMoreSettled = useCallback(
() => setSettledVisibleCount((count) => count + SETTLED_TAIL_PAGE_COUNT),
@@ -1475,13 +1531,12 @@ export default function SidebarV2() {
const toggleSettledShelf = useCallback(() => setSettledShelfExpanded((value) => !value), []);
const renderedSettledThreads = useMemo(() => {
if (settledShelfExpanded) return visibleSettledThreads;
if (routeThreadKey === null) return [];
if (routeTaskKey === null) return [];
const routeThread = visibleSettledThreads.find(
(thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
(thread) => workspaceTaskKey(thread) === routeTaskKey,
);
return routeThread === undefined ? [] : [routeThread];
}, [routeThreadKey, settledShelfExpanded, visibleSettledThreads]);
}, [routeTaskKey, settledShelfExpanded, visibleSettledThreads]);
// The snoozed shelf is collapsed by default: out of the way, never gone.
// Collapsed threads don't render (and so don't participate in jump
@@ -1494,13 +1549,10 @@ export default function SidebarV2() {
// snoozed thread reached by route (deep link, open before snoozing
// elsewhere) keeps its row — with highlight and wake affordance — same
// exception the settled tail's "Show more" makes.
if (routeThreadKey === null) return [];
const routeThread = snoozedThreads.find(
(thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === routeThreadKey,
);
if (routeTaskKey === null) return [];
const routeThread = snoozedThreads.find((thread) => workspaceTaskKey(thread) === routeTaskKey);
return routeThread === undefined ? [] : [routeThread];
}, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]);
}, [routeTaskKey, snoozedShelfExpanded, snoozedThreads]);
const orderedThreads = useMemo(
() => [...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads],
@@ -1812,6 +1864,52 @@ export default function SidebarV2() {
},
[attemptUnsnooze, planForwardNavigation, snoozeThread],
);
const taskTabsForRef = useCallback(
(threadRef: ScopedThreadRef) => taskTabsByThreadKey.get(scopedThreadKey(threadRef)) ?? [],
[taskTabsByThreadKey],
);
const attemptSettleTask = useCallback(
(threadRef: ScopedThreadRef) => {
const tabs = taskTabsForRef(threadRef);
const coSettlingKeys = new Set(
tabs.map((tab) => scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id))),
);
for (const tab of tabs) {
attemptSettle(scopeThreadRef(tab.environmentId, tab.id), { coSettlingKeys });
}
},
[attemptSettle, taskTabsForRef],
);
const attemptUnsettleTask = useCallback(
(threadRef: ScopedThreadRef) => {
for (const tab of taskTabsForRef(threadRef)) {
attemptUnsettle(scopeThreadRef(tab.environmentId, tab.id));
}
},
[attemptUnsettle, taskTabsForRef],
);
const attemptSnoozeTask = useCallback(
(threadRef: ScopedThreadRef, preset: SnoozePreset) => {
const tabs = taskTabsForRef(threadRef);
const coSnoozingKeys = new Set(
tabs.map((tab) => scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id))),
);
for (const tab of tabs) {
attemptSnooze(scopeThreadRef(tab.environmentId, tab.id), preset, {
coSnoozingKeys,
});
}
},
[attemptSnooze, taskTabsForRef],
);
const attemptUnsnoozeTask = useCallback(
(threadRef: ScopedThreadRef) => {
for (const tab of taskTabsForRef(threadRef)) {
attemptUnsnooze(scopeThreadRef(tab.environmentId, tab.id));
}
},
[attemptUnsnooze, taskTabsForRef],
);
const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
const handleMultiSelectContextMenu = useCallback(
@@ -1827,13 +1925,20 @@ export default function SidebarV2() {
);
if (threadKeys.length === 0) return;
const count = threadKeys.length;
const selectedTabsByKey = new Map<string, EnvironmentThreadShell>();
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
if (!thread) continue;
const tabs = taskTabsByThreadKey.get(threadKey) ?? [thread];
for (const tab of tabs) {
selectedTabsByKey.set(scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id)), tab);
}
}
const selectedTabEntries = [...selectedTabsByKey.entries()];
// Snooze (N) is offered when every selected thread can actually take
// it — a mixed selection with blocked-on-you work would half-apply.
const selectionNow = new Date().toISOString();
const snoozableThreads = threadKeys.flatMap((threadKey) => {
const thread = threadByKeyRef.current.get(threadKey);
return thread ? [thread] : [];
});
const snoozableThreads = selectedTabEntries.map(([, thread]) => thread);
const canSnoozeSelection = snoozableThreads.every(
(thread) =>
serverConfigs.get(thread.environmentId)?.environment.capabilities.threadSnooze === true &&
@@ -1870,7 +1975,7 @@ export default function SidebarV2() {
if (preset) {
// Post-snooze navigation must skip threads snoozing in this same
// batch — they are all leaving the card block together.
const coSnoozingKeys = new Set(threadKeys);
const coSnoozingKeys = new Set(selectedTabsByKey.keys());
for (const thread of snoozableThreads) {
attemptSnooze(scopeThreadRef(thread.environmentId, thread.id), preset, {
coSnoozingKeys,
@@ -1885,18 +1990,16 @@ export default function SidebarV2() {
// batch — they are all leaving the card block together. Rows that
// are already explicitly settled are skipped: nothing to do on a
// valid mixed selection.
const coSettlingKeys = new Set(threadKeys);
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
if (!thread || thread.settledOverride === "settled") continue;
const coSettlingKeys = new Set(selectedTabsByKey.keys());
for (const [, thread] of selectedTabEntries) {
if (thread.settledOverride === "settled") continue;
attemptSettle(scopeThreadRef(thread.environmentId, thread.id), { coSettlingKeys });
}
clearSelection();
return;
}
if (clicked.value === "mark-unread") {
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
for (const [threadKey, thread] of selectedTabEntries) {
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
}
clearSelection();
@@ -1907,8 +2010,8 @@ export default function SidebarV2() {
const confirmed = await settlePromise(() =>
api.dialogs.confirm(
[
`Delete ${count} thread${count === 1 ? "" : "s"}?`,
"This permanently clears conversation history for these threads.",
`Delete ${count} task${count === 1 ? "" : "s"}?`,
"This permanently clears conversation history for every tab in these tasks.",
].join("\n"),
),
);
@@ -1919,9 +2022,7 @@ export default function SidebarV2() {
// really gone, or the first delete would treat still-alive batch mates
// as deleted and remove a worktree they still point at.
const deletedThreadKeys = new Set<string>();
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
if (!thread) continue;
for (const [threadKey, thread] of selectedTabEntries) {
const result = await deleteThread(scopeThreadRef(thread.environmentId, thread.id), {
deletedThreadKeys,
});
@@ -1951,6 +2052,7 @@ export default function SidebarV2() {
markThreadUnread,
removeFromSelection,
serverConfigs,
taskTabsByThreadKey,
],
);
@@ -1967,6 +2069,7 @@ export default function SidebarV2() {
}
const thread = threadByKeyRef.current.get(threadKey);
if (!thread) return;
const taskTabs = taskTabsForRef(threadRef);
// Un-settle works on every settled row: for explicit settles it
// clears the override, for auto-settled rows it pins the thread
// active until real activity clears the pin. Environments without
@@ -1994,8 +2097,8 @@ export default function SidebarV2() {
...(supportsSettlement
? [
isSettled
? { id: "unsettle", label: "Un-settle thread" }
: { id: "settle", label: "Settle thread" },
? { id: "unsettle", label: "Un-settle task" }
: { id: "settle", label: "Settle task" },
]
: []),
...(supportsSnooze
@@ -2013,9 +2116,9 @@ export default function SidebarV2() {
},
]
: []),
{ id: "rename", label: "Rename thread" },
{ id: "rename", label: "Rename task" },
{ id: "mark-unread", label: "Mark unread" },
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
{ id: "delete", label: "Delete task", destructive: true, icon: "trash" },
],
position,
),
@@ -2025,7 +2128,7 @@ export default function SidebarV2() {
const preset = snoozePresets.find(
(candidate) => `snooze:${candidate.id}` === clicked.value,
);
if (preset) attemptSnooze(threadRef, preset);
if (preset) attemptSnoozeTask(threadRef, preset);
return;
}
switch (clicked.value) {
@@ -2053,43 +2156,53 @@ export default function SidebarV2() {
return;
}
case "settle":
attemptSettle(threadRef);
attemptSettleTask(threadRef);
return;
case "unsettle":
attemptUnsettle(threadRef);
attemptUnsettleTask(threadRef);
return;
case "unsnooze":
attemptUnsnooze(threadRef);
attemptUnsnoozeTask(threadRef);
return;
case "rename":
startThreadRename(threadRef, thread.title);
return;
case "mark-unread":
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
for (const tab of taskTabs) {
markThreadUnread(
scopedThreadKey(scopeThreadRef(tab.environmentId, tab.id)),
tab.latestTurn?.completedAt,
);
}
return;
case "delete": {
if (confirmThreadDelete) {
const confirmed = await settlePromise(() =>
api.dialogs.confirm(
[
`Delete thread "${thread.title}"?`,
"This permanently clears conversation history for this thread.",
`Delete task "${thread.title}" and its ${taskTabs.length} tab${taskTabs.length === 1 ? "" : "s"}?`,
"This permanently clears conversation history for every tab in the task.",
].join("\n"),
),
);
if (confirmed._tag === "Failure" || !confirmed.value) return;
}
const result = await deleteThread(threadRef);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
return;
const deletedThreadKeys = new Set<string>();
for (const tab of taskTabs) {
const tabRef = scopeThreadRef(tab.environmentId, tab.id);
const result = await deleteThread(tabRef, { deletedThreadKeys });
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete task",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
return;
}
deletedThreadKeys.add(scopedThreadKey(tabRef));
}
return;
}
@@ -2099,16 +2212,17 @@ export default function SidebarV2() {
})();
},
[
attemptSettle,
attemptSnooze,
attemptUnsettle,
attemptUnsnooze,
attemptSettleTask,
attemptSnoozeTask,
attemptUnsettleTask,
attemptUnsnoozeTask,
confirmThreadDelete,
deleteThread,
handleMultiSelectContextMenu,
markThreadUnread,
serverConfigs,
startThreadRename,
taskTabsForRef,
],
);
@@ -2221,7 +2335,7 @@ export default function SidebarV2() {
<SidebarMenuButton
size="sm"
type="button"
aria-label="Search threads and commands"
aria-label="Search tasks and commands"
className="h-8 gap-2 rounded-md border-0 bg-transparent px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
data-testid="command-palette-trigger"
/>
@@ -2246,7 +2360,7 @@ export default function SidebarV2() {
className="relative size-8 justify-center rounded-md border-0 bg-transparent p-0 text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
onClick={handleNewThreadClick}
disabled={projects.length === 0}
aria-label="New thread"
aria-label="New task"
/>
}
>
@@ -2257,7 +2371,7 @@ export default function SidebarV2() {
/>
</TooltipTrigger>
<TooltipPopup side="right">
{newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"}
{newThreadShortcutLabel ? `New task (${newThreadShortcutLabel})` : "New task"}
</TooltipPopup>
</Tooltip>
</div>
@@ -2268,7 +2382,7 @@ export default function SidebarV2() {
<div className="flex items-center gap-1">
<Menu open={projectScopeMenuOpen} onOpenChange={setProjectScopeMenuOpen}>
<MenuTrigger
aria-label="Filter threads by project"
aria-label="Filter tasks by project"
className="flex h-8 min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md px-2 text-left text-sm font-medium text-sidebar-muted-foreground outline-none hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
>
{scopedProjectGroup ? (
@@ -2417,7 +2531,8 @@ export default function SidebarV2() {
// the wake signal must survive the trip. Still-snoozed
// rows resolve to null on their own.
wokeAt={threadWokeAt(thread, { now: snoozeNow })}
isActive={routeThreadKey === threadKey}
tabCount={taskTabCountByKey.get(workspaceTaskKey(thread)) ?? 1}
isActive={routeTaskKey === workspaceTaskKey(thread)}
jumpLabel={showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null}
currentEnvironmentId={primaryEnvironmentId}
environmentLabel={environmentLabelById.get(thread.environmentId) ?? null}
@@ -2439,10 +2554,10 @@ export default function SidebarV2() {
isRenaming={renamingThreadKey === threadKey}
renamingTitle={renamingThreadKey === threadKey ? renamingTitle : ""}
onContextMenu={handleThreadContextMenu}
onSettle={attemptSettle}
onUnsettle={attemptUnsettle}
onSnooze={attemptSnooze}
onUnsnooze={attemptUnsnooze}
onSettle={attemptSettleTask}
onUnsettle={attemptUnsettleTask}
onSnooze={attemptSnoozeTask}
onUnsnooze={attemptUnsnoozeTask}
onChangeRequestState={handleChangeRequestState}
/>
);
@@ -2544,9 +2659,9 @@ export default function SidebarV2() {
</button>
</>
) : scopedProjectGroup ? (
`No threads in ${scopedProjectGroup.displayName} yet`
`No tasks in ${scopedProjectGroup.displayName} yet`
) : (
"No threads yet"
"No tasks yet"
)}
</div>
) : null}
@@ -0,0 +1,139 @@
import { GitForkIcon, PlusIcon, XIcon } from "lucide-react";
import { useState } from "react";
import { shortcutLabelForCommand } from "../keybindings";
import { useClientSettings } from "../hooks/useSettings";
import { type WorkspaceTaskTab, useWorkspaceTaskTabs } from "../hooks/useWorkspaceTaskTabs";
import { cn } from "../lib/utils";
import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
function tabStatusClass(tab: WorkspaceTaskTab): string {
if (tab.blocked) return "bg-amber-500";
if (tab.working) return "animate-pulse bg-sky-500 motion-reduce:animate-none";
return "bg-muted-foreground/35";
}
export function WorkspaceTaskTabs() {
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
const { tabs, keybindings, hasTask, canForkContext, createTab, closeTab, navigateToTab } =
useWorkspaceTaskTabs();
const [creatingMode, setCreatingMode] = useState<"fresh" | "portable" | null>(null);
if (!sidebarV2Enabled || !hasTask) return null;
const newTabShortcut = shortcutLabelForCommand(keybindings, "chat.newTab");
const workingCount = tabs.filter((tab) => tab.working).length;
const create = (mode: "fresh" | "portable") => {
if (creatingMode !== null) return;
setCreatingMode(mode);
void createTab(mode).finally(() => setCreatingMode(null));
};
return (
<TooltipProvider delay={250} closeDelay={0}>
<nav
aria-label="Task tabs"
data-testid="workspace-task-tabs"
className="flex h-10 shrink-0 items-end gap-1 border-b border-border/70 bg-background px-3 sm:px-5"
>
<div className="flex min-w-0 flex-1 items-end gap-0.5 overflow-x-auto [scrollbar-width:none]">
{tabs.map((tab, index) => (
<div
key={tab.key}
className={cn(
"group/task-tab relative flex h-9 max-w-56 min-w-24 shrink-0 items-center rounded-t-md border border-b-0 px-2.5 text-xs transition-colors",
tab.active
? "border-border bg-card text-foreground shadow-[0_-1px_8px_hsl(var(--foreground)/0.03)]"
: "border-transparent text-muted-foreground hover:bg-muted/60 hover:text-foreground",
)}
>
<button
type="button"
className="flex min-w-0 flex-1 items-center gap-2 text-left outline-none"
onClick={() => void navigateToTab(tab)}
aria-current={tab.active ? "page" : undefined}
>
<span
aria-hidden
className={cn("size-1.5 shrink-0 rounded-full", tabStatusClass(tab))}
/>
<span className="truncate">
{index === 0 && tab.title === "Tab 1" ? "Main" : tab.title}
</span>
{tab.forkProvenance?.mode === "portable" ? (
<GitForkIcon aria-label="Context fork" className="size-3 shrink-0 opacity-50" />
) : null}
</button>
{tabs.length > 1 && tab.position > 0 ? (
<button
type="button"
aria-label={`Close ${tab.title}`}
disabled={tab.working || tab.blocked}
onClick={(event) => {
event.stopPropagation();
void closeTab(tab);
}}
className="ml-1 inline-flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground/50 opacity-0 transition-opacity hover:bg-muted hover:text-foreground focus-visible:opacity-100 disabled:cursor-not-allowed disabled:opacity-20 group-hover/task-tab:opacity-100"
>
<XIcon className="size-3" />
</button>
) : null}
</div>
))}
</div>
<div className="flex h-9 shrink-0 items-center gap-0.5 pb-1">
{workingCount > 0 ? (
<span
role="status"
className={cn(
"mr-1 hidden whitespace-nowrap font-mono text-[10px] sm:inline",
workingCount > 1 ? "text-amber-600 dark:text-amber-400" : "text-sky-600",
)}
title="Agents in this task share one worktree"
>
{workingCount} running · shared tree
</span>
) : null}
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="New task tab"
disabled={creatingMode !== null}
onClick={() => create("fresh")}
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-50"
/>
}
>
<PlusIcon className="size-4" />
</TooltipTrigger>
<TooltipPopup side="bottom">
New tab{newTabShortcut ? ` (${newTabShortcut})` : ""}
</TooltipPopup>
</Tooltip>
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="Fork context into a new task tab"
disabled={!canForkContext || creatingMode !== null}
onClick={() => create("portable")}
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-35"
/>
}
>
<GitForkIcon className="size-3.5" />
</TooltipTrigger>
<TooltipPopup side="bottom">
{canForkContext
? "Fork this tab’s context into a new tab"
: "Send the first message before forking context"}
</TooltipPopup>
</Tooltip>
</div>
</nav>
</TooltipProvider>
);
}
@@ -62,7 +62,7 @@ export function BetaSettingsPanel() {
<SettingsSection title="Beta features">
<SettingsRow
title="Sidebar v2"
description="One flat thread list in creation order. Active work renders as rich cards; settled threads collapse to compact rows. Settling requires an up-to-date server — on older servers threads simply stay active. Switch back any time."
description="Treat sidebar items as tasks. Each task can hold multiple provider tabs that share one worktree; active work renders as rich cards and settled tasks collapse to compact rows. Switch back any time."
control={
<Switch
checked={sidebarV2Enabled}
+41
View File
@@ -12,6 +12,7 @@ import {
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
WorkspaceTaskId,
type ModelSelection,
type ProviderOptionSelection,
} from "@t3tools/contracts";
@@ -850,6 +851,46 @@ describe("composerDraftStore project draft thread mapping", () => {
expect(draftByKey(draftId)).toBeUndefined();
});
it("retains sibling task-tab drafts and their fork metadata when remapping the project", () => {
const store = useComposerDraftStore.getState();
const workspaceTaskId = WorkspaceTaskId.make("task-a");
store.setProjectDraftThreadId(projectRef, draftId, {
threadId,
workspaceTaskId,
tabPosition: 0,
retainPreviousDraft: true,
});
store.setPrompt(draftId, "main tab draft");
store.setProjectDraftThreadId(projectRef, otherDraftId, {
threadId: otherThreadId,
workspaceTaskId,
tabPosition: 1,
forkProvenance: {
mode: "portable",
sourceThreadId: threadId,
createdAt: "2026-07-24T00:00:00.000Z",
},
retainPreviousDraft: true,
});
expect(useComposerDraftStore.getState().getDraftThread(draftId)).toMatchObject({
threadId,
workspaceTaskId,
tabPosition: 0,
});
expect(draftByKey(draftId)?.prompt).toBe("main tab draft");
expect(useComposerDraftStore.getState().getDraftThread(otherDraftId)).toMatchObject({
threadId: otherThreadId,
workspaceTaskId,
tabPosition: 1,
forkProvenance: {
mode: "portable",
sourceThreadId: threadId,
},
});
});
it("keeps composer drafts when the thread is still mapped by another project", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
+84 -1
View File
@@ -15,7 +15,9 @@ import {
type ServerProvider,
type ScopedProjectRef,
type ScopedThreadRef,
ThreadForkProvenance,
ThreadId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import {
parseScopedProjectKey,
@@ -55,6 +57,7 @@ import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewC
const isRuntimeMode = Schema.is(RuntimeMode);
const isProviderDriverKind = Schema.is(ProviderDriverKind);
const isReviewCommentContext = Schema.is(ReviewCommentContextSchema);
const isThreadForkProvenance = Schema.is(ThreadForkProvenance);
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
const COMPOSER_DRAFT_STORAGE_VERSION = 8;
@@ -206,6 +209,10 @@ type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState &
const PersistedDraftThreadState = Schema.Struct({
threadId: ThreadId,
workspaceTaskId: Schema.optionalKey(WorkspaceTaskId),
tabLabel: Schema.optionalKey(Schema.NullOr(Schema.String)),
tabPosition: Schema.optionalKey(Schema.Number),
forkProvenance: Schema.optionalKey(Schema.NullOr(ThreadForkProvenance)),
environmentId: Schema.String,
projectId: ProjectId,
logicalProjectKey: Schema.optionalKey(Schema.String),
@@ -285,6 +292,10 @@ export interface ComposerThreadDraftState {
*/
export interface DraftSessionState {
threadId: ThreadId;
workspaceTaskId?: WorkspaceTaskId | undefined;
tabLabel?: string | null | undefined;
tabPosition?: number | undefined;
forkProvenance?: ThreadForkProvenance | null | undefined;
environmentId: EnvironmentId;
projectId: ProjectId;
logicalProjectKey: string;
@@ -359,6 +370,11 @@ interface ComposerDraftStoreState {
startFromOrigin?: boolean;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
workspaceTaskId?: WorkspaceTaskId;
tabLabel?: string | null;
tabPosition?: number;
forkProvenance?: ThreadForkProvenance | null;
retainPreviousDraft?: boolean;
},
) => void;
/** Creates or updates the draft session tracked for a concrete project ref. */
@@ -374,6 +390,11 @@ interface ComposerDraftStoreState {
startFromOrigin?: boolean;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
workspaceTaskId?: WorkspaceTaskId;
tabLabel?: string | null;
tabPosition?: number;
forkProvenance?: ThreadForkProvenance | null;
retainPreviousDraft?: boolean;
},
) => void;
/** Updates mutable draft-session metadata without touching composer content. */
@@ -1331,6 +1352,11 @@ function createDraftThreadState(
startFromOrigin?: boolean;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
workspaceTaskId?: WorkspaceTaskId;
tabLabel?: string | null;
tabPosition?: number;
forkProvenance?: ThreadForkProvenance | null;
retainPreviousDraft?: boolean;
},
): DraftThreadState {
const projectChanged =
@@ -1357,6 +1383,10 @@ function createDraftThreadState(
: options.startFromOrigin;
return {
threadId,
workspaceTaskId: options?.workspaceTaskId ?? existingThread?.workspaceTaskId,
tabLabel: options?.tabLabel ?? existingThread?.tabLabel ?? null,
tabPosition: options?.tabPosition ?? existingThread?.tabPosition ?? 0,
forkProvenance: options?.forkProvenance ?? existingThread?.forkProvenance ?? null,
environmentId: projectRef.environmentId,
projectId: projectRef.projectId,
logicalProjectKey,
@@ -1396,6 +1426,10 @@ function draftThreadsEqual(left: DraftThreadState | undefined, right: DraftThrea
return (
!!left &&
left.threadId === right.threadId &&
left.workspaceTaskId === right.workspaceTaskId &&
left.tabLabel === right.tabLabel &&
left.tabPosition === right.tabPosition &&
Equal.equals(left.forkProvenance, right.forkProvenance) &&
left.environmentId === right.environmentId &&
left.projectId === right.projectId &&
left.logicalProjectKey === right.logicalProjectKey &&
@@ -1524,6 +1558,23 @@ function normalizePersistedDraftThreads(
const normalizedEnvironmentId = environmentId as EnvironmentId;
draftThreadsByThreadKey[threadKey] = {
threadId,
...(typeof candidateDraftThread.workspaceTaskId === "string" &&
candidateDraftThread.workspaceTaskId.length > 0
? {
workspaceTaskId: WorkspaceTaskId.make(candidateDraftThread.workspaceTaskId),
}
: {}),
...(typeof candidateDraftThread.tabLabel === "string"
? { tabLabel: candidateDraftThread.tabLabel }
: {}),
...(typeof candidateDraftThread.tabPosition === "number" &&
Number.isInteger(candidateDraftThread.tabPosition) &&
candidateDraftThread.tabPosition >= 0
? { tabPosition: candidateDraftThread.tabPosition }
: {}),
...(isThreadForkProvenance(candidateDraftThread.forkProvenance)
? { forkProvenance: candidateDraftThread.forkProvenance }
: {}),
environmentId: normalizedEnvironmentId,
projectId: projectId as ProjectId,
logicalProjectKey:
@@ -1907,9 +1958,32 @@ function partializeComposerDraftStoreState(
};
persistedDraftsByThreadKey[threadKey] = persistedDraft;
}
const persistedDraftThreadsByThreadKey = Object.fromEntries(
Object.entries(state.draftThreadsByThreadKey).map(([draftId, draft]) => [
draftId,
{
threadId: draft.threadId,
...(draft.workspaceTaskId !== undefined ? { workspaceTaskId: draft.workspaceTaskId } : {}),
...(draft.tabLabel !== undefined ? { tabLabel: draft.tabLabel } : {}),
...(draft.tabPosition !== undefined ? { tabPosition: draft.tabPosition } : {}),
...(draft.forkProvenance !== undefined ? { forkProvenance: draft.forkProvenance } : {}),
environmentId: draft.environmentId,
projectId: draft.projectId,
logicalProjectKey: draft.logicalProjectKey,
createdAt: draft.createdAt,
runtimeMode: draft.runtimeMode,
interactionMode: draft.interactionMode,
branch: draft.branch,
worktreePath: draft.worktreePath,
envMode: draft.envMode,
startFromOrigin: draft.startFromOrigin,
...(draft.promotedTo !== undefined ? { promotedTo: draft.promotedTo } : {}),
},
]),
) as PersistedComposerDraftStoreState["draftThreadsByThreadKey"];
return {
draftsByThreadKey: persistedDraftsByThreadKey,
draftThreadsByThreadKey: state.draftThreadsByThreadKey,
draftThreadsByThreadKey: persistedDraftThreadsByThreadKey,
logicalProjectDraftThreadKeyByLogicalProjectKey:
state.logicalProjectDraftThreadKeyByLogicalProjectKey,
stickyModelSelectionByProvider: compactModelSelectionByProvider(
@@ -2149,6 +2223,10 @@ function toHydratedDraftThreadState(
): DraftThreadState {
return {
threadId: persistedDraftThread.threadId,
workspaceTaskId: persistedDraftThread.workspaceTaskId,
tabLabel: persistedDraftThread.tabLabel ?? null,
tabPosition: persistedDraftThread.tabPosition ?? 0,
forkProvenance: persistedDraftThread.forkProvenance ?? null,
environmentId: persistedDraftThread.environmentId as EnvironmentId,
projectId: persistedDraftThread.projectId,
logicalProjectKey:
@@ -2288,6 +2366,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
if (
previousThreadKeyForLogicalProject &&
previousThreadKeyForLogicalProject !== draftId &&
options?.retainPreviousDraft !== true &&
!isComposerThreadKeyInUse(
nextLogicalProjectDraftThreadKeyByLogicalProjectKey,
previousThreadKeyForLogicalProject,
@@ -2359,6 +2438,10 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
: options.startFromOrigin;
const nextDraftThread: DraftThreadState = {
threadId: existing.threadId,
workspaceTaskId: existing.workspaceTaskId,
tabLabel: existing.tabLabel,
tabPosition: existing.tabPosition,
forkProvenance: existing.forkProvenance,
environmentId: nextProjectRef.environmentId,
projectId: nextProjectRef.projectId,
logicalProjectKey: existing.logicalProjectKey,
+2 -1
View File
@@ -4,7 +4,7 @@ import {
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef } from "@t3tools/contracts";
import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef, WorkspaceTaskId } from "@t3tools/contracts";
import { useParams, useRouter } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import {
@@ -249,6 +249,7 @@ export function useNewThreadHandler() {
return (async () => {
setLogicalProjectDraftThreadId(logicalProjectKey, projectRef, draftId, {
threadId,
workspaceTaskId: WorkspaceTaskId.make(String(threadId)),
createdAt,
branch: options?.branch ?? null,
worktreePath: options?.worktreePath ?? null,
+332
View File
@@ -0,0 +1,332 @@
import { useAtomValue } from "@effect/atom-react";
import {
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import {
type ModelSelection,
type ScopedThreadRef,
type ThreadForkProvenance,
ThreadId,
ProviderInstanceId,
WorkspaceTaskId,
} from "@t3tools/contracts";
import { useParams, useRouter } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import { DraftId, type DraftSessionState, useComposerDraftStore } from "../composerDraftStore";
import {
deriveLogicalProjectKeyFromSettings,
selectProjectGroupingSettings,
} from "../logicalProject";
import { newDraftId, newThreadId } from "../lib/utils";
import { resolveWorkspaceTaskId } from "../lib/workspaceTasks";
import { primaryServerKeybindingsAtom } from "../state/server";
import { threadEnvironment } from "../state/threads";
import { useProjects, useServerConfigs, useThreadShells } from "../state/entities";
import { useAtomCommand } from "../state/use-atom-command";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
import { useClientSettings } from "./useSettings";
export type WorkspaceTaskTab =
| {
readonly kind: "server";
readonly key: string;
readonly threadRef: ScopedThreadRef;
readonly title: string;
readonly modelSelection: ModelSelection;
readonly position: number;
readonly active: boolean;
readonly working: boolean;
readonly blocked: boolean;
readonly forkProvenance: ThreadForkProvenance | null;
}
| {
readonly kind: "draft";
readonly key: string;
readonly draftId: DraftId;
readonly threadId: ThreadId;
readonly title: string;
readonly modelSelection: ModelSelection | null;
readonly position: number;
readonly active: boolean;
readonly working: false;
readonly blocked: false;
readonly forkProvenance: ThreadForkProvenance | null;
};
interface CurrentTaskContext {
readonly environmentId: EnvironmentThreadShell["environmentId"];
readonly projectId: EnvironmentThreadShell["projectId"];
readonly threadId: ThreadId;
readonly workspaceTaskId: WorkspaceTaskId;
readonly branch: string | null;
readonly worktreePath: string | null;
readonly runtimeMode: EnvironmentThreadShell["runtimeMode"];
readonly interactionMode: EnvironmentThreadShell["interactionMode"];
readonly modelSelection: ModelSelection;
readonly logicalProjectKey: string;
readonly sourceIsServer: boolean;
}
function draftTaskId(draft: DraftSessionState): WorkspaceTaskId {
return draft.workspaceTaskId ?? WorkspaceTaskId.make(String(draft.threadId));
}
export function useWorkspaceTaskTabs() {
const router = useRouter();
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const threads = useThreadShells();
const projects = useProjects();
const serverConfigs = useServerConfigs();
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const draftSessions = useComposerDraftStore((state) => state.draftThreadsByThreadKey);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const currentServerThread =
routeTarget?.kind === "server"
? (threads.find(
(thread) =>
thread.environmentId === routeTarget.threadRef.environmentId &&
thread.id === routeTarget.threadRef.threadId,
) ?? null)
: null;
const currentDraft =
routeTarget?.kind === "draft" ? (draftSessions[routeTarget.draftId] ?? null) : null;
const currentProject = currentServerThread
? (projects.find(
(project) =>
project.environmentId === currentServerThread.environmentId &&
project.id === currentServerThread.projectId,
) ?? null)
: currentDraft
? (projects.find(
(project) =>
project.environmentId === currentDraft.environmentId &&
project.id === currentDraft.projectId,
) ?? null)
: null;
const currentContext: CurrentTaskContext | null = currentServerThread
? {
environmentId: currentServerThread.environmentId,
projectId: currentServerThread.projectId,
threadId: currentServerThread.id,
workspaceTaskId: resolveWorkspaceTaskId(currentServerThread),
branch: currentServerThread.branch,
worktreePath: currentServerThread.worktreePath,
runtimeMode: currentServerThread.runtimeMode,
interactionMode: currentServerThread.interactionMode,
modelSelection: currentServerThread.modelSelection,
logicalProjectKey: currentProject
? deriveLogicalProjectKeyFromSettings(currentProject, projectGroupingSettings)
: scopedProjectKey(
scopeProjectRef(currentServerThread.environmentId, currentServerThread.projectId),
),
sourceIsServer: true,
}
: currentDraft && currentProject
? {
environmentId: currentDraft.environmentId,
projectId: currentDraft.projectId,
threadId: currentDraft.threadId,
workspaceTaskId: draftTaskId(currentDraft),
branch: currentDraft.branch,
worktreePath: currentDraft.worktreePath,
runtimeMode: currentDraft.runtimeMode,
interactionMode: currentDraft.interactionMode,
modelSelection: currentProject.defaultModelSelection ?? {
instanceId: ProviderInstanceId.make("codex"),
model: "default",
},
logicalProjectKey: currentDraft.logicalProjectKey,
sourceIsServer: false,
}
: null;
const supportsTaskTabs =
currentContext !== null &&
serverConfigs.get(currentContext.environmentId)?.environment.capabilities.workspaceTaskTabs ===
true;
const tabs = useMemo<ReadonlyArray<WorkspaceTaskTab>>(() => {
if (currentContext === null) return [];
const serverTabs: WorkspaceTaskTab[] = threads.flatMap((thread) => {
if (
thread.environmentId !== currentContext.environmentId ||
resolveWorkspaceTaskId(thread) !== currentContext.workspaceTaskId ||
thread.tabClosedAt != null
) {
return [];
}
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
return [
{
kind: "server",
key: scopedThreadKey(threadRef),
threadRef,
title: thread.tabLabel ?? (thread.tabPosition === 0 ? "Main" : thread.title),
modelSelection: thread.modelSelection,
position: thread.tabPosition ?? 0,
active:
routeTarget?.kind === "server" &&
routeTarget.threadRef.environmentId === thread.environmentId &&
routeTarget.threadRef.threadId === thread.id,
working: thread.session?.status === "running" || thread.session?.status === "starting",
blocked: thread.hasPendingApprovals || thread.hasPendingUserInput,
forkProvenance: thread.forkProvenance ?? null,
},
];
});
const draftTabs: WorkspaceTaskTab[] = Object.entries(draftSessions).flatMap(
([rawDraftId, draft]) => {
if (
draft.environmentId !== currentContext.environmentId ||
draftTaskId(draft) !== currentContext.workspaceTaskId ||
draft.promotedTo != null
) {
return [];
}
const draftId = DraftId.make(rawDraftId);
const composer = useComposerDraftStore.getState().getComposerDraft(draftId);
const activeProvider = composer?.activeProvider ?? null;
const modelSelection = activeProvider
? (composer?.modelSelectionByProvider[activeProvider] ?? null)
: null;
return [
{
kind: "draft",
key: `draft:${draftId}`,
draftId,
threadId: draft.threadId,
title: draft.tabLabel ?? `Tab ${(draft.tabPosition ?? 0) + 1}`,
modelSelection,
position: draft.tabPosition ?? 0,
active: routeTarget?.kind === "draft" && routeTarget.draftId === draftId,
working: false,
blocked: false,
forkProvenance: draft.forkProvenance ?? null,
},
];
},
);
return [...serverTabs, ...draftTabs].toSorted(
(left, right) => left.position - right.position || left.key.localeCompare(right.key),
);
}, [currentContext, draftSessions, routeTarget, threads]);
const navigateToTab = useCallback(
(tab: WorkspaceTaskTab) => {
if (tab.kind === "server") {
return router.navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(tab.threadRef),
});
}
return router.navigate({
to: "/draft/$draftId",
params: { draftId: tab.draftId },
});
},
[router],
);
const createTab = useCallback(
async (mode: "fresh" | "portable" = "fresh") => {
if (currentContext === null || !supportsTaskTabs) return;
if (mode === "portable" && !currentContext.sourceIsServer) return;
const draftId = newDraftId();
const threadId = newThreadId();
const createdAt = new Date().toISOString();
const position = tabs.reduce((max, tab) => Math.max(max, tab.position), -1) + 1;
const forkProvenance: ThreadForkProvenance = {
mode,
sourceThreadId: mode === "portable" ? currentContext.threadId : null,
createdAt,
};
const store = useComposerDraftStore.getState();
const currentComposer =
routeTarget?.kind === "server"
? store.getComposerDraft(routeTarget.threadRef)
: routeTarget?.kind === "draft"
? store.getComposerDraft(routeTarget.draftId)
: null;
const activeProvider = currentComposer?.activeProvider ?? null;
const carriedModelSelection =
(activeProvider ? currentComposer?.modelSelectionByProvider[activeProvider] : undefined) ??
currentContext.modelSelection;
store.setLogicalProjectDraftThreadId(
currentContext.logicalProjectKey,
scopeProjectRef(currentContext.environmentId, currentContext.projectId),
draftId,
{
threadId,
workspaceTaskId: currentContext.workspaceTaskId,
tabPosition: position,
tabLabel: null,
forkProvenance,
createdAt,
branch: currentContext.branch,
worktreePath: currentContext.worktreePath,
envMode: currentContext.worktreePath ? "worktree" : "local",
startFromOrigin: false,
runtimeMode: currentContext.runtimeMode,
interactionMode: currentContext.interactionMode,
retainPreviousDraft: true,
},
);
store.applyStickyState(draftId);
store.setModelSelection(draftId, carriedModelSelection, { replaceOptions: true });
await router.navigate({
to: "/draft/$draftId",
params: { draftId },
});
},
[currentContext, routeTarget, router, supportsTaskTabs, tabs],
);
const closeTab = useCallback(
async (tab: WorkspaceTaskTab) => {
if (tabs.length <= 1 || tab.position === 0 || tab.working || tab.blocked) return;
const index = tabs.findIndex((candidate) => candidate.key === tab.key);
const fallback = tabs[index + 1] ?? tabs[index - 1] ?? null;
if (tab.kind === "draft") {
useComposerDraftStore.getState().clearDraftThread(tab.draftId);
} else {
const result = await updateThreadMetadata({
environmentId: tab.threadRef.environmentId,
input: {
threadId: tab.threadRef.threadId,
tabClosedAt: new Date().toISOString(),
},
});
if (result._tag === "Failure") return;
}
if (tab.active && fallback) {
await navigateToTab(fallback);
}
},
[navigateToTab, tabs, updateThreadMetadata],
);
return {
tabs,
keybindings,
hasTask: currentContext !== null && supportsTaskTabs,
canForkContext: currentContext?.sourceIsServer === true && supportsTaskTabs,
createTab,
closeTab,
navigateToTab,
} as const;
}
+76
View File
@@ -0,0 +1,76 @@
import { describe, expect, it } from "@effect/vitest";
import {
EnvironmentId,
ProjectId,
ProviderInstanceId,
ThreadId,
WorkspaceTaskId,
type OrchestrationThreadShell,
} from "@t3tools/contracts";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { groupThreadsByWorkspaceTask, taskPresentationThread } from "./workspaceTasks";
function makeThread(
id: string,
overrides: Partial<OrchestrationThreadShell & { environmentId: EnvironmentId }> = {},
): EnvironmentThreadShell {
return {
id: ThreadId.make(id),
environmentId: EnvironmentId.make("local"),
projectId: ProjectId.make("project-1"),
title: id,
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: "/tmp/task",
latestTurn: null,
createdAt: "2026-07-24T00:00:00.000Z",
updatedAt: "2026-07-24T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...overrides,
};
}
describe("workspace task grouping", () => {
it("backfills legacy shells to one-task/one-tab groups", () => {
const groups = groupThreadsByWorkspaceTask([makeThread("legacy")]);
expect(groups).toHaveLength(1);
expect(groups[0]?.id).toBe("legacy");
});
it("orders sibling tabs and aggregates task status under the root title", () => {
const taskId = WorkspaceTaskId.make("task-1");
const groups = groupThreadsByWorkspaceTask([
makeThread("child", {
workspaceTaskId: taskId,
title: "Alternative",
tabPosition: 1,
hasPendingApprovals: true,
updatedAt: "2026-07-24T01:00:00.000Z",
}),
makeThread("root", {
workspaceTaskId: taskId,
title: "Task title",
tabPosition: 0,
}),
]);
const group = groups[0]!;
const presentation = taskPresentationThread(group, null);
expect(group.tabs.map((thread) => thread.id)).toEqual(["root", "child"]);
expect(presentation.title).toBe("Task title");
expect(presentation.hasPendingApprovals).toBe(true);
expect(presentation.updatedAt).toBe("2026-07-24T01:00:00.000Z");
});
});
+129
View File
@@ -0,0 +1,129 @@
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
import { WorkspaceTaskId } from "@t3tools/contracts";
export interface WorkspaceTaskGroup {
readonly id: WorkspaceTaskId;
readonly key: string;
readonly tabs: ReadonlyArray<EnvironmentThreadShell>;
readonly root: EnvironmentThreadShell;
}
export function resolveWorkspaceTaskId(
thread: Pick<EnvironmentThreadShell, "id" | "workspaceTaskId">,
): WorkspaceTaskId {
return thread.workspaceTaskId ?? WorkspaceTaskId.make(String(thread.id));
}
export function workspaceTaskKey(
thread: Pick<EnvironmentThreadShell, "environmentId" | "id" | "workspaceTaskId">,
): string {
return `${thread.environmentId}:${resolveWorkspaceTaskId(thread)}`;
}
export function groupThreadsByWorkspaceTask(
threads: ReadonlyArray<EnvironmentThreadShell>,
): ReadonlyArray<WorkspaceTaskGroup> {
const grouped = new Map<string, EnvironmentThreadShell[]>();
for (const thread of threads) {
const key = workspaceTaskKey(thread);
const existing = grouped.get(key);
if (existing) {
existing.push(thread);
} else {
grouped.set(key, [thread]);
}
}
return [...grouped.entries()].map(([key, unsortedTabs]) => {
const tabs = unsortedTabs.toSorted(
(left, right) =>
(left.tabPosition ?? 0) - (right.tabPosition ?? 0) ||
left.createdAt.localeCompare(right.createdAt) ||
left.id.localeCompare(right.id),
);
return {
id: resolveWorkspaceTaskId(tabs[0]!),
key,
tabs,
root: tabs[0]!,
};
});
}
function representativePriority(thread: EnvironmentThreadShell): number {
if (thread.hasPendingApprovals) return 5;
if (thread.hasPendingUserInput) return 4;
if (thread.session?.status === "error") return 3;
if (thread.session?.status === "running" || thread.session?.status === "starting") return 2;
return 1;
}
export function taskPresentationThread(
task: WorkspaceTaskGroup,
activeThreadKey: string | null,
): EnvironmentThreadShell {
const activeTab =
activeThreadKey === null
? null
: (task.tabs.find(
(thread) =>
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)) === activeThreadKey,
) ?? null);
const representative = [...task.tabs].toSorted(
(left, right) =>
representativePriority(right) - representativePriority(left) ||
right.updatedAt.localeCompare(left.updatedAt),
)[0]!;
const source =
activeTab && representativePriority(activeTab) >= representativePriority(representative)
? activeTab
: representative;
const updatedAt = task.tabs.reduce(
(latest, thread) => (thread.updatedAt > latest ? thread.updatedAt : latest),
task.root.updatedAt,
);
const latestUserMessageAt = task.tabs.reduce<string | null>(
(latest, thread) =>
thread.latestUserMessageAt !== null &&
(latest === null || thread.latestUserMessageAt > latest)
? thread.latestUserMessageAt
: latest,
null,
);
return {
...source,
// Task title and workspace identity are owned by the root tab. Status and
// recency are aggregated from every sibling tab.
id: task.root.id,
environmentId: task.root.environmentId,
title: task.root.title,
projectId: task.root.projectId,
branch: task.root.branch,
worktreePath: task.root.worktreePath,
workspaceTaskId: task.id,
tabLabel: null,
tabPosition: 0,
updatedAt,
latestUserMessageAt,
hasPendingApprovals: task.tabs.some((thread) => thread.hasPendingApprovals),
hasPendingUserInput: task.tabs.some((thread) => thread.hasPendingUserInput),
hasActionableProposedPlan: task.tabs.some((thread) => thread.hasActionableProposedPlan),
};
}
export function workspaceTaskTabCountByThread(
tasks: ReadonlyArray<WorkspaceTaskGroup>,
): ReadonlyMap<string, number> {
const counts = new Map<string, number>();
for (const task of tasks) {
for (const thread of task.tabs) {
counts.set(
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)),
task.tabs.length,
);
}
}
return counts;
}
+11
View File
@@ -21,6 +21,7 @@ import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { stackedThreadToast, toastManager } from "~/components/ui/toast";
import { primaryServerKeybindingsAtom } from "~/state/server";
import { useWorkspaceTaskTabs } from "../hooks/useWorkspaceTaskTabs";
function ChatRouteGlobalShortcuts() {
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
@@ -29,6 +30,7 @@ function ChatRouteGlobalShortcuts() {
useHandleNewThread();
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
const workspaceTaskTabs = useWorkspaceTaskTabs();
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const projects = useProjects();
const primaryEnvironmentId = usePrimaryEnvironmentId();
@@ -108,6 +110,14 @@ function ChatRouteGlobalShortcuts() {
return;
}
if (command === "chat.newTab") {
if (!sidebarV2Enabled || !workspaceTaskTabs.hasTask) return;
event.preventDefault();
event.stopPropagation();
void workspaceTaskTabs.createTab("fresh");
return;
}
if (command === "preview.toggle") {
event.preventDefault();
event.stopPropagation();
@@ -169,6 +179,7 @@ function ChatRouteGlobalShortcuts() {
selectedThreadKeysSize,
sidebarV2Enabled,
terminalOpen,
workspaceTaskTabs,
]);
return null;
+2
View File
@@ -29,6 +29,8 @@ const makeEntityId = <Brand extends string>(brand: Brand) => {
export const ThreadId = makeEntityId("ThreadId");
export type ThreadId = typeof ThreadId.Type;
export const WorkspaceTaskId = makeEntityId("WorkspaceTaskId");
export type WorkspaceTaskId = typeof WorkspaceTaskId.Type;
export const ProjectId = makeEntityId("ProjectId");
export type ProjectId = typeof ProjectId.Type;
export const EnvironmentId = makeEntityId("EnvironmentId");
+3
View File
@@ -47,6 +47,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
/** Server understands thread.snooze / thread.unsnooze commands. Same
version-skew contract as threadSettlement. */
threadSnooze: Schema.optionalKey(Schema.Boolean),
/** Server persists workspace-task tab metadata and portable context-fork
provenance. Missing means clients must keep the legacy one-thread UI. */
workspaceTaskTabs: Schema.optionalKey(Schema.Boolean),
/** The update path clients should offer for this server. Absent on
servers that must be relaunched manually (dev checkouts, Windows
foreground runs, pre-update servers). */
+1
View File
@@ -65,6 +65,7 @@ const STATIC_KEYBINDING_COMMANDS = [
"commandPalette.toggle",
"chat.new",
"chat.newLocal",
"chat.newTab",
"editor.openFavorite",
...MODEL_PICKER_KEYBINDING_COMMANDS,
...THREAD_KEYBINDING_COMMANDS,
+30
View File
@@ -19,6 +19,7 @@ import {
ThreadId,
TrimmedNonEmptyString,
TurnId,
WorkspaceTaskId,
} from "./baseSchemas.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
@@ -342,9 +343,28 @@ export const OrchestrationLatestTurn = Schema.Struct({
});
export type OrchestrationLatestTurn = typeof OrchestrationLatestTurn.Type;
export const ThreadForkProvenance = Schema.Struct({
mode: Schema.Literals(["fresh", "portable"]),
sourceThreadId: Schema.NullOr(ThreadId),
createdAt: IsoDateTime,
});
export type ThreadForkProvenance = typeof ThreadForkProvenance.Type;
const ThreadTaskFields = {
// Optional at the wire boundary so a task-aware client remains compatible
// with pre-task servers. New servers always materialize these fields and
// legacy rows are backfilled to one task with one tab.
workspaceTaskId: Schema.optional(WorkspaceTaskId),
tabLabel: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
tabPosition: Schema.optional(NonNegativeInt),
tabClosedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
forkProvenance: Schema.optional(Schema.NullOr(ThreadForkProvenance)),
} as const;
export const OrchestrationThread = Schema.Struct({
id: ThreadId,
projectId: ProjectId,
...ThreadTaskFields,
title: TrimmedNonEmptyString,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
@@ -401,6 +421,7 @@ export type OrchestrationProjectShell = typeof OrchestrationProjectShell.Type;
export const OrchestrationThreadShell = Schema.Struct({
id: ThreadId,
projectId: ProjectId,
...ThreadTaskFields,
title: TrimmedNonEmptyString,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
@@ -546,6 +567,7 @@ const ThreadCreateCommand = Schema.Struct({
commandId: CommandId,
threadId: ThreadId,
projectId: ProjectId,
...ThreadTaskFields,
title: TrimmedNonEmptyString,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
@@ -621,6 +643,9 @@ const ThreadMetaUpdateCommand = Schema.Struct({
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
expectedBranch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
tabLabel: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
tabPosition: Schema.optional(NonNegativeInt),
tabClosedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
});
const ThreadRuntimeModeSetCommand = Schema.Struct({
@@ -641,6 +666,7 @@ const ThreadInteractionModeSetCommand = Schema.Struct({
const ThreadTurnStartBootstrapCreateThread = Schema.Struct({
projectId: ProjectId,
...ThreadTaskFields,
title: TrimmedNonEmptyString,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode,
@@ -940,6 +966,7 @@ export const ProjectDeletedPayload = Schema.Struct({
export const ThreadCreatedPayload = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
...ThreadTaskFields,
title: TrimmedNonEmptyString,
modelSelection: ModelSelection,
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_RUNTIME_MODE))),
@@ -1003,6 +1030,9 @@ export const ThreadMetaUpdatedPayload = Schema.Struct({
modelSelection: Schema.optional(ModelSelection),
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
tabLabel: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
tabPosition: Schema.optional(NonNegativeInt),
tabClosedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
updatedAt: IsoDateTime,
});
+1
View File
@@ -36,6 +36,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ key: "mod+0", command: "preview.resetZoom", when: "previewFocus" },
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+t", command: "chat.newTab", when: "!terminalFocus" },
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
{ key: "mod+shift+m", command: "modelPicker.toggle", when: "!terminalFocus" },