Polish task tabs and restore closed tabs

This commit is contained in:
Theo Browne committed 2026-07-27 03:02:05 -07:00
1 parent ad25d0b247
commit f7bcc489f9
12 files changed
+392 -157

No files matched your search

+2
View File
@@ -198,6 +198,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("chat.newTab"), "mod+t");
assert.equal(defaultsByCommand.get("chat.reopenClosedTab"), "mod+shift+t");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
+1 -2
View File
@@ -317,8 +317,7 @@ function SidebarV2ThreadTooltip({
<div className="flex min-w-0 items-start gap-2">
<SquareStackIcon aria-hidden className="mt-0.5 size-4 shrink-0 stroke-current" />
<div className="min-w-0 flex-1 wrap-break-word leading-5">
{tabCount} tabs sharing this worktree and branch. Each tab keeps its own
conversation.
{tabCount} tabs · Shared files, separate chats.
</div>
</div>
) : null}
+168 -122
View File
@@ -1,25 +1,52 @@
import { CircleDashedIcon, GitForkIcon, InfoIcon, PlusIcon, XIcon } from "lucide-react";
import {
CircleDashedIcon,
CopyPlusIcon,
HistoryIcon,
PlusIcon,
RotateCcwIcon,
XIcon,
} from "lucide-react";
import { useMemo, useState } from "react";
import { shortcutLabelForCommand } from "../keybindings";
import { useClientSettings } from "../hooks/useSettings";
import { type WorkspaceTaskTab, useWorkspaceTaskTabs } from "../hooks/useWorkspaceTaskTabs";
import {
TASK_TABS_SHARED_SCOPE_EXPLANATION,
type ClosedWorkspaceTaskTab,
type WorkspaceTaskTab,
useWorkspaceTaskTabs,
} from "../hooks/useWorkspaceTaskTabs";
import {
describeTaskTabContexts,
type TaskTabContextDescriptor,
type TaskTabContextSource,
} from "../lib/taskTabContext";
import { cn } from "../lib/utils";
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "./ui/menu";
import { Tooltip, TooltipPopup, TooltipProvider, TooltipTrigger } from "./ui/tooltip";
function tabThreadId(tab: WorkspaceTaskTab): string {
return String(tab.kind === "server" ? tab.threadRef.threadId : tab.threadId);
type AnyWorkspaceTaskTab = WorkspaceTaskTab | ClosedWorkspaceTaskTab;
function tabContextSource(tab: AnyWorkspaceTaskTab): TaskTabContextSource {
return {
kind: tab.kind,
threadId: String(tab.kind === "server" ? tab.threadRef.threadId : tab.threadId),
title: tab.title,
position: tab.position,
forkProvenance: tab.forkProvenance
? {
mode: tab.forkProvenance.mode,
sourceThreadId:
tab.forkProvenance.sourceThreadId === null
? null
: String(tab.forkProvenance.sourceThreadId),
}
: null,
};
}
/**
* State is carried by shape and text as well as hue: blocked tabs get a filled
* ring plus "Waiting on you", working tabs get a dashed spinner glyph. Colour
* is the accent, never the only signal.
* ring plus "Waiting on you", working tabs get a dashed spinner glyph.
*/
function TabStateGlyph(props: { tab: WorkspaceTaskTab }) {
const { tab } = props;
@@ -35,8 +62,6 @@ function TabStateGlyph(props: { tab: WorkspaceTaskTab }) {
);
}
if (tab.working) {
// Duty-cycled steps() pulse from index.css, not a continuous spin: this
// strip can be on screen for hours on a 120Hz display.
return (
<CircleDashedIcon
role="img"
@@ -48,48 +73,60 @@ function TabStateGlyph(props: { tab: WorkspaceTaskTab }) {
return null;
}
function contextChipClass(kind: TaskTabContextDescriptor["kind"], active: boolean): string {
if (!active) return "border-border/30 bg-background/30 text-muted-foreground/60";
return kind === "snapshot"
? "border-border/60 bg-muted/80 text-muted-foreground/90"
: "border-border/45 bg-muted/60 text-muted-foreground/75";
function ContextSummary(props: {
context: TaskTabContextDescriptor;
active: boolean;
className?: string;
}) {
return (
<span
aria-hidden
className={cn(
"hidden shrink-0 truncate text-[10px] font-normal whitespace-nowrap md:inline",
props.active ? "text-muted-foreground/80" : "text-muted-foreground/55",
props.className,
)}
>
· {props.context.label}
</span>
);
}
export function WorkspaceTaskTabs() {
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
const { tabs, keybindings, hasTask, canForkContext, createTab, closeTab, navigateToTab } =
useWorkspaceTaskTabs();
const {
tabs,
closedTabs,
keybindings,
hasTask,
canForkContext,
createTab,
closeTab,
reopenTab,
navigateToTab,
} = useWorkspaceTaskTabs();
const [creatingMode, setCreatingMode] = useState<"fresh" | "portable" | null>(null);
const contexts = useMemo(
() =>
describeTaskTabContexts(
tabs.map((tab) => ({
kind: tab.kind,
threadId: tabThreadId(tab),
title: tab.title,
position: tab.position,
forkProvenance: tab.forkProvenance
? {
mode: tab.forkProvenance.mode,
sourceThreadId:
tab.forkProvenance.sourceThreadId === null
? null
: String(tab.forkProvenance.sourceThreadId),
}
: null,
})),
),
[tabs],
);
const [reopeningKey, setReopeningKey] = useState<string | null>(null);
const contextByTabKey = useMemo(() => {
const allTabs = [...tabs, ...closedTabs];
const contexts = describeTaskTabContexts(allTabs.map(tabContextSource));
return new Map(allTabs.map((tab, index) => [tab.key, contexts[index]!]));
}, [closedTabs, tabs]);
if (!sidebarV2Enabled || !hasTask) return null;
const newTabShortcut = shortcutLabelForCommand(keybindings, "chat.newTab");
const reopenShortcut = shortcutLabelForCommand(keybindings, "chat.reopenClosedTab");
const create = (mode: "fresh" | "portable") => {
if (creatingMode !== null) return;
setCreatingMode(mode);
void createTab(mode).finally(() => setCreatingMode(null));
};
const reopen = (tab: ClosedWorkspaceTaskTab) => {
if (reopeningKey !== null) return;
setReopeningKey(tab.key);
void reopenTab(tab).finally(() => setReopeningKey(null));
};
return (
<TooltipProvider delay={250} closeDelay={0}>
@@ -98,11 +135,9 @@ export function WorkspaceTaskTabs() {
data-testid="workspace-task-tabs"
className="flex h-9 shrink-0 items-center gap-2 border-b border-border/60 bg-background px-3 sm:px-5"
>
{/* One segmented control, not browser chrome: the tabs sit inside a
single inset track so the strip reads as a compact control. */}
<div className="flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto rounded-md bg-muted/40 p-0.5 [scrollbar-width:none]">
{tabs.map((tab, index) => {
const context = contexts[index];
{tabs.map((tab) => {
const context = contextByTabKey.get(tab.key);
return (
<div
key={tab.key}
@@ -125,39 +160,24 @@ export function WorkspaceTaskTabs() {
}
>
<TabStateGlyph tab={tab} />
{tab.forkProvenance?.mode === "portable" ? (
<GitForkIcon aria-hidden className="size-3 shrink-0 opacity-45" />
) : null}
<span className="truncate font-medium">
{context?.title ?? tab.title}
{/* Context stays legible to assistive tech even when the
chip is hidden at narrow widths. */}
{context ? <span className="sr-only"> — {context.label}</span> : null}
</span>
{context ? (
<span
aria-hidden
className={cn(
"hidden max-w-40 shrink-0 truncate rounded-sm border px-1 py-px text-[9px] leading-3.5 font-normal whitespace-nowrap md:inline-block",
contextChipClass(context.kind, tab.active),
)}
>
{context.label}
</span>
) : null}
{context ? <ContextSummary context={context} active={tab.active} /> : null}
</TooltipTrigger>
<TooltipPopup side="bottom" className="max-w-72">
<span className="block px-0.5 py-0.5 text-left leading-relaxed whitespace-normal">
<TooltipPopup side="bottom" className="max-w-56">
<span className="block text-left">
<span className="font-medium text-foreground">
{context?.label ?? "Own context"}
{context?.label ?? "Independent"}
</span>
{context ? (
<span className="mt-0.5 block text-muted-foreground">{context.detail}</span>
<span className="ml-1.5 text-muted-foreground">{context.detail}</span>
) : null}
</span>
</TooltipPopup>
</Tooltip>
{tabs.length > 1 && tab.position > 0 ? (
{tabs.length > 1 ? (
<button
type="button"
aria-label={`Close ${context?.title ?? tab.title}`}
@@ -175,67 +195,93 @@ export function WorkspaceTaskTabs() {
);
})}
</div>
<div className="flex shrink-0 items-center gap-0.5">
<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 empty 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" className="max-w-64">
<span className="block py-0.5 text-left whitespace-normal">
{canForkContext
? "New tab seeded with a one-time snapshot of this tab's conversation"
: "Send the first message before forking context"}
</span>
</TooltipPopup>
</Tooltip>
{/* Stated once for the whole task, so individual tabs don't need to
repeat the shared-worktree / separate-history caveat. */}
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="How task tabs share context"
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground/60 transition-colors hover:bg-muted hover:text-foreground"
/>
}
>
<InfoIcon className="size-3.5" />
</TooltipTrigger>
<TooltipPopup side="bottom" align="end" className="max-w-72">
<span className="block py-0.5 text-left leading-relaxed whitespace-normal">
{TASK_TABS_SHARED_SCOPE_EXPLANATION}
</span>
</TooltipPopup>
</Tooltip>
{closedTabs.length > 0 ? (
<Menu>
<Tooltip>
<TooltipTrigger
render={
<MenuTrigger
render={
<button
type="button"
aria-label="Closed tabs"
className="inline-flex size-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
/>
}
/>
}
>
<HistoryIcon className="size-3.5" />
</TooltipTrigger>
<TooltipPopup side="bottom">
Closed tabs{reopenShortcut ? ` (${reopenShortcut})` : ""}
</TooltipPopup>
</Tooltip>
<MenuPopup align="end" className="min-w-52 max-w-72">
{closedTabs.map((tab, index) => {
const context = contextByTabKey.get(tab.key);
return (
<MenuItem
key={tab.key}
disabled={reopeningKey !== null}
onClick={() => reopen(tab)}
>
<RotateCcwIcon />
<span className="min-w-0 flex-1 truncate">{context?.title ?? tab.title}</span>
{context ? (
<span className="max-w-28 truncate text-xs text-muted-foreground">
{context.label}
</span>
) : null}
{index === 0 && reopenShortcut ? (
<MenuShortcut>{reopenShortcut}</MenuShortcut>
) : null}
</MenuItem>
);
})}
</MenuPopup>
</Menu>
) : null}
<Menu>
<Tooltip>
<TooltipTrigger
render={
<MenuTrigger
render={
<button
type="button"
aria-label="New tab"
disabled={creatingMode !== null}
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>
<MenuPopup align="end" className="min-w-48">
<MenuItem disabled={creatingMode !== null} onClick={() => create("fresh")}>
<PlusIcon />
Empty
{newTabShortcut ? <MenuShortcut>{newTabShortcut}</MenuShortcut> : null}
</MenuItem>
<MenuItem
disabled={!canForkContext || creatingMode !== null}
onClick={() => create("portable")}
>
<CopyPlusIcon />
Copy current context
</MenuItem>
</MenuPopup>
</Menu>
</div>
</nav>
</TooltipProvider>
+49
View File
@@ -898,6 +898,55 @@ describe("composerDraftStore project draft thread mapping", () => {
expect(draftByKey(otherDraftId)?.prompt).toBe("fork tab draft");
});
it("soft-closes and reopens draft tabs without losing composer state", () => {
const store = useComposerDraftStore.getState();
const closedAt = "2026-07-27T12:00:00.000Z";
store.setProjectDraftThreadId(projectRef, draftId, {
threadId,
workspaceTaskId: WorkspaceTaskId.make("task-a"),
tabPosition: 1,
});
store.setPrompt(draftId, "keep this unsent");
store.setDraftThreadContext(draftId, { tabClosedAt: closedAt });
expect(useComposerDraftStore.getState().getDraftThread(draftId)?.tabClosedAt).toBe(closedAt);
expect(draftByKey(draftId)?.prompt).toBe("keep this unsent");
const persistApi = useComposerDraftStore.persist as unknown as {
getOptions: () => {
partialize: (state: ReturnType<typeof useComposerDraftStore.getState>) => unknown;
};
};
const persistedState = persistApi.getOptions().partialize(useComposerDraftStore.getState()) as {
draftThreadsByThreadKey?: Record<string, { tabClosedAt?: string }>;
};
expect(persistedState.draftThreadsByThreadKey?.[draftId]?.tabClosedAt).toBe(closedAt);
store.setDraftThreadContext(draftId, { tabClosedAt: null });
expect(useComposerDraftStore.getState().getDraftThread(draftId)?.tabClosedAt).toBeNull();
expect(draftByKey(draftId)?.prompt).toBe("keep this unsent");
});
it("retains a closed draft when its project mapping moves to another task", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectRef, draftId, {
threadId,
workspaceTaskId: WorkspaceTaskId.make("task-a"),
tabPosition: 1,
});
store.setPrompt(draftId, "restore me later");
store.setDraftThreadContext(draftId, { tabClosedAt: "2026-07-27T12:00:00.000Z" });
store.setProjectDraftThreadId(projectRef, otherDraftId, {
threadId: otherThreadId,
workspaceTaskId: WorkspaceTaskId.make("task-b"),
});
expect(useComposerDraftStore.getState().getDraftThread(draftId)?.tabClosedAt).not.toBeNull();
expect(draftByKey(draftId)?.prompt).toBe("restore me later");
});
it("keeps composer drafts when the thread is still mapped by another project", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectRef, draftId, { threadId });
+22
View File
@@ -213,6 +213,7 @@ const PersistedDraftThreadState = Schema.Struct({
tabLabel: Schema.optionalKey(Schema.NullOr(Schema.String)),
tabPosition: Schema.optionalKey(Schema.Number),
forkProvenance: Schema.optionalKey(Schema.NullOr(ThreadForkProvenance)),
tabClosedAt: Schema.optionalKey(Schema.NullOr(Schema.String)),
environmentId: Schema.String,
projectId: ProjectId,
logicalProjectKey: Schema.optionalKey(Schema.String),
@@ -296,6 +297,7 @@ export interface DraftSessionState {
tabLabel?: string | null | undefined;
tabPosition?: number | undefined;
forkProvenance?: ThreadForkProvenance | null | undefined;
tabClosedAt: string | null;
environmentId: EnvironmentId;
projectId: ProjectId;
logicalProjectKey: string;
@@ -374,6 +376,7 @@ interface ComposerDraftStoreState {
tabLabel?: string | null;
tabPosition?: number;
forkProvenance?: ThreadForkProvenance | null;
tabClosedAt?: string | null;
retainPreviousDraft?: boolean;
},
) => void;
@@ -394,6 +397,7 @@ interface ComposerDraftStoreState {
tabLabel?: string | null;
tabPosition?: number;
forkProvenance?: ThreadForkProvenance | null;
tabClosedAt?: string | null;
retainPreviousDraft?: boolean;
},
) => void;
@@ -409,6 +413,7 @@ interface ComposerDraftStoreState {
startFromOrigin?: boolean;
runtimeMode?: RuntimeMode;
interactionMode?: ProviderInteractionMode;
tabClosedAt?: string | null;
},
) => void;
clearProjectDraftThreadId: (projectRef: ScopedProjectRef) => void;
@@ -1356,6 +1361,7 @@ function createDraftThreadState(
tabLabel?: string | null;
tabPosition?: number;
forkProvenance?: ThreadForkProvenance | null;
tabClosedAt?: string | null;
retainPreviousDraft?: boolean;
},
): DraftThreadState {
@@ -1387,6 +1393,10 @@ function createDraftThreadState(
tabLabel: options?.tabLabel ?? existingThread?.tabLabel ?? null,
tabPosition: options?.tabPosition ?? existingThread?.tabPosition ?? 0,
forkProvenance: options?.forkProvenance ?? existingThread?.forkProvenance ?? null,
tabClosedAt:
options?.tabClosedAt === undefined
? (existingThread?.tabClosedAt ?? null)
: options.tabClosedAt,
environmentId: projectRef.environmentId,
projectId: projectRef.projectId,
logicalProjectKey,
@@ -1430,6 +1440,7 @@ function draftThreadsEqual(left: DraftThreadState | undefined, right: DraftThrea
left.tabLabel === right.tabLabel &&
left.tabPosition === right.tabPosition &&
Equal.equals(left.forkProvenance, right.forkProvenance) &&
left.tabClosedAt === right.tabClosedAt &&
left.environmentId === right.environmentId &&
left.projectId === right.projectId &&
left.logicalProjectKey === right.logicalProjectKey &&
@@ -1575,6 +1586,9 @@ function normalizePersistedDraftThreads(
...(isThreadForkProvenance(candidateDraftThread.forkProvenance)
? { forkProvenance: candidateDraftThread.forkProvenance }
: {}),
...(typeof candidateDraftThread.tabClosedAt === "string"
? { tabClosedAt: candidateDraftThread.tabClosedAt }
: {}),
environmentId: normalizedEnvironmentId,
projectId: projectId as ProjectId,
logicalProjectKey:
@@ -1646,6 +1660,7 @@ function normalizePersistedDraftThreads(
worktreePath: null,
envMode: "local",
startFromOrigin: false,
tabClosedAt: null,
promotedTo: null,
};
} else if (
@@ -1967,6 +1982,7 @@ function partializeComposerDraftStoreState(
...(draft.tabLabel !== undefined ? { tabLabel: draft.tabLabel } : {}),
...(draft.tabPosition !== undefined ? { tabPosition: draft.tabPosition } : {}),
...(draft.forkProvenance !== undefined ? { forkProvenance: draft.forkProvenance } : {}),
...(draft.tabClosedAt !== null ? { tabClosedAt: draft.tabClosedAt } : {}),
environmentId: draft.environmentId,
projectId: draft.projectId,
logicalProjectKey: draft.logicalProjectKey,
@@ -2227,6 +2243,7 @@ function toHydratedDraftThreadState(
tabLabel: persistedDraftThread.tabLabel ?? null,
tabPosition: persistedDraftThread.tabPosition ?? 0,
forkProvenance: persistedDraftThread.forkProvenance ?? null,
tabClosedAt: persistedDraftThread.tabClosedAt ?? null,
environmentId: persistedDraftThread.environmentId as EnvironmentId,
projectId: persistedDraftThread.projectId,
logicalProjectKey:
@@ -2367,11 +2384,13 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
previousDraftThread?.workspaceTaskId !== undefined &&
nextDraftThread.workspaceTaskId !== undefined &&
previousDraftThread.workspaceTaskId === nextDraftThread.workspaceTaskId;
const previousDraftIsClosed = previousDraftThread?.tabClosedAt != null;
if (
previousThreadKeyForLogicalProject &&
previousThreadKeyForLogicalProject !== draftId &&
options?.retainPreviousDraft !== true &&
!sharesWorkspaceTask &&
!previousDraftIsClosed &&
!isComposerThreadKeyInUse(
nextLogicalProjectDraftThreadKeyByLogicalProjectKey,
previousThreadKeyForLogicalProject,
@@ -2447,6 +2466,8 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
tabLabel: existing.tabLabel,
tabPosition: existing.tabPosition,
forkProvenance: existing.forkProvenance,
tabClosedAt:
options.tabClosedAt === undefined ? existing.tabClosedAt : options.tabClosedAt,
environmentId: nextProjectRef.environmentId,
projectId: nextProjectRef.projectId,
logicalProjectKey: existing.logicalProjectKey,
@@ -2475,6 +2496,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
nextDraftThread.createdAt === existing.createdAt &&
nextDraftThread.runtimeMode === existing.runtimeMode &&
nextDraftThread.interactionMode === existing.interactionMode &&
nextDraftThread.tabClosedAt === existing.tabClosedAt &&
nextDraftThread.branch === existing.branch &&
nextDraftThread.worktreePath === existing.worktreePath &&
nextDraftThread.envMode === existing.envMode &&
+113 -5
View File
@@ -58,6 +58,27 @@ export type WorkspaceTaskTab =
readonly forkProvenance: ThreadForkProvenance | null;
};
export type ClosedWorkspaceTaskTab =
| {
readonly kind: "server";
readonly key: string;
readonly threadRef: ScopedThreadRef;
readonly title: string;
readonly position: number;
readonly forkProvenance: ThreadForkProvenance | null;
readonly closedAt: string;
}
| {
readonly kind: "draft";
readonly key: string;
readonly draftId: DraftId;
readonly threadId: ThreadId;
readonly title: string;
readonly position: number;
readonly forkProvenance: ThreadForkProvenance | null;
readonly closedAt: string;
};
interface CurrentTaskContext {
readonly environmentId: EnvironmentThreadShell["environmentId"];
readonly projectId: EnvironmentThreadShell["projectId"];
@@ -191,6 +212,7 @@ export function useWorkspaceTaskTabs() {
if (
draft.environmentId !== currentContext.environmentId ||
draftTaskId(draft) !== currentContext.workspaceTaskId ||
draft.tabClosedAt != null ||
draft.promotedTo != null
) {
return [];
@@ -223,8 +245,64 @@ export function useWorkspaceTaskTabs() {
);
}, [currentContext, draftSessions, routeTarget, threads]);
const closedTabs = useMemo<ReadonlyArray<ClosedWorkspaceTaskTab>>(() => {
if (currentContext === null) return [];
const serverTabs: ClosedWorkspaceTaskTab[] = 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),
position: thread.tabPosition ?? 0,
forkProvenance: thread.forkProvenance ?? null,
closedAt: thread.tabClosedAt,
},
];
});
const draftTabs: ClosedWorkspaceTaskTab[] = Object.entries(draftSessions).flatMap(
([rawDraftId, draft]) => {
if (
draft.environmentId !== currentContext.environmentId ||
draftTaskId(draft) !== currentContext.workspaceTaskId ||
draft.tabClosedAt == null ||
draft.promotedTo != null
) {
return [];
}
const draftId = DraftId.make(rawDraftId);
return [
{
kind: "draft",
key: `draft:${draftId}`,
draftId,
threadId: draft.threadId,
title: draft.tabLabel ?? `Tab ${(draft.tabPosition ?? 0) + 1}`,
position: draft.tabPosition ?? 0,
forkProvenance: draft.forkProvenance ?? null,
closedAt: draft.tabClosedAt,
},
];
},
);
return [...serverTabs, ...draftTabs].toSorted(
(left, right) =>
right.closedAt.localeCompare(left.closedAt) ||
left.position - right.position ||
left.key.localeCompare(right.key),
);
}, [currentContext, draftSessions, threads]);
const navigateToTab = useCallback(
(tab: WorkspaceTaskTab) => {
(tab: WorkspaceTaskTab | ClosedWorkspaceTaskTab) => {
if (tab.kind === "server") {
return router.navigate({
to: "/$environmentId/$threadId",
@@ -247,7 +325,8 @@ export function useWorkspaceTaskTabs() {
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 position =
[...tabs, ...closedTabs].reduce((max, tab) => Math.max(max, tab.position), -1) + 1;
const forkProvenance: ThreadForkProvenance = {
mode,
sourceThreadId: mode === "portable" ? currentContext.threadId : null,
@@ -293,16 +372,18 @@ export function useWorkspaceTaskTabs() {
params: { draftId },
});
},
[currentContext, routeTarget, router, supportsTaskTabs, tabs],
[closedTabs, currentContext, routeTarget, router, supportsTaskTabs, tabs],
);
const closeTab = useCallback(
async (tab: WorkspaceTaskTab) => {
if (tabs.length <= 1 || tab.position === 0 || tab.working || tab.blocked) return;
if (tabs.length <= 1 || 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);
useComposerDraftStore
.getState()
.setDraftThreadContext(tab.draftId, { tabClosedAt: new Date().toISOString() });
} else {
const result = await updateThreadMetadata({
environmentId: tab.threadRef.environmentId,
@@ -320,13 +401,40 @@ export function useWorkspaceTaskTabs() {
[navigateToTab, tabs, updateThreadMetadata],
);
const reopenTab = useCallback(
async (tab: ClosedWorkspaceTaskTab) => {
if (tab.kind === "draft") {
useComposerDraftStore.getState().setDraftThreadContext(tab.draftId, { tabClosedAt: null });
} else {
const result = await updateThreadMetadata({
environmentId: tab.threadRef.environmentId,
input: {
threadId: tab.threadRef.threadId,
tabClosedAt: null,
},
});
if (result._tag === "Failure") return;
}
await navigateToTab(tab);
},
[navigateToTab, updateThreadMetadata],
);
const reopenLastClosedTab = useCallback(async () => {
const lastClosed = closedTabs[0];
if (lastClosed) await reopenTab(lastClosed);
}, [closedTabs, reopenTab]);
return {
tabs,
closedTabs,
keybindings,
hasTask: currentContext !== null && supportsTaskTabs,
canForkContext: currentContext?.sourceIsServer === true && supportsTaskTabs,
createTab,
closeTab,
reopenTab,
reopenLastClosedTab,
navigateToTab,
} as const;
}
+5
View File
@@ -124,6 +124,7 @@ const DEFAULT_BINDINGS = compile([
whenAst: whenNot(whenIdentifier("terminalFocus")),
},
{ shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" },
{ shortcut: modShortcut("t", { shiftKey: true }), command: "chat.reopenClosedTab" },
{ shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" },
{ shortcut: modShortcut("o"), command: "editor.openFavorite" },
{ shortcut: modShortcut("[", { shiftKey: true }), command: "thread.previous" },
@@ -318,6 +319,10 @@ describe("shortcutLabelForCommand", () => {
"⌘B",
);
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O");
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.reopenClosedTab", "MacIntel"),
"⇧⌘T",
);
assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D");
assert.strictEqual(
shortcutLabelForCommand(DEFAULT_BINDINGS, "rightPanel.toggle", "MacIntel"),
+11 -11
View File
@@ -23,8 +23,8 @@ describe("task tab context descriptors", () => {
const [main] = describeTaskTabContexts([tab({ threadId: "root", title: "Tab 1" })]);
expect(main?.title).toBe("Main");
expect(main?.kind).toBe("main");
expect(main?.label).toBe("Own context");
expect(main?.detail).toContain("one-time context fork");
expect(main?.label).toBe("Independent");
expect(main?.detail).toBe("Separate chat history.");
});
it("keeps an explicit tab label on the first tab", () => {
@@ -43,8 +43,8 @@ describe("task tab context descriptors", () => {
}),
]);
expect(draft?.kind).toBe("empty");
expect(draft?.label).toBe("Starts empty");
expect(draft?.detail).toContain("no conversation yet");
expect(draft?.label).toBe("Empty");
expect(draft?.detail).toBe("No chat history.");
});
it("describes a started sibling tab as independent, not shared", () => {
@@ -58,8 +58,8 @@ describe("task tab context descriptors", () => {
}),
]);
expect(started?.kind).toBe("own");
expect(started?.label).toBe("Own context");
expect(started?.detail).toContain("does not follow the other tabs");
expect(started?.label).toBe("Independent");
expect(started?.detail).toBe("Separate chat history.");
});
it("resolves a portable fork's source to the sibling tab label", () => {
@@ -75,8 +75,8 @@ describe("task tab context descriptors", () => {
]);
expect(fork?.kind).toBe("snapshot");
expect(fork?.sourceTitle).toBe("Main");
expect(fork?.label).toBe("Snapshot from Main");
expect(fork?.detail).toContain("bounded snapshot");
expect(fork?.label).toBe("From Main");
expect(fork?.detail).toBe("Copies Main once on send.");
});
it("describes a started fork in the past tense once it owns a thread", () => {
@@ -89,8 +89,8 @@ describe("task tab context descriptors", () => {
forkProvenance: { mode: "portable", sourceThreadId: "root" },
}),
]);
expect(fork?.label).toBe("Snapshot from Main");
expect(fork?.detail).toContain("continued independently");
expect(fork?.label).toBe("From Main");
expect(fork?.detail).toBe("Started from Main; now independent.");
});
it("falls back to a neutral phrase when the source tab is gone", () => {
@@ -103,7 +103,7 @@ describe("task tab context descriptors", () => {
}),
]);
expect(fork?.sourceTitle).toBeNull();
expect(fork?.label).toBe("Snapshot from another tab");
expect(fork?.label).toBe("From other tab");
});
it("never invents message counts", () => {
+11 -17
View File
@@ -28,7 +28,7 @@ export interface TaskTabContextDescriptor {
readonly kind: TaskTabContextKind;
/** Tab name as rendered in the strip. */
readonly title: string;
/** Short chip label, e.g. "Snapshot from Main". */
/** Short inline label, e.g. "From Main". */
readonly label: string;
/** One sentence expanding the label, for tooltips. */
readonly detail: string;
@@ -36,11 +36,7 @@ export interface TaskTabContextDescriptor {
readonly sourceTitle: string | null;
}
/** Shared across every tab of a task, so it is stated once and not per tab. */
export const TASK_TABS_SHARED_SCOPE_EXPLANATION =
"Tabs in this task share the same project, worktree, and branch. Each keeps its own ongoing conversation. A context fork copies one bounded snapshot; it does not keep histories in sync.";
const FALLBACK_SOURCE_TITLE = "another tab";
const FALLBACK_SOURCE_TITLE = "other tab";
/**
* Mirrors the legacy strip fallback: the first tab reads as "Main" even when a
@@ -63,11 +59,11 @@ function describeOne(
return {
...base,
kind: "snapshot",
label: `Snapshot from ${from}`,
label: `From ${from}`,
detail:
tab.kind === "draft"
? `On its first message this tab receives a bounded snapshot of ${from}'s conversation, then continues independently.`
: `Started from a bounded snapshot of ${from}'s conversation and has continued independently since.`,
? `Copies ${from} once on send.`
: `Started from ${from}; now independent.`,
};
}
@@ -75,9 +71,8 @@ function describeOne(
return {
...base,
kind: "empty",
label: "Starts empty",
detail:
"This tab has no conversation yet. Once you send a message its context is its own — no history is carried over.",
label: "Empty",
detail: "No chat history.",
};
}
@@ -85,17 +80,16 @@ function describeOne(
return {
...base,
kind: "main",
label: "Own context",
detail:
"The task's first tab keeps its own conversation. Other tabs only receive it through a one-time context fork.",
label: "Independent",
detail: "Separate chat history.",
};
}
return {
...base,
kind: "own",
label: "Own context",
detail: "This tab keeps an independent conversation and does not follow the other tabs.",
label: "Independent",
detail: "Separate chat history.",
};
}
+8
View File
@@ -118,6 +118,14 @@ function ChatRouteGlobalShortcuts() {
return;
}
if (command === "chat.reopenClosedTab") {
if (!sidebarV2Enabled || workspaceTaskTabs.closedTabs.length === 0) return;
event.preventDefault();
event.stopPropagation();
void workspaceTaskTabs.reopenLastClosedTab();
return;
}
if (command === "preview.toggle") {
event.preventDefault();
event.stopPropagation();
+1
View File
@@ -66,6 +66,7 @@ const STATIC_KEYBINDING_COMMANDS = [
"chat.new",
"chat.newLocal",
"chat.newTab",
"chat.reopenClosedTab",
"editor.openFavorite",
...MODEL_PICKER_KEYBINDING_COMMANDS,
...THREAD_KEYBINDING_COMMANDS,
+1
View File
@@ -37,6 +37,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
{ 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+t", command: "chat.reopenClosedTab", 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" },