Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(workbench): one session action menu everywhere + ⌘⇧D archive (#1165)

Qi Qi1241392de305
diff --git a/docs/plans/workbench-session-action-menu.md b/docs/plans/workbench-session-action-menu.md
new file mode 100644
index 000000000..d10005463
--- /dev/null
+++ b/docs/plans/workbench-session-action-menu.md
@@ -0,0 +1,245 @@
+# Workbench: one session action menu (⋯ everywhere) + ⌘⇧D archive
+
+## Why
+
+The session action set exists in **three places, implemented three times, discovered three
+different ways**:
+
+| Surface | Affordance | Items |
+|---|---|---|
+| Desktop sidebar (`WorkbenchSidebar.tsx` `SessionRow`) | hover **pin** button + **right-click** popover | pin, reference, fork (disabled + tooltip), rename, hide, archive |
+| Mobile projects (`ProjectsPage.tsx` `MobileSessionRow`) | always-visible **⋯** popover | pin, rename, fork (**hidden**), hide, archive — no reference |
+| Chat header (`ChatPage.tsx` `ChatHeaderBar`) | **nothing** | you must leave the chat, find the tree row, and right-click it |
+
+Consequences the user hit directly:
+
+- One arbitrary action (pin) got promoted to a permanent hover button; the other five hide
+ behind right-click, which has no touch equivalent and no visual hint.
+- The surface where you spend all your time (the chat) can't rename, fork, pin, hide or
+ archive the session you are looking at.
+- The two existing menus have already drifted (fork disabled vs. hidden; reference missing),
+ which is exactly the reuse-ladder failure mode CLAUDE.md §6 calls out — third repeat →
+ extract.
+
+## Goal
+
+1. One session-action model, rendered by every surface — sidebar ⋯, sidebar right-click,
+ mobile ⋯, chat header ⋯ — so a new action lands everywhere at once.
+2. Sidebar: pin button → ⋯ menu, without losing the at-a-glance pinned signal.
+3. Chat header: the full menu in the top-right corner.
+4. `⌘⇧D` / `Ctrl+Shift+D` archives the chat session you're reading (via the existing confirm
+ dialog — never a silent destructive keystroke).
+
+## Design
+
+### A. `useSessionActions.tsx` + `sessionActions.tsx` — one model, four render sites
+
+Split in two by the fast-refresh lint policy (a `.tsx` module may export components *or*
+hooks, not both): `useSessionActions.tsx` owns the model and the writes, `sessionActions.tsx`
+owns the descriptor type plus the two presentational pieces (`SessionActionsTrigger`,
+`SessionActionMenu`).
+
+`useSessionActions({ session, projectId, onRenameStart, onOpenSession, onArchived,
+onSessionPatched, archiveHint })` returns:
+
+- `actions: SessionActionDescriptor[]` — ordered, grouped `{ id, group, icon, label, hint,
+ title, disabled, pending, danger, onSelect }`
+- `archiveDialog` — the wired `<ArchiveSessionDialog>` element (open state + confirm live in
+ the hook, so no surface re-wires it)
+- `requestArchive()` — opens that dialog; the keyboard shortcut calls it
+
+Writes go through the existing `useWorkbenchProjectsTree()` provider (cache patching stays in
+one place) and `api.setSessionVisibility` / `hideSessionToBackground`. Pending state (pin,
+fork) is owned by the hook.
+
+Surface-specific behavior stays in callbacks, not in copies of the list:
+
+- `onRenameStart` — sidebar/mobile open their inline `<Input>`; the chat focuses the header's
+ existing click-to-edit `TitleField` (via an imperative handle) instead of adding a second
+ editor.
+- `onOpenSession` — the sidebar routes through `useUnsavedChangesActionGuard()`; mobile and
+ chat navigate plainly.
+- `onArchived` — the chat leaves for `/inbox`; the rows just drop.
+- `onSessionPatched` — the chat syncs its own `session` copy (the provider cache is the
+ sidebar's, not the chat's).
+
+`session: null` (or a read-only session) yields `actions: []`, no dialog, and a no-op
+`requestArchive()` — so the hook can be called unconditionally at the top of `ChatPage`.
+
+`<SessionActionMenu actions={...} />` renders a labelled `role="group"` of buttons with a
+hairline divider between groups, danger styling for archive, `hint` right-aligned in mono (the
+⌘⇧D badge), the disabled-fork explanation as an on-screen second line (not `title` alone), and
+arrow-key/Home/End roving focus. `<SessionActionMenu…Content>` wraps it in the `PopoverContent`
+every surface shares, so the popover's width, alignment and close-focus handling are also
+written once. `<SessionActionsTrigger>` is the shared ⋯ button (hover-revealed in rows, always
+visible on coarse pointers and while the menu is open).
+
+Semantics are the popover's, not a fake menu's: the container is a Radix `Popover`, which
+injects `aria-haspopup="dialog"` + `aria-expanded` into the trigger and owns focus containment.
+Claiming `role="menu"` / `role="menuitem"` on top of that would promise AT behavior (type-ahead, single
+tab stop, `aria-haspopup="menu"`) that the popover does not implement — see the review round
+below.
+
+Harmonized semantics (drift fixed while unifying):
+
+- **Fork**: disabled + `sessionForkUnavailable` tooltip on *every* surface (teaches why);
+ the mobile hide is dropped.
+- **Reference this session**: stays contextual — visible only when another chat's composer is
+ mounted. The chat header therefore hides it automatically (you can't reference yourself).
+- **Archive**: last, pink, divider above, confirm dialog unchanged.
+
+### B. Sidebar row
+
+```
+ ● What's nex ⋯ ← hover / focus-within / coarse pointer / menu open
+ ● Release checklist 📌 3 ← pinned glyph inline, always visible
+```
+
+- `SessionPinAction` (the interactive hover pin) is deleted; the ⋯ takes the right rail and
+ right-click keeps opening the same menu through `PopoverAnchor`.
+- The pinned signal survives as the existing non-interactive `SessionPinIndicator` (cyan pin),
+ moved inline before the unread badge — always visible, no layout jump, and it frees the row
+ padding helper to reserve the rail on hover only (`sessionPinLayout.ts` →
+ `sessionRowLayout.ts`, `sessionRowActionPaddingClass`).
+- Trade-off accepted: pin/unpin is 2 clicks instead of 1. Pin is a rare deliberate act; ⋯
+ makes six actions discoverable instead of one. Pin stays the *first* menu item.
+
+### C. Chat header
+
+```
+← │ What's nex ✏️ │ [CLAUDE ▾] │ 🖊 Visualize ⋯
+```
+
+Rightmost control, present in chat mode and Show Page mode. Items: Pin to top · Rename ·
+Fork session · Hide to background · Archive session (⌘⇧D).
+
+**Read-only sessions withdraw the ⋯ entirely.** An archived or runtime-owned (`visibility:
+system`) session refuses every one of these server-side (409 `archived` / 403
+`reserved_session`), so offering a menu of guaranteed failures is worse than offering none —
+the same reasoning `showPageControlActions` already applies to Visualize/Share/annotate. The
+`Archived` / `System session` badge remains the explanation.
+
+### D. `⌘⇧D` — archive the current chat session
+
+`chatShortcuts.ts`, following the existing pure-chord-module pattern
+(`apps/dockShortcuts.ts`, `apps/windowChords.ts`) so the matcher is unit-testable without a DOM:
+
+- `isArchiveSessionChord(e)` — exact `(meta|ctrl) + shift + KeyD`, no alt; matched on
+ `e.code` so it survives keyboard layouts.
+- `archiveSessionShortcutLabel()` — `⇧⌘D` on Apple, `Ctrl+Shift+D` elsewhere; rendered as the
+ menu item's `hint` so the shortcut is *discoverable* instead of folklore.
+ `isApplePlatform()` joins `lib/platform.ts` (a third local copy of the UA sniff would be the
+ same drift this plan removes).
+
+- `inForegroundSurface(target)` / `isArchiveSessionKeydown(event, target)` — the ownership half
+ of the decision: the chat stays *mounted* under app windows and dialogs, so "ChatPage is
+ rendered" is not "chat owns the keyboard".
+
+Registered by `ChatPage` on `window` (same shape as the shell's ⌘K):
+
+- It **opens the confirm dialog**, never archives directly — a destructive keystroke needs a
+ guard, and the dialog already exists.
+- Bound **only while `canArchive`** — a read-only or still-loading chat never attaches the
+ listener, so it can't `preventDefault()` a chord it won't act on.
+- `preventDefault()` (once the chord is ours) so Chrome/Firefox's own ⌘⇧D (bookmark-all-tabs)
+ doesn't fire.
+- Deliberately wins from inside the composer, like ⌘K — it's a command, not text entry — but
+ yields to any app window (`[data-window-id]`, `[data-window-owner-id]`) or dialog stacked over
+ the chat.
+- Also bound **inside the Show Page iframe** via `bindFrameChord`: an iframe keydown never
+ reaches the parent window, so without it the chord silently dies whenever focus is in the
+ visualized page.
+
+## Files
+
+- new `ui/src/components/workbench/useSessionActions.tsx` (model + writes)
+- new `ui/src/components/workbench/sessionActions.tsx` (descriptor type + ⋯ trigger + menu)
+- new `ui/src/components/workbench/chatShortcuts.ts`
+- new `ui/src/components/workbench/sessionRowLayout.ts` (replaces `sessionPinLayout.ts`)
+- `SessionPinAction.tsx` → `SessionPinIndicator.tsx` (interactive pin deleted, indicator kept)
+- `WorkbenchSidebar.tsx`, `ProjectsPage.tsx`, `ChatPage.tsx` — consume the shared model
+- `lib/platform.ts` — `isApplePlatform()`
+- `context/WorkbenchProjectsContext.ts` + `Provider.tsx` — pin/fork/archive take a **nullable**
+ project id (review round, finding 1)
+- `components/apps/windowChords.ts` — `bindFrameChord()` generalized out of
+ `bindShowPageFrameCloseShortcut()` (review round, finding 6)
+- `i18n/en.json` + `zh.json` — reuse existing `workbench.session*` keys; new keys only for the
+ chat menu's aria-label if needed
+
+## Tests
+
+- `sessionActions.test.tsx` — menu markup (labelled `role="group"`, grouping/divider, danger
+ archive, focusable disabled fork with its visible reason, hint badge, empty list) and the ⋯
+ trigger: rendered *inside* a `Popover` it must expose `aria-haspopup="dialog"` +
+ `aria-expanded`, and rendered bare it must write neither (asserting them on a bare trigger is
+ what made the first version of this test pass while the shipped markup said something else).
+- `useSessionActions.test.tsx` — the writes, with the contexts mocked: a project-less session
+ reaches `setSessionPinned(null, …)` / `forkSession(null, …)` / `archiveSession(null, …)`, an
+ explicit `projectId` overrides the row's own, cancelling the unsaved-changes prompt forks
+ **nothing**, a granted authorization wraps the navigation in `runNavigation`, a double click
+ forks once, `onSessionPatched` names the initiating session, and a read-only session yields no
+ actions, no dialog and `canArchive: false`.
+- `SessionPinIndicator.test.tsx` — the passive pin glyph and `sessionRowActionPaddingClass`;
+ together with the above it replaces `SessionPinAction.test.tsx`.
+- `chatShortcuts.test.ts` — exact chord matching (rejects plain ⌘D, ⌥⌘⇧D, KeyD alone), the
+ foreground-surface ownership check, and both platform labels.
+- `windowChords.test.ts` — `bindFrameChord` runs an arbitrary chord with the *frame's*
+ `activeElement`, steals nothing on a non-match, and detaches on cleanup.
+- `ChatArchivedReadOnly.test.tsx` — new case: a read-only header passed a non-empty
+ `sessionActions` still renders no ⋯ (`ChatHeaderBar` re-states the withdrawal itself, so the
+ guarantee doesn't rest on the hook alone).
+- `npm run build` in `ui/`; `ruff check` is a no-op here (frontend-only change).
+
+## Review round — Codex (`gpt-5.6-sol`) on the full diff
+
+Nine findings, all fixed in place. The three blockers were all "the happy path was the only
+path":
+
+| # | Finding | Fix |
+|---|---|---|
+| 1 | **BLOCKER** `project_id` is `null` for every session outside a project (the server derives it from `scope_id`), so pin and fork no-oped and **archive confirmed without archiving** on standalone sessions | provider mutations take `projectId: string \| null`; the API call always runs, only the *cache placement* is skipped. The project id is a cache address, not a permission. |
+| 2 | **BLOCKER** fork ran before the unsaved-changes prompt (the guard lived in `onOpenSession`), so cancelling left an **orphan forked session** | `authorizeNavigation()` is a pre-flight — the prompt is synchronous, so it runs before `forkSession`, and the returned authorization is carried into the post-await navigation via `runNavigation`. |
+| 3 | **BLOCKER** the window-level ⌘⇧D was scoped to "ChatPage mounted", so it fired for keystrokes owned by app windows/dialogs and `preventDefault()`ed the browser chord even on read-only chats | listener attached only while `canArchive`; `isArchiveSessionKeydown` yields to `[data-window-id]` / `[data-window-owner-id]` / `[role=dialog\|alertdialog]`. |
+| 4 | async completions weren't tied to the initiating session | `onSessionPatched(changes, sessionId)`; `ChatPage` patches only if `session.id` still matches. |
+| 5 | closing the popover *before* rename/reference let Radix's close-autofocus overwrite the focus the action had just requested | `onCloseAutoFocus` is prevented for the two focus-transferring actions only. |
+| 6 | the chord died while focus was inside the Show Page iframe | `bindFrameChord()` generalized out of the ⌥W bridge and bound on the frame too. |
+| 7 | the trigger's hand-written `aria-haspopup="menu"` was silently overridden by Radix's `"dialog"` (`asChild` spreads its props last) — and the test asserted the *unwrapped* markup, so it passed | trigger stops writing popover state it doesn't own; the test renders it inside a `Popover` and separately pins the bare-render contract. |
+| 8 | `End` focused the wrong item | `Home`/`End` → `focusItem(0)` / `focusItem(actions.length - 1)`. |
+| 9 | disabled fork used `disabled`, so it couldn't be focused and its explanation was unreachable by keyboard | `aria-disabled` + `tabIndex` kept, with the reason rendered on screen under the label. |
+
+Round 2 on `0f230780` returned one P2, also valid: the archive confirm dialog kept a bare
+`open` boolean, but the hook owning it outlives any one session (`ChatPage` is reused across
+session ids), so a request made for A was **inherited** by B — dialog re-appears open and
+re-pointed, one Enter from archiving the wrong session. Fixed by storing the requested session
+id and deriving `open` from `archiveRequestIsLive(requestedId, targetId)` in
+`sessionArchived.ts`, plus forgetting a stale request so it cannot resurrect later.
+
+Round 3 on `cd302fa4` returned one P2, also valid: the chat header forked **before** the
+unsaved-changes prompt. The blocker is mounted on the *router* (`UnsavedChangesProvider`'s
+`useBlocker`, reached from `RouterRoot`), so any plain `navigate()` prompts only after the write
+has already happened — cancelling left an orphan forked session. The sidebar row avoided it by
+passing an `authorizeNavigation` option; the chat header simply never passed one, and
+`ProjectsPage`'s `MobileSessionRow` had the same hole (a third occurrence the review did not
+flag). Fixed at the layer that owns the write instead of per call site: `useSessionActions` now
+calls `useUnsavedChangesActionGuard()` itself, gates `fork` on `authorizeNavigation()` returning
+non-`null` before touching the API, and navigates through `authorization.runNavigation(...)` so
+the router does not prompt twice for one action. The option is gone, so a new surface inherits
+the pre-flight rather than having to remember it.
+
+Deliberately not changed: no `@radix-ui/react-dropdown-menu` dependency (not installed; a true
+menu role would be the honest fix for #7's *other* half, but the popover semantics are now
+truthful about what they are).
+
+## Todo
+
+1. [x] plan
+2. [x] `sessionActions.tsx` + `sessionRowLayout.ts` + `SessionPinIndicator.tsx`
+3. [x] sidebar `SessionRow` → ⋯ + inline pin indicator
+4. [x] mobile `MobileSessionRow` → shared model
+5. [x] chat header ⋯ + `TitleField` imperative rename
+6. [x] `chatShortcuts.ts` + ⌘⇧D wiring in `ChatPage`
+7. [x] i18n en/zh
+8. [x] tests + `npm run build`
+9. [x] Codex review round — 9 findings fixed + `useSessionActions.test.tsx`
+10. [x] round 2 — per-session archive request (`archiveRequestIsLive`)
+11. [x] round 3 — unsaved-changes pre-flight owned by `useSessionActions`
diff --git a/ui/src/components/apps/windowChords.test.ts b/ui/src/components/apps/windowChords.test.ts
index 5f046b028..67d067d1c 100644
--- a/ui/src/components/apps/windowChords.test.ts
+++ b/ui/src/components/apps/windowChords.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ bindFrameChord,
bindShowPageFrameCloseShortcut,
inTerminalSurface,
inTextEntrySurface,
@@ -94,6 +95,47 @@ describe('bindShowPageFrameCloseShortcut', () => {
});
});
+// A keydown inside an iframe never reaches the parent window, so every parent-level
+// chord (⌥W close, ⌘⇧D archive) has to be bound in the frame's own document too.
+describe('bindFrameChord', () => {
+ it('runs an arbitrary chord in the frame, with the frame’s focused element', () => {
+ const iframeEvents = new ListenerHub();
+ const frameWindow = new ListenerHub();
+ const active = elWithClosest((s) => s === '.editor');
+ const frame = {
+ contentDocument: { activeElement: active },
+ contentWindow: frameWindow,
+ addEventListener: iframeEvents.addEventListener.bind(iframeEvents),
+ removeEventListener: iframeEvents.removeEventListener.bind(iframeEvents),
+ } as unknown as HTMLIFrameElement;
+ const run = vi.fn();
+ const seen: Array<Element | null> = [];
+ const cleanup = bindFrameChord(
+ frame,
+ (event, activeInFrame) => {
+ seen.push(activeInFrame);
+ return event.code === 'KeyD' && event.metaKey && event.shiftKey;
+ },
+ run,
+ );
+
+ const matching = { code: 'KeyD', metaKey: true, shiftKey: true, preventDefault: vi.fn() };
+ frameWindow.emit('keydown', matching);
+ expect(run).toHaveBeenCalledTimes(1);
+ expect(matching.preventDefault).toHaveBeenCalledTimes(1);
+ expect(seen[0]).toBe(active); // the predicate sees the frame's realm, not ours
+
+ const other = { code: 'KeyD', metaKey: true, shiftKey: false, preventDefault: vi.fn() };
+ frameWindow.emit('keydown', other);
+ expect(run).toHaveBeenCalledTimes(1);
+ expect(other.preventDefault).not.toHaveBeenCalled(); // no chord, no stolen key
+
+ cleanup();
+ frameWindow.emit('keydown', matching);
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+});
+
describe('windowIdForKeyboardTarget', () => {
const attributedElement = (attributes: Record<string, string>): Element =>
({ getAttribute: (name: string) => attributes[name] ?? null }) as unknown as Element;
diff --git a/ui/src/components/apps/windowChords.ts b/ui/src/components/apps/windowChords.ts
index 5c201b00a..59fbb90ac 100644
--- a/ui/src/components/apps/windowChords.ts
+++ b/ui/src/components/apps/windowChords.ts
@@ -28,30 +28,29 @@ export function inTextEntrySurface(el: Element | null): boolean {
);
}
-/** Bind the browser-safe close chord to one mounted same-origin Show Page frame. */
-export function bindShowPageFrameCloseShortcut(
+/**
+ * Bind one chord to a mounted same-origin iframe's own document.
+ *
+ * A keydown inside an iframe never reaches the parent window, so every parent-level
+ * chord is dead while the frame has focus unless it is bound here too. `match` is
+ * given the event and the frame's focused element (its realm, hence the duck-typed
+ * predicates above); returning true consumes the key and runs `run`.
+ */
+export function bindFrameChord(
iframe: HTMLIFrameElement,
- onClose: () => void,
+ match: (event: KeyboardEvent, activeInFrame: Element | null) => boolean,
+ run: () => void,
): () => void {
const onKeyDown = (event: KeyboardEvent) => {
- if (
- event.code !== 'KeyW' ||
- !event.altKey ||
- event.metaKey ||
- event.ctrlKey ||
- event.shiftKey
- ) {
- return;
- }
let active: Element | null = null;
try {
active = iframe.contentDocument?.activeElement ?? null;
} catch {
active = null;
}
- if (inTextEntrySurface(active)) return;
+ if (!match(event, active)) return;
event.preventDefault();
- onClose();
+ run();
};
const attach = () => {
@@ -77,6 +76,24 @@ export function bindShowPageFrameCloseShortcut(
};
}
+/** Bind the browser-safe close chord to one mounted same-origin Show Page frame. */
+export function bindShowPageFrameCloseShortcut(
+ iframe: HTMLIFrameElement,
+ onClose: () => void,
+): () => void {
+ return bindFrameChord(
+ iframe,
+ (event, active) =>
+ event.code === 'KeyW' &&
+ event.altKey &&
+ !event.metaKey &&
+ !event.ctrlKey &&
+ !event.shiftKey &&
+ !inTextEntrySurface(active),
+ onClose,
+ );
+}
+
/** Resolve focused window chrome, including controls rendered in a body portal. */
export function windowIdForKeyboardTarget(target: Element | null, layer: Element | null): string | null {
if (!target || !layer) return null;
diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
index 96cf3f38e..7ac3d5227 100644
--- a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
@@ -3,6 +3,7 @@ import type { ReactElement } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { MemoryRouter } from 'react-router-dom';
+import { Archive } from 'lucide-react';
import { describe, expect, it } from 'vitest';
import en from '../../i18n/en.json';
@@ -16,6 +17,7 @@ import { sessionAgentDisplayName } from './sessionAgentName';
import { Composer } from './Composer';
import { QuickReplies } from './QuickReplies';
import {
+ archiveRequestIsLive,
isSessionArchivedConflict,
isSessionArchivedError,
isSessionReadOnly,
@@ -341,6 +343,51 @@ describe('read-only header withdraws the Show Page controls', () => {
// re-asserted here so the header render is checked as a whole).
expect(countButtons(markup)).toBe(1); // just Back
});
+
+ it('withdraws the session ⋯ menu on a read-only header even if actions are passed', () => {
+ // useSessionActions already returns an empty list for a read-only session, so
+ // this pins the second half: pin / rename / fork / hide / archive are all
+ // refused server-side (409 archived / 403 reserved_session), so the header must
+ // not mount a trigger for them. The trigger is the only new button in the
+ // cluster, hence the same Back-only count as above.
+ const markup = render(
+ <ChatHeaderBar
+ session={session({ status: 'archived' })}
+ agents={[]}
+ defaultAgentName={null}
+ onPatch={async () => undefined}
+ onBack={() => undefined}
+ working={false}
+ showPageMode={false}
+ showPageBusy={false}
+ onToggleShowPage={() => undefined}
+ onPrepareShowPageLaunch={async () => false}
+ annotation={{
+ state: null,
+ iframeRef: { current: null },
+ handleIframeLoad: () => undefined,
+ enable: () => undefined,
+ disable: () => undefined,
+ setMode: () => undefined,
+ }}
+ readOnlyReason="archived"
+ sessionActions={[
+ {
+ id: 'archive',
+ group: 'lifecycle',
+ icon: Archive,
+ label: en.workbench.sessionArchive,
+ danger: true,
+ onSelect: () => undefined,
+ },
+ ]}
+ />,
+ );
+ expect(markup).toContain('Model Hub');
+ expect(markup).not.toContain(en.workbench.sessionActions);
+ expect(markup).not.toContain(en.workbench.sessionArchive);
+ expect(countButtons(markup)).toBe(1); // still just Back
+ });
});
// ── Codex review #4 (Composer.tsx / ChatPage.tsx:2426) ────────────────────────
@@ -915,3 +962,21 @@ describe('agent-authored local file links', () => {
expect(markup).not.toContain('href="/tmp/preview.png"');
});
});
+
+// ── Codex review round 2 (useSessionActions.tsx:216) ─────────────────────────
+// The archive confirm dialog is owned by a hook instance that OUTLIVES the session
+// it was opened for: ChatPage is reused across session ids. Stored as a bare `open`
+// boolean, a request for A was inherited by B — the dialog re-appeared already open,
+// re-pointed, one Enter from archiving the wrong session.
+describe('a pending archive request belongs to one session', () => {
+ it('is live only while the target is still the session it was requested for', () => {
+ expect(archiveRequestIsLive('ses_a', 'ses_a')).toBe(true);
+ // Navigated on, or the row moved: B must not inherit A's request.
+ expect(archiveRequestIsLive('ses_a', 'ses_b')).toBe(false);
+ // The target went read-only mid-flight (another tab archived it) or unloaded.
+ expect(archiveRequestIsLive('ses_a', null)).toBe(false);
+ // Nothing requested: an existing target never opens the dialog by itself.
+ expect(archiveRequestIsLive(null, 'ses_a')).toBe(false);
+ expect(archiveRequestIsLive(null, null)).toBe(false);
+ });
+});
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 57db760b0..510c21ab6 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1,4 +1,4 @@
-import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { Fragment, forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Image as ImageIcon, Info, Loader2, MapPin, MessageSquare, MessageSquareQuote, Pencil, Terminal, Undo2, UploadCloud, X } from 'lucide-react';
@@ -53,6 +53,18 @@ import {
insertMessageOrdered,
} from '../../lib/transcriptOrder';
import { AgentRoutePicker } from './AgentRoutePicker';
+import {
+ archiveSessionShortcutLabel,
+ isArchiveSessionChord,
+ isArchiveSessionKeydown,
+} from './chatShortcuts';
+import { bindFrameChord } from '../apps/windowChords';
+import {
+ SessionActionMenuContent,
+ SessionActionsTrigger,
+ type SessionActionDescriptor,
+} from './sessionActions';
+import { useSessionActions } from './useSessionActions';
import { ShowPageShareControl } from './ShowPageShareControl';
import { ShowPageAnnotateControl } from './ShowPageAnnotateControl';
import { ShowPageLaunchControl } from './ShowPageLaunchControl';
@@ -146,6 +158,11 @@ const emptyRuntimeState = (): SessionRuntimeState => ({
// below the viewport.
const MAX_RETAINED_MESSAGES = 300;
+// Display label for the archive chord (⇧⌘D / Ctrl+Shift+D). Resolved once at
+// module load — the platform can't change mid-session — and shown as the archive
+// row's hint so the shortcut is discoverable instead of folklore.
+const ARCHIVE_SHORTCUT_LABEL = archiveSessionShortcutLabel();
+
// Mirrors design.pen kxEkn — the inline header replaces the old "Session
// settings" dialog. Title is click-to-edit; the cyan-bordered pill on the
// right opens a single popover that drives agent / model / effort all at
@@ -263,6 +280,19 @@ export const ChatPage: React.FC = () => {
// show the stale enabled/mode and could send control messages to the freshly
// remounted overlay before it rebroadcasts. Re-points reset via the URL change.
const annotation = useShowPageAnnotation(showPageActive ? showPageUrl : null);
+ // The mounted Show Page frame, so parent-level chords can also be bound inside
+ // its document (see the ⌘⇧D effect). Stable callback + ref, never state: a ref
+ // callback that set state would re-create itself on every commit and re-attach
+ // forever. Effects run after refs are attached, so the frame is here in time.
+ const showPageFrameRef = useRef<HTMLIFrameElement | null>(null);
+ const annotationSetIframe = annotation.setIframe;
+ const setShowPageIframe = useCallback<React.RefCallback<HTMLIFrameElement>>(
+ (node) => {
+ showPageFrameRef.current = node;
+ annotationSetIframe(node);
+ },
+ [annotationSetIframe],
+ );
useEffect(() => {
// ChatPage is reused across :sessionId. Clear the previous frame immediately;
// once the new session row loads, the restore effect below applies its own
@@ -1869,6 +1899,63 @@ export const ChatPage: React.FC = () => {
[api, session, t],
);
+ // Session-level actions (pin / rename / fork / hide / archive) — the same model
+ // the sidebar rows and the mobile projects rows render, so the chat no longer
+ // sends the user back to the tree to act on the session they're reading. A
+ // read-only session yields no actions and an inert requestArchive: every one of
+ // them is refused server-side (409 archived / 403 reserved_session), so the
+ // header withdraws the ⋯ rather than offering guaranteed failures.
+ const titleFieldRef = useRef<TitleFieldHandle | null>(null);
+ const {
+ actions: sessionActions,
+ archiveDialog: sessionArchiveDialog,
+ requestArchive,
+ canArchive,
+ } = useSessionActions({
+ session: readOnly ? null : session,
+ // Rename focuses the header's existing click-to-edit title instead of adding
+ // a second editor for the same field.
+ onRenameStart: () => titleFieldRef.current?.startEditing(),
+ onOpenSession: (id) => navigate(`/chat/${encodeURIComponent(id)}`),
+ onArchived: () => navigate('/inbox'),
+ // The provider cache feeds the sidebar, not this page's own session copy. The
+ // write resolves after an await, so only patch if we're still on that session.
+ onSessionPatched: (changes, sessionId) =>
+ setSession((prev) => (prev && prev.id === sessionId ? { ...prev, ...changes } : prev)),
+ archiveHint: ARCHIVE_SHORTCUT_LABEL,
+ });
+
+ // ⌘⇧D / Ctrl+Shift+D archives the session being read. It OPENS THE CONFIRM
+ // DIALOG — a destructive action never fires straight off a keystroke — and like
+ // the shell's ⌘K it wins from inside the composer, because it's a command, not
+ // text.
+ //
+ // Bound only while there IS something to archive: preventDefault on a read-only
+ // or still-loading chat would swallow the browser's own ⌘⇧D (bookmark all tabs)
+ // and do nothing in return. And "ChatPage is mounted" is not "chat owns the
+ // keyboard" — it stays mounted under app windows and dialogs — so a keystroke
+ // belonging to a foreground surface is left to that surface (Codex).
+ useEffect(() => {
+ if (!canArchive) return;
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (!isArchiveSessionKeydown(e, e.target as Element | null)) return;
+ e.preventDefault();
+ requestArchive();
+ };
+ window.addEventListener('keydown', onKeyDown);
+ return () => window.removeEventListener('keydown', onKeyDown);
+ }, [canArchive, requestArchive]);
+
+ // A keydown inside the Show Page iframe never reaches this window, so the same
+ // chord is bound to the frame's own document while it is mounted — otherwise the
+ // shortcut silently dies as soon as the user clicks into the page they asked for.
+ useEffect(() => {
+ if (!canArchive) return;
+ const frame = showPageFrameRef.current;
+ if (!frame) return;
+ return bindFrameChord(frame, (event) => isArchiveSessionChord(event), requestArchive);
+ }, [canArchive, requestArchive, showPageActive, showPageUrl]);
+
// Ordered media-proxy image URLs across the whole session — feeds the lightbox
// so it pages left/right through every image, in render order (each message's
// attachments first, then any inline images in its text).
@@ -2059,6 +2146,8 @@ export const ChatPage: React.FC = () => {
annotation={annotation}
onAnnotateOpenChange={setAnnotateOpen}
readOnlyReason={readOnlyReason}
+ sessionActions={sessionActions}
+ titleFieldRef={titleFieldRef}
/>
{showPageActive && showPageUrl && (
@@ -2076,7 +2165,7 @@ export const ChatPage: React.FC = () => {
// isolation isn't the security boundary anyway. We still drop the exotic
// capabilities the page never needs (top navigation, pointer lock, etc.).
<iframe
- ref={annotation.setIframe}
+ ref={setShowPageIframe}
onLoad={annotation.handleIframeLoad}
title={t('chat.showPage.title')}
src={showPageUrl}
@@ -2184,6 +2273,9 @@ export const ChatPage: React.FC = () => {
readOnlyReason={readOnlyReason}
/>
</div>
+ {/* Archive confirm — mounted at the chat surface (not inside the header's
+ popover) so the ⌘⇧D chord can open it in Show Page mode too. */}
+ {sessionArchiveDialog}
</div>
</VaultProvisionDialogProvider>
</FileViewerProvider>
@@ -2602,6 +2694,12 @@ const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, se
);
};
+// Imperative handle on the header's click-to-edit title, so Rename can be one
+// menu row instead of a duplicate dialog.
+interface TitleFieldHandle {
+ startEditing: () => void;
+}
+
interface ChatHeaderBarProps {
session: WorkbenchSession;
agents: VibeAgentBrief[];
@@ -2624,16 +2722,27 @@ interface ChatHeaderBarProps {
// cluster is withdrawn entirely (see showPageControlActions). The REASON, not a
// boolean, because it also picks the badge: a runtime-owned row is not "Archived".
readOnlyReason: SessionReadOnlyReason | null;
+ // Shared session actions (pin / rename / fork / hide / archive), rendered behind
+ // the ⋯ at the far right. Empty (or absent) withdraws the trigger — which is what
+ // a read-only session yields, since every one of those writes is refused.
+ sessionActions?: SessionActionDescriptor[];
+ // Lets the menu's Rename row focus the title field that already lives here.
+ titleFieldRef?: React.Ref<TitleFieldHandle>;
}
// Exported for the read-only regression test (ChatArchivedReadOnly.test.tsx),
// which renders the header alone rather than mounting the whole page. Note the
// live (non-readOnly) header pulls in AgentRoutePicker → useApi, so only the
// read-only rendering is reachable without an ApiProvider.
-export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason }) => {
+export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onPrepareShowPageLaunch, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnlyReason, sessionActions, titleFieldRef }) => {
const { t } = useTranslation();
const readOnly = readOnlyReason !== null;
const showPageActions = showPageControlActions(readOnly, showPageMode);
+ const [actionsOpen, setActionsOpen] = useState(false);
+ // ``!readOnly`` twice over: useSessionActions already yields an empty list for a
+ // read-only session, and the withdrawal is re-stated here so this header cannot
+ // grow a ⋯ full of guaranteed-409 rows if a future caller passes actions anyway.
+ const hasSessionActions = !readOnly && (sessionActions?.length ?? 0) > 0;
const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;
const sessionAgentLabel = sessionAgentDisplayName(session, agents);
// Backend locks once a NATIVE conversation exists — a native can only be
@@ -2688,7 +2797,13 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, d
>
<ArrowLeft className="size-3.5" />
</Button>
- <TitleField key={session.id} title={session.title} onCommit={(title) => onPatch({ title })} readOnly={readOnly} />
+ <TitleField
+ key={session.id}
+ ref={titleFieldRef}
+ title={session.title}
+ onCommit={(title) => onPatch({ title })}
+ readOnly={readOnly}
+ />
{/* Hidden while the Show Page is open so the view gets the full width.
On a read-only session the route is frozen, so show it as static text
plus a badge naming WHY instead of an interactive picker. A runtime-owned
@@ -2745,7 +2860,7 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, d
the three can do anything but 409 or frame a dead page. There is no
read-only page-serving path to offer instead; see
showPageControlActions for the per-control reasoning. */}
- {showPageActions.visualize && (
+ {(showPageActions.visualize || hasSessionActions) && (
<div className="ml-auto flex items-center gap-1.5">
{showPageActions.annotate && (
<ShowPageAnnotateControl
@@ -2756,14 +2871,16 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, d
onPopoverOpenChange={onAnnotateOpenChange}
/>
)}
- <ShowPageLaunchControl
- sessionId={session.id}
- title={session.title}
- showPageMode={showPageMode}
- busy={showPageBusy}
- onToggle={onToggleShowPage}
- onPrepareLaunch={onPrepareShowPageLaunch}
- />
+ {showPageActions.visualize && (
+ <ShowPageLaunchControl
+ sessionId={session.id}
+ title={session.title}
+ showPageMode={showPageMode}
+ busy={showPageBusy}
+ onToggle={onToggleShowPage}
+ onPrepareLaunch={onPrepareShowPageLaunch}
+ />
+ )}
{showPageActions.share && (
<ShowPageShareControl
sessionId={session.id}
@@ -2771,6 +2888,26 @@ export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, d
onOpenChange={onShareOpenChange}
/>
)}
+ {/* Rightmost: the same session action menu the sidebar row uses, so
+ pin / rename / fork / hide / archive are reachable from the chat
+ without going back to the drawer. */}
+ {hasSessionActions && (
+ <Popover open={actionsOpen} onOpenChange={setActionsOpen}>
+ <PopoverTrigger asChild>
+ <SessionActionsTrigger
+ label={t('workbench.sessionActions')}
+ open={actionsOpen}
+ variant="bar"
+ />
+ </PopoverTrigger>
+ <SessionActionMenuContent
+ actions={sessionActions ?? []}
+ label={t('workbench.sessionActions')}
+ align="end"
+ onClose={() => setActionsOpen(false)}
+ />
+ </Popover>
+ )}
</div>
)}
</div>
@@ -2785,7 +2922,7 @@ interface TitleFieldProps {
readOnly?: boolean;
}
-const TitleField: React.FC<TitleFieldProps> = ({ title, onCommit, readOnly }) => {
+const TitleField = forwardRef<TitleFieldHandle, TitleFieldProps>(({ title, onCommit, readOnly }, ref) => {
const { t } = useTranslation();
const [editing, setEditing] = useState(false);
const [value, setValue] = useState(title ?? '');
@@ -2799,6 +2936,21 @@ const TitleField: React.FC<TitleFieldProps> = ({ title, onCommit, readOnly }) =>
if (editing) inputRef.current?.focus();
}, [editing]);
+ // The ⋯ menu's Rename row drives the header title the user already sees
+ // instead of opening a second dialog for the same field. Inert while
+ // read-only, where the title is static text with no input to focus.
+ useImperativeHandle(
+ ref,
+ () => ({
+ startEditing: () => {
+ if (readOnly) return;
+ setEditing(true);
+ inputRef.current?.focus();
+ },
+ }),
+ [readOnly],
+ );
+
if (readOnly) {
return (
<span className="min-w-0 flex-1 truncate text-[16px] font-bold text-foreground">
@@ -2847,7 +2999,8 @@ const TitleField: React.FC<TitleFieldProps> = ({ title, onCommit, readOnly }) =>
className="h-8 flex-1 px-2 text-[15px] font-bold"
/>
);
-};
+});
+TitleField.displayName = 'TitleField';
interface TranscriptProps {
messages: WorkbenchMessage[];
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index f8f8d8f4d..43332f962 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -6,16 +6,12 @@ import {
ChevronDown,
ChevronRight,
Ellipsis,
- EyeOff,
FileText,
Folder,
FolderOpen,
FolderPlus,
- GitFork,
Loader2,
Pencil,
- Pin,
- PinOff,
Plus,
RotateCw,
Settings2,
@@ -26,20 +22,18 @@ import clsx from 'clsx';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import type { ProjectSessionsState } from '../../context/WorkbenchProjectsContext';
-import { useApi } from '../../context/ApiContext';
import type { WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
-import { useToast } from '../../context/ToastContext';
import { formatRelativeTime } from '../../lib/relativeTime';
-import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
-import { ArchiveSessionDialog } from './ArchiveSessionDialog';
import { NewProjectDialog } from './NewProjectDialog';
import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';
import { ProjectSettingsDialog } from './ProjectSettingsDialog';
-import { SessionPinIndicator } from './SessionPinAction';
+import { SessionActionMenuContent, SessionActionsTrigger } from './sessionActions';
+import { useSessionActions } from './useSessionActions';
+import { SessionPinIndicator } from './SessionPinIndicator';
const DOT: Record<string, string> = {
running: 'bg-mint shadow-[0_0_7px_rgba(91,255,160,0.9)]',
@@ -244,8 +238,9 @@ const MobileProjectRow: React.FC<{
);
};
-// Session row: tap to open the chat, ⋯ to rename (the desktop sidebar exposes
-// rename via right-click). Inline rename, same keyboard-safe reasoning as above.
+// Session row: tap to open the chat, ⋯ for the shared session action menu (the
+// same items the desktop sidebar and the chat header show — see sessionActions.tsx).
+// Rename is inline, keyboard-safe on iOS for the same reason as the project row.
const MobileSessionRow: React.FC<{
projectId: string;
session: WorkbenchSession;
@@ -253,18 +248,24 @@ const MobileSessionRow: React.FC<{
onOpen: () => void;
}> = ({ projectId, session, unread, onOpen }) => {
const { t } = useTranslation();
- const api = useApi();
- const { showToast } = useToast();
- const { renameSession, setSessionPinned, archiveSession, forkSession } = useWorkbenchProjectsTree();
+ const { renameSession } = useWorkbenchProjectsTree();
const navigate = useNavigate();
const [menuOpen, setMenuOpen] = useState(false);
- const [archiveOpen, setArchiveOpen] = useState(false);
const [renaming, setRenaming] = useState(false);
const [draft, setDraft] = useState(session.title ?? '');
const inputRef = useRef<HTMLInputElement | null>(null);
const handledRef = useRef(false);
- const forkingRef = useRef(false);
- const pinningRef = useRef(false);
+
+ const { actions, archiveDialog } = useSessionActions({
+ session,
+ projectId,
+ onRenameStart: () => {
+ setDraft(session.title ?? '');
+ handledRef.current = false;
+ setRenaming(true);
+ },
+ onOpenSession: (sessionId) => navigate(`/chat/${encodeURIComponent(sessionId)}`),
+ });
useEffect(() => {
if (renaming) inputRef.current?.focus();
@@ -288,18 +289,6 @@ const MobileSessionRow: React.FC<{
setRenaming(false);
};
- const togglePinned = async () => {
- if (pinningRef.current) return;
- pinningRef.current = true;
- try {
- await setSessionPinned(projectId, session.id, !session.pinned);
- } catch {
- // apiFetch already surfaced the error toast.
- } finally {
- pinningRef.current = false;
- }
- };
-
if (renaming) {
return (
<div className="flex items-center gap-2 px-3 py-2">
@@ -344,93 +333,21 @@ const MobileSessionRow: React.FC<{
</button>
<Popover open={menuOpen} onOpenChange={setMenuOpen}>
<PopoverTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- aria-label={t('workbench.sessionActions')}
- className="size-8 shrink-0 text-muted"
- >
- <Ellipsis className="size-3.5" />
- </Button>
+ <SessionActionsTrigger
+ label={t('workbench.sessionActions')}
+ open={menuOpen}
+ variant="bar"
+ className="size-8"
+ />
</PopoverTrigger>
- <PopoverContent align="end" className="w-[176px] p-1">
- <MenuItem
- icon={session.pinned ? PinOff : Pin}
- onClick={() => {
- setMenuOpen(false);
- void togglePinned();
- }}
- >
- {t(session.pinned ? 'workbench.sessionUnpin' : 'workbench.sessionPin')}
- </MenuItem>
- <MenuItem
- icon={Pencil}
- onClick={() => {
- setMenuOpen(false);
- setDraft(session.title ?? '');
- handledRef.current = false;
- setRenaming(true);
- }}
- >
- {t('workbench.sessionRename')}
- </MenuItem>
- {/* Fork is hidden until the session has a native agent session to fork
- (mirrors the desktop sidebar's fork gate). */}
- {session.native_session_id && (
- <MenuItem
- icon={GitFork}
- onClick={async () => {
- setMenuOpen(false);
- // The row stays mounted after the menu closes, so guard against a
- // second tap (reopened menu) spawning a duplicate fork in flight.
- if (forkingRef.current) return;
- forkingRef.current = true;
- try {
- const forked = await forkSession(projectId, session.id);
- if (forked) navigate(`/chat/${encodeURIComponent(forked.id)}`);
- } finally {
- forkingRef.current = false;
- }
- }}
- >
- {t('workbench.sessionFork')}
- </MenuItem>
- )}
- <MenuItem
- icon={EyeOff}
- onClick={() => {
- setMenuOpen(false);
- void hideSessionToBackground({
- sessionId: session.id,
- setSessionVisibility: api.setSessionVisibility,
- showToast,
- hiddenMessage: t('workbench.sessionHiddenToast'),
- undoLabel: t('common.undo'),
- });
- }}
- >
- {t('workbench.sessionHideToBackground')}
- </MenuItem>
- <MenuItem
- icon={Archive}
- danger
- onClick={() => {
- setMenuOpen(false);
- setArchiveOpen(true);
- }}
- >
- {t('workbench.sessionArchive')}
- </MenuItem>
- </PopoverContent>
+ <SessionActionMenuContent
+ actions={actions}
+ label={t('workbench.sessionActions')}
+ align="end"
+ onClose={() => setMenuOpen(false)}
+ />
</Popover>
- <ArchiveSessionDialog
- sessionId={archiveOpen ? session.id : null}
- sessionTitle={session.title}
- open={archiveOpen}
- onOpenChange={setArchiveOpen}
- onConfirm={() => archiveSession(projectId, session.id)}
- />
+ {archiveDialog}
</div>
);
};
diff --git a/ui/src/components/workbench/SessionPinAction.test.tsx b/ui/src/components/workbench/SessionPinAction.test.tsx
deleted file mode 100644
index 2168e8e73..000000000
--- a/ui/src/components/workbench/SessionPinAction.test.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-import { renderToStaticMarkup } from 'react-dom/server';
-import { describe, expect, it } from 'vitest';
-
-import { SessionPinAction, SessionPinIndicator } from './SessionPinAction';
-import { sessionPinRowPaddingClass } from './sessionPinLayout';
-
-const renderAction = (pinned: boolean, pending = false) =>
- renderToStaticMarkup(
- <SessionPinAction
- pinned={pinned}
- pending={pending}
- pinLabel="Pin to top"
- unpinLabel="Unpin"
- onToggle={() => undefined}
- />,
- );
-
-describe('SessionPinAction', () => {
- it('keeps the 24px action target out of the session row layout', () => {
- const html = renderAction(false);
-
- expect(html).toContain('absolute inset-y-0 right-2 flex items-center');
- expect(html).toContain('grid size-6');
- });
-
- it('reveals an unpinned action on row hover, keyboard focus, and coarse pointers', () => {
- const html = renderAction(false);
-
- expect(html).toContain('aria-pressed="false"');
- expect(html).toContain('opacity-0');
- expect(html).toContain('group-hover/sess:opacity-100');
- expect(html).toContain('group-focus-within/sess:opacity-100');
- expect(html).toContain('pointer-coarse:opacity-100');
- });
-
- it('keeps a pinned action visible without a resting background and gives hover feedback', () => {
- const html = renderAction(true);
-
- expect(html).toContain('aria-pressed="true"');
- expect(html).toContain('opacity-100');
- expect(html).not.toMatch(/(?:class="|\s)bg-[^\s"]+/);
- expect(html).toContain('hover:bg-cyan/[0.18]');
- expect(html).toContain('hover:scale-105');
- expect(html).toContain('group-hover/pin:-rotate-12');
- });
-
- it('shows a disabled progress state while persistence is pending', () => {
- const html = renderAction(false, true);
-
- expect(html).toContain('disabled=""');
- expect(html).toContain('animate-spin');
- expect(html).toContain('cursor-wait');
- });
-});
-
-describe('SessionPinIndicator', () => {
- it('renders no passive status for an unpinned session', () => {
- const html = renderToStaticMarkup(<SessionPinIndicator pinned={false} label="Pinned" />);
-
- expect(html).toBe('');
- });
-
- it('renders a non-interactive status icon for a pinned session', () => {
- const html = renderToStaticMarkup(<SessionPinIndicator pinned label="Pinned" />);
-
- expect(html).toContain('role="img"');
- expect(html).toContain('aria-label="Pinned"');
- expect(html).toContain('text-cyan');
- expect(html).not.toMatch(/(?:class="|\s)bg-[^\s"]+/);
- expect(html).not.toContain('<button');
- });
-});
-
-describe('sessionPinRowPaddingClass', () => {
- it('uses the full title width until an unpinned action is revealed', () => {
- const className = sessionPinRowPaddingClass(false);
-
- expect(className).toContain('pr-2.5');
- expect(className).toContain('hover:pr-10');
- expect(className).toContain('focus-within:pr-10');
- expect(className).toContain('pointer-coarse:pr-10');
- });
-
- it('always reserves action space for a pinned session', () => {
- expect(sessionPinRowPaddingClass(true)).toBe('pr-10');
- });
-});
diff --git a/ui/src/components/workbench/SessionPinAction.tsx b/ui/src/components/workbench/SessionPinAction.tsx
deleted file mode 100644
index 1325d6cd6..000000000
--- a/ui/src/components/workbench/SessionPinAction.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import clsx from 'clsx';
-import { Loader2, Pin } from 'lucide-react';
-import type { MouseEventHandler } from 'react';
-
-interface SessionPinActionProps {
- pinned: boolean;
- pending: boolean;
- pinLabel: string;
- unpinLabel: string;
- onToggle: () => void;
- className?: string;
-}
-
-interface SessionPinIndicatorProps {
- pinned: boolean;
- label: string;
- className?: string;
-}
-
-export const SessionPinIndicator: React.FC<SessionPinIndicatorProps> = ({ pinned, label, className }) => {
- if (!pinned) return null;
-
- return (
- <span
- role="img"
- aria-label={label}
- title={label}
- className={clsx('flex shrink-0 text-cyan', className)}
- >
- <Pin className="size-3" aria-hidden="true" />
- </span>
- );
-};
-
-export const SessionPinAction: React.FC<SessionPinActionProps> = ({
- pinned,
- pending,
- pinLabel,
- unpinLabel,
- onToggle,
- className,
-}) => {
- const label = pinned ? unpinLabel : pinLabel;
- const handleClick: MouseEventHandler<HTMLButtonElement> = (event) => {
- event.stopPropagation();
- onToggle();
- };
-
- return (
- <span className={clsx('absolute inset-y-0 right-2 flex items-center', className)}>
- <button
- type="button"
- disabled={pending}
- aria-label={label}
- aria-pressed={pinned}
- title={label}
- onClick={handleClick}
- className={clsx(
- 'group/pin grid size-6 shrink-0 place-items-center rounded-md transition-[opacity,transform,background-color,color,box-shadow] duration-150 ease-out',
- 'hover:-translate-y-px hover:scale-105 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-cyan/60 motion-reduce:transform-none',
- pending
- ? 'cursor-wait text-muted opacity-100 hover:translate-y-0 hover:scale-100'
- : pinned
- ? 'text-cyan opacity-100 hover:bg-cyan/[0.18] hover:ring-1 hover:ring-cyan/30'
- : 'text-muted opacity-0 hover:bg-foreground/[0.08] hover:text-foreground group-hover/sess:opacity-100 group-focus-within/sess:opacity-100 pointer-coarse:opacity-100',
- )}
- >
- {pending ? (
- <Loader2 className="size-3 animate-spin" aria-hidden="true" />
- ) : (
- <Pin
- className="size-3 transition-transform duration-150 group-hover/pin:-rotate-12 group-hover/pin:scale-110 motion-reduce:transform-none"
- aria-hidden="true"
- />
- )}
- </button>
- </span>
- );
-};
diff --git a/ui/src/components/workbench/SessionPinIndicator.test.tsx b/ui/src/components/workbench/SessionPinIndicator.test.tsx
new file mode 100644
index 000000000..7b1e1a8de
--- /dev/null
+++ b/ui/src/components/workbench/SessionPinIndicator.test.tsx
@@ -0,0 +1,36 @@
+import { renderToStaticMarkup } from 'react-dom/server';
+import { describe, expect, it } from 'vitest';
+
+import { SessionPinIndicator } from './SessionPinIndicator';
+import { sessionRowActionPaddingClass } from './sessionRowLayout';
+
+describe('SessionPinIndicator', () => {
+ it('renders no passive status for an unpinned session', () => {
+ expect(renderToStaticMarkup(<SessionPinIndicator pinned={false} label="Pinned" />)).toBe('');
+ });
+
+ it('renders a non-interactive status icon for a pinned session', () => {
+ const html = renderToStaticMarkup(<SessionPinIndicator pinned label="Pinned" />);
+
+ expect(html).toContain('role="img"');
+ expect(html).toContain('aria-label="Pinned"');
+ expect(html).toContain('text-cyan');
+ // Pin / unpin lives in the row's ⋯ menu now; this glyph must not look clickable.
+ expect(html).not.toContain('<button');
+ });
+});
+
+describe('sessionRowActionPaddingClass', () => {
+ it('gives the title the full width until the ⋯ trigger is revealed', () => {
+ const className = sessionRowActionPaddingClass(false);
+
+ expect(className).toContain('pr-2.5');
+ expect(className).toContain('hover:pr-10');
+ expect(className).toContain('focus-within:pr-10');
+ expect(className).toContain('pointer-coarse:pr-10');
+ });
+
+ it('holds the rail open while the menu is open, so the row cannot shift under it', () => {
+ expect(sessionRowActionPaddingClass(true)).toBe('pr-10');
+ });
+});
diff --git a/ui/src/components/workbench/SessionPinIndicator.tsx b/ui/src/components/workbench/SessionPinIndicator.tsx
new file mode 100644
index 000000000..5c831bd03
--- /dev/null
+++ b/ui/src/components/workbench/SessionPinIndicator.tsx
@@ -0,0 +1,26 @@
+import clsx from 'clsx';
+import { Pin } from 'lucide-react';
+
+interface SessionPinIndicatorProps {
+ pinned: boolean;
+ label: string;
+ className?: string;
+}
+
+// Passive "this row is pinned" status. Not a button: pinning moved into the row's
+// ⋯ action menu (see sessionActions.tsx), so this glyph only has to keep the state
+// visible at a glance — including when the row is not hovered.
+export const SessionPinIndicator: React.FC<SessionPinIndicatorProps> = ({ pinned, label, className }) => {
+ if (!pinned) return null;
+
+ return (
+ <span
+ role="img"
+ aria-label={label}
+ title={label}
+ className={clsx('flex shrink-0 text-cyan', className)}
+ >
+ <Pin className="size-3" aria-hidden="true" />
+ </span>
+ );
+};
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 052f75810..09fe28f3a 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -10,19 +10,14 @@ import {
ChevronRight,
CodeXml,
Ellipsis,
- EyeOff,
FileText,
Folder,
FolderOpen,
FolderPlus,
- GitFork,
- Hash,
Inbox,
KeyRound,
Loader2,
Pencil,
- Pin,
- PinOff,
Plus,
Search,
Settings2,
@@ -34,17 +29,14 @@ import type { LucideIcon } from 'lucide-react';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { useWindowManager } from '../../context/WindowManagerContext';
-import { useComposerInsertTarget } from '../../context/ComposerBridgeContext';
import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
-import { useApi } from '../../context/ApiContext';
import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
-import { useToast } from '../../context/ToastContext';
-import { SessionPinAction } from './SessionPinAction';
-import { sessionPinRowPaddingClass } from './sessionPinLayout';
+import { SessionPinIndicator } from './SessionPinIndicator';
+import { sessionRowActionPaddingClass } from './sessionRowLayout';
+import { SessionActionMenuContent, SessionActionsTrigger } from './sessionActions';
+import { useSessionActions } from './useSessionActions';
import { formatRelativeTime } from '../../lib/relativeTime';
-import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';
-import { ArchiveSessionDialog } from './ArchiveSessionDialog';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
import { Markdown } from '../ui/markdown';
@@ -205,34 +197,22 @@ const STATUS_DOT_CLASS: Record<string, string> = {
idle: 'bg-muted',
};
-// One session row under a project. Left-click opens the chat; right-click opens
-// the session action menu. Rename calls api.updateSession({ title }); the live
-// session.activity 'updated' event then patches the title in this list (see the
-// onSessionActivity handler in WorkbenchSidebar), so no manual local patch here.
+// One session row under a project. Left-click opens the chat; the hover-revealed
+// ⋯ (and right-click anywhere on the row) opens the shared session action menu —
+// see sessionActions.tsx, which owns the items and the writes for every surface.
+// Rename is inline here: the commit calls the provider, whose session.activity
+// 'updated' event patches the title in this list, so no manual local patch.
const SessionRow: React.FC<{
+ projectId: string;
session: WorkbenchSession;
unread: number;
- onForkSession: (sessionId: string) => Promise<WorkbenchSession | null>;
- onSetPinned: (sessionId: string, pinned: boolean) => Promise<void>;
- onRenameSession: (sessionId: string, title: string) => Promise<void>;
- onArchiveSession: (sessionId: string) => Promise<void>;
-}> = ({ session, unread, onForkSession, onSetPinned, onRenameSession, onArchiveSession }) => {
+}> = ({ projectId, session, unread }) => {
const { t } = useTranslation();
const navigate = useNavigate();
- const api = useApi();
- const { showToast } = useToast();
- const authorizeRouteAction = useUnsavedChangesActionGuard();
+ const { renameSession } = useWorkbenchProjectsTree();
const location = useLocation();
const active = location.pathname === `/chat/${session.id}`;
- // "Reference this session" shows only when a chat composer is mounted (a chat
- // is open) AND this row isn't that open session — you can't reference yourself.
- const insertTarget = useComposerInsertTarget();
- const canReference = insertTarget != null && insertTarget.sessionId !== session.id;
const [menuOpen, setMenuOpen] = useState(false);
- const [archiveOpen, setArchiveOpen] = useState(false);
- const [forking, setForking] = useState(false);
- const [pinning, setPinning] = useState(false);
- const pinningRef = useRef(false);
const [renaming, setRenaming] = useState(false);
const [draft, setDraft] = useState(session.title ?? '');
const inputRef = useRef<HTMLInputElement | null>(null);
@@ -241,6 +221,24 @@ const SessionRow: React.FC<{
// must NOT let that trailing blur commit the stale draft (Codex P2).
const handledRef = useRef(false);
+ const { actions, archiveDialog } = useSessionActions({
+ session,
+ projectId,
+ onRenameStart: () => {
+ setDraft(session.title ?? '');
+ handledRef.current = false;
+ setRenaming(true);
+ },
+ // Forking navigates, and useSessionActions runs the unsaved-changes guard
+ // itself — before the fork request, so a cancelled prompt writes nothing.
+ onOpenSession: (sessionId) => navigate(`/chat/${encodeURIComponent(sessionId)}`),
+ // Archiving the chat we are currently viewing leaves it directly — don't rely
+ // solely on the replay-less SSE 'archived' event to navigate away.
+ onArchived: () => {
+ if (active) navigate('/inbox');
+ },
+ });
+
useEffect(() => {
if (renaming) inputRef.current?.focus();
}, [renaming]);
@@ -253,7 +251,7 @@ const SessionRow: React.FC<{
// No-op when unchanged; an empty name clears to "untitled" like the header.
if (trimmed === (session.title ?? '').trim()) return;
try {
- await onRenameSession(session.id, trimmed);
+ await renameSession(projectId, session.id, trimmed);
} catch {
// The shared apiFetch layer already surfaced the error toast.
}
@@ -290,20 +288,6 @@ const SessionRow: React.FC<{
}
const displayName = session.title?.trim() || t('workbench.untitledSession');
- const canFork = !!session.native_session_id && !forking;
- const togglePinned = async () => {
- if (pinningRef.current) return;
- pinningRef.current = true;
- setPinning(true);
- try {
- await onSetPinned(session.id, !session.pinned);
- } catch {
- // apiFetch already surfaced the error toast.
- } finally {
- pinningRef.current = false;
- setPinning(false);
- }
- };
return (
<>
<Popover open={menuOpen} onOpenChange={setMenuOpen}>
@@ -315,7 +299,7 @@ const SessionRow: React.FC<{
}}
className={clsx(
'group/sess relative flex items-center gap-2 rounded-md py-1.5 pl-[26px] text-left transition-[background-color,padding-right] duration-150 ease-out motion-reduce:transition-none',
- sessionPinRowPaddingClass(session.pinned),
+ sessionRowActionPaddingClass(menuOpen),
active
? 'border-l-2 border-mint bg-mint-soft pl-[24px] font-semibold text-foreground'
: 'hover:bg-foreground/[0.04]',
@@ -341,134 +325,31 @@ const SessionRow: React.FC<{
>
{displayName}
</span>
+ {/* Pinned state is a passive glyph now that pin/unpin lives in the ⋯
+ menu — inline with the title so it stays visible unhovered and
+ nothing shifts when the trigger appears. */}
+ <SessionPinIndicator pinned={session.pinned} label={t('workbench.sessionPinned')} />
{unread > 0 && (
<span className="inline-flex min-w-[1.1rem] items-center justify-center rounded-full bg-mint px-1.5 font-mono text-[9px] font-bold text-[#080812]">
{unread > 99 ? '99+' : unread}
</span>
)}
</button>
- <SessionPinAction
- pinned={session.pinned}
- pending={pinning}
- pinLabel={t('workbench.sessionPin')}
- unpinLabel={t('workbench.sessionUnpin')}
- onToggle={() => void togglePinned()}
- />
+ <span className="absolute inset-y-0 right-2 flex items-center">
+ <PopoverTrigger asChild>
+ <SessionActionsTrigger label={t('workbench.sessionActions')} open={menuOpen} />
+ </PopoverTrigger>
+ </span>
</div>
</PopoverAnchor>
- <PopoverContent align="start" className="w-[176px] p-1">
- <button
- type="button"
- disabled={pinning}
- onClick={() => {
- setMenuOpen(false);
- void togglePinned();
- }}
- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04] disabled:cursor-not-allowed disabled:text-muted"
- >
- {pinning ? (
- <Loader2 className="size-3 animate-spin text-muted" />
- ) : session.pinned ? (
- <PinOff className="size-3 text-muted" />
- ) : (
- <Pin className="size-3 text-muted" />
- )}
- {t(session.pinned ? 'workbench.sessionUnpin' : 'workbench.sessionPin')}
- </button>
- {canReference && (
- <button
- type="button"
- onClick={() => {
- setMenuOpen(false);
- insertTarget?.insertSessionReference(session.id, session.title);
- }}
- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
- >
- <Hash className="size-3 text-muted" />
- {t('workbench.sessionReference')}
- </button>
- )}
- <button
- type="button"
- disabled={!canFork}
- title={!session.native_session_id ? t('workbench.sessionForkUnavailable') : undefined}
- onClick={async () => {
- if (!canFork) return;
- const authorization = authorizeRouteAction();
- if (!authorization) return;
- setMenuOpen(false);
- setForking(true);
- try {
- const forked = await onForkSession(session.id);
- if (forked) {
- authorization.runNavigation(() => navigate(`/chat/${encodeURIComponent(forked.id)}`));
- }
- } finally {
- setForking(false);
- }
- }}
- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04] disabled:cursor-not-allowed disabled:text-muted disabled:hover:bg-transparent"
- >
- {forking ? <Loader2 className="size-3 animate-spin text-muted" /> : <GitFork className="size-3 text-muted" />}
- {t('workbench.sessionFork')}
- </button>
- <button
- type="button"
- onClick={() => {
- setMenuOpen(false);
- setDraft(session.title ?? '');
- handledRef.current = false;
- setRenaming(true);
- }}
- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
- >
- <Pencil className="size-3 text-muted" />
- {t('workbench.sessionRename')}
- </button>
- <button
- type="button"
- onClick={() => {
- setMenuOpen(false);
- void hideSessionToBackground({
- sessionId: session.id,
- setSessionVisibility: api.setSessionVisibility,
- showToast,
- hiddenMessage: t('workbench.sessionHiddenToast'),
- undoLabel: t('common.undo'),
- });
- }}
- className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
- >
- <EyeOff className="size-3 text-muted" />
- {t('workbench.sessionHideToBackground')}
- </button>
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => {
- setMenuOpen(false);
- setArchiveOpen(true);
- }}
- className="h-auto w-full justify-start gap-2 rounded px-2 py-1.5 text-left text-[12px] font-normal text-pink hover:bg-pink/[0.08] hover:text-pink"
- >
- <Archive className="size-3" />
- {t('workbench.sessionArchive')}
- </Button>
- </PopoverContent>
+ <SessionActionMenuContent
+ actions={actions}
+ label={t('workbench.sessionActions')}
+ align="start"
+ onClose={() => setMenuOpen(false)}
+ />
</Popover>
- <ArchiveSessionDialog
- sessionId={archiveOpen ? session.id : null}
- sessionTitle={session.title}
- open={archiveOpen}
- onOpenChange={setArchiveOpen}
- onConfirm={async () => {
- await onArchiveSession(session.id);
- // If we're viewing the chat we just archived, leave it directly — don't
- // rely solely on the replay-less SSE 'archived' event to navigate away.
- if (active) navigate('/inbox');
- }}
- />
+ {archiveDialog}
</>
);
};
@@ -489,10 +370,6 @@ const ProjectRow: React.FC<{
unreadBySession: Record<string, number>;
onRename: (next: string) => Promise<void>;
onArchive: () => Promise<void>;
- onForkSession: (sessionId: string) => Promise<WorkbenchSession | null>;
- onSetPinned: (sessionId: string, pinned: boolean) => Promise<void>;
- onRenameSession: (sessionId: string, title: string) => Promise<void>;
- onArchiveSession: (sessionId: string) => Promise<void>;
}> = ({
project,
expanded,
@@ -507,10 +384,6 @@ const ProjectRow: React.FC<{
unreadBySession,
onRename,
onArchive,
- onForkSession,
- onSetPinned,
- onRenameSession,
- onArchiveSession,
}) => {
const { t } = useTranslation();
const wm = useWindowManager();
@@ -702,12 +575,9 @@ const ProjectRow: React.FC<{
sessions.map((session) => (
<SessionRow
key={session.id}
+ projectId={project.id}
session={session}
unread={unreadBySession[session.id] || 0}
- onForkSession={onForkSession}
- onSetPinned={onSetPinned}
- onRenameSession={onRenameSession}
- onArchiveSession={onArchiveSession}
/>
))}
{hasMore && (
@@ -755,12 +625,8 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
loadMore,
creatingSession,
createSessionForProject,
- forkSession,
renameProject,
archiveProject,
- renameSession,
- setSessionPinned,
- archiveSession,
upsertProjectToTop,
} = useWorkbenchProjectsTree();
const [popoverOpen, setPopoverOpen] = useState(false);
@@ -1000,10 +866,6 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
unreadBySession={unreadBySession}
onRename={(next) => renameProject(project.id, next)}
onArchive={() => archiveProject(project.id)}
- onForkSession={(sessionId) => forkSession(project.id, sessionId)}
- onSetPinned={(sessionId, pinned) => setSessionPinned(project.id, sessionId, pinned)}
- onRenameSession={(sessionId, title) => renameSession(project.id, sessionId, title)}
- onArchiveSession={(sessionId) => archiveSession(project.id, sessionId)}
/>
);
})}
diff --git a/ui/src/components/workbench/chatShortcuts.test.ts b/ui/src/components/workbench/chatShortcuts.test.ts
new file mode 100644
index 000000000..7d9dbd6a9
--- /dev/null
+++ b/ui/src/components/workbench/chatShortcuts.test.ts
@@ -0,0 +1,107 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ archiveSessionShortcutLabel,
+ inForegroundSurface,
+ isArchiveSessionChord,
+ isArchiveSessionKeydown,
+} from './chatShortcuts';
+
+const chord = (over: Partial<Record<'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey', boolean>> & { code?: string }) => ({
+ altKey: false,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ code: 'KeyD',
+ ...over,
+});
+
+describe('isArchiveSessionChord', () => {
+ it('matches ⌘⇧D and Ctrl+Shift+D', () => {
+ expect(isArchiveSessionChord(chord({ metaKey: true, shiftKey: true }))).toBe(true);
+ expect(isArchiveSessionChord(chord({ ctrlKey: true, shiftKey: true }))).toBe(true);
+ });
+
+ it('needs Shift, so plain ⌘D (bookmark) is left to the browser', () => {
+ expect(isArchiveSessionChord(chord({ metaKey: true }))).toBe(false);
+ expect(isArchiveSessionChord(chord({ ctrlKey: true }))).toBe(false);
+ });
+
+ it('rejects a bare ⇧D so typing a capital letter never archives', () => {
+ expect(isArchiveSessionChord(chord({ shiftKey: true }))).toBe(false);
+ });
+
+ it('rejects extra modifiers — Alt, or Ctrl and ⌘ together', () => {
+ expect(isArchiveSessionChord(chord({ metaKey: true, shiftKey: true, altKey: true }))).toBe(false);
+ expect(isArchiveSessionChord(chord({ metaKey: true, ctrlKey: true, shiftKey: true }))).toBe(false);
+ });
+
+ it('matches the physical D key, not the produced character', () => {
+ expect(isArchiveSessionChord(chord({ metaKey: true, shiftKey: true, code: 'KeyE' }))).toBe(false);
+ // Dvorak: ``code`` is still KeyD even though the character would differ.
+ expect(isArchiveSessionChord(chord({ metaKey: true, shiftKey: true, code: 'KeyD' }))).toBe(true);
+ });
+});
+
+// Mock an Element by its closest() behavior alone — realm-agnostic and jsdom-free
+// (same pattern as apps/windowChords.test.ts).
+const elWithClosest = (matches: (selector: string) => boolean): Element =>
+ ({ closest: (selector: string) => (matches(selector) ? ({} as Element) : null) }) as unknown as Element;
+
+// ── Codex review (ChatPage.tsx:1897) ─────────────────────────────────────────
+// The chat stays MOUNTED under app windows and dialogs, so a window-level chord
+// bound on "ChatPage is mounted" fired for keystrokes that belonged to the surface
+// on top — ⌘⇧D in a Terminal window opened the archive prompt for the chat behind
+// it.
+describe('inForegroundSurface', () => {
+ it('claims a keystroke inside an app window, including a portalled control', () => {
+ expect(inForegroundSurface(elWithClosest((s) => s.includes('[data-window-id]')))).toBe(true);
+ expect(inForegroundSurface(elWithClosest((s) => s.includes('[data-window-owner-id]')))).toBe(true);
+ });
+
+ it('claims a keystroke inside any dialog (Radix content included)', () => {
+ expect(inForegroundSurface(elWithClosest((s) => s.includes('[role="dialog"]')))).toBe(true);
+ expect(inForegroundSurface(elWithClosest((s) => s.includes('[role="alertdialog"]')))).toBe(true);
+ });
+
+ it('leaves the plain chat surface — and a non-Element target — to the chat', () => {
+ expect(inForegroundSurface(elWithClosest(() => false))).toBe(false);
+ expect(inForegroundSurface(null)).toBe(false);
+ // `window` / `document` as event.target: no closest() at all, not foreign.
+ expect(inForegroundSurface({} as Element)).toBe(false);
+ });
+});
+
+describe('isArchiveSessionKeydown', () => {
+ const archiveChord = chord({ metaKey: true, shiftKey: true });
+
+ it('fires for the chord on the chat surface', () => {
+ expect(isArchiveSessionKeydown(archiveChord, elWithClosest(() => false))).toBe(true);
+ expect(isArchiveSessionKeydown(archiveChord, null)).toBe(true);
+ });
+
+ it('yields the chord to a window or dialog stacked over the chat', () => {
+ expect(isArchiveSessionKeydown(archiveChord, elWithClosest((s) => s.includes('[data-window-id]')))).toBe(false);
+ expect(isArchiveSessionKeydown(archiveChord, elWithClosest((s) => s.includes('[role="dialog"]')))).toBe(false);
+ });
+
+ it('still ignores everything that is not the chord', () => {
+ expect(isArchiveSessionKeydown(chord({ metaKey: true }), null)).toBe(false);
+ });
+});
+
+describe('archiveSessionShortcutLabel', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('uses Apple glyphs on macOS', () => {
+ vi.stubGlobal('navigator', { platform: 'MacIntel', userAgent: 'Mozilla/5.0 (Macintosh)' });
+ expect(archiveSessionShortcutLabel()).toBe('⇧⌘D');
+ });
+
+ it('spells the modifiers out elsewhere', () => {
+ vi.stubGlobal('navigator', { platform: 'Linux x86_64', userAgent: 'Mozilla/5.0 (X11; Linux x86_64)' });
+ expect(archiveSessionShortcutLabel()).toBe('Ctrl+Shift+D');
+ });
+});
diff --git a/ui/src/components/workbench/chatShortcuts.ts b/ui/src/components/workbench/chatShortcuts.ts
new file mode 100644
index 000000000..fbe8befba
--- /dev/null
+++ b/ui/src/components/workbench/chatShortcuts.ts
@@ -0,0 +1,53 @@
+import { isApplePlatform } from '../../lib/platform';
+
+// Chat-page keyboard chords, kept as pure matchers (same shape as
+// apps/dockShortcuts.ts and apps/windowChords.ts) so the exactness of each chord
+// is unit-testable without a DOM.
+
+type ChordEvent = Pick<KeyboardEvent, 'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey' | 'code'>;
+
+/**
+ * ⌘⇧D / Ctrl+Shift+D — archive the session the user is reading.
+ *
+ * Matched on ``code`` so a non-QWERTY layout still resolves the physical D, and
+ * required EXACT: Alt must be clear, and the other modifier must not be held too
+ * (Ctrl+⌘⇧D is somebody else's chord, not ours). The caller opens the archive
+ * confirm dialog — a destructive action never fires straight off a keystroke.
+ */
+export function isArchiveSessionChord(event: ChordEvent): boolean {
+ if (event.altKey || !event.shiftKey || event.code !== 'KeyD') return false;
+ // Exactly one of meta / ctrl, so ⌘ works on macOS and Ctrl everywhere else.
+ return event.metaKey !== event.ctrlKey;
+}
+
+/**
+ * True when the keystroke belongs to a surface stacked ON TOP of the chat rather
+ * than to the chat itself.
+ *
+ * The chat stays mounted under an app window (Terminal, Editor, Files…) and under
+ * every dialog, so "ChatPage is mounted" is not "chat owns the keyboard": without
+ * this, ⌘⇧D typed into a Terminal window or a Settings dialog would open the
+ * archive prompt for whatever session happens to be behind it (Codex).
+ *
+ * Duck-typed on `closest` (like apps/windowChords.ts) so a non-Element target —
+ * `window`, `document` — is simply not foreign, and elements from a same-origin
+ * iframe realm still work.
+ */
+export function inForegroundSurface(el: Element | null): boolean {
+ return !!el?.closest?.('[data-window-id], [data-window-owner-id], [role="dialog"], [role="alertdialog"]');
+}
+
+/**
+ * The whole window-level decision for the archive chord: it is our chord, AND the
+ * keystroke belongs to the chat rather than to a surface stacked on top of it.
+ * ChatPage binds this on `window` only while the session is actually archivable, so
+ * a read-only or still-loading chat never consumes the browser's ⌘⇧D either.
+ */
+export function isArchiveSessionKeydown(event: ChordEvent, target: Element | null): boolean {
+ return isArchiveSessionChord(event) && !inForegroundSurface(target);
+}
+
+/** Display label for the archive chord, shown as the menu row's hint badge. */
+export function archiveSessionShortcutLabel(): string {
+ return isApplePlatform() ? '⇧⌘D' : 'Ctrl+Shift+D';
+}
diff --git a/ui/src/components/workbench/sessionActions.test.tsx b/ui/src/components/workbench/sessionActions.test.tsx
new file mode 100644
index 000000000..90af57679
--- /dev/null
+++ b/ui/src/components/workbench/sessionActions.test.tsx
@@ -0,0 +1,145 @@
+import { renderToStaticMarkup } from 'react-dom/server';
+import { Archive, EyeOff, GitFork, Pencil, Pin } from 'lucide-react';
+import { describe, expect, it } from 'vitest';
+
+import { Popover, PopoverTrigger } from '../ui/popover';
+import { SessionActionMenu, SessionActionsTrigger, type SessionActionDescriptor } from './sessionActions';
+
+const row = (over: Partial<SessionActionDescriptor> & Pick<SessionActionDescriptor, 'id' | 'group' | 'label'>) =>
+ ({ icon: Pin, onSelect: () => undefined, ...over }) as SessionActionDescriptor;
+
+// The shape ``useSessionActions`` produces for a live, forkable session.
+const fullMenu = (): SessionActionDescriptor[] => [
+ row({ id: 'pin', group: 'organize', label: 'Pin to top', icon: Pin }),
+ row({ id: 'rename', group: 'organize', label: 'Rename', icon: Pencil }),
+ row({ id: 'fork', group: 'continue', label: 'Fork session', icon: GitFork }),
+ row({ id: 'hide', group: 'continue', label: 'Hide to background', icon: EyeOff }),
+ row({ id: 'archive', group: 'lifecycle', label: 'Archive session', icon: Archive, danger: true, hint: '⇧⌘D' }),
+];
+
+const renderMenu = (actions: SessionActionDescriptor[]) =>
+ renderToStaticMarkup(<SessionActionMenu actions={actions} label="Session actions" />);
+
+const countButtons = (markup: string) => (markup.match(/<button/g) ?? []).length;
+
+describe('SessionActionMenu', () => {
+ // ── Codex review (sessionActions.tsx:101) ───────────────────────────────────
+ // The body used to claim role="menu" / role="menuitem" inside a Radix Popover,
+ // which is a dialog: that announces a menu keyboard contract (one tab stop,
+ // type-ahead) the popover does not implement. It is a labelled group of buttons
+ // now — what it actually is.
+ it('exposes a labelled group of buttons rather than a fake menu', () => {
+ const html = renderMenu(fullMenu());
+
+ expect(html).toContain('role="group"');
+ expect(html).toContain('aria-label="Session actions"');
+ expect(html).not.toContain('role="menu"');
+ expect(html).not.toContain('role="menuitem"');
+ expect(countButtons(html)).toBe(5);
+ expect(html).toContain('Pin to top');
+ expect(html).toContain('Rename');
+ expect(html).toContain('Fork session');
+ expect(html).toContain('Hide to background');
+ expect(html).toContain('Archive session');
+ });
+
+ it('draws one hairline divider per group change, never above the first row', () => {
+ const html = renderMenu(fullMenu());
+
+ // organize → continue and continue → lifecycle; pin/rename and fork/hide pair up.
+ expect(html.match(/border-t border-border/g)).toHaveLength(2);
+ expect(html.indexOf('border-t border-border')).toBeGreaterThan(html.indexOf('Pin to top'));
+ });
+
+ it('styles archive as destructive and shows its keyboard hint', () => {
+ const html = renderMenu(fullMenu());
+
+ expect(html).toContain('text-pink');
+ expect(html).toContain('⇧⌘D');
+ expect(html).toContain('font-mono');
+ });
+
+ // ── Codex review (sessionActions.tsx:93) ────────────────────────────────────
+ // A natively ``disabled`` button cannot be focused, so the only place the reason
+ // lived — the ``title`` tooltip — was unreachable by keyboard AND by touch. The
+ // row stays focusable via aria-disabled and states the reason on screen.
+ it('keeps an unforkable session’s fork row focusable and explains it on screen', () => {
+ const reason = 'This session has no native agent session to fork yet.';
+ const html = renderMenu([
+ row({ id: 'fork', group: 'continue', label: 'Fork session', icon: GitFork, disabled: true, title: reason }),
+ ]);
+
+ expect(html).toContain('aria-disabled="true"');
+ expect(html).not.toContain('disabled=""'); // focusable, so the reason is reachable
+ expect(html).toContain(`title="${reason}"`);
+ // Visible text, not only the tooltip: touch pointers never get a tooltip.
+ expect(html).toContain(`>${reason}</span>`);
+ expect(html).toContain('Fork session');
+ });
+
+ it('swaps a pending row’s icon for a spinner', () => {
+ const html = renderMenu([row({ id: 'pin', group: 'organize', label: 'Pin to top', pending: true, disabled: true })]);
+
+ expect(html).toContain('animate-spin');
+ });
+
+ it('renders nothing for an empty action list (read-only session)', () => {
+ const html = renderMenu([]);
+
+ expect(countButtons(html)).toBe(0);
+ });
+});
+
+describe('SessionActionsTrigger', () => {
+ // ── Codex review (sessionActions.tsx:67) ────────────────────────────────────
+ // The trigger used to hand-write aria-haspopup="menu"; <PopoverTrigger asChild>
+ // spreads its own props LAST, so the shipped button always said "dialog" and only
+ // a direct render (the old test) ever saw "menu". The composed render is the truth.
+ it('takes its popup semantics from the popover it triggers', () => {
+ const composed = renderToStaticMarkup(
+ <Popover open>
+ <PopoverTrigger asChild>
+ <SessionActionsTrigger label="Session actions" open />
+ </PopoverTrigger>
+ </Popover>,
+ );
+
+ expect(composed).toContain('aria-label="Session actions"');
+ expect(composed).toContain('aria-haspopup="dialog"');
+ expect(composed).toContain('aria-expanded="true"');
+ expect(composed).toContain('data-state="open"');
+
+ const closed = renderToStaticMarkup(
+ <Popover open={false}>
+ <PopoverTrigger asChild>
+ <SessionActionsTrigger label="Session actions" open={false} />
+ </PopoverTrigger>
+ </Popover>,
+ );
+ expect(closed).toContain('aria-expanded="false"');
+
+ // Rendered on its own it claims no popup at all — no second, contradictory
+ // source of truth for what the button opens.
+ const bare = renderToStaticMarkup(<SessionActionsTrigger label="Session actions" open={false} />);
+ expect(bare).toContain('aria-label="Session actions"');
+ expect(bare).not.toContain('aria-haspopup');
+ expect(bare).not.toContain('aria-expanded');
+ });
+
+ it('hides the row variant until hover, keyboard focus, a coarse pointer, or an open menu', () => {
+ const closed = renderToStaticMarkup(<SessionActionsTrigger label="Session actions" open={false} />);
+
+ expect(closed).toContain('opacity-0');
+ expect(closed).toContain('group-hover/sess:opacity-100');
+ expect(closed).toContain('group-focus-within/sess:opacity-100');
+ expect(closed).toContain('pointer-coarse:opacity-100');
+ expect(renderToStaticMarkup(<SessionActionsTrigger label="Session actions" open />)).toContain('opacity-100');
+ });
+
+ it('keeps the bar variant (chat header, mobile row) permanently visible', () => {
+ const html = renderToStaticMarkup(<SessionActionsTrigger label="Session actions" open={false} variant="bar" />);
+
+ expect(html).not.toContain('opacity-0');
+ expect(html).toContain('size-7');
+ });
+});
diff --git a/ui/src/components/workbench/sessionActions.tsx b/ui/src/components/workbench/sessionActions.tsx
new file mode 100644
index 000000000..5e91b72b2
--- /dev/null
+++ b/ui/src/components/workbench/sessionActions.tsx
@@ -0,0 +1,220 @@
+import * as React from 'react';
+import { useRef } from 'react';
+import { Ellipsis, Loader2 } from 'lucide-react';
+import clsx from 'clsx';
+import type { LucideIcon } from 'lucide-react';
+
+import { Button } from '../ui/button';
+import { PopoverContent } from '../ui/popover';
+
+// Presentation half of the shared session action menu: the ⋯ trigger and the menu
+// body, used by the desktop sidebar row, the mobile projects row and the chat
+// header. The actions themselves (labels, writes, pending state) come from
+// useSessionActions.tsx — one model, so the surfaces cannot drift again.
+
+export type SessionActionId = 'pin' | 'reference' | 'fork' | 'rename' | 'hide' | 'archive';
+
+/** Menu grouping — rendered with a hairline divider between groups. */
+export type SessionActionGroup = 'organize' | 'continue' | 'lifecycle';
+
+export interface SessionActionDescriptor {
+ id: SessionActionId;
+ group: SessionActionGroup;
+ icon: LucideIcon;
+ label: string;
+ /** Keyboard hint badge (e.g. ``⇧⌘D``), right-aligned in the menu row. */
+ hint?: string;
+ /** Why this action is unavailable. Rendered as VISIBLE text under the label (a
+ * touch user never sees a ``title`` tooltip) as well as the native tooltip. */
+ title?: string;
+ disabled?: boolean;
+ /** A write is in flight: the icon becomes a spinner and the row stops accepting clicks. */
+ pending?: boolean;
+ danger?: boolean;
+ onSelect: () => void;
+}
+
+// The ⋯ trigger. Rows reveal it on hover / keyboard focus and keep it visible on
+// coarse pointers (touch has no hover) and while its menu is open; the chat
+// header always shows it. forwardRef + prop spread so <PopoverTrigger asChild>
+// can attach its own ref and handlers.
+//
+// It deliberately writes NO aria-haspopup / aria-expanded of its own: <PopoverTrigger
+// asChild> injects both (as `dialog`, which is what a Popover actually opens), and
+// because those injected props are spread last they would override ours anyway —
+// a hand-written `aria-haspopup="menu"` was a lie that only the direct-render test
+// could see (Codex). `open` still drives the reveal styling.
+interface SessionActionsTriggerProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
+ label: string;
+ open: boolean;
+ /** ``row``: hover-revealed inside a session row. ``bar``: always visible. */
+ variant?: 'row' | 'bar';
+}
+
+export const SessionActionsTrigger = React.forwardRef<HTMLButtonElement, SessionActionsTriggerProps>(
+ ({ label, open, variant = 'row', className, ...rest }, ref) => (
+ <Button
+ ref={ref}
+ type="button"
+ variant="ghost"
+ size="icon"
+ aria-label={label}
+ title={label}
+ className={clsx(
+ 'shrink-0 text-muted transition hover:text-foreground',
+ variant === 'row'
+ ? [
+ 'size-6 opacity-0 group-hover/sess:opacity-100 group-focus-within/sess:opacity-100 pointer-coarse:opacity-100',
+ open && 'opacity-100',
+ ]
+ : 'size-7',
+ className,
+ )}
+ {...rest}
+ >
+ <Ellipsis className="size-3.5" />
+ </Button>
+ ),
+);
+SessionActionsTrigger.displayName = 'SessionActionsTrigger';
+
+const GROUP_ORDER: SessionActionGroup[] = ['organize', 'continue', 'lifecycle'];
+
+// The menu body. Shared by all trigger sites so the rows, the divider between
+// groups and the danger styling can't drift again.
+//
+// A labelled GROUP of buttons, not role="menu": the surrounding Radix Popover is a
+// dialog, and a menu role inside it promises a keyboard contract (single tab stop,
+// type-ahead, aria-activedescendant) that a popover does not implement — the two
+// together announced a menu whose items tabbed like dialog buttons (Codex). Tabbing
+// through the buttons inside the popover's focus scope is now the honest model;
+// arrow keys / Home / End are kept as a convenience on top.
+//
+// Unavailable rows use `aria-disabled` instead of `disabled` so they stay focusable
+// and their reason is reachable by keyboard and screen reader; the click handler is
+// what actually inhibits them.
+export const SessionActionMenu: React.FC<{
+ actions: SessionActionDescriptor[];
+ /** Close the surface's popover — called after any row fires. */
+ onAction?: (id: SessionActionId) => void;
+ label?: string;
+}> = ({ actions, onAction, label }) => {
+ const itemsRef = useRef<Array<HTMLButtonElement | null>>([]);
+
+ const focusItem = (index: number) => itemsRef.current[index]?.focus();
+ const moveFocus = (from: number, delta: number) => {
+ if (actions.length === 0) return;
+ focusItem((from + delta + actions.length) % actions.length);
+ };
+
+ return (
+ <div role="group" aria-label={label} className="flex flex-col">
+ {actions.map((action, index) => {
+ const Icon = action.icon;
+ const previous = actions[index - 1];
+ const newGroup =
+ previous != null && GROUP_ORDER.indexOf(previous.group) !== GROUP_ORDER.indexOf(action.group);
+ const reason = action.disabled ? action.title : undefined;
+ return (
+ <div key={action.id} className={clsx(newGroup && 'mt-1 border-t border-border pt-1')}>
+ <button
+ ref={(node) => {
+ itemsRef.current[index] = node;
+ }}
+ type="button"
+ aria-disabled={action.disabled || undefined}
+ title={action.title}
+ onClick={() => {
+ if (action.disabled) return;
+ onAction?.(action.id);
+ action.onSelect();
+ }}
+ onKeyDown={(event) => {
+ if (event.key === 'ArrowDown') {
+ event.preventDefault();
+ moveFocus(index, 1);
+ } else if (event.key === 'ArrowUp') {
+ event.preventDefault();
+ moveFocus(index, -1);
+ } else if (event.key === 'Home') {
+ event.preventDefault();
+ focusItem(0);
+ } else if (event.key === 'End') {
+ event.preventDefault();
+ focusItem(actions.length - 1);
+ }
+ }}
+ className={clsx(
+ 'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] transition',
+ 'focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-cyan/60',
+ action.disabled
+ ? 'cursor-not-allowed text-muted hover:bg-transparent'
+ : action.danger
+ ? 'text-pink hover:bg-pink/[0.08]'
+ : 'text-foreground hover:bg-foreground/[0.04]',
+ )}
+ >
+ {action.pending ? (
+ <Loader2 className="size-3 shrink-0 animate-spin text-muted" aria-hidden="true" />
+ ) : (
+ <Icon
+ className={clsx('size-3 shrink-0', action.danger && !action.disabled ? '' : 'text-muted')}
+ aria-hidden="true"
+ />
+ )}
+ <span className="flex flex-1 flex-col gap-0.5 overflow-hidden">
+ <span className="truncate">{action.label}</span>
+ {reason && <span className="text-[10.5px] leading-tight text-muted">{reason}</span>}
+ </span>
+ {action.hint && (
+ <span className="shrink-0 font-mono text-[10px] text-muted" aria-hidden="true">
+ {action.hint}
+ </span>
+ )}
+ </button>
+ </div>
+ );
+ })}
+ </div>
+ );
+};
+
+// Actions that hand focus to an editor elsewhere (an inline rename <Input>, the
+// chat header title, another chat's composer). Radix restores focus to the trigger
+// on close — asynchronously, so it lands AFTER the editor focused itself and the
+// caret (and, on touch, the on-screen keyboard) is lost (Codex).
+const FOCUS_TRANSFER_ACTIONS: readonly SessionActionId[] = ['rename', 'reference'];
+
+// One popover body for every surface: same width, padding, close-on-select and
+// close-autofocus policy, so the three trigger sites can't drift on any of them.
+export const SessionActionMenuContent: React.FC<{
+ actions: SessionActionDescriptor[];
+ label: string;
+ align?: 'start' | 'center' | 'end';
+ className?: string;
+ /** Close the surface's popover (it owns the open state). */
+ onClose: () => void;
+}> = ({ actions, label, align = 'start', className, onClose }) => {
+ const transferredFocus = useRef(false);
+
+ return (
+ <PopoverContent
+ align={align}
+ className={clsx('w-[196px] p-1', className)}
+ onCloseAutoFocus={(event) => {
+ if (!transferredFocus.current) return;
+ transferredFocus.current = false;
+ event.preventDefault(); // leave focus where the action put it
+ }}
+ >
+ <SessionActionMenu
+ actions={actions}
+ label={label}
+ onAction={(id) => {
+ transferredFocus.current = FOCUS_TRANSFER_ACTIONS.includes(id);
+ onClose();
+ }}
+ />
+ </PopoverContent>
+ );
+};
diff --git a/ui/src/components/workbench/sessionArchived.ts b/ui/src/components/workbench/sessionArchived.ts
index 23625f8ea..0e77b6eca 100644
--- a/ui/src/components/workbench/sessionArchived.ts
+++ b/ui/src/components/workbench/sessionArchived.ts
@@ -89,6 +89,24 @@ export const markSessionArchived = (
): WorkbenchSession | null =>
prev && prev.id === sessionId && prev.status !== 'archived' ? { ...prev, status: 'archived' } : prev;
+/** Whether a pending archive request still belongs to the session in front of the
+ * user — i.e. whether the confirm dialog may be open.
+ *
+ * The archive request outlives no session but its own. ``ChatPage`` (and the hook
+ * that owns this state) is REUSED across session ids — a route param change, not a
+ * remount — so a request stored as a bare ``open`` boolean is inherited: open the
+ * dialog for A, have A go read-only mid-flight (another tab archived it, SSE
+ * converges) or simply navigate to B, and the dialog re-appears already open and
+ * re-pointed at B, one Enter away from archiving the wrong session (Codex).
+ *
+ * Storing the requested ID and comparing it here closes that by construction: the
+ * dialog can only be open for the session the user actually asked about, and a
+ * target that moved or disappeared cannot inherit the request. */
+export const archiveRequestIsLive = (
+ requestedSessionId: string | null,
+ targetSessionId: string | null,
+): boolean => requestedSessionId !== null && requestedSessionId === targetSessionId;
+
/** Which text-selection actions the transcript offers.
*
* "Quote" appends into the composer and "Ask in a new session" forks — a
diff --git a/ui/src/components/workbench/sessionPinLayout.ts b/ui/src/components/workbench/sessionPinLayout.ts
deleted file mode 100644
index 69aedb76f..000000000
--- a/ui/src/components/workbench/sessionPinLayout.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export const sessionPinRowPaddingClass = (pinned: boolean) =>
- pinned
- ? 'pr-10'
- : 'pr-2.5 hover:pr-10 focus-within:pr-10 pointer-coarse:pr-10';
diff --git a/ui/src/components/workbench/sessionRowLayout.ts b/ui/src/components/workbench/sessionRowLayout.ts
new file mode 100644
index 000000000..bf8199ba3
--- /dev/null
+++ b/ui/src/components/workbench/sessionRowLayout.ts
@@ -0,0 +1,7 @@
+// Right-hand rail for a session row's ⋯ action trigger. The trigger is absolutely
+// positioned, so the row reserves the space only while it is revealed — on hover,
+// on keyboard focus, and always on coarse pointers (touch has no hover) or while
+// its menu is open. A pinned row no longer forces the rail open: its pin glyph is
+// inline with the title, so nothing shifts when the trigger appears.
+export const sessionRowActionPaddingClass = (menuOpen: boolean) =>
+ menuOpen ? 'pr-10' : 'pr-2.5 hover:pr-10 focus-within:pr-10 pointer-coarse:pr-10';
diff --git a/ui/src/components/workbench/useSessionActions.test.tsx b/ui/src/components/workbench/useSessionActions.test.tsx
new file mode 100644
index 000000000..a65a0a5a1
--- /dev/null
+++ b/ui/src/components/workbench/useSessionActions.test.tsx
@@ -0,0 +1,238 @@
+import type { ReactElement } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { WorkbenchSession } from '../../context/ApiContext';
+import type { UnsavedChangesActionAuthorization } from '../../lib/unsavedChangesRegistry';
+import type { ArchiveSessionDialogProps } from './ArchiveSessionDialog';
+import { useSessionActions, type SessionActionsHandle, type SessionActionsOptions } from './useSessionActions';
+
+// The hook only needs four contexts and `t`. Mocking them (rather than mounting the
+// real providers) keeps this a jsdom-free unit test of the WRITES — which project id
+// reaches the provider, in what order the unsaved-changes guard runs, and which
+// session id a resolved write reports.
+const mocks = vi.hoisted(() => ({
+ forkSession: vi.fn<(projectId: string | null, sessionId: string) => Promise<WorkbenchSession | null>>(),
+ setSessionPinned: vi.fn<(projectId: string | null, sessionId: string, pinned: boolean) => Promise<void>>(),
+ archiveSession: vi.fn<(projectId: string | null, sessionId: string) => Promise<void>>(),
+ setSessionVisibility: vi.fn(),
+ showToast: vi.fn(),
+ authorizeRouteAction: vi.fn<() => UnsavedChangesActionAuthorization | null>(),
+}));
+
+vi.mock('../../context/ApiContext', () => ({
+ useApi: () => ({ setSessionVisibility: mocks.setSessionVisibility }),
+}));
+vi.mock('../../context/ToastContext', () => ({ useToast: () => ({ showToast: mocks.showToast }) }));
+vi.mock('../../context/ComposerBridgeContext', () => ({ useComposerInsertTarget: () => null }));
+vi.mock('../../context/WorkbenchProjectsContext', () => ({
+ useWorkbenchProjectsTree: () => ({
+ forkSession: mocks.forkSession,
+ setSessionPinned: mocks.setSessionPinned,
+ archiveSession: mocks.archiveSession,
+ }),
+}));
+vi.mock('../../context/useUnsavedChangesActionGuard', () => ({
+ useUnsavedChangesActionGuard: () => mocks.authorizeRouteAction,
+}));
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+const session = (over: Partial<WorkbenchSession> = {}): WorkbenchSession =>
+ ({
+ id: 'ses_standalone',
+ scope_id: 'scope-1',
+ project_id: null, // standalone: no project-bound scope, so no project row
+ title: 'Standalone',
+ status: 'active',
+ pinned: false,
+ agent_status: 'idle',
+ native_session_id: 'native-1',
+ ...over,
+ }) as WorkbenchSession;
+
+// renderToStaticMarkup runs the hook body once and never re-renders, which is all
+// this needs: the returned descriptors close over refs and callbacks, so calling
+// them afterwards exercises the real write paths (the pending state updates are
+// no-ops on the server, and are covered by the presentation test instead).
+const Probe = ({
+ options,
+ capture,
+}: {
+ options: SessionActionsOptions;
+ capture: (handle: SessionActionsHandle) => void;
+}) => {
+ capture(useSessionActions(options));
+ return null;
+};
+const mount = (options: SessionActionsOptions): SessionActionsHandle => {
+ let handle: SessionActionsHandle | null = null;
+ renderToStaticMarkup(
+ <Probe
+ options={options}
+ capture={(captured) => {
+ handle = captured;
+ }}
+ />,
+ );
+ if (!handle) throw new Error('hook did not run');
+ return handle;
+};
+
+const select = (h: SessionActionsHandle, id: string) => {
+ const action = h.actions.find((candidate) => candidate.id === id);
+ if (!action) throw new Error(`no ${id} action`);
+ action.onSelect();
+};
+const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+const confirmArchive = (h: SessionActionsHandle) =>
+ (h.archiveDialog as ReactElement<ArchiveSessionDialogProps>).props.onConfirm();
+
+const options = (over: Partial<SessionActionsOptions> = {}): SessionActionsOptions => ({
+ session: session(),
+ onRenameStart: vi.fn(),
+ onOpenSession: vi.fn(),
+ ...over,
+});
+
+/** What the real gate returns when there is nothing unsaved to warn about: an
+ * authorization that runs the navigation straight through. */
+const grantedAuthorization = (): UnsavedChangesActionAuthorization => ({
+ runNavigation: vi.fn((navigation: () => void) => navigation()),
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.forkSession.mockResolvedValue(session({ id: 'ses_forked' }));
+ mocks.setSessionPinned.mockResolvedValue(undefined);
+ mocks.archiveSession.mockResolvedValue(undefined);
+ mocks.authorizeRouteAction.mockImplementation(grantedAuthorization);
+});
+
+// ── Codex review (useSessionActions.tsx:81) ──────────────────────────────────
+// `project_id` is the `proj_*` suffix of the scope id, so it is NULL for every
+// session outside a project. The hook used to bail out of pin / fork when it was
+// null, and archive CONFIRMED SUCCESSFULLY without archiving anything: the dialog
+// closed, the row stayed. The project id is a cache address, not a permission.
+describe('a session with no project (project_id: null)', () => {
+ it('pins through to the API and reports the write', () => {
+ const onSessionPatched = vi.fn();
+ const h = mount(options({ onSessionPatched }));
+
+ select(h, 'pin');
+
+ expect(mocks.setSessionPinned).toHaveBeenCalledWith(null, 'ses_standalone', true);
+ return flush().then(() => {
+ // The id travels with the patch: the write resolves after an await, and the
+ // surface may have navigated to another session by then.
+ expect(onSessionPatched).toHaveBeenCalledWith({ pinned: true }, 'ses_standalone');
+ });
+ });
+
+ it('forks and opens the fork', async () => {
+ const onOpenSession = vi.fn();
+ const h = mount(options({ onOpenSession }));
+
+ select(h, 'fork');
+ await flush();
+
+ expect(mocks.forkSession).toHaveBeenCalledWith(null, 'ses_standalone');
+ expect(onOpenSession).toHaveBeenCalledWith('ses_forked');
+ });
+
+ it('actually archives when the dialog is confirmed', async () => {
+ const onArchived = vi.fn();
+ const h = mount(options({ onArchived }));
+
+ // The dialog is closed and bound to nothing until it is asked for — the hook
+ // instance is reused across sessions, so an inherited `open` is the bug class
+ // `archiveRequestIsLive` exists to prevent.
+ const dialog = (h.archiveDialog as ReactElement<ArchiveSessionDialogProps>).props;
+ expect(dialog.open).toBe(false);
+ expect(dialog.sessionId).toBeNull();
+
+ await confirmArchive(h);
+
+ expect(mocks.archiveSession).toHaveBeenCalledWith(null, 'ses_standalone');
+ expect(onArchived).toHaveBeenCalledTimes(1);
+ });
+
+ it('still routes a project-owned session through its project', () => {
+ const h = mount(options({ session: session({ project_id: 'proj-1' }) }));
+ select(h, 'pin');
+ expect(mocks.setSessionPinned).toHaveBeenCalledWith('proj-1', 'ses_standalone', true);
+
+ // An explicit projectId (what the sidebar rows pass) wins over the row's own.
+ const owned = mount(options({ session: session({ project_id: 'proj-1' }), projectId: 'proj-2' }));
+ select(owned, 'pin');
+ expect(mocks.setSessionPinned).toHaveBeenLastCalledWith('proj-2', 'ses_standalone', true);
+ });
+});
+
+// ── Codex review (useSessionActions.tsx:139) ─────────────────────────────────
+// The sidebar's unsaved-changes prompt used to run inside `onOpenSession`, i.e.
+// AFTER the fork request had already been sent: cancelling the prompt left an orphan
+// forked session behind. The guard is a pre-flight now — and the hook asks for it
+// ITSELF rather than taking it as an option, so a surface cannot forget to pass it
+// (the chat header and the mobile projects row both had).
+describe('fork under the unsaved-changes guard', () => {
+ it('consults the router guard without being handed one', () => {
+ mount(options());
+ expect(mocks.authorizeRouteAction).not.toHaveBeenCalled(); // asked per action, not per render
+ });
+
+ it('writes nothing when the user cancels the prompt', async () => {
+ mocks.authorizeRouteAction.mockReturnValue(null);
+ const onOpenSession = vi.fn();
+ const h = mount(options({ onOpenSession }));
+
+ select(h, 'fork');
+ await flush();
+
+ expect(mocks.authorizeRouteAction).toHaveBeenCalledTimes(1);
+ expect(mocks.forkSession).not.toHaveBeenCalled();
+ expect(onOpenSession).not.toHaveBeenCalled();
+ });
+
+ it('carries the granted authorization into the navigation', async () => {
+ const granted = grantedAuthorization();
+ mocks.authorizeRouteAction.mockReturnValue(granted);
+ const onOpenSession = vi.fn();
+ const h = mount(options({ onOpenSession }));
+
+ select(h, 'fork');
+ await flush();
+
+ expect(mocks.forkSession).toHaveBeenCalledTimes(1);
+ // Navigating THROUGH runNavigation is what stops the guard prompting twice for
+ // one action; calling navigate() directly would re-block it.
+ expect(granted.runNavigation).toHaveBeenCalledTimes(1);
+ expect(onOpenSession).toHaveBeenCalledWith('ses_forked');
+ });
+
+ it('never forks twice from a double click', async () => {
+ const h = mount(options());
+
+ select(h, 'fork');
+ select(h, 'fork'); // before any re-render could disable the row
+
+ await flush();
+ expect(mocks.forkSession).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('a read-only session', () => {
+ it('offers nothing to click, no dialog, and an inert shortcut', () => {
+ for (const readOnly of [session({ status: 'archived' }), session({ visibility: 'system' }), null]) {
+ const h = mount(options({ session: readOnly }));
+
+ expect(h.actions).toEqual([]);
+ expect(h.archiveDialog).toBeNull();
+ // canArchive is what ChatPage binds ⌘⇧D on, so the chord is not swallowed.
+ expect(h.canArchive).toBe(false);
+ h.requestArchive();
+ expect(mocks.archiveSession).not.toHaveBeenCalled();
+ }
+
+ expect(mount(options()).canArchive).toBe(true);
+ });
+});
diff --git a/ui/src/components/workbench/useSessionActions.tsx b/ui/src/components/workbench/useSessionActions.tsx
new file mode 100644
index 000000000..0bb353375
--- /dev/null
+++ b/ui/src/components/workbench/useSessionActions.tsx
@@ -0,0 +1,260 @@
+import type * as React from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Archive, EyeOff, GitFork, Hash, Pencil, Pin, PinOff } from 'lucide-react';
+
+import { useApi } from '../../context/ApiContext';
+import type { WorkbenchSession } from '../../context/ApiContext';
+import { useComposerInsertTarget } from '../../context/ComposerBridgeContext';
+import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
+import { useToast } from '../../context/ToastContext';
+import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
+import { hideSessionToBackground } from '../../lib/sessionVisibilityActions';
+import { archiveRequestIsLive, isSessionReadOnly } from './sessionArchived';
+import { ArchiveSessionDialog } from './ArchiveSessionDialog';
+import type { SessionActionDescriptor } from './sessionActions';
+
+// ── One session action model, four render sites ───────────────────────────────
+// The desktop sidebar row, its right-click menu, the mobile projects row and the
+// chat header all offer the SAME six actions. They used to be written out three
+// times (and had already drifted: fork was disabled-with-tooltip on desktop but
+// hidden on mobile, and "reference" existed only on desktop). This hook owns the
+// list, the writes and the pending state; each surface owns only where the
+// trigger sits and what "rename" / "open" / "archived" mean locally. The rows
+// themselves render through SessionActionMenu (sessionActions.tsx).
+
+export interface SessionActionsOptions {
+ /** ``null`` (no session yet, or a read-only one) yields no actions and an inert
+ * archive request, so callers can invoke the hook unconditionally. */
+ session: WorkbenchSession | null;
+ /** Project whose cached list holds the row — a CACHE address, not a permission.
+ * Defaults to ``session.project_id``, which is ``null`` for a standalone session
+ * (no project-bound scope); the writes run either way. */
+ projectId?: string | null;
+ /** Start the surface's own rename editor (inline input / chat header title). */
+ onRenameStart: () => void;
+ /** Navigate to a session (the fork target). Always called inside the
+ * unsaved-changes authorization's runner (see below). */
+ onOpenSession: (sessionId: string) => void;
+ /** After a successful archive — the chat leaves the dead session, rows just drop. */
+ onArchived?: () => void;
+ /** Mirror a write into a surface-local copy of the session (the chat page holds
+ * its own ``session`` state, which the provider cache doesn't feed). The session
+ * id is passed back so a surface that has since moved on can ignore it. */
+ onSessionPatched?: (changes: Partial<WorkbenchSession>, sessionId: string) => void;
+ /** Keyboard hint for the archive row (see chatShortcuts). */
+ archiveHint?: string;
+}
+
+export interface SessionActionsHandle {
+ actions: SessionActionDescriptor[];
+ /** Render this next to the menu — it carries its own open state. */
+ archiveDialog: React.ReactNode;
+ /** Open the archive confirm dialog (menu row, or the ⌘⇧D shortcut). */
+ requestArchive: () => void;
+ /** ``requestArchive`` can actually do something — i.e. there is a writable
+ * session. The keyboard shortcut binds only while this is true, so it never
+ * swallows the browser's own ⌘⇧D on a read-only or still-loading chat. */
+ canArchive: boolean;
+}
+
+export const useSessionActions = ({
+ session,
+ projectId,
+ onRenameStart,
+ onOpenSession,
+ onArchived,
+ onSessionPatched,
+ archiveHint,
+}: SessionActionsOptions): SessionActionsHandle => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const { forkSession, setSessionPinned, archiveSession } = useWorkbenchProjectsTree();
+ // Owned HERE, not passed in per surface: the unsaved-changes blocker is mounted on
+ // the ROUTER, so any surface that navigates after a write — sidebar, mobile row,
+ // chat header — is prompted only once the fork already exists, and cancelling
+ // orphans it. Asking inside the hook means a new surface inherits the pre-flight
+ // instead of having to remember an option (Codex found the chat header missing it).
+ const authorizeNavigation = useUnsavedChangesActionGuard();
+ const insertTarget = useComposerInsertTarget();
+ // The session an archive request was made FOR, not a bare "open" flag: this hook
+ // instance outlives any one session (ChatPage is reused across ids), so a boolean
+ // would be inherited by the next session — see archiveRequestIsLive.
+ const [archiveRequestId, setArchiveRequestId] = useState<string | null>(null);
+ const [pinning, setPinning] = useState(false);
+ const [forking, setForking] = useState(false);
+ // Refs, not the state above: a second click can land before React re-renders
+ // with the disabled row (a double fork spawns two sessions).
+ const pinningRef = useRef(false);
+ const forkingRef = useRef(false);
+
+ // A read-only session (archived, or a runtime-owned ``system`` row) refuses every
+ // one of these server-side — 409 archived / 403 reserved_session — so the whole
+ // menu is withdrawn rather than offered as a list of guaranteed failures. Same
+ // reasoning showPageControlActions already applies to the Show Page cluster.
+ const target = session && !isSessionReadOnly(session) ? session : null;
+ const targetId = target?.id ?? null;
+ const ownerProjectId = projectId ?? target?.project_id ?? null;
+
+ // Derived, so a target that moved or went read-only closes the dialog in the SAME
+ // render rather than a frame later.
+ const archiveOpen = archiveRequestIsLive(archiveRequestId, targetId);
+ // ...and forget the request once it is stale, so coming back to that session later
+ // does not resurrect a dialog the user has long since walked away from.
+ useEffect(() => {
+ setArchiveRequestId(null);
+ }, [targetId]);
+
+ const requestArchive = useCallback(() => {
+ if (!targetId) return;
+ setArchiveRequestId(targetId);
+ }, [targetId]);
+
+ const togglePinned = useCallback(async () => {
+ if (!target || pinningRef.current) return;
+ pinningRef.current = true;
+ setPinning(true);
+ const next = !target.pinned;
+ const pinnedId = target.id;
+ try {
+ await setSessionPinned(ownerProjectId, pinnedId, next);
+ // Carry the id: this resolves after an await, and the surface may have moved
+ // to another session by then (patching it would flip the wrong row).
+ onSessionPatched?.({ pinned: next }, pinnedId);
+ } catch {
+ // apiFetch already surfaced the error toast.
+ } finally {
+ pinningRef.current = false;
+ setPinning(false);
+ }
+ }, [target, ownerProjectId, setSessionPinned, onSessionPatched]);
+
+ const fork = useCallback(async () => {
+ if (!target || forkingRef.current) return;
+ // Ask FIRST (the prompt is synchronous), write second: a cancelled
+ // unsaved-changes prompt must not leave a forked session nobody navigated to.
+ // ``null`` is the user cancelling; with nothing unsaved the gate authorizes
+ // straight through.
+ const authorization = authorizeNavigation();
+ if (!authorization) return;
+ forkingRef.current = true;
+ setForking(true);
+ try {
+ const forked = await forkSession(ownerProjectId, target.id);
+ if (!forked) return;
+ // runNavigation carries the already-granted authorization into the route
+ // change, so the router blocker doesn't prompt a second time for one action.
+ authorization.runNavigation(() => onOpenSession(forked.id));
+ } finally {
+ forkingRef.current = false;
+ setForking(false);
+ }
+ }, [target, ownerProjectId, forkSession, onOpenSession, authorizeNavigation]);
+
+ const hide = useCallback(() => {
+ if (!target) return;
+ void hideSessionToBackground({
+ sessionId: target.id,
+ setSessionVisibility: api.setSessionVisibility,
+ showToast,
+ hiddenMessage: t('workbench.sessionHiddenToast'),
+ undoLabel: t('common.undo'),
+ });
+ }, [target, api.setSessionVisibility, showToast, t]);
+
+ const actions = useMemo<SessionActionDescriptor[]>(() => {
+ if (!target) return [];
+ const canFork = Boolean(target.native_session_id);
+ // "Reference this session" needs a chat composer mounted somewhere else — you
+ // cannot reference the session you are already typing in, which is also why
+ // the chat header never shows this row for its own session.
+ const canReference = insertTarget != null && insertTarget.sessionId !== target.id;
+ const rows: SessionActionDescriptor[] = [
+ {
+ id: 'pin',
+ group: 'organize',
+ icon: target.pinned ? PinOff : Pin,
+ label: t(target.pinned ? 'workbench.sessionUnpin' : 'workbench.sessionPin'),
+ pending: pinning,
+ disabled: pinning,
+ onSelect: () => void togglePinned(),
+ },
+ {
+ id: 'rename',
+ group: 'organize',
+ icon: Pencil,
+ label: t('workbench.sessionRename'),
+ onSelect: onRenameStart,
+ },
+ ];
+ if (canReference) {
+ rows.push({
+ id: 'reference',
+ group: 'continue',
+ icon: Hash,
+ label: t('workbench.sessionReference'),
+ onSelect: () => insertTarget?.insertSessionReference(target.id, target.title),
+ });
+ }
+ rows.push(
+ {
+ id: 'fork',
+ group: 'continue',
+ icon: GitFork,
+ label: t('workbench.sessionFork'),
+ // Disabled-with-a-reason on every surface: a session with no native
+ // conversation has nothing to fork, and hiding the row (what mobile used
+ // to do) teaches the user nothing.
+ disabled: !canFork || forking,
+ pending: forking,
+ title: canFork ? undefined : t('workbench.sessionForkUnavailable'),
+ onSelect: () => void fork(),
+ },
+ {
+ id: 'hide',
+ group: 'continue',
+ icon: EyeOff,
+ label: t('workbench.sessionHideToBackground'),
+ onSelect: hide,
+ },
+ {
+ id: 'archive',
+ group: 'lifecycle',
+ icon: Archive,
+ label: t('workbench.sessionArchive'),
+ hint: archiveHint,
+ danger: true,
+ onSelect: requestArchive,
+ },
+ );
+ return rows;
+ }, [
+ target,
+ insertTarget,
+ t,
+ pinning,
+ forking,
+ togglePinned,
+ onRenameStart,
+ fork,
+ hide,
+ requestArchive,
+ archiveHint,
+ ]);
+
+ const archiveDialog = target ? (
+ <ArchiveSessionDialog
+ sessionId={archiveOpen ? archiveRequestId : null}
+ sessionTitle={target.title}
+ open={archiveOpen}
+ onOpenChange={(open) => setArchiveRequestId(open ? targetId : null)}
+ onConfirm={async () => {
+ await archiveSession(ownerProjectId, target.id);
+ onArchived?.();
+ }}
+ />
+ ) : null;
+
+ return { actions, archiveDialog, requestArchive, canArchive: target != null };
+};
diff --git a/ui/src/context/WorkbenchProjectsContext.ts b/ui/src/context/WorkbenchProjectsContext.ts
index 41f102228..c3a3a6c6a 100644
--- a/ui/src/context/WorkbenchProjectsContext.ts
+++ b/ui/src/context/WorkbenchProjectsContext.ts
@@ -37,8 +37,10 @@ export interface WorkbenchProjectsTree {
* the caller navigates (this provider is mounted outside the router). null on failure.
* `overrides` lets the create surfaces pin an agent/backend; omit for the server default. */
createSessionForProject: (projectId: string, overrides?: Partial<WorkbenchSessionCreate>) => Promise<WorkbenchSession | null>;
- /** Fork an existing session, prepend the new row to the source project, and return it for navigation. */
- forkSession: (projectId: string, sessionId: string) => Promise<WorkbenchSession | null>;
+ /** Fork an existing session, prepend the new row to the source project, and return it for navigation.
+ * `projectId` is a CACHE address, not a permission: a standalone session (`project_id: null`,
+ * i.e. no project-bound scope) forks with `null` and simply has no row to place. */
+ forkSession: (projectId: string | null, sessionId: string) => Promise<WorkbenchSession | null>;
renameProject: (projectId: string, name: string) => Promise<void>;
/** Persist the project's default Agent route (Project Settings) and patch the
* shared cache so the sidebar + Projects page reflect it. Pass an all-null
@@ -52,11 +54,14 @@ export interface WorkbenchProjectsTree {
archiveProject: (projectId: string) => Promise<void>;
/** Throws on failure so the row's inline editor can fall back; patches title on success. */
renameSession: (projectId: string, sessionId: string, title: string) => Promise<void>;
- /** Persist pin state and keep the session in the project's pinned-first order. */
- setSessionPinned: (projectId: string, sessionId: string, pinned: boolean) => Promise<void>;
+ /** Persist pin state and keep the session in the project's pinned-first order.
+ * `null` project = standalone session: the write still happens, only the
+ * project-scoped re-ordering is skipped. */
+ setSessionPinned: (projectId: string | null, sessionId: string, pinned: boolean) => Promise<void>;
/** Permanently archive a session: calls the API (which reclaims its bound
- * tasks/watches/runs) then drops the row from the tree. Throws on failure. */
- archiveSession: (projectId: string, sessionId: string) => Promise<void>;
+ * tasks/watches/runs) then drops the row from the tree. Throws on failure.
+ * `null` project = standalone session (nothing to drop from the tree). */
+ archiveSession: (projectId: string | null, sessionId: string) => Promise<void>;
/** After NewProjectDialog: dedup-by-id, hoist to top, expand, fetch sessions if not loaded. */
upsertProjectToTop: (project: WorkbenchProject) => void;
}
diff --git a/ui/src/context/WorkbenchProjectsProvider.tsx b/ui/src/context/WorkbenchProjectsProvider.tsx
index 001eafa2d..44c9942a0 100644
--- a/ui/src/context/WorkbenchProjectsProvider.tsx
+++ b/ui/src/context/WorkbenchProjectsProvider.tsx
@@ -502,10 +502,15 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
);
const forkSession = useCallback(
- async (projectId: string, sessionId: string): Promise<WorkbenchSession | null> => {
- const alreadyLoaded = sessionsRef.current[projectId]?.sessions != null;
+ async (projectId: string | null, sessionId: string): Promise<WorkbenchSession | null> => {
+ // A standalone session (no project-bound scope, so `project_id: null`) has no
+ // bucket in this tree. The fork itself is session-keyed, so it still runs —
+ // only the cache placement below is skipped, otherwise "fork" would silently
+ // do nothing for every session outside a project (Codex).
+ const alreadyLoaded = projectId != null && sessionsRef.current[projectId]?.sessions != null;
try {
const session = await api.forkSession(sessionId);
+ if (projectId == null) return session;
if (alreadyLoaded) {
setSessions((prev) => {
const cur = prev[projectId] ?? EMPTY_SESSIONS;
@@ -594,9 +599,12 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
);
const setSessionPinned = useCallback(
- async (projectId: string, sessionId: string, pinned: boolean) => {
+ async (projectId: string | null, sessionId: string, pinned: boolean) => {
const updated = await api.updateSession(sessionId, { pinned });
+ // Session-keyed: patches whatever project holds the row (none, for a
+ // standalone session). Only the pinned-first re-order needs a project.
setSessions((prev) => patchSessionRow(prev, sessionId, () => updated, true));
+ if (projectId == null) return;
const loaded = sessionsRef.current[projectId]?.sessions?.length ?? 0;
void reconcileSessions(projectId, { minCount: loaded });
},
@@ -604,10 +612,11 @@ export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ c
);
const archiveSession = useCallback(
- async (projectId: string, sessionId: string) => {
+ async (projectId: string | null, sessionId: string) => {
// Archive is terminal — the API reclaims bound tasks/watches/runs server-side.
// Drop the row from the tree on success; throw so the caller's dialog can react.
await api.archiveSession(sessionId);
+ if (projectId == null) return; // standalone session: no tree row to drop
setSessions((prev) => {
const state = prev[projectId];
if (!state?.sessions) return prev;
diff --git a/ui/src/lib/platform.ts b/ui/src/lib/platform.ts
index aabcd7894..77f568d80 100644
--- a/ui/src/lib/platform.ts
+++ b/ui/src/lib/platform.ts
@@ -17,6 +17,14 @@ export function isIosDevice(): boolean {
);
}
+// Apple keyboard conventions: ⌘ is the command modifier and shortcut labels use
+// the glyphs. Only affects how a chord is *displayed* and which modifier a
+// matcher prefers — never gates behavior.
+export function isApplePlatform(): boolean {
+ if (typeof navigator === 'undefined') return false;
+ return /Mac|iP(hone|ad|od)/i.test(navigator.platform || navigator.userAgent || '');
+}
+
// Launched from the Home Screen / installed as a PWA: no browser chrome.
// ``navigator.standalone`` is Apple's proprietary signal; the display-mode
// media query is the cross-browser one.