TypeScript
feat(web): undo settle, snooze and archive, with a mod+z shortcut (#12848)
Julius Marminge5781b5240bd5
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 667eb0e11f6..c9540e4a0a8 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -229,6 +229,8 @@ import {} from "@t3tools/client-runtime/state/subagentRuntime";import { BranchToolbar, type BranchToolbarHandle } from "./BranchToolbar";import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";+import { isEditableFocused } from "../lib/editableFocus";+import { undoLatestThreadAction } from "../hooks/showUndoToast";import ThreadTerminalDrawer from "./ThreadTerminalDrawer";import {AlarmClockIcon,@@ -6647,11 +6649,12 @@ export default function ChatView(props: ChatViewProps) {}, [activeThreadKey, focusComposer, terminalUiState.terminalOpen]);const getShortcutContext = useCallback(- () => ({+ (eventTarget: EventTarget | null = document.activeElement) => ({terminalFocus: getTerminalFocusOwner() !== null,terminalOpen: Boolean(terminalUiState.terminalOpen),previewFocus: isPreviewFocused(),previewOpen: previewPanelOpen,+ editableFocus: isEditableFocused(eventTarget),modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,isWeb: !isElectron,isDesktop: isElectron,@@ -6679,7 +6682,7 @@ export default function ChatView(props: ChatViewProps) {if (event.defaultPrevented && terminalFocusOwner === null) {return;}- const shortcutContext = getShortcutContext();+ const shortcutContext = getShortcutContext(event.target);if (!shortcutContext.terminalFocus &&@@ -6728,6 +6731,17 @@ export default function ChatView(props: ChatViewProps) {return;}+ if (command === "thread.undo") {+ // Only claim the chord when there is an Undo to run; otherwise the+ // page keeps its native behavior for the key.+ if (event.repeat) return;+ if (undoLatestThreadAction()) {+ event.preventDefault();+ event.stopPropagation();+ }+ return;+ }+if (command === "thread.pin") {event.preventDefault();event.stopPropagation();diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex cffe4c7dd0a..23c55fe8ecc 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -208,12 +208,7 @@ import {type TerminalStatusIndicator,useLinkedThreadPullRequest,} from "./ThreadStatusIndicators";-import {- resolveSnoozePresets,- snoozeWakeDescription,- snoozeWakeLabel,- type SnoozePreset,-} from "./Sidebar.snooze";+import { resolveSnoozePresets, snoozeWakeLabel, type SnoozePreset } from "./Sidebar.snooze";import { ProjectFavicon, type ProjectFaviconProject } from "./ProjectFavicon";import { ThreadSearchMatchExcerpt } from "./ThreadSearchMatch";import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";@@ -3082,7 +3077,9 @@ export default function Sidebar() {settlingThreadKeysRef.current.add(threadKey);try {const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys);- const result = await settleThread(threadRef);+ const result = await settleThread(threadRef, {+ undoToast: opts.coSettlingKeys === undefined,+ });if (result._tag === "Failure") {// Never navigate away from a thread that did not settle.if (!isAtomCommandInterrupted(result)) {@@ -3734,7 +3731,9 @@ export default function Sidebar() {// Snoozing the open thread moves you forward, same as settle —// both park the thread you're done with for now.const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys);- const result = await snoozeThread(threadRef, preset.snoozedUntil);+ const result = await snoozeThread(threadRef, preset.snoozedUntil, {+ undoToast: opts.coSnoozingKeys === undefined,+ });if (result._tag === "Failure") {// Never navigate away from a thread that did not snooze.return isAtomCommandInterrupted(result)@@ -3780,23 +3779,9 @@ export default function Sidebar() {);return;}- if (outcome.status !== "success") return;- // Snooze hides the row, so the toast is the only confirmation —- // and the Undo is the escape hatch for a mis-click.- toastManager.add(- stackedThreadToast({- type: "success",- title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`,- timeout: 5_000,- actionProps: {- children: "Undo",- onClick: () => attemptUnsnooze(threadRef),- },- }),- );})();},- [attemptUnsnooze, performSnooze, timestampFormat],+ [performSnooze],);const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);diff --git a/apps/web/src/hooks/showUndoToast.test.ts b/apps/web/src/hooks/showUndoToast.test.tsindex a3798d5dc70..ced0b2bc550 100644--- a/apps/web/src/hooks/showUndoToast.test.ts+++ b/apps/web/src/hooks/showUndoToast.test.ts@@ -3,7 +3,7 @@ import * as Cause from "effect/Cause";import { afterEach, describe, expect, it, vi } from "vite-plus/test";import { toastManager } from "../components/ui/toast";-import { showUndoToast } from "./showUndoToast";+import { showUndoToast, undoLatestThreadAction } from "./showUndoToast";import * as ThreadUndo from "./threadUndo";afterEach(() => vi.restoreAllMocks());@@ -93,3 +93,35 @@ describe("showUndoToast", () => {expect(add).toHaveBeenCalledOnce();});});++describe("undoLatestThreadAction", () => {+ it("runs the newest live Undo once and then reports nothing to undo", () => {+ const { options } = setup();+ const older = vi.fn(async () => AsyncResult.success(undefined));+ const newer = vi.fn(async () => AsyncResult.success(undefined));+ showUndoToast({ ...options, undo: older, claim: ThreadUndo.begin("settle", "env/a") });+ showUndoToast({ ...options, undo: newer, claim: ThreadUndo.begin("snooze", "env/b") });+ expect(undoLatestThreadAction()).toBe(true);+ expect(newer).toHaveBeenCalledOnce();+ expect(older).not.toHaveBeenCalled();+ expect(undoLatestThreadAction()).toBe(true);+ expect(older).toHaveBeenCalledOnce();+ expect(undoLatestThreadAction()).toBe(false);+ });++ it("skips a superseded toast and a closed toast", () => {+ const { add, options } = setup();+ const superseded = vi.fn(async () => AsyncResult.success(undefined));+ const closed = vi.fn(async () => AsyncResult.success(undefined));+ const live = vi.fn(async () => AsyncResult.success(undefined));+ showUndoToast({ ...options, undo: live, claim: ThreadUndo.begin("archive", "env/live") });+ showUndoToast({ ...options, undo: closed, claim: ThreadUndo.begin("archive", "env/closed") });+ add.mock.calls[1]?.[0].onClose?.();+ showUndoToast({ ...options, undo: superseded, claim: ThreadUndo.begin("pin", "env/stale") });+ ThreadUndo.invalidate("pin", "env/stale");+ expect(undoLatestThreadAction()).toBe(true);+ expect(superseded).not.toHaveBeenCalled();+ expect(closed).not.toHaveBeenCalled();+ expect(live).toHaveBeenCalledOnce();+ });+});diff --git a/apps/web/src/hooks/showUndoToast.ts b/apps/web/src/hooks/showUndoToast.tsindex 3b9393f098c..14d532411e7 100644--- a/apps/web/src/hooks/showUndoToast.ts+++ b/apps/web/src/hooks/showUndoToast.ts@@ -7,6 +7,20 @@ import {import { stackedThreadToast, toastManager } from "../components/ui/toast";import type * as ThreadUndo from "./threadUndo";+// Undo toasts still on screen, oldest first, so the `thread.undo` shortcut+// mirrors the newest toast's button without knowing which action it was.+const liveUndos: Array<() => Promise<void> | null> = [];++/** Runs the newest Undo whose claim still holds; false when nothing is left to undo. */+export function undoLatestThreadAction(): boolean {+ // A superseded entry drops itself when tried, so keep going until one+ // runs or the list is empty.+ while (liveUndos.length > 0) {+ if (liveUndos[liveUndos.length - 1]?.() !== null) return true;+ }+ return false;+}+/** Shows a single-use Undo while its thread action still owns the claim. */export function showUndoToast({title,@@ -23,6 +37,7 @@ export function showUndoToast({}) {if (!claim.isCurrent()) return;let undoStarted = false;+ let toastId: string | undefined;const reportFailure = (error: unknown) => {toastManager.add(stackedThreadToast({@@ -32,7 +47,26 @@ export function showUndoToast({}),);};- const toastId = toastManager.add({+ const forget = () => {+ const index = liveUndos.indexOf(run);+ if (index !== -1) liveUndos.splice(index, 1);+ };+ const run = () => {+ forget();+ if (undoStarted || !claim.isCurrent()) return null;+ undoStarted = true;+ claim.finish();+ if (toastId !== undefined) toastManager.close(toastId);+ return undo()+ .then((result) => {+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ reportFailure(squashAtomCommandFailure(result));+ }+ })+ .catch(reportFailure);+ };+ liveUndos.push(run);+ toastId = toastManager.add({...stackedThreadToast({type: "success",title,@@ -41,21 +75,13 @@ export function showUndoToast({actionProps: {children: "Undo",onClick: async () => {- if (undoStarted || !claim.isCurrent()) return;- undoStarted = true;- claim.finish();- toastManager.close(toastId);- try {- const result = await undo();- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- reportFailure(squashAtomCommandFailure(result));- }- } catch (error) {- reportFailure(error);- }+ await run();},},}),- onClose: claim.finish,+ onClose: () => {+ claim.finish();+ forget();+ },});}diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.tsindex b4bf973f023..8a24c5110fa 100644--- a/apps/web/src/hooks/useThreadActionMenu.ts+++ b/apps/web/src/hooks/useThreadActionMenu.ts@@ -11,7 +11,7 @@ import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";import { useRouter } from "@tanstack/react-router";import { useCallback, useMemo } from "react";-import { resolveSnoozePresets, snoozeWakeDescription } from "../components/Sidebar.snooze";+import { resolveSnoozePresets } from "../components/Sidebar.snooze";import {buildThreadActionMenuItems,type ThreadActionMenuId,@@ -162,29 +162,9 @@ export function useThreadActionMenu(input: {: snoozePresets.find((candidate) => `snooze:${candidate.id}` === action);if (!preset) return;const result = await snoozeThread(threadRef, preset.snoozedUntil);- if (result._tag === "Failure") {- if (!isAtomCommandInterrupted(result)) {- failureToast("Failed to snooze thread", squashAtomCommandFailure(result));- }- return;+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {+ failureToast("Failed to snooze thread", squashAtomCommandFailure(result));}- toastManager.add(- stackedThreadToast({- type: "success",- title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`,- timeout: 5_000,- actionProps: {- children: "Undo",- onClick: () => {- void unsnoozeThread(threadRef).then((undone) => {- if (undone._tag === "Failure" && !isAtomCommandInterrupted(undone)) {- failureToast("Failed to wake thread", squashAtomCommandFailure(undone));- }- });- },- },- }),- );return;}const reportFailure = async (diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.tsindex 9a8dfe48c58..40a06ba9676 100644--- a/apps/web/src/hooks/useThreadActions.ts+++ b/apps/web/src/hooks/useThreadActions.ts@@ -15,6 +15,7 @@ import { useRouter } from "@tanstack/react-router";import { useCallback, useMemo, useRef } from "react";import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic";+import { snoozeWakeDescription } from "../components/Sidebar.snooze";import { useComposerDraftStore } from "../composerDraftStore";import { terminalEnvironment } from "../state/terminal";import { appAtomRegistry } from "../rpc/atomRegistry";@@ -222,6 +223,7 @@ export function useThreadActions() {const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);const confirmThreadUnpin = useClientSettings((settings) => settings.confirmThreadUnpin);+ const timestampFormat = useClientSettings((settings) => settings.timestampFormat);const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);const clearProjectDraftThreadById = useComposerDraftStore((store) => store.clearProjectDraftThreadById,@@ -252,6 +254,30 @@ export function useThreadActions() {return resolveThreadRouteRef(currentRouteParams);}, [router]);+ const unarchiveThread = useCallback(+ async (target: ScopedThreadRef, opts: { navigate?: boolean } = {}) => {+ ThreadUndo.invalidate("archive", scopedThreadKey(target));+ const result = await unarchiveThreadMutation({+ environmentId: target.environmentId,+ input: { threadId: target.threadId },+ });+ if (result._tag === "Failure") {+ return result;+ }+ refreshArchivedThreadsForEnvironment(target.environmentId);+ if (opts.navigate) {+ return settlePromise(() =>+ router.navigate({+ to: "/$environmentId/$threadId",+ params: buildThreadRouteParams(target),+ }),+ );+ }+ return result;+ },+ [router, unarchiveThreadMutation],+ );+const archiveThread = useCallback(async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => {const resolved = resolveThreadTarget(target);@@ -272,11 +298,13 @@ export function useThreadActions() {const shouldNavigateToDraft =currentRouteThreadRef?.threadId === threadRef.threadId &¤tRouteThreadRef.environmentId === threadRef.environmentId;+ const action = ThreadUndo.begin("archive", scopedThreadKey(threadRef));const archiveResult = await archiveThreadMutation({environmentId: threadRef.environmentId,input: { threadId: threadRef.threadId },});if (archiveResult._tag === "Failure") {+ action.finish();return archiveResult;}const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });@@ -285,6 +313,14 @@ export function useThreadActions() {}refreshArchivedThreadsForEnvironment(threadRef.environmentId);opts.onArchived?.();+ showUndoToast({+ title: "Thread archived",+ description: thread.title,+ claim: action,+ // Undo also brings the reader back when archiving moved them to a draft.+ undo: () => unarchiveThread(threadRef, { navigate: shouldNavigateToDraft }),+ failureTitle: "Failed to undo archive",+ });if (shouldNavigateToDraft) {const navigationResult = await settlePromise(() =>@@ -298,21 +334,13 @@ export function useThreadActions() {return archiveResult;},- [archiveThreadMutation, getCurrentRouteThreadRef, markThreadVisited, resolveThreadTarget],- );-- const unarchiveThread = useCallback(- async (target: ScopedThreadRef) => {- const result = await unarchiveThreadMutation({- environmentId: target.environmentId,- input: { threadId: target.threadId },- });- if (result._tag === "Success") {- refreshArchivedThreadsForEnvironment(target.environmentId);- }- return result;- },- [unarchiveThreadMutation],+ [+ archiveThreadMutation,+ getCurrentRouteThreadRef,+ markThreadVisited,+ resolveThreadTarget,+ unarchiveThread,+ ],);const deleteThread = useCallback(@@ -508,38 +536,6 @@ export function useThreadActions() {],);- const settleThread = useCallback(- async (target: ScopedThreadRef) => {- // Version skew: never send the command to a server that predates it —- // the raw protocol rejection would read as a random failure.- if (!readEnvironmentSupportsSettlement(target.environmentId)) {- return AsyncResult.failure(- Cause.fail(- new ThreadSettlementUnsupportedError({- environmentId: target.environmentId,- threadId: target.threadId,- }),- ),- );- }- const resolved = resolveThreadTarget(target);- const wokeAt = resolved- ? threadWokeAt(resolved.thread, { now: new Date().toISOString() })- : null;- // Settle is a high-frequency lifecycle action and stays silent — no- // toast.- const result = await settleThreadMutation({- environmentId: target.environmentId,- input: { threadId: target.threadId },- });- if (result._tag === "Success" && wokeAt !== null) {- markThreadVisited(scopedThreadKey(target), wokeAt);- }- return result;- },- [markThreadVisited, resolveThreadTarget, settleThreadMutation],- );-const unsettleThread = useCallback(async (target: ScopedThreadRef) => {if (!readEnvironmentSupportsSettlement(target.environmentId)) {@@ -552,6 +548,7 @@ export function useThreadActions() {),);}+ ThreadUndo.invalidate("settle", scopedThreadKey(target));// reason "user" pins the thread active: auto-settle (PR merged /// inactivity) stays suppressed until real activity clears the pin.return unsettleThreadMutation({@@ -631,6 +628,89 @@ export function useThreadActions() {[pinThread, unpinThreadMutation],);+ const settleThread = useCallback(+ async (+ target: ScopedThreadRef,+ // Batch callers settle a selection at once and stay silent as before.+ opts: { undoToast?: boolean } = {},+ ) => {+ // Version skew: never send the command to a server that predates it —+ // the raw protocol rejection would read as a random failure.+ if (!readEnvironmentSupportsSettlement(target.environmentId)) {+ return AsyncResult.failure(+ Cause.fail(+ new ThreadSettlementUnsupportedError({+ environmentId: target.environmentId,+ threadId: target.threadId,+ }),+ ),+ );+ }+ const resolved = resolveThreadTarget(target);+ const wokeAt = resolved+ ? threadWokeAt(resolved.thread, { now: new Date().toISOString() })+ : null;+ // Settling also drops the pin and the snooze server-side, so Undo+ // has to put those back as well.+ const pinOrderKey = resolved?.thread.pinnedAt != null ? resolved.thread.pinOrderKey : null;+ const wasPinned = resolved?.thread.pinnedAt != null;+ const snoozedUntil = resolved?.thread.snoozedUntil ?? null;+ // An older unpin/snooze Undo would re-pin or re-snooze, and the server+ // treats either as a promotion that un-settles; settling supersedes them.+ ThreadUndo.invalidate("pin", scopedThreadKey(target));+ ThreadUndo.invalidate("snooze", scopedThreadKey(target));+ const action = ThreadUndo.begin("settle", scopedThreadKey(target));+ const result = await settleThreadMutation({+ environmentId: target.environmentId,+ input: { threadId: target.threadId },+ });+ if (result._tag !== "Success") {+ action.finish();+ return result;+ }+ if (wokeAt !== null) {+ markThreadVisited(scopedThreadKey(target), wokeAt);+ }+ if (opts.undoToast === false) {+ action.finish();+ return result;+ }+ showUndoToast({+ title: "Thread settled",+ description: resolved?.thread.title,+ claim: action,+ undo: async () => {+ const unsettled = await unsettleThread(target);+ if (unsettled._tag !== "Success") return unsettled;+ if (wasPinned) {+ const pinned = await pinThread(+ target,+ pinOrderKey == null ? {} : { orderKey: pinOrderKey },+ );+ if (pinned._tag !== "Success") return pinned;+ }+ if (snoozedUntil !== null) {+ return snoozeThreadMutation({+ environmentId: target.environmentId,+ input: { threadId: target.threadId, snoozedUntil },+ });+ }+ return unsettled;+ },+ failureTitle: "Failed to undo settle",+ });+ return result;+ },+ [+ markThreadVisited,+ pinThread,+ resolveThreadTarget,+ settleThreadMutation,+ snoozeThreadMutation,+ unsettleThread,+ ],+ );+const confirmAndUnpinThread = useCallback(async (target: ScopedThreadRef) => {const localApi = readLocalApi();@@ -695,8 +775,34 @@ export function useThreadActions() {[reorderActiveThreadMutation],);+ const unsnoozeThread = useCallback(+ async (target: ScopedThreadRef) => {+ if (!readEnvironmentSupportsSnooze(target.environmentId)) {+ return AsyncResult.failure(+ Cause.fail(+ new ThreadSnoozeUnsupportedError({+ environmentId: target.environmentId,+ threadId: target.threadId,+ }),+ ),+ );+ }+ ThreadUndo.invalidate("snooze", scopedThreadKey(target));+ return unsnoozeThreadMutation({+ environmentId: target.environmentId,+ input: { threadId: target.threadId, reason: "user" },+ });+ },+ [unsnoozeThreadMutation],+ );+const snoozeThread = useCallback(- async (target: ScopedThreadRef, snoozedUntil: string) => {+ async (+ target: ScopedThreadRef,+ snoozedUntil: string,+ // Batch callers report one toast for the whole selection instead.+ opts: { undoToast?: boolean } = {},+ ) => {// Version skew: never send the command to a server that predates it.if (!readEnvironmentSupportsSnooze(target.environmentId)) {return AsyncResult.failure(@@ -722,32 +828,26 @@ export function useThreadActions() {),);}- return snoozeThreadMutation({+ const action = ThreadUndo.begin("snooze", scopedThreadKey(target));+ const result = await snoozeThreadMutation({environmentId: target.environmentId,input: { threadId: target.threadId, snoozedUntil },});- },- [resolveThreadTarget, snoozeThreadMutation],- );-- const unsnoozeThread = useCallback(- async (target: ScopedThreadRef) => {- if (!readEnvironmentSupportsSnooze(target.environmentId)) {- return AsyncResult.failure(- Cause.fail(- new ThreadSnoozeUnsupportedError({- environmentId: target.environmentId,- threadId: target.threadId,- }),- ),- );+ if (result._tag !== "Success" || opts.undoToast === false) {+ action.finish();+ return result;}- return unsnoozeThreadMutation({- environmentId: target.environmentId,- input: { threadId: target.threadId, reason: "user" },+ // Snooze hides the row, so the toast is the only confirmation.+ showUndoToast({+ title: `Snoozed until ${snoozeWakeDescription(snoozedUntil, new Date(), timestampFormat)}`,+ description: resolved?.thread.title,+ claim: action,+ undo: () => unsnoozeThread(target),+ failureTitle: "Failed to wake thread",});+ return result;},- [unsnoozeThreadMutation],+ [resolveThreadTarget, snoozeThreadMutation, timestampFormat, unsnoozeThread],);const confirmAndDeleteThread = useCallback(diff --git a/apps/web/src/hooks/useThreadActions.undo.test.ts b/apps/web/src/hooks/useThreadActions.undo.test.tsindex 6185a292c57..eacffd146e2 100644--- a/apps/web/src/hooks/useThreadActions.undo.test.ts+++ b/apps/web/src/hooks/useThreadActions.undo.test.ts@@ -1,69 +1,233 @@import { EnvironmentId, ThreadId } from "@t3tools/contracts";-import { afterEach, describe, expect, it, vi } from "vite-plus/test";+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";import { useThreadActions } from "./useThreadActions";import { threadEnvironment } from "../state/threads";import { toastManager } from "../components/ui/toast";-const commands = vi.hoisted(() => ({ pin: vi.fn(), unpin: vi.fn() }));+const commands = vi.hoisted(() => ({+ pin: vi.fn(),+ unpin: vi.fn(),+ archive: vi.fn(),+ unarchive: vi.fn(),+ settle: vi.fn(),+ unsettle: vi.fn(),+ snooze: vi.fn(),+ unsnooze: vi.fn(),+}));+const router = vi.hoisted(() => ({+ navigate: vi.fn(async () => {}),+ state: { matches: [{ params: {} as Record<string, string> }] },+}));vi.mock("react", async (original) => ({...(await original<typeof import("react")>()),useCallback: (callback: unknown) => callback,useMemo: (create: () => unknown) => create(),useRef: (value: unknown) => ({ current: value }),}));-vi.mock("@tanstack/react-router", () => ({ useRouter: () => ({}) }));+vi.mock("@tanstack/react-router", () => ({ useRouter: () => router }));vi.mock("./useSettings", () => ({ useClientSettings: () => false }));vi.mock("./useHandleNewThread", () => ({ useNewThreadHandler: () => vi.fn() }));vi.mock("../composerDraftStore", () => ({ useComposerDraftStore: () => vi.fn() }));vi.mock("../terminalUiStateStore", () => ({ useTerminalUiStateStore: () => vi.fn() }));vi.mock("../uiStateStore", () => ({ useUiStateStore: () => vi.fn() }));+vi.mock("../lib/archivedThreadsState", () => ({ refreshArchivedThreadsForEnvironment: vi.fn() }));+const threadShell = vi.hoisted(() => ({+ title: "Thread",+ pinOrderKey: "a0",+ pinnedAt: null as string | null,+ snoozedUntil: null as string | null,+ projectId: "project",+ environmentId: "undo-env",+ session: null,+}));vi.mock("../state/entities", async (original) => ({...(await original<typeof import("../state/entities")>()),readEnvironmentSupportsPinning: () => true,readEnvironmentSupportsPinReorder: () => true,- readThreadShell: () => ({ title: "Thread", pinOrderKey: "a0" }),+ readEnvironmentSupportsSettlement: () => true,+ readEnvironmentSupportsSnooze: () => true,+ readThreadShell: () => threadShell,}));vi.mock("../state/use-atom-command", () => ({- useAtomCommand: (command: unknown) =>- command === threadEnvironment.pin- ? commands.pin- : command === threadEnvironment.unpin- ? commands.unpin- : vi.fn(),+ useAtomCommand: (command: unknown) => {+ switch (command) {+ case threadEnvironment.pin:+ return commands.pin;+ case threadEnvironment.unpin:+ return commands.unpin;+ case threadEnvironment.archive:+ return commands.archive;+ case threadEnvironment.unarchive:+ return commands.unarchive;+ case threadEnvironment.settle:+ return commands.settle;+ case threadEnvironment.unsettle:+ return commands.unsettle;+ case threadEnvironment.snooze:+ return commands.snooze;+ case threadEnvironment.unsnooze:+ return commands.unsnooze;+ default:+ return vi.fn();+ }+ },}));+const target = {+ environmentId: EnvironmentId.make("undo-env"),+ threadId: ThreadId.make("thread"),+};+const event = {} as Parameters<NonNullable<React.ComponentProps<"button">["onClick"]>>[0];++function undoOf(+ add: { mock: { calls: Array<[Parameters<typeof toastManager.add>[0]]> } },+ index: number,+) {+ const onClick = add.mock.calls[index]?.[0].actionProps?.onClick;+ expect(onClick).toBeTypeOf("function");+ return () => onClick?.(event);+}++beforeEach(() => {+ for (const command of Object.values(commands)) {+ command.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });+ }+ router.navigate.mockClear();+ router.state.matches[0]!.params = {};+ threadShell.pinnedAt = null;+ threadShell.snoozedUntil = null;+});afterEach(() => vi.restoreAllMocks());describe("unpin Undo", () => {it("ignores an old toast across hook instances and still restores the latest unpin", async () => {- commands.pin.mockResolvedValue({ _tag: "Success", value: undefined });- commands.unpin.mockResolvedValue({ _tag: "Success", value: undefined });const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");vi.spyOn(toastManager, "close").mockImplementation(() => {});const sidebar = useThreadActions();const header = useThreadActions();- const target = {- environmentId: EnvironmentId.make("undo-env"),- threadId: ThreadId.make("thread"),- };await sidebar.unpinThread(target);- const staleUndo = add.mock.calls[0]?.[0].actionProps?.onClick;+ const staleUndo = undoOf(add, 0);await header.pinThread(target, { orderKey: "a1" });await header.unpinThread(target);- const latestUndo = add.mock.calls[1]?.[0].actionProps?.onClick;- expect(staleUndo).toBeTypeOf("function");- expect(latestUndo).toBeTypeOf("function");- const event = {} as Parameters<NonNullable<typeof staleUndo>>[0];- staleUndo?.(event);+ const latestUndo = undoOf(add, 1);+ await staleUndo();expect(commands.pin).toHaveBeenCalledTimes(1);- latestUndo?.(event);+ await latestUndo();expect(commands.pin).toHaveBeenCalledTimes(2);expect(commands.pin).toHaveBeenLastCalledWith({environmentId: target.environmentId,input: { threadId: target.threadId, orderKey: "a0" },});- latestUndo?.(event);+ await latestUndo();expect(commands.pin).toHaveBeenCalledTimes(2);});});++describe("archive Undo", () => {+ it("unarchives and returns to the thread when archiving left it", async () => {+ const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");+ vi.spyOn(toastManager, "close").mockImplementation(() => {});+ router.state.matches[0]!.params = {+ environmentId: target.environmentId,+ threadId: target.threadId,+ };+ const actions = useThreadActions();+ await actions.archiveThread(target);+ expect(add).toHaveBeenCalledWith(expect.objectContaining({ title: "Thread archived" }));+ await undoOf(add, 0)();+ expect(commands.unarchive).toHaveBeenCalledExactlyOnceWith({+ environmentId: target.environmentId,+ input: { threadId: target.threadId },+ });+ expect(router.navigate).toHaveBeenCalledWith(+ expect.objectContaining({+ to: "/$environmentId/$threadId",+ params: { environmentId: target.environmentId, threadId: target.threadId },+ }),+ );+ });++ it("stays put when the archived thread was not open", async () => {+ const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");+ vi.spyOn(toastManager, "close").mockImplementation(() => {});+ const actions = useThreadActions();+ await actions.archiveThread(target);+ await undoOf(add, 0)();+ expect(commands.unarchive).toHaveBeenCalledOnce();+ expect(router.navigate).not.toHaveBeenCalled();+ });++ it("shows no Undo when the archive failed", async () => {+ commands.archive.mockResolvedValue({ _tag: "Failure", cause: new Error("nope") });+ const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");+ await useThreadActions().archiveThread(target);+ expect(add).not.toHaveBeenCalled();+ });+});++describe("settle and snooze Undo", () => {+ it("un-settles from the toast and expires the Undo after a manual un-settle", async () => {+ const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");+ vi.spyOn(toastManager, "close").mockImplementation(() => {});+ const actions = useThreadActions();+ await actions.settleThread(target);+ expect(add).toHaveBeenCalledWith(expect.objectContaining({ title: "Thread settled" }));+ const undo = undoOf(add, 0);+ await actions.unsettleThread(target);+ await undo();+ expect(commands.unsettle).toHaveBeenCalledOnce();+ });++ it("re-pins and re-snoozes a thread that settling had cleared", async () => {+ const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");+ vi.spyOn(toastManager, "close").mockImplementation(() => {});+ const snoozedUntil = "2030-01-01T09:00:00.000Z";+ threadShell.pinnedAt = "2026-01-01T00:00:00.000Z";+ threadShell.snoozedUntil = snoozedUntil;+ const actions = useThreadActions();+ await actions.settleThread(target);+ await undoOf(add, 0)();+ expect(commands.unsettle).toHaveBeenCalledOnce();+ expect(commands.pin).toHaveBeenCalledExactlyOnceWith({+ environmentId: target.environmentId,+ input: { threadId: target.threadId, orderKey: "a0" },+ });+ expect(commands.snooze).toHaveBeenCalledExactlyOnceWith({+ environmentId: target.environmentId,+ input: { threadId: target.threadId, snoozedUntil },+ });+ });++ it("expires an older unpin Undo when the thread is settled", async () => {+ const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");+ vi.spyOn(toastManager, "close").mockImplementation(() => {});+ const actions = useThreadActions();+ await actions.unpinThread(target);+ const staleUnpinUndo = undoOf(add, 0);+ await actions.settleThread(target);+ await staleUnpinUndo();+ expect(commands.pin).not.toHaveBeenCalled();+ });++ it("stays silent for batch settles", async () => {+ const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");+ await useThreadActions().settleThread(target, { undoToast: false });+ expect(add).not.toHaveBeenCalled();+ });++ it("wakes the thread from the snooze toast", async () => {+ const add = vi.spyOn(toastManager, "add").mockReturnValue("toast");+ vi.spyOn(toastManager, "close").mockImplementation(() => {});+ const actions = useThreadActions();+ await actions.snoozeThread(target, new Date(Date.now() + 60_000).toISOString());+ expect(add).toHaveBeenCalledWith(+ expect.objectContaining({ title: expect.stringMatching(/^Snoozed until /) }),+ );+ await undoOf(add, 0)();+ expect(commands.unsnooze).toHaveBeenCalledExactlyOnceWith({+ environmentId: target.environmentId,+ input: { threadId: target.threadId, reason: "user" },+ });+ });+});diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.tsindex d9c3eccbeb4..82348be3b6e 100644--- a/apps/web/src/keybindings.test.ts+++ b/apps/web/src/keybindings.test.ts@@ -226,6 +226,33 @@ describe("settle thread shortcut", () => {});});+describe("thread undo shortcut", () => {+ it("resolves mod+z with nothing editable focused", () => {+ assert.equal(+ resolveShortcutCommand(event({ key: "z", metaKey: true }), DEFAULT_RESOLVED_KEYBINDINGS, {+ platform: "MacIntel",+ context: { terminalFocus: false, editableFocus: false },+ }),+ "thread.undo",+ );+ });++ it("leaves native undo alone inside text fields and terminals", () => {+ assert.isNull(+ resolveShortcutCommand(event({ key: "z", ctrlKey: true }), DEFAULT_RESOLVED_KEYBINDINGS, {+ platform: "Win32",+ context: { editableFocus: true },+ }),+ );+ assert.isNull(+ resolveShortcutCommand(event({ key: "z", ctrlKey: true }), DEFAULT_RESOLVED_KEYBINDINGS, {+ platform: "Win32",+ context: { terminalFocus: true },+ }),+ );+ });+});+describe("copy thread reference shortcut", () => {it("resolves Cmd+Shift+C on macOS and Ctrl+Shift+C elsewhere", () => {assert.equal(diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.tsindex 84d325c38d9..b615d356443 100644--- a/apps/web/src/keybindings.ts+++ b/apps/web/src/keybindings.ts@@ -36,6 +36,9 @@ export interface ShortcutMatchContext {previewOpen: boolean;isWeb: boolean;isDesktop: boolean;+ /** A text field, textarea, select or rich-text editor owns the keyboard.+ Optional: only chords that collide with native editing consult it. */+ editableFocus?: boolean;[key: string]: boolean;}@@ -149,6 +152,7 @@ function resolveContext(options: ShortcutMatchOptions | undefined): ShortcutMatcpreviewOpen: false,isWeb: !isElectron,isDesktop: isElectron,+ editableFocus: false,...options?.context,};}diff --git a/apps/web/src/lib/editableFocus.ts b/apps/web/src/lib/editableFocus.tsnew file mode 100644index 00000000000..ad704a39f61--- /dev/null+++ b/apps/web/src/lib/editableFocus.ts@@ -0,0 +1,17 @@+const EDITABLE_SELECTOR = [+ "input",+ "textarea",+ "select",+ '[contenteditable=""]',+ '[contenteditable="true"]',+ '[contenteditable="plaintext-only"]',+ '[role="textbox"]',+].join(",");++/**+ * Whether a text-editing element owns the keyboard. Shortcuts that share+ * their chord with native editing (mod+z) must yield when this is true.+ */+export function isEditableFocused(target: EventTarget | null = document.activeElement): boolean {+ return target instanceof Element && target.closest(EDITABLE_SELECTOR) !== null;+}diff --git a/docs/user/keybindings.md b/docs/user/keybindings.mdindex 9c2f92a3e33..78c792d2985 100644--- a/docs/user/keybindings.md+++ b/docs/user/keybindings.md@@ -84,9 +84,10 @@ Join modifiers and a key with `+`, such as `mod+shift+d` or `ctrl+l`.## When conditionsAvailable context keys are `terminalFocus`, `terminalOpen`, `previewFocus`,-`previewOpen`, `modelPickerOpen`, `isWeb`, and `isDesktop`. `isWeb` is true in a-browser tab. `isDesktop` is true in the desktop app. Unknown keys evaluate to-`false`.+`previewOpen`, `modelPickerOpen`, `editableFocus`, `isWeb`, and `isDesktop`.+`editableFocus` is true while a text field, the composer, or another editor has+the keyboard. `isWeb` is true in a browser tab. `isDesktop` is true in the+desktop app. Unknown keys evaluate to `false`.`mod+1` through `mod+9` jump to the first nine threads, and to models while themodel picker is open. Those defaults use `isDesktop` so they do not steal the@@ -110,6 +111,11 @@ a shortcut.`thread.stop` interrupts the running turn in the focused thread. It has no defaultshortcut; assign one in **Settings → Keybindings**.+`thread.undo` (`mod+z` by default) reverses the most recent thread action that is+still offering **Undo** in a notification, such as an unpin, settle, snooze, or+archive. Its default rule skips text fields and terminals so native undo keeps+working there.+`chat.new` may ask you to choose a project when there is more than one.`chat.newLocal` skips that chooser. Both use your[new-thread defaults](./thread-sidebar.md#start-a-thread).diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.mdindex e921b4c57a4..3d3215a193f 100644--- a/docs/user/thread-sidebar.md+++ b/docs/user/thread-sidebar.md@@ -29,7 +29,11 @@ and worktree while you stay in the new thread composer. This requires a Git projPin a thread from its menu to keep it above your active work.-On web and desktop, unpinning offers Undo for five seconds to restore the thread's pinned position.+On web and desktop, unpinning, settling, snoozing, and archiving a thread each show+a notification with **Undo** for five seconds. Undo restores the thread's previous+state, including its pinned position, and reopens an archived thread you were+viewing. `mod+z` triggers the most recent Undo when no text field is focused; see+[Keybindings](./keybindings.md#commands-with-special-behavior).On web and desktop, you can also drag files from your computer onto any thread row:the thread opens and the files are attached in its composer, ready fordiff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.tsindex 44d76ded170..5093ba9a25a 100644--- a/packages/contracts/src/keybindings.ts+++ b/packages/contracts/src/keybindings.ts@@ -42,6 +42,7 @@ const THREAD_KEYBINDING_COMMANDS = ["thread.copyReference","thread.settle","thread.pin",+ "thread.undo",...THREAD_JUMP_KEYBINDING_COMMANDS,] as const;export type ThreadKeybindingCommand = (typeof THREAD_KEYBINDING_COMMANDS)[number];diff --git a/packages/shared/src/keybindings.ts b/packages/shared/src/keybindings.tsindex d76d4c248a9..ee159b6838a 100644--- a/packages/shared/src/keybindings.ts+++ b/packages/shared/src/keybindings.ts@@ -62,6 +62,7 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [{ key: "mod+shift+c", command: "thread.copyReference", when: "!terminalFocus" },{ key: "mod+shift+s", command: "thread.settle", when: "!terminalFocus" },{ key: "mod+shift+p", command: "thread.pin", when: "!terminalFocus" },+ { key: "mod+z", command: "thread.undo", when: "!terminalFocus && !editableFocus" },...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({key: `mod+${index + 1}`,command,