Restore closed server task tabs

This commit is contained in:
Theo Browne committed 2026-07-27 03:15:52 -07:00
1 parent f7bcc489f9
commit 0273d5d63b
16 files changed
+223 -5

No files matched your search

@@ -83,6 +83,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -191,6 +193,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -274,6 +278,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -342,6 +348,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -395,6 +403,8 @@ describe("CheckpointDiffQuery.layer", () => {
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
getClosedTaskTabs: () =>
Effect.die("CheckpointDiffQuery should not request closed task tabs"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -192,6 +192,7 @@ describe("OrchestrationEngine", () => {
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getClosedTaskTabs: () => Effect.succeed([]),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
@@ -468,6 +468,12 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
assert.deepEqual(closedShellSnapshot.threads, []);
const closedThreadShell = yield* snapshotQuery.getThreadShellById(ThreadId.make("thread-1"));
assert.equal(closedThreadShell._tag, "None");
const closedTaskTabs = yield* snapshotQuery.getClosedTaskTabs();
assert.equal(closedTaskTabs.length, 1);
assert.equal(closedTaskTabs[0]?.id, ThreadId.make("thread-1"));
assert.equal(closedTaskTabs[0]?.tabClosedAt, "2026-02-24T00:00:09.000Z");
assert.isNull(closedTaskTabs[0]?.session);
assert.isNull(closedTaskTabs[0]?.latestTurn);
const closedThreadDetail = yield* snapshotQuery.getThreadDetailById(
ThreadId.make("thread-1"),
);
@@ -246,6 +246,39 @@ function mapProjectShellRow(
};
}
function mapThreadShellRow(
row: Schema.Schema.Type<typeof ProjectionThreadDbRowSchema>,
): OrchestrationThreadShell {
return {
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,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
settledOverride: row.settledOverride,
settledAt: row.settledAt,
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
session: null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
};
}
function mapProposedPlanRow(
row: Schema.Schema.Type<typeof ProjectionThreadProposedPlanDbRowSchema>,
): OrchestrationProposedPlan {
@@ -399,6 +432,46 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listClosedTaskTabRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
execute: () =>
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",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
settled_override AS "settledOverride",
settled_at AS "settledAt",
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NULL
AND tab_closed_at IS NOT NULL
ORDER BY tab_closed_at DESC, thread_id ASC
`,
});
const listArchivedThreadRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
@@ -1756,6 +1829,17 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getClosedTaskTabs: ProjectionSnapshotQueryShape["getClosedTaskTabs"] = () =>
listClosedTaskTabRows(undefined).pipe(
Effect.map((rows) => rows.map(mapThreadShellRow)),
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getClosedTaskTabs:query",
"ProjectionSnapshotQuery.getClosedTaskTabs:decodeRows",
),
),
);
const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
listProjectionStateRows(undefined).pipe(
Effect.mapError(
@@ -2166,6 +2250,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getSnapshot,
getShellSnapshot,
getArchivedShellSnapshot,
getClosedTaskTabs,
getSnapshotSequence,
getCounts,
getActiveProjectByWorkspaceRoot,
@@ -94,6 +94,15 @@ export interface ProjectionSnapshotQueryShape {
ProjectionRepositoryError
>;
/**
* Read closed, non-archived task-tab shells so clients can offer restore
* without bootstrapping them into normal navigation state.
*/
readonly getClosedTaskTabs: () => Effect.Effect<
ReadonlyArray<OrchestrationThreadShell>,
ProjectionRepositoryError
>;
/**
* Read the latest projection snapshot sequence without hydrating read-model
* entities.
@@ -30,6 +30,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
@@ -196,6 +196,7 @@ describe("ProviderSessionReaper", () => {
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
getCounts: () => Effect.die("unused"),
+10
View File
@@ -5553,11 +5553,16 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
},
],
};
const closedTaskTab = makeDefaultOrchestrationThreadShell({
id: ThreadId.make("thread-closed"),
tabClosedAt: now,
});
yield* buildAppUnderTest({
layers: {
projectionSnapshotQuery: {
getSnapshot: () => Effect.succeed(snapshot),
getClosedTaskTabs: () => Effect.succeed([closedTaskTab]),
},
orchestrationEngine: {
dispatch: () => Effect.succeed({ sequence: 7 }),
@@ -5624,6 +5629,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
),
);
assert.deepEqual(replayResult, []);
const closedTaskTabs = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client[ORCHESTRATION_WS_METHODS.getClosedTaskTabs]({})),
);
assert.deepEqual(closedTaskTabs, [closedTaskTab]);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -81,6 +81,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () =>
Deferred.await(releaseCounts).pipe(
@@ -138,6 +139,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () =>
@@ -194,6 +196,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
@@ -244,6 +247,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets preserves typed UUID generation fa
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getClosedTaskTabs: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
+18
View File
@@ -292,6 +292,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[ORCHESTRATION_WS_METHODS.replayEvents, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.subscribeShell, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.getClosedTaskTabs, AuthOrchestrationReadScope],
[ORCHESTRATION_WS_METHODS.subscribeThread, AuthOrchestrationReadScope],
[WS_METHODS.serverProbe, AuthOrchestrationReadScope],
[WS_METHODS.serverGetConfig, AuthOrchestrationReadScope],
@@ -1362,6 +1363,23 @@ const makeWsRpcLayer = (
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.getClosedTaskTabs]: (_input) =>
observeRpcEffect(
ORCHESTRATION_WS_METHODS.getClosedTaskTabs,
projectionSnapshotQuery.getClosedTaskTabs().pipe(
Effect.tapError((cause) =>
Effect.logError("orchestration closed task tabs load failed", { cause }),
),
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load closed task tabs",
cause,
}),
),
),
{ "rpc.aggregate": "orchestration" },
),
[ORCHESTRATION_WS_METHODS.subscribeThread]: (input) =>
observeRpcStreamEffect(
ORCHESTRATION_WS_METHODS.subscribeThread,
+22 -5
View File
@@ -22,11 +22,12 @@ import {
deriveLogicalProjectKeyFromSettings,
selectProjectGroupingSettings,
} from "../logicalProject";
import { refreshClosedTaskTabsForEnvironment, useClosedTaskTabs } from "../lib/closedTaskTabsState";
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 { readThreadShell, useProjects, useServerConfigs, useThreadShells } from "../state/entities";
import { useAtomCommand } from "../state/use-atom-command";
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
import { useClientSettings } from "./useSettings";
@@ -97,6 +98,16 @@ function draftTaskId(draft: DraftSessionState): WorkspaceTaskId {
return draft.workspaceTaskId ?? WorkspaceTaskId.make(String(draft.threadId));
}
async function waitForThreadShellState(
threadRef: ScopedThreadRef,
expectedToExist: boolean,
): Promise<void> {
const deadline = Date.now() + 3_000;
while ((readThreadShell(threadRef) !== null) !== expectedToExist && Date.now() < deadline) {
await new Promise<void>((resolve) => setTimeout(resolve, 50));
}
}
export function useWorkspaceTaskTabs() {
const router = useRouter();
const routeTarget = useParams({
@@ -177,6 +188,9 @@ export function useWorkspaceTaskTabs() {
currentContext !== null &&
serverConfigs.get(currentContext.environmentId)?.environment.capabilities.workspaceTaskTabs ===
true;
const closedServerTaskTabs = useClosedTaskTabs(
supportsTaskTabs ? currentContext.environmentId : null,
);
const tabs = useMemo<ReadonlyArray<WorkspaceTaskTab>>(() => {
if (currentContext === null) return [];
@@ -247,15 +261,14 @@ export function useWorkspaceTaskTabs() {
const closedTabs = useMemo<ReadonlyArray<ClosedWorkspaceTaskTab>>(() => {
if (currentContext === null) return [];
const serverTabs: ClosedWorkspaceTaskTab[] = threads.flatMap((thread) => {
const serverTabs: ClosedWorkspaceTaskTab[] = closedServerTaskTabs.flatMap((thread) => {
if (
thread.environmentId !== currentContext.environmentId ||
resolveWorkspaceTaskId(thread) !== currentContext.workspaceTaskId ||
thread.tabClosedAt == null
) {
return [];
}
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const threadRef = scopeThreadRef(currentContext.environmentId, thread.id);
return [
{
kind: "server",
@@ -299,7 +312,7 @@ export function useWorkspaceTaskTabs() {
left.position - right.position ||
left.key.localeCompare(right.key),
);
}, [currentContext, draftSessions, threads]);
}, [closedServerTaskTabs, currentContext, draftSessions]);
const navigateToTab = useCallback(
(tab: WorkspaceTaskTab | ClosedWorkspaceTaskTab) => {
@@ -393,6 +406,8 @@ export function useWorkspaceTaskTabs() {
},
});
if (result._tag === "Failure") return;
await waitForThreadShellState(tab.threadRef, false);
refreshClosedTaskTabsForEnvironment(tab.threadRef.environmentId);
}
if (tab.active && fallback) {
await navigateToTab(fallback);
@@ -414,6 +429,8 @@ export function useWorkspaceTaskTabs() {
},
});
if (result._tag === "Failure") return;
await waitForThreadShellState(tab.threadRef, true);
refreshClosedTaskTabsForEnvironment(tab.threadRef.environmentId);
}
await navigateToTab(tab);
},
+32
View File
@@ -0,0 +1,32 @@
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId, OrchestrationThreadShell } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { orchestrationEnvironment } from "../state/orchestration";
const EMPTY_CLOSED_TASK_TABS: ReadonlyArray<OrchestrationThreadShell> = Object.freeze([]);
const EMPTY_CLOSED_TASK_TABS_ATOM = Atom.make(AsyncResult.success(EMPTY_CLOSED_TASK_TABS)).pipe(
Atom.withLabel("web:closed-task-tabs:empty"),
);
function closedTaskTabsAtom(environmentId: EnvironmentId) {
return orchestrationEnvironment.closedTaskTabs({
environmentId,
input: {},
});
}
export function refreshClosedTaskTabsForEnvironment(environmentId: EnvironmentId): void {
appAtomRegistry.refresh(closedTaskTabsAtom(environmentId));
}
export function useClosedTaskTabs(
environmentId: EnvironmentId | null,
): ReadonlyArray<OrchestrationThreadShell> {
const result = useAtomValue(
environmentId === null ? EMPTY_CLOSED_TASK_TABS_ATOM : closedTaskTabsAtom(environmentId),
);
return Option.getOrElse(AsyncResult.value(result), () => EMPTY_CLOSED_TASK_TABS);
}
@@ -20,5 +20,9 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
label: "environment-data:orchestration:archived-shell-snapshot",
tag: ORCHESTRATION_WS_METHODS.getArchivedShellSnapshot,
}),
closedTaskTabs: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:orchestration:closed-task-tabs",
tag: ORCHESTRATION_WS_METHODS.getClosedTaskTabs,
}),
};
}
+2
View File
@@ -93,6 +93,7 @@ import type {
OrchestrationGetTurnDiffInput,
OrchestrationGetTurnDiffResult,
OrchestrationShellSnapshot,
OrchestrationThreadShell,
OrchestrationShellStreamItem,
OrchestrationSubscribeThreadInput,
OrchestrationThreadStreamItem,
@@ -1245,6 +1246,7 @@ export interface EnvironmentApi {
input: OrchestrationGetFullThreadDiffInput,
) => Promise<OrchestrationGetFullThreadDiffResult>;
getArchivedShellSnapshot: () => Promise<OrchestrationShellSnapshot>;
getClosedTaskTabs: () => Promise<ReadonlyArray<OrchestrationThreadShell>>;
subscribeShell: (
callback: (event: OrchestrationShellStreamItem) => void,
options?: {
+8
View File
@@ -29,6 +29,7 @@ export const ORCHESTRATION_WS_METHODS = {
getFullThreadDiff: "orchestration.getFullThreadDiff",
replayEvents: "orchestration.replayEvents",
getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",
getClosedTaskTabs: "orchestration.getClosedTaskTabs",
subscribeShell: "orchestration.subscribeShell",
subscribeThread: "orchestration.subscribeThread",
} as const;
@@ -448,6 +449,9 @@ export const OrchestrationThreadShell = Schema.Struct({
});
export type OrchestrationThreadShell = typeof OrchestrationThreadShell.Type;
export const OrchestrationClosedTaskTabs = Schema.Array(OrchestrationThreadShell);
export type OrchestrationClosedTaskTabs = typeof OrchestrationClosedTaskTabs.Type;
export const OrchestrationShellSnapshot = Schema.Struct({
snapshotSequence: NonNegativeInt,
projects: Schema.Array(OrchestrationProjectShell),
@@ -1422,6 +1426,10 @@ export const OrchestrationRpcSchemas = {
input: Schema.Struct({}),
output: OrchestrationShellSnapshot,
},
getClosedTaskTabs: {
input: Schema.Struct({}),
output: OrchestrationClosedTaskTabs,
},
subscribeThread: {
input: OrchestrationSubscribeThreadInput,
output: OrchestrationThreadStreamItem,
+10
View File
@@ -646,6 +646,15 @@ export const WsOrchestrationGetArchivedShellSnapshotRpc = Rpc.make(
},
);
export const WsOrchestrationGetClosedTaskTabsRpc = Rpc.make(
ORCHESTRATION_WS_METHODS.getClosedTaskTabs,
{
payload: OrchestrationRpcSchemas.getClosedTaskTabs.input,
success: OrchestrationRpcSchemas.getClosedTaskTabs.output,
error: Schema.Union([OrchestrationGetSnapshotError, EnvironmentAuthorizationError]),
},
);
export const WsOrchestrationSubscribeShellRpc = Rpc.make(ORCHESTRATION_WS_METHODS.subscribeShell, {
payload: OrchestrationRpcSchemas.subscribeShell.input,
success: OrchestrationRpcSchemas.subscribeShell.output,
@@ -767,6 +776,7 @@ export const WsRpcGroup = RpcGroup.make(
WsOrchestrationGetFullThreadDiffRpc,
WsOrchestrationReplayEventsRpc,
WsOrchestrationGetArchivedShellSnapshotRpc,
WsOrchestrationGetClosedTaskTabsRpc,
WsOrchestrationSubscribeShellRpc,
WsOrchestrationSubscribeThreadRpc,
);