Compare commits

..
Author SHA1 Message Date
paseo-bot[bot]andtheunlimited64 e53e93ed26 test(server): reproduce unchanged workspace updates after reconnect
Preserve the redundant-delivery reproduction from #5530 without claiming that it explains the Android freeze. The regression intentionally fails on current main.

Co-authored-by: theunlimited64 <theunlimited64@gmail.com>
2026-11-06 13:03:03 +00:00
paseo-bot[bot] c8bd4717c9 test(server): wait for Git ref observation before injecting events (#8924)
Zero in-flight fetches also describes observation that has not started. Wait for the first fetch to start and settle, and exercise delayed watcher setup so missing callbacks cannot silently skip the test events.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-06 12:25:42 +00:00
Mohamed Boudra 6c1b48d296 Archive a workspace from its sidebar row, with undo (#8904)
* feat(app): archive a workspace from its sidebar row and undo it

Hovering a workspace row on desktop shows an archive button next to the
row menu. Archiving shows a toast with Undo and a Cmd/Ctrl+Z shortcut so a
mis-click costs one keystroke instead of a trip through History.

The daemon serializes archive and undo per workspace across every
connection. An undo that lands while an archive is still tearing down
aborts it at the next checkpoint and restores only the agents that archive
took down; deleting the worktree directory is the point of no return, after
which undo recreates the worktree.

* fix(server,app): close archive and undo races found in review

- An archive request now claims the workspace's archive queue before
  looking up the workspace, so an undo sent right behind it cancels it
  instead of running first and losing to the archive.
- A repeat archive of an already archived workspace no longer wipes the
  agents the earlier archive saved for undo.
- Undo no longer brings back an agent that was archived before the
  workspace archive and only loaded to read its history.
- Each local archive or undo request owns its own intent token, so a
  late response to an earlier request cannot release a newer request's
  hold on the row. An archive canceled by another client's undo puts the
  row back.
- The undo failure toast shows translated copy; the cause goes to the log.

* fix(app): keep a workspace's layout when another client restores it during the undo window

The undo window purged tabs and layout whenever it closed after a
finished archive. If another client restored the workspace before this
client's toast closed, the restored workspace lost its saved
arrangement. The archive now commits only if the workspace is still gone
when the window closes.

* fix(app): show the archived toast's Undo as a button

* fix(app): keep a workspace's agent tabs when it is opened while its undo runs

* fix(app): keep a row whose undo is running when a directory snapshot omits it
2026-11-06 16:16:11 +07:00
paseo-bot[bot]andluke 1a626230d9 Keep clients current when parent archive detaches an unloaded child (#8903)
* fix(server): retain archived parent provenance on detach

* fix(server): publish stored child detach updates on parent archive

Keep subscribed clients current when an unloaded child survives its parent archive. Narrow the contributor change to the missing update; archived-parent provenance remains a separate feature.

Co-authored-by: luke <luopeihuan@gmail.com>

* test(server): clean up the detach fixture static directory

Keep the test daemon static directory inside the fixture root so cleanup removes all test-owned directories.

* fix(server): retain runtime settings in stored agent updates

Parent archive publishes stored survivors through the manager. Preserve their saved runtime model and thinking settings so the update matches stored fetches and subscription filters.

---------

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-06 09:16:01 +00:00
Mohamed Boudra 4b285a113d Space the touch composer toolbar by what it paints (#8909)
* feat(app): tighten the touch composer toolbar onto the text column

On touch, the toolbar's icon-only glyphs were 20pt muted outlines at a 1.5px
stroke in loosely spaced slots, and the row sat on a flat -6 margin, so the
attach + and the trailing control floated inside the text column. Touch now
places 44pt slots edge to edge, draws icon-only glyphs at 24pt with a 2px
foreground stroke, keeps label-paired glyphs at 20pt, and runs the context
ring at 26pt with a 3px stroke. The row overhangs into the composer padding
by each end control's ink inset (composerToolbarOverhang), so the + ink and
the trailing glyph or send/stop disc sit on the text column's edges.
Pointer sizing is unchanged.

The folded model control now drops its thinking label before the model
label truncates, and the model label truncates on a word boundary
("Ten second…") instead of leaving a space before the ellipsis. Both are
decided from measured widths. The web reports layout widths rounded to whole
pixels, so a tie counts as not fitting.

* fix(app): measure replacement model labels instead of hiding them

The folded model label and TailEllipsisText kept their measuring views mounted
when the label text changed, while discarding the cached widths. A retained
measuring node whose size does not change emits no new layout event on web or
native, so after switching to a model whose label (or a shortened prefix of it)
has the same width, the widths stayed unknown and the label stayed transparent.
Keying each measurer by what it measures remounts it, so every width is
measured again.

Also move the label width sweep into a named helper so the test body states
the expected label order.

* feat(app): space the touch composer toolbar by what it paints

- Lay each control out at its painted width, 20pt apart, with a disc-sized circle that is both its frame and its fully rounded pressed highlight. Pickers are 36pt pills.
- Match the header icons: 20pt glyphs at 1.5px, an 18pt context ring at 2px.
- Always end the row in a disc (voice mode, send or stop) so it does not shift, nested into the composer's corner, with a concentric 26pt corner radius on touch.
- Stop the picker row's clip from flattening the picker highlight's left edge.
- Budget the density ladder on laid-out widths.

* fix(app): disable the stand-in send disc and keep form model fields in their box

- An empty new chat's stand-in Send is disabled until there is content, as in fullscreen.
- A custom model selector trigger, such as the schedule form's field, drops the toolbar slot's margins.
2026-11-06 15:56:09 +07:00
Mohamed BoudraandDavid Greenspan 4281372bee fix(app): keep the chat readable with the keyboard open on iOS 26+ (#8918)
iOS 26 adds a scroll edge effect, a blur at each edge of every scroll view,
and places it in the scroll view's own coordinates without applying
transforms. The keyboard lifts the chat with a translateY, so on iPhones the
blur lands over the readable conversation and stays until the next scroll.
The app draws its own header fade, so the app's ScrollView component class,
which backs every React Native ScrollView, hides all four edge effects.

Co-authored-by: David Greenspan <155814+dgreensp@users.noreply.github.com>
2026-11-06 15:14:23 +07:00
Mohamed Boudra e79e826e23 Stop re-rendering every chat message on each agent update (#8916)
* fix(app): keep unchanged agent fields when an agent update is accepted

* fix(app): share unchanged agent fields at the store write, not in the update policy
2026-11-06 14:48:10 +07:00
Mohamed Boudra 4928500e1f fix(app): keep chat rows their size while their tab is hidden on Android (#8911) 2026-11-06 14:08:09 +07:00
Mohamed Boudra 1e2ab3d596 Keep the first prompt on screen when a new agent starts on Android (#8898)
* refactor(app): stop resetting the chat timeline when its agent id changes

A mounted timeline only ever shows one agent: every host keys its panel by tab id,
and a tab keeps its id across a target change only when a draft becomes the agent
it created. The per-agent resets inside the timeline therefore never had a different
agent to reset for. They only fired at that create handoff, where they hid and
re-placed a timeline that was already on screen.

Delete them: LegendList's dataKey and the placed agent id, the web viewport key,
the bottom anchor's resetForAgent, the history window's agent id, and the
expansion and path-opener resets in the stream view.

* fix(app): keep one chat timeline across the draft-to-agent handoff

A draft tab and the agent its first prompt creates rendered two different panels:
DraftPanel mounted its own dock and list, and the retarget swapped it for AgentPanel's.
On Android, with the LegendList timeline, the swap blanked the first turn and re-placed it.

Render both from the agent panel. A draft supplies its timeline from the pending create
in the create-flow store (composer/draft/timeline.ts) and its composer in the composer
slot. The retarget then re-renders the same stream view with the agent's timeline, so the
list instance and its measured rows stay mounted. Agent gating is unchanged.

Float the compact header over draft tabs as it already floats over agent tabs. The
header sat in flow above a draft and over an agent, so the list viewport grew 92 dp at
the retarget and the turn moved.

The handoff E2E now fails if the first row disappears, hides, or shifts down while the
draft becomes the agent.

* fix(app): load subagents and tasks only for an agent, not a draft tab
2026-11-06 13:38:10 +07:00
paseo-bot[bot] 2716bd96de test(terminal): observe original process completion after exit (#8892)
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-06 06:27:04 +00:00
110 changed files with 5635 additions and 1267 deletions
+21
View File
@@ -259,6 +259,27 @@ archived workspace. History navigation must not infer workspace lifecycle from `
or mutate either lifecycle. The workspace route asks the daemon for authoritative recovery state;
only the route's explicit Unarchive or Restore action changes the archived workspace.
Workspace archive is undoable from the archived toast, or with Cmd/Ctrl+Z, while the toast is up.
The daemon runs one archive lane per workspace, shared by every connection
(`packages/server/src/server/workspace-archive-operations.ts`):
| A request arrives while | Result |
| ------------------------ | --------------------------------------------------------- |
| an archive runs: archive | joins the running archive |
| an archive runs: undo | aborts the archive, waits for it to settle, then restores |
| an undo runs: archive | waits for the undo, then archives |
| an undo runs: undo | joins the running undo |
A request takes its place in the lane before its first `await`. Arrival order decides, so an undo
sent right behind its archive still cancels it.
An aborted archive stops at its next checkpoint and reports `canceled`; the undo unarchives only
the agents that archive itself archived. Deleting the worktree directory is the point of no
return: an undo after it recreates the worktree through workspace recovery. The client shows or
hides the row by the latest local intent, so a late remove or upsert from a superseded request
does not flip it back. Tabs and layout are purged only once the undo window closes with the
archive committed.
History navigation opens the selected agent without changing either archive state. Workspace
**Restore** recovers only the workspace; the selected archived agent stays open with its callout.
The agent's **Unarchive** runs the provider's native unarchive hook before interactive resume and
+6 -2
View File
@@ -68,7 +68,11 @@ the sidebar. Apply it as `backgroundColor`; setting `opacity` on the control als
`destructive` is filled with `destructive`. It only appears inside a confirm. The button on the page is `outline`; the destructive button is the confirm button inside the dialog.
Controls come in two sizes, defined once in `control-geometry.ts`. The default is the right size almost everywhere — pages, dialogs, forms, settings rows, the setup flow — so don't pass a size. It is 32px tall where a pointer drives it and 44px where controls are touch-sized, so every touch control meets the iOS HIG's 44pt hit region. The hit region is not the painted area: a filled toolbar control such as the composer's send or stop keeps the 44pt frame and paints a 36pt disc inside it (`TOOLBAR_DISC_SIZE`), so it does not outweigh its unpainted neighbours. `sm` is 28px pointer and 32px touch, with `fontSize.sm` labels, and is for tight chrome only: toolbars, nested settings rows, dense inline row actions. A `size="sm"` on an ordinary page or dialog is wrong, and so is choosing a size from `useIsCompactFormFactor()`.
Controls come in two sizes, defined once in `control-geometry.ts`. The default is the right size almost everywhere — pages, dialogs, forms, settings rows, the setup flow — so don't pass a size. It is 32px tall where a pointer drives it and 44px where controls are touch-sized, so every touch control meets the iOS HIG's 44pt hit region. `sm` is 28px pointer and 32px touch, with `fontSize.sm` labels, and is for tight chrome only: toolbars, nested settings rows, dense inline row actions. A `size="sm"` on an ordinary page or dialog is wrong, and so is choosing a size from `useIsCompactFormFactor()`.
Dense toolbar rows, such as the composer's, are the exception to the 44pt control. Touch-sized the row is 44pt tall and each control is a 36pt circle (`TOOLBAR_DISC_SIZE`): send and stop fill it, and every other control's pressed highlight fills it, so every highlight is the same fully rounded shape. Labelled pickers are 36pt pills. A control lays out at the width of what it paints (`toolbarSlot`, `toolbarContentSlot`) and its circle reaches into the gaps, so `TOOLBAR_CONTROL_GAP`, 20pt, is the visible space between glyphs. Toolbar glyphs match the header icons: 20pt, the app's 1.5px stroke, resting at `foreground` (`toolbarGlyphsFor`). The context ring is 18pt with a 2px stroke (`TOOLBAR_RINGS`): a circle fills its box where an outline glyph does not, and a thin circle reads lighter than a glyph at the same stroke. A disc's solid glyph, such as the stop square, stays at the `md` size (`TOOLBAR_DISC_GLYPH_SIZES`). Pointer-sized toolbars keep 28px controls, a 4px gap, and a 16pt muted glyph that brightens on hover.
In the composer, the first glyph's ink starts on the text column's edge, and the trailing control is always a disc, so the row does not shift as it changes between voice mode, send and stop. The disc nests into the corner, as far from the right edge as from the bottom, and touch-sized the composer's corner radius is concentric with it (`packages/app/src/composer/input/toolbar-rails.ts`).
One gate, `resolveControlSizing`, picks touch or pointer sizing: touch when the layout is compact or the device has a touch screen. An iPad with the sidebar docked is wide and touch-sized; a desktop is pointer-sized; a phone is both compact and touch. The touch-screen fact is read once at startup (`hasTouchScreen` in `hooks/use-fine-pointer.ts`), so attaching a mouse or keyboard to a tablet never shrinks its controls. Stylesheets take sizes from `bySizing({ touch, pointer })`, which resolves to a breakpoint value, so a caller never sees which sizing it got. Rows, icon buttons and icon slots take theirs from `styles/density.ts`, which uses the same gate. An `{ xs, md }` literal for a hit target or glyph is wrong: on an iPad it yields the pointer size.
@@ -140,7 +144,7 @@ Things align to their glyphs, not to their boxes. A row's leading icon, its titl
Pick the rails from the content, then hold them. A settings card establishes a leading rail at the icon's left edge and a trailing rail at the last glyph's right edge; every row in that card uses the same two. A row whose icon is absent still starts its title on the leading rail. Indentation is a new rail, not an arbitrary offset.
The pressable is bigger than the glyph, and that is fine. Hit areas grow outward from the aligned content — they never move it. A button that looks two pixels off because its padding is asymmetric is misaligned even though its box is correct.
The pressable is bigger than the glyph, and that is fine. Hit areas grow outward from the aligned content — they never move it. A button that looks two pixels off because its padding is asymmetric is misaligned even though its box is correct. The composer toolbar is the worked example: its outermost ink, the attach `+` on the left and the trailing glyph or send/stop disc on the right, sits on the text column's edges, and the 44pt touch slots overhang into the composer padding by each end control's ink inset (`composerToolbarOverhang`).
Optical alignment beats arithmetic when a glyph disagrees with its bounding box. Icons with visual weight on one side, chevrons, and single-character labels usually need a small nudge to look centered. Trust the eye, then leave a comment saying the offset is optical.
+7
View File
@@ -84,3 +84,10 @@ its DOM-derived scope.
Escape interrupts an agent only in the message input or an unclaimed surface.
A focused terminal excludes that binding. The source leaves terminal Escape alone;
terminal Escape/Ctrl forwarding is a separate feature.
## Keys shared with text editing
A binding on a key the platform already uses for editing, such as Cmd/Ctrl+Z for
workspace archive undo, declares `editable: false` and registers its handler with
`isActive` true only while it has work. An inactive handler leaves the key
unhandled, so the pipeline skips `preventDefault` and the platform's own undo runs.
@@ -235,6 +235,7 @@ async function beginTimelineRowStabilityCheck(
lastTop: initialRow.getBoundingClientRect().top,
largestDownwardShift: 0,
sawMissing: false,
sawHidden: false,
};
const windowState = window as unknown as Record<string, unknown>;
windowState.__messageSubmissionTimelineRowStability = state;
@@ -245,6 +246,9 @@ async function beginTimelineRowStabilityCheck(
requestAnimationFrame(checkFrame);
return;
}
if (!initialRow.checkVisibility({ opacityProperty: true, visibilityProperty: true })) {
state.sawHidden = true;
}
const top = initialRow.getBoundingClientRect().top;
state.largestDownwardShift = Math.max(state.largestDownwardShift, top - state.lastTop);
state.lastTop = top;
@@ -257,14 +261,24 @@ async function beginTimelineRowStabilityCheck(
const result = await page.evaluate(() => {
const windowState = window as unknown as Record<string, unknown>;
const state = windowState.__messageSubmissionTimelineRowStability as
| { active: boolean; largestDownwardShift: number; sawMissing: boolean }
| {
active: boolean;
largestDownwardShift: number;
sawMissing: boolean;
sawHidden: boolean;
}
| undefined;
if (!state) throw new Error("Timeline-row stability check was not started");
state.active = false;
delete windowState.__messageSubmissionTimelineRowStability;
return { largestDownwardShift: state.largestDownwardShift, sawMissing: state.sawMissing };
return {
largestDownwardShift: state.largestDownwardShift,
sawMissing: state.sawMissing,
sawHidden: state.sawHidden,
};
});
expect(result.sawMissing).toBe(false);
expect(result.sawHidden).toBe(false);
expect(result.largestDownwardShift).toBeLessThanOrEqual(2);
};
}
@@ -1178,7 +1192,13 @@ test.describe("Agent message submission", () => {
test.setTimeout(120_000);
const toasts = await recordPanelToasts(page);
const pending = await beginDraftCreateSubmission(page, draftCreateScenario);
// The created agent takes over the draft's timeline: the same row stays mounted and painted.
const finishTimelineRowStabilityCheck = await beginTimelineRowStabilityCheck(
page,
pending.userMessage,
);
await completeDraftCreateSubmission(page, draftCreateScenario, pending);
await finishTimelineRowStabilityCheck();
// A chat this client just created is current by construction; it is never out of date.
await toasts.expectNeverShown("agent-updating-toast");
});
@@ -1,8 +1,14 @@
import { test, expect } from "../support/fixtures";
import { openWorkspaceWithAgents } from "../support/helpers/archive-tab";
import { fillComposerDraft } from "../support/helpers/composer";
import {
expectComposerToolbarOnTextRails,
expectNoCollapsedComposerToolbarFrame,
expectNoFrameTruncatesModelBesideThinking,
readSettledModelTriggerLabels,
recordComposerToolbarFrames,
recordModelTriggerFramesFromLoad,
sweepModelTriggerLabels,
} from "../support/helpers/composer-control-density";
import { clickNewChat, gotoWorkspace } from "../support/helpers/launcher";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
@@ -124,3 +130,128 @@ test.describe("Composer controls folding on a touch device", () => {
}
});
});
test.describe("Folded model control on a phone", () => {
// Wide enough for "Ten second stream" and "Low" side by side; narrower, they no longer fit.
test.use({ viewport: { width: 480, height: 844 }, isMobile: true, hasTouch: true });
test.describe.configure({ timeout: 180_000 });
test("hides the thinking label before the model label truncates", async ({ page }) => {
const session = await seedMockAgentWorkspace({
repoPrefix: "composer-density-labels-",
title: "Label priority chat",
model: "ten-second-stream",
});
try {
await recordModelTriggerFramesFromLoad(page);
await openAgentRoute(page, session);
await expect(
page.getByTestId("combined-model-selector-thinking-label").filter({ visible: true }),
).toHaveText("Low");
await readSettledModelTriggerLabels(page);
// From the first frame on, the control never guesses: it paints both labels only once it
// has measured that they fit.
await expectNoFrameTruncatesModelBesideThinking(page);
const sweep = await sweepModelTriggerLabels(page, {
from: 480,
to: 280,
step: 4,
height: 844,
});
expect(sweep.widest).toMatchObject({
modelText: "Ten second stream",
thinkingShown: true,
modelTruncated: false,
});
expect(sweep.thinkingHidden).toMatchObject({
modelText: "Ten second stream",
modelTruncated: false,
});
expect(sweep.modelTruncated.width).toBeLessThan(sweep.thinkingHidden.width);
// A clean tail: the label ends on a whole word and the ellipsis, never on a space.
expect(sweep.modelTruncated).toMatchObject({
modelText: "Ten second…",
thinkingShown: false,
});
} finally {
await session.cleanup();
}
});
});
test.describe("Composer toolbar rails on touch", () => {
test.use({ isMobile: true, hasTouch: true });
test.describe.configure({ timeout: 180_000 });
for (const viewport of [
{ device: "phone", width: 390, height: 844 },
{ device: "tablet", width: 1024, height: 1366 },
]) {
test(`the toolbar starts on the text rail and ends in a disc nested in the corner on a ${viewport.device}`, async ({
page,
}) => {
await page.setViewportSize({ width: viewport.width, height: viewport.height });
const idle = await seedMockAgentWorkspace({
repoPrefix: "composer-rails-idle-",
title: "Rails idle chat",
});
let running: Awaited<ReturnType<typeof seedMockAgentWorkspace>> | null = null;
try {
await openAgentRoute(page, idle);
await expect(page.getByTestId("message-input-root").filter({ visible: true })).toBeVisible({
timeout: 30_000,
});
await test.step("empty composer: attach on the left, voice mode on the right", async () => {
await expectComposerToolbarOnTextRails(page);
});
await test.step("draft: the send disc on the right", async () => {
await fillComposerDraft(page, "Refactor the composer toolbar");
await expect(page.getByRole("button", { name: /send/i }).first()).toBeVisible();
await expectComposerToolbarOnTextRails(page);
});
running = await seedMockAgentWorkspace({
repoPrefix: "composer-rails-running-",
title: "Rails running chat",
model: "one-minute-stream",
initialPrompt: "stream for a while",
});
await openAgentRoute(page, running);
await test.step("running agent: the stop disc on the right", async () => {
await expect(page.getByRole("button", { name: /stop agent/i }).first()).toBeVisible({
timeout: 30_000,
});
await expectComposerToolbarOnTextRails(page);
});
} finally {
await idle.cleanup();
await running?.cleanup();
}
});
}
});
test.describe("Composer trailing disc on a new chat", () => {
test.use({ isMobile: true, hasTouch: true, viewport: { width: 1024, height: 1366 } });
test("an empty draft holds a disabled send disc until there is something to send", async ({
page,
}) => {
const workspace = await seedWorkspace({ repoPrefix: "composer-placeholder-send-" });
try {
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
const send = page
.getByTestId("message-input-root")
.filter({ visible: true })
.getByRole("button", { name: "Send message", exact: true });
await expect(send).toBeDisabled({ timeout: 30_000 });
await fillComposerDraft(page, "Refactor the composer toolbar");
await expect(send).toBeEnabled();
} finally {
await workspace.cleanup();
}
});
});
@@ -0,0 +1,186 @@
import type { Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
archiveWorkspaceFromDaemon,
connectNewWorkspaceDaemonClient,
createWorktreeViaDaemon,
openProjectViaDaemon,
} from "../support/helpers/new-workspace";
import { getServerId } from "../support/helpers/server-id";
import { expectWorkspaceAbsentFromSidebar } from "../support/helpers/sidebar";
import { createMockIdleAgent, openWorkspaceWithAgents } from "../support/helpers/archive-tab";
import { connectSeedClient } from "../support/helpers/seed-client";
import { createTempGitRepo } from "../support/helpers/workspace";
import { getWorkspaceTabTestIds } from "../support/helpers/workspace-tabs";
import {
archiveFromRowButton,
createGatedTeardown,
expectDirectoryPresence,
expectHostWorkspaceSettledActive,
outlastUndoWindow,
pressUndoShortcut,
rowArchiveButton,
rowKebab,
undoButton,
workspaceRow,
workspaceTitleWidth,
} from "../support/helpers/workspace-archive-undo";
import {
waitForSidebarHydration,
waitForWorkspaceInSidebar,
} from "../support/helpers/workspace-ui";
test.describe("Workspace archive undo", () => {
let client: Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
let tempRepo: { path: string; cleanup: () => Promise<void> };
const worktreeDirectories = new Set<string>();
test.describe.configure({ timeout: 120_000 });
test.beforeEach(async () => {
client = await connectNewWorkspaceDaemonClient();
tempRepo = await createTempGitRepo("archive-undo-");
});
test.afterEach(async () => {
for (const directory of worktreeDirectories) {
await archiveWorkspaceFromDaemon(client, directory).catch(() => undefined);
}
worktreeDirectories.clear();
await client?.close().catch(() => undefined);
await tempRepo?.cleanup().catch(() => undefined);
});
async function seedWorktree(page: Page, slug: string) {
await openProjectViaDaemon(client, tempRepo.path);
const worktree = await createWorktreeViaDaemon(client, {
cwd: tempRepo.path,
slug: `${slug}-${Date.now()}`,
});
worktreeDirectories.add(worktree.workspaceDirectory);
await gotoAppShell(page);
await waitForSidebarHydration(page);
await waitForWorkspaceInSidebar(page, {
serverId: getServerId(),
workspaceId: worktree.workspaceId,
});
return worktree;
}
test("the hover archive button overlays the title instead of narrowing it", async ({ page }) => {
const worktree = await seedWorktree(page, "archive-button-overlay");
await page.mouse.move(0, 0);
await expect(rowArchiveButton(page, worktree.workspaceId)).toHaveCount(0);
const restingWidth = await workspaceTitleWidth(page, worktree.workspaceId);
await workspaceRow(page, worktree.workspaceId).hover();
await expect(rowArchiveButton(page, worktree.workspaceId)).toBeVisible();
await expect(page.getByTestId("sidebar-workspace-trailing-scrim")).toBeVisible();
expect(await workspaceTitleWidth(page, worktree.workspaceId)).toBe(restingWidth);
const [buttonBox, kebabBox] = await Promise.all([
rowArchiveButton(page, worktree.workspaceId).boundingBox(),
rowKebab(page, worktree.workspaceId).boundingBox(),
]);
expect(buttonBox && kebabBox && buttonBox.x + buttonBox.width <= kebabBox.x).toBe(true);
});
test("Cmd/Ctrl+Z right after archiving keeps the worktree", async ({ page }) => {
const worktree = await seedWorktree(page, "archive-undo-shortcut");
await archiveFromRowButton(page, worktree.workspaceId);
await pressUndoShortcut(page);
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible();
await expect(undoButton(page)).toHaveCount(0);
await expectHostWorkspaceSettledActive(client, worktree.workspaceId);
// Once the host settled, any remove the canceled archive sent has already arrived.
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible();
await expectDirectoryPresence(worktree.workspaceDirectory, true);
});
test("Undo after the worktree was removed recreates it", async ({ page }) => {
const worktree = await seedWorktree(page, "archive-undo-recreate");
await archiveFromRowButton(page, worktree.workspaceId);
// Hovering the toast holds it, and with it the undo, open while the archive finishes.
await undoButton(page).hover();
await expectDirectoryPresence(worktree.workspaceDirectory, false);
await undoButton(page).click();
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible({ timeout: 30_000 });
await expectDirectoryPresence(worktree.workspaceDirectory, true);
});
test("hovering Undo keeps the toast open past its deadline, and its close ends the undo", async ({
page,
}) => {
await page.clock.install({ time: Date.now() });
const worktree = await seedWorktree(page, "archive-undo-hold");
await archiveFromRowButton(page, worktree.workspaceId);
await page.getByTestId("workspace-archived-toast").hover({ position: { x: 8, y: 8 } });
await undoButton(page).hover();
await outlastUndoWindow(page);
await expect(undoButton(page)).toBeVisible();
await page.mouse.move(0, 0);
await outlastUndoWindow(page);
await expect(undoButton(page)).toHaveCount(0);
// The toast took the undo with it.
await pressUndoShortcut(page);
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
});
test("opening the workspace while its undo is still running keeps its tabs", async ({ page }) => {
const teardown = createGatedTeardown();
const repo = await createTempGitRepo("archive-undo-tabs-", {
paseoConfig: teardown.paseoConfig,
});
const seedClient = await connectSeedClient();
try {
await openProjectViaDaemon(client, repo.path);
const worktree = await createWorktreeViaDaemon(client, {
cwd: repo.path,
slug: `archive-undo-tabs-${Date.now()}`,
});
worktreeDirectories.add(worktree.workspaceDirectory);
const target = { cwd: worktree.workspaceDirectory, workspaceId: worktree.workspaceId };
const agents = [
await createMockIdleAgent(seedClient, { ...target, title: "first" }),
await createMockIdleAgent(seedClient, { ...target, title: "second" }),
] as const;
await openWorkspaceWithAgents(page, [agents[0], agents[1]]);
const tabsBefore = await getWorkspaceTabTestIds(page);
await archiveFromRowButton(page, worktree.workspaceId);
// The archive has taken its agents down and now parks in teardown.
await teardown.expectStarted();
await undoButton(page).click();
await workspaceRow(page, worktree.workspaceId).click();
for (const agent of agents) {
await expect(page.getByTestId(`workspace-tab-agent_${agent.id}`).first()).toBeVisible();
}
teardown.release();
await expectHostWorkspaceSettledActive(client, worktree.workspaceId);
await expect.poll(() => getWorkspaceTabTestIds(page)).toEqual(tabsBefore);
} finally {
teardown.release();
await seedClient.close().catch(() => undefined);
await repo.cleanup().catch(() => undefined);
}
});
test("Cmd/Ctrl+Z without an archive to undo leaves the sidebar alone", async ({ page }) => {
const worktree = await seedWorktree(page, "archive-undo-none");
await pressUndoShortcut(page);
await expect(undoButton(page)).toHaveCount(0);
await expect(workspaceRow(page, worktree.workspaceId)).toBeVisible();
});
});
@@ -53,3 +53,192 @@ export async function expectNoCollapsedComposerToolbarFrame(page: Page): Promise
const collapsed = frames.filter((frame) => frame.labels.some((label) => label === ""));
expect(collapsed, `collapsed toolbar frames: ${JSON.stringify(collapsed)}`).toEqual([]);
}
/** What the folded model control's labels show, read from the DOM. */
export interface ModelTriggerLabelState {
thinkingShown: boolean;
modelShown: boolean;
modelText: string;
modelTruncated: boolean;
}
declare global {
interface Window {
__modelTriggerFrames?: ModelTriggerLabelState[];
}
}
function readModelTriggerLabelStateInPage(): ModelTriggerLabelState {
const visible = (node: Element) => node.getClientRects().length > 0;
const model = Array.from(
document.querySelectorAll('[data-testid="combined-model-selector-model-label"]'),
).find(visible);
const thinking = Array.from(
document.querySelectorAll('[data-testid="combined-model-selector-thinking-label"]'),
).find(visible);
const shown = (node: Element | null): boolean => {
for (let current = node; current; current = current.parentElement) {
if (Number(getComputedStyle(current).opacity) === 0) return false;
}
return true;
};
const modelShown = model !== undefined && shown(model);
const modelText = model?.textContent ?? "";
return {
modelShown,
modelText,
thinkingShown: modelShown && thinking !== undefined,
modelTruncated:
model !== undefined && (modelText.endsWith("…") || model.scrollWidth > model.clientWidth),
};
}
/** Records the folded model control's labels on every painted frame from page load. */
export async function recordModelTriggerFramesFromLoad(page: Page): Promise<void> {
await page.addInitScript(`(() => {
const read = ${readModelTriggerLabelStateInPage.toString()};
const frames = [];
window.__modelTriggerFrames = frames;
const tick = () => {
frames.push(read());
requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
})()`);
}
/** The model control's labels once two reads 100ms apart agree. */
export async function readSettledModelTriggerLabels(page: Page): Promise<ModelTriggerLabelState> {
let previous = await page.evaluate(readModelTriggerLabelStateInPage);
for (;;) {
await page.waitForTimeout(100);
const next = await page.evaluate(readModelTriggerLabelStateInPage);
if (JSON.stringify(next) === JSON.stringify(previous)) return next;
previous = next;
}
}
/** The labels at the widths where the folded model control changes what it shows. */
export interface ModelTriggerLabelSweep {
/** The labels at the widest width. */
widest: ModelTriggerLabelState & { width: number };
/** The first width at which the thinking label is hidden. */
thinkingHidden: ModelTriggerLabelState & { width: number };
/** The first width at which the model label is truncated. */
modelTruncated: ModelTriggerLabelState & { width: number };
}
/**
* Narrows the viewport step by step and records where the thinking label disappears and where the
* model label first truncates.
*/
export async function sweepModelTriggerLabels(
page: Page,
widths: { from: number; to: number; step: number; height: number },
): Promise<ModelTriggerLabelSweep> {
const steps: (ModelTriggerLabelState & { width: number })[] = [];
for (let width = widths.from; width >= widths.to; width -= widths.step) {
await page.setViewportSize({ width, height: widths.height });
const labels = await readSettledModelTriggerLabels(page);
steps.push({ ...labels, width });
if (labels.modelTruncated || !labels.modelShown) break;
}
const thinkingHidden = steps.find((step) => !step.thinkingShown);
const modelTruncated = steps.find((step) => step.modelTruncated);
if (!thinkingHidden || !modelTruncated) {
throw new Error(`the sweep never hid the thinking label and truncated the model label`);
}
return { widest: steps[0], thinkingHidden, modelTruncated };
}
/** No frame recorded so far painted a truncated model label beside the thinking label. */
export async function expectNoFrameTruncatesModelBesideThinking(page: Page): Promise<void> {
const frames = await page.evaluate(() => window.__modelTriggerFrames ?? []);
expect(frames.some((frame) => frame.modelShown)).toBe(true);
const wrong = frames
.map((frame, index) => ({ ...frame, index }))
.filter((frame) => frame.thinkingShown && frame.modelTruncated);
expect(wrong, `of ${frames.length} frames`).toEqual([]);
}
/** Where the composer toolbar's ends sit against the composer, in CSS pixels. */
export interface ComposerToolbarRails {
/** Where the text column starts. */
textLeft: number;
/** Where the toolbar's leftmost ink starts. */
inkLeft: number;
/** How far the trailing disc sits from the composer's right edge. */
discRightInset: number;
/** How far the trailing disc sits from the composer's bottom edge. */
discBottomInset: number;
}
/**
* Reads where the toolbar's ink starts against the text column and where the trailing disc sits
* in the composer's corner. A control's ink is its filled disc when it has one, otherwise its
* glyph's stroked geometry.
*/
export async function readComposerToolbarRails(page: Page): Promise<ComposerToolbarRails> {
const root = page.locator('[data-testid="message-input-root"]:visible').first();
return root.evaluate((element) => {
const textarea = element.querySelector("textarea");
if (!textarea) throw new Error("composer has no text input");
const composerRect = element.getBoundingClientRect();
const textLeft =
textarea.getBoundingClientRect().left +
Number.parseFloat(getComputedStyle(textarea).paddingLeft);
const isFilled = (node: Element) => {
const color = getComputedStyle(node).backgroundColor;
return color !== "" && color !== "transparent" && !/rgba\(.*,\s*0\)$/.test(color);
};
const glyphInkLeft = (svg: SVGSVGElement) => {
let left = Number.POSITIVE_INFINITY;
for (const shape of Array.from(
svg.querySelectorAll<SVGGraphicsElement>("path, circle, rect, line, polyline"),
)) {
const matrix = shape.getScreenCTM();
if (!matrix) continue;
const box = shape.getBBox();
const stroke = Number.parseFloat(getComputedStyle(shape).strokeWidth || "0");
left = Math.min(left, matrix.a * (box.x - stroke / 2) + matrix.e);
}
return left;
};
const band = composerRect.bottom - 64;
let inkLeft = Number.POSITIVE_INFINITY;
let trailingDisc: DOMRect | null = null;
for (const control of Array.from(element.querySelectorAll('[role="button"]'))) {
const rect = control.getBoundingClientRect();
if (rect.width === 0 || rect.top < band) continue;
const disc = [control, ...Array.from(control.querySelectorAll("div"))].find(isFilled);
const svg = control.querySelector("svg");
if (disc) {
const discRect = disc.getBoundingClientRect();
inkLeft = Math.min(inkLeft, discRect.left);
if (!trailingDisc || discRect.right > trailingDisc.right) trailingDisc = discRect;
} else if (svg) {
inkLeft = Math.min(inkLeft, glyphInkLeft(svg));
}
}
if (!trailingDisc) throw new Error("composer toolbar has no trailing disc");
return {
textLeft,
inkLeft,
discRightInset: composerRect.right - trailingDisc.right,
discBottomInset: composerRect.bottom - trailingDisc.bottom,
};
});
}
/**
* The toolbar's left ink sits on the text column's edge, and its trailing disc nests into the
* corner, as far from the right edge as from the bottom edge. Within half a pixel.
*/
export async function expectComposerToolbarOnTextRails(page: Page): Promise<void> {
const rails = await readComposerToolbarRails(page);
// A precision of 0 digits passes within half a pixel.
expect(rails.inkLeft).toBeCloseTo(rails.textLeft, 0);
expect(rails.discRightInset).toBeCloseTo(rails.discBottomInset, 0);
}
@@ -0,0 +1,97 @@
import { existsSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Page } from "@playwright/test";
import { expect } from "../fixtures";
import type { connectNewWorkspaceDaemonClient } from "./new-workspace";
import { getServerId } from "./server-id";
import { expectWorkspaceAbsentFromSidebar } from "./sidebar";
type DaemonClient = Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
const UNDO_SHORTCUT = process.platform === "darwin" ? "Meta+Z" : "Control+Z";
/** The archived toast's lifetime, from `WORKSPACE_ARCHIVE_UNDO_WINDOW_MS`. */
const UNDO_WINDOW_MS = 6000;
export function workspaceRow(page: Page, workspaceId: string) {
return page.getByTestId(`sidebar-workspace-row-${getServerId()}:${workspaceId}`);
}
export function rowArchiveButton(page: Page, workspaceId: string) {
return page.getByTestId(`sidebar-workspace-archive-button-${getServerId()}:${workspaceId}`);
}
export function rowKebab(page: Page, workspaceId: string) {
return page.getByTestId(`sidebar-workspace-kebab-${getServerId()}:${workspaceId}`);
}
export function undoButton(page: Page) {
return page.getByRole("button", { name: /^Undo/ });
}
export async function workspaceTitleWidth(page: Page, workspaceId: string): Promise<number> {
const box = await page
.getByTestId(`sidebar-workspace-title-${getServerId()}:${workspaceId}`)
.boundingBox();
if (!box) throw new Error(`Title of ${workspaceId} is not laid out`);
return box.width;
}
/** Archives a workspace with its row's hover button and waits for the undo toast. */
export async function archiveFromRowButton(page: Page, workspaceId: string): Promise<void> {
page.once("dialog", (dialog) => void dialog.accept());
await workspaceRow(page, workspaceId).hover();
await rowArchiveButton(page, workspaceId).click();
await expectWorkspaceAbsentFromSidebar(page, workspaceId);
await expect(undoButton(page)).toBeVisible();
}
export async function pressUndoShortcut(page: Page): Promise<void> {
await page.keyboard.press(UNDO_SHORTCUT);
}
/** Moves the page clock past the moment an unheld archived toast would have closed. */
export async function outlastUndoWindow(page: Page): Promise<void> {
await page.clock.fastForward(UNDO_WINDOW_MS + 1000);
}
/** Waits until the host lists the workspace as active with no archive running on it. */
export async function expectHostWorkspaceSettledActive(
client: DaemonClient,
workspaceId: string,
): Promise<void> {
await expect
.poll(
async () => {
const { entries } = await client.fetchWorkspaces();
const entry = entries.find((candidate) => candidate.id === workspaceId);
return entry ? { active: true, archiving: Boolean(entry.archivingAt) } : null;
},
{ timeout: 30_000 },
)
.toEqual({ active: true, archiving: false });
}
export async function expectDirectoryPresence(directory: string, present: boolean): Promise<void> {
await expect.poll(() => existsSync(directory), { timeout: 30_000 }).toBe(present);
}
export interface GatedTeardown {
/** The `paseo.json` config whose worktree teardown parks until released. */
paseoConfig: Record<string, unknown>;
expectStarted(): Promise<void>;
release(): void;
}
/** A worktree teardown that parks an archive mid-flight, so an undo lands while it runs. */
export function createGatedTeardown(): GatedTeardown {
const gateDir = mkdtempSync(path.join(tmpdir(), "archive-undo-gate-"));
const startedPath = path.join(gateDir, "started");
const releasePath = path.join(gateDir, "release");
const teardown = `node -e "const fs=require('fs');fs.writeFileSync('${startedPath}','started');const timer=setInterval(()=>{if(fs.existsSync('${releasePath}'))clearInterval(timer)},20)"`;
return {
paseoConfig: { worktree: { teardown: [teardown] } },
expectStarted: () => expectDirectoryPresence(startedPath, true),
release: () => writeFileSync(releasePath, "release\n"),
};
}
@@ -54,6 +54,28 @@ using namespace facebook::react;
[[RCTComponentViewFactory currentComponentViewFactory] registerComponentViewClass:self];
}
// iOS 26 blurs a scroll view's edges and places the blur in the scroll view's own coordinates,
// ignoring transforms. The keyboard lifts the chat with a translateY, so on iPhones the blur lands
// over the readable chat and stays until the next scroll (#7883). React Native hides it for
// inverted lists for the same reason (https://github.com/react/react-native/pull/58684). The app
// draws its own header fade, so every edge is hidden; hiding only top and bottom leaves the side
// effects, which also cover a transformed list on device.
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
#if defined(__IPHONE_26_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_26_0
if (@available(iOS 26.0, *)) {
UIScrollView *scrollView = self.scrollView;
scrollView.topEdgeEffect.hidden = YES;
scrollView.bottomEdgeEffect.hidden = YES;
scrollView.leftEdgeEffect.hidden = YES;
scrollView.rightEdgeEffect.hidden = YES;
}
#endif
}
return self;
}
- (void)mountingTransactionWillMount:(const MountingTransaction &)transaction
withSurfaceTelemetry:(const SurfaceTelemetry &)surfaceTelemetry
{
+1
View File
@@ -18,6 +18,7 @@ import { getModeVisuals, type AgentProviderDefinition } from "@getpaseo/protocol
export interface AgentControlIconProps {
size: number;
color: string;
strokeWidth?: number;
}
export type AgentControlIcon = ComponentType<AgentControlIconProps>;
@@ -65,7 +65,6 @@ interface BottomAnchorControllerDriver {
pendingVerification: AttemptContext | null;
blockedReason: BottomAnchorBlockedReason | null;
};
resetForAgent: () => void;
applyRouteRequest: (request: BottomAnchorRouteRequest | null) => void;
requestLocalAnchor: (request: BottomAnchorLocalRequest) => void;
beginUserScroll: () => void;
@@ -480,17 +479,6 @@ function createBottomAnchorControllerDriver(
blockedReason,
};
},
resetForAgent() {
lastRouteRequestKey = null;
pendingRequest = null;
blockedReason = null;
cancelPendingAttempt();
stickyMeasurementRevision = 0;
lastVerifiedStickyMeasurementRevision = 0;
isUserScrollActive = false;
mode = "sticky-bottom";
input.onModeChange("sticky-bottom");
},
applyRouteRequest(request) {
if (!request) {
return;
@@ -741,10 +729,6 @@ export function useBottomAnchorController(input: {
});
}
useEffect(() => {
driverRef.current?.resetForAgent();
}, [input.agentId]);
useEffect(() => {
driverRef.current?.applyRouteRequest(input.routeRequest);
}, [input.routeRequest]);
@@ -129,7 +129,8 @@ function mountList(heldRowId: string) {
}
return position - state.scroll;
};
return { render, scrollTo, heldRowTop };
const rowSize = (rowId: string) => listRef.current?.getState().sizes.get(rowId);
return { render, scrollTo, heldRowTop, rowSize };
}
it("anchors a data change on a held row whose top is above the viewport", async () => {
@@ -169,3 +170,21 @@ it("anchors a size change on a held row whose top is above the viewport", async
expect(list.heldRowTop()).toBe(-20);
});
it("keeps measured row sizes while the list is not laid out", async () => {
// A hidden retained tab is display: none. Its rows still render, and a row measured there
// reports 0 x 0. When the tab shows again, a row whose frame did not change gets no new layout
// event, so a 0 recorded while hidden would stay and the next row would overlap it.
const rows: Row[] = Array.from({ length: 3 }, (_, index) => ({ id: `row-${index}`, height: 40 }));
const list = mountList("row-0");
list.render(rows);
await wait(150);
expect(rows.map((row) => list.rowSize(row.id))).toEqual([40, 40, 40]);
host.style.display = "none";
await wait(150);
list.render(rows.map((row) => ({ ...row })));
await wait(150);
expect(rows.map((row) => list.rowSize(row.id))).toEqual([40, 40, 40]);
});
@@ -137,9 +137,8 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
} = props;
const { renderHistoryMountedRow, renderLiveHeadRow, renderLiveAuxiliary } = renderers;
const listRef = useRef<LegendListRef>(null);
// LegendList places the rows of each agent once, behind a hidden reveal (`dataKey`).
const [placedAgentId, setPlacedAgentId] = useState<string | null>(null);
const isListPlaced = placedAgentId === agentId;
// LegendList places the rows once, behind a hidden reveal, when the list mounts.
const [isListPlaced, setIsListPlaced] = useState(false);
const isListPlacedRef = useRef(isListPlaced);
isListPlacedRef.current = isListPlaced;
const streamViewportMetricsRef = useRef({
@@ -384,23 +383,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
);
useEffect(() => {
streamViewportMetricsRef.current = {
containerKey: "native-virtualized",
contentHeight: 0,
viewportWidth: 0,
viewportHeight: 0,
offsetY: 0,
viewportMeasuredForKey: null,
contentMeasuredForKey: null,
};
scrollOffsetYRef.current = 0;
isUserScrollActiveRef.current = false;
clearPendingUserScrollEnd();
disclosureHold.cancel();
historyStartReadyRef.current = false;
const initialHistoryStartState = createHistoryStartPaginationState();
historyStartPaginationStateRef.current = initialHistoryStartState;
setHistoryStartPaginationState(initialHistoryStartState);
const frame = requestAnimationFrame(() => {
historyStartReadyRef.current = true;
evaluateHistoryStart();
@@ -411,7 +393,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
historyStartSettleSchedulerRef.current?.cancel();
historyStartSettleSchedulerRef.current = null;
};
}, [agentId, clearPendingUserScrollEnd, disclosureHold, evaluateHistoryStart]);
}, [clearPendingUserScrollEnd, evaluateHistoryStart]);
useEffect(() => {
const handle: StreamViewportHandle = {
@@ -623,7 +605,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
const handleListPlaced = useStableEvent(() => {
isListPlacedRef.current = true;
setPlacedAgentId(agentId);
setIsListPlaced(true);
streamViewportMetricsRef.current = {
...streamViewportMetricsRef.current,
contentMeasuredForKey: "native-virtualized",
@@ -711,7 +693,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
onContentSizeChange={handleContentSizeChange}
onItemSizeChanged={handleItemSizeChanged}
onReady={handleListPlaced}
dataKey={agentId}
maintainVisibleContentPosition={maintainVisibleContentPosition}
renderScrollComponent={renderScrollComponent}
recycleItems={false}
+2 -10
View File
@@ -839,10 +839,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
]);
useEffect(() => {
const initialHistoryStartState = createHistoryStartPaginationState();
historyStartPaginationStateRef.current = initialHistoryStartState;
setHistoryStartPaginationState(initialHistoryStartState);
readingAnchor.reset();
const frame = window.requestAnimationFrame(() => {
historyStartReadyRef.current = true;
evaluateHistoryStart();
@@ -853,7 +849,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
historyStartSettleSchedulerRef.current?.cancel();
historyStartSettleSchedulerRef.current = null;
};
}, [evaluateHistoryStart, props.agentId, readingAnchor]);
}, [evaluateHistoryStart]);
useLayoutEffect(() => {
if (!isActiveRef.current || !isActivationReady) {
@@ -1395,11 +1391,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
export function createWebStreamStrategy(input: CreateWebStreamStrategyInput): StreamStrategy {
return createStreamStrategy({
render: (renderInput) => (
<WebStreamViewport
key={renderInput.agentId}
{...renderInput}
isMobileBreakpoint={input.isMobileBreakpoint}
/>
<WebStreamViewport {...renderInput} isMobileBreakpoint={input.isMobileBreakpoint} />
),
orderTailReverse: false,
orderHeadReverse: false,
@@ -21,7 +21,7 @@ describe("useStreamHistoryWindow", () => {
]).flat();
const { result } = renderHook(() =>
useStreamHistoryWindow({ agentId: "agent-1", items, loadRemoteOlder: vi.fn() }),
useStreamHistoryWindow({ items, loadRemoteOlder: vi.fn() }),
);
expect(result.current.start).toBe(2);
@@ -35,7 +35,6 @@ describe("useStreamHistoryWindow", () => {
const loadRemoteOlder = vi.fn(async () => true);
const { result } = renderHook(() =>
useStreamHistoryWindow({
agentId: "agent-1",
items: [
message("u1", "user_message"),
message("a1", "assistant_message"),
@@ -67,8 +66,7 @@ describe("useStreamHistoryWindow", () => {
message("a2", "assistant_message"),
];
const { result, rerender } = renderHook(
({ history }) =>
useStreamHistoryWindow({ agentId: "agent-1", items: history, loadRemoteOlder: vi.fn() }),
({ history }) => useStreamHistoryWindow({ items: history, loadRemoteOlder: vi.fn() }),
{ initialProps: { history: items } },
);
@@ -91,8 +89,7 @@ describe("useStreamHistoryWindow", () => {
message("a2", "assistant_message"),
];
const { result, rerender } = renderHook(
({ history }) =>
useStreamHistoryWindow({ agentId: "agent-1", items: history, loadRemoteOlder: vi.fn() }),
({ history }) => useStreamHistoryWindow({ items: history, loadRemoteOlder: vi.fn() }),
{ initialProps: { history: items } },
);
@@ -108,8 +105,7 @@ describe("useStreamHistoryWindow", () => {
configurable: true,
});
const { result, rerender } = renderHook(
({ history }) =>
useStreamHistoryWindow({ agentId: "agent-1", items: history, loadRemoteOlder: vi.fn() }),
({ history }) => useStreamHistoryWindow({ items: history, loadRemoteOlder: vi.fn() }),
{
initialProps: {
history: [
@@ -142,7 +138,6 @@ describe("useStreamHistoryWindow", () => {
});
const { result } = renderHook(() =>
useStreamHistoryWindow({
agentId: "agent-1",
items: [
message("u1", "user_message"),
message("a1", "assistant_message"),
@@ -28,22 +28,17 @@ function findEarlierHistoryWindowStart(input: {
}
interface HistoryWindowBoundary {
agentId: string;
boundaryItemId: string | null;
initialized: boolean;
}
function reconcileHistoryWindow(input: {
current: HistoryWindowBoundary;
agentId: string;
boundaryIndex: number;
initialBoundaryItemId: string | null;
hasItems: boolean;
}): HistoryWindowBoundary {
const { current, agentId, boundaryIndex, initialBoundaryItemId, hasItems } = input;
if (current.agentId !== agentId) {
return { agentId, boundaryItemId: initialBoundaryItemId, initialized: hasItems };
}
const { current, boundaryIndex, initialBoundaryItemId, hasItems } = input;
if (!current.initialized && hasItems) {
return { ...current, boundaryItemId: initialBoundaryItemId, initialized: true };
}
@@ -54,28 +49,26 @@ function reconcileHistoryWindow(input: {
}
export function useStreamHistoryWindow(input: {
agentId: string;
items: StreamItem[];
loadRemoteOlder: () => boolean | Promise<boolean>;
}) {
const { agentId, items, loadRemoteOlder } = input;
const { items, loadRemoteOlder } = input;
const initialStart = useMemo(
() => findMountedWindowStart({ items, minMountedCount: getMountedRecentStreamItems() }),
[items],
);
const initialBoundaryItemId = initialStart === 0 ? null : (items[initialStart]?.id ?? null);
const [window, setWindow] = useState(() => ({
agentId,
boundaryItemId: initialBoundaryItemId,
initialized: items.length > 0,
}));
const boundaryItemId = window.agentId === agentId ? window.boundaryItemId : null;
const boundaryItemId = window.boundaryItemId;
const boundaryIndex = useMemo(
() => (boundaryItemId === null ? -1 : items.findIndex((item) => item.id === boundaryItemId)),
[boundaryItemId, items],
);
let start = initialStart;
if (window.agentId === agentId && window.initialized) {
if (window.initialized) {
if (window.boundaryItemId === null) {
start = 0;
} else if (boundaryIndex >= 0) {
@@ -87,13 +80,12 @@ export function useStreamHistoryWindow(input: {
setWindow((current) =>
reconcileHistoryWindow({
current,
agentId,
boundaryIndex,
initialBoundaryItemId,
hasItems: items.length > 0,
}),
);
}, [agentId, boundaryIndex, initialBoundaryItemId, items.length]);
}, [boundaryIndex, initialBoundaryItemId, items.length]);
const revealLoadedHistory = useCallback(
(itemId?: string): boolean => {
@@ -106,13 +98,12 @@ export function useStreamHistoryWindow(input: {
return false;
}
setWindow({
agentId,
boundaryItemId: items[nextStart]?.id ?? null,
initialized: true,
});
return true;
},
[agentId, items, start],
[items, start],
);
const loadOlder = useCallback(async (): Promise<boolean> => {
return revealLoadedHistory() || (await loadRemoteOlder());
+1 -6
View File
@@ -430,10 +430,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
loadOlder: historyPagination.onLoadOlder,
}
: agentHistoryPagination;
useEffect(() => {
setExpandedInlineToolCallIds(new Set());
setExpandedTurnHostIds(new Set());
}, [agentId]);
const isActive = useRetainedPanelActive();
const openInlineFile = useStableEvent(
@@ -476,7 +472,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
useEffect(() => {
if (!isActive) inlinePathOpener.cancel();
return () => inlinePathOpener.cancel();
}, [inlinePathOpener, isActive, agentId]);
}, [inlinePathOpener, isActive]);
const handleInlinePathPress = useStableEvent(
(target: InlinePathTarget, disposition: OpenFileDisposition) => {
if (isActive) void inlinePathOpener.open(target, disposition);
@@ -551,7 +547,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
revealLoadedHistory,
loadOlder,
} = useStreamHistoryWindow({
agentId,
items: presentation.tail,
loadRemoteOlder,
});
+2
View File
@@ -55,6 +55,7 @@ import { DesktopWindowControls } from "@/components/desktop/window-controls";
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
import { WorkspaceRenameHost } from "@/components/workspace-rename-host";
import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo";
import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture";
import { ProviderSettingsHost } from "@/components/provider-settings-host";
import { WorkspaceSetupDialog } from "@/components/workspace-setup-dialog";
@@ -557,6 +558,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
<PluginCommandCenterActions />
<WorkspacePinShortcutHandler />
<WorkspaceRenameHost />
<WorkspaceArchiveUndoShortcutHost />
<CommandCenter />
<AddProjectFlowHost />
<HostChooserModal />
@@ -13,7 +13,11 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import {
TOOLBAR_GLYPH_SIZES,
toolbarContentSlot,
type ToolbarGlyph,
} from "@/components/ui/control-geometry";
const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
@@ -61,7 +65,7 @@ interface CombinedModelSelectorProps {
*/
triggerFill?: boolean;
toolbar?: {
glyphSize: number;
glyph: ToolbarGlyph;
showCaret: boolean;
};
}
@@ -253,11 +257,13 @@ export function CombinedModelSelector({
chevron={toolbar?.showCaret === false ? null : undefined}
>
{selectedProvider.trim().length > 0 ? (
<View style={toolbar?.glyphSize === 20 ? styles.toolbarGlyph20 : styles.toolbarGlyph16}>
<View style={toolbar ? styles.toolbarGlyph : styles.glyph}>
<ModelProviderGlyph
provider={selectedProvider}
serverId={serverId}
size={toolbar?.glyphSize ?? ICON_SIZE.md}
size={toolbar?.glyph.size ?? ICON_SIZE.md}
strokeWidth={toolbar?.glyph.strokeWidth}
tone={toolbar?.glyph.tone}
/>
</View>
) : null}
@@ -293,31 +299,30 @@ const styles = StyleSheet.create((theme) => ({
paddingHorizontal: 0,
},
trigger: {
height: TOOLBAR_CONTROL_HEIGHT,
minWidth: 0,
flexShrink: 1,
flexDirection: "row",
alignItems: "center",
backgroundColor: "transparent",
gap: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius["2xl"],
...toolbarContentSlot(theme.spacing[2]),
borderRadius: theme.borderRadius.full,
},
triggerHovered: {
backgroundColor: theme.colors.surface2,
},
toolbarGlyph16: {
width: 16,
height: 16,
glyph: {
width: ICON_SIZE.md,
height: ICON_SIZE.md,
flexShrink: 0,
},
toolbarGlyph20: {
width: 20,
height: 20,
toolbarGlyph: {
width: TOOLBAR_GLYPH_SIZES.label,
height: TOOLBAR_GLYPH_SIZES.label,
flexShrink: 0,
},
triggerPressed: {
backgroundColor: theme.colors.surface0,
backgroundColor: theme.colors.surface2,
},
triggerDisabled: {
opacity: 0.5,
@@ -329,9 +334,11 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
// A custom trigger, such as a form field, owns its own box: none of the toolbar slot applies.
customTriggerWrapper: {
paddingHorizontal: 0,
paddingVertical: 0,
marginHorizontal: 0,
height: "auto",
},
triggerFill: {
@@ -1,5 +1,11 @@
import { useCallback, useMemo, useState } from "react";
import { Pressable, Text, View, useWindowDimensions } from "react-native";
import {
Pressable,
type PressableStateCallbackType,
Text,
View,
useWindowDimensions,
} from "react-native";
import Svg, { Circle } from "react-native-svg";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
@@ -9,7 +15,7 @@ import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative } from "@/constants/platform";
import { useHostReportsUsage } from "@/usage";
import type { Theme } from "@/styles/theme";
import { TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { TOOLBAR_DISC_SIZE, type ToolbarRing } from "@/components/ui/control-geometry";
import { ContextWindowDetails } from "./context-window-details";
import { ContextWindowSheet } from "./context-window-sheet";
import { formatContextPercentage } from "./context-window-meter.utils";
@@ -21,8 +27,8 @@ interface ContextWindowMeterProps {
usedTokens: number | null;
totalCostUsd?: number | null;
showPercentage?: boolean;
/** Optional glyph envelope for icon-toolbar alignment. */
glyphSize?: number;
/** The ring's box and stroke when it sits in an icon toolbar. */
toolbarRing?: ToolbarRing;
}
const SVG_SIZE = 14;
@@ -71,7 +77,7 @@ function getProgressColor(percentage: number, theme: Theme): string {
return theme.colors.foregroundMuted;
}
function getMeterGeometry(showPercentage: boolean, glyphSize?: number) {
function getMeterGeometry(showPercentage: boolean, ring?: ToolbarRing) {
if (showPercentage) {
return {
svgSize: COMPACT_SVG_SIZE,
@@ -80,8 +86,8 @@ function getMeterGeometry(showPercentage: boolean, glyphSize?: number) {
containerStyle: styles.containerWithLabel,
};
}
const resolvedSize = glyphSize ?? SVG_SIZE;
const resolvedStrokeWidth = glyphSize ? 2 : STROKE_WIDTH;
const resolvedSize = ring?.size ?? SVG_SIZE;
const resolvedStrokeWidth = ring?.strokeWidth ?? STROKE_WIDTH;
return {
svgSize: resolvedSize,
radius: (resolvedSize - resolvedStrokeWidth) / 2,
@@ -151,7 +157,7 @@ export function ContextWindowMeter({
usedTokens,
totalCostUsd,
showPercentage = false,
glyphSize,
toolbarRing,
}: ContextWindowMeterProps) {
const { t, i18n } = useTranslation();
const { width } = useWindowDimensions();
@@ -165,7 +171,7 @@ export function ContextWindowMeter({
const closeSheet = useCallback(() => setIsSheetOpen(false), []);
const percentage =
maxTokens !== null && usedTokens !== null ? getUsagePercentage(maxTokens, usedTokens) : null;
const geometry = getMeterGeometry(showPercentage, glyphSize);
const geometry = getMeterGeometry(showPercentage, toolbarRing);
const context = useMemo(
() =>
@@ -184,6 +190,10 @@ export function ContextWindowMeter({
const formattedSessionCost =
typeof totalCostUsd === "number" ? formatSessionCost(totalCostUsd) : null;
const containerStyle = geometry.containerStyle;
const pressableStyle = useCallback(
({ pressed }: PressableStateCallbackType) => [containerStyle, pressed && styles.pressed],
[containerStyle],
);
const ring = (
<ContextWindowRing
size={geometry.svgSize}
@@ -207,7 +217,7 @@ export function ContextWindowMeter({
return (
<>
<Pressable
style={containerStyle}
style={pressableStyle}
testID="context-window-meter"
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
@@ -241,7 +251,7 @@ export function ContextWindowMeter({
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile>
<TooltipTrigger asChild triggerRefProp="ref">
<Pressable
style={containerStyle}
style={pressableStyle}
testID="context-window-meter"
accessibilityRole="image"
accessibilityLabel={accessibilityLabel}
@@ -307,20 +317,23 @@ export function ContextWindowMeter({
const styles = StyleSheet.create((theme) => ({
container: {
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
width: TOOLBAR_DISC_SIZE,
height: TOOLBAR_DISC_SIZE,
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
},
containerWithLabel: {
height: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_DISC_SIZE,
flexDirection: "row",
alignItems: "center",
justifyContent: "center",
gap: theme.spacing[1],
borderRadius: theme.borderRadius.full,
},
pressed: {
backgroundColor: theme.colors.surface2,
},
percentageLabel: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
@@ -1,42 +0,0 @@
import { act } from "react";
import { createRoot } from "react-dom/client";
import { within, waitFor } from "@testing-library/dom";
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
import { expect, it } from "vitest";
import { normalizeMarkdownHtml } from "./html";
const FLAGS = { hardSoftBreaks: true, latexMath: false };
it.each([false, true])(
"renders table-cell breaks on separate lines (details: %s)",
async (details) => {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
const table =
"| A | B |\n|---|---|\n| 1 | first<br/>second |\n| 2 | first<br />second |\n| 3 | first<br>second |";
const source = details ? `<details><summary>Results</summary>\n${table}\n</details>` : table;
try {
act(() =>
root.render(
<EnrichedMarkdownText markdown={normalizeMarkdownHtml(source)} md4cFlags={FLAGS} />,
),
);
await waitFor(() => expect(within(container).getAllByRole("row")).toHaveLength(4));
for (const row of within(container).getAllByRole("row").slice(1)) {
const cell = within(row).getAllByRole("cell")[1];
expect(cell.innerText).toBe("first\nsecond");
const first = document.createRange();
first.selectNodeContents(cell.firstChild!);
const second = document.createRange();
second.selectNodeContents(cell.lastChild!);
expect(second.getBoundingClientRect().top).toBeGreaterThan(
first.getBoundingClientRect().top,
);
}
} finally {
act(() => root.unmount());
container.remove();
}
},
);
+7 -25
View File
@@ -1,7 +1,5 @@
import { Parser } from "htmlparser2";
import { fromMarkdown } from "mdast-util-from-markdown";
import { gfmTable } from "micromark-extension-gfm-table";
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
import { decodeString } from "micromark-util-decode-string";
import type { Nodes } from "mdast";
@@ -36,35 +34,25 @@ const EMPHASIS: Readonly<Record<string, string>> = { b: "**", strong: "**", i: "
export function normalizeMarkdownHtml(source: string): string {
if (!source.includes("<")) return source;
const htmlRanges: { start: number; end: number }[] = [];
const tableRanges: { start: number; end: number }[] = [];
function findHtml(node: Nodes) {
if (node.type === "html" && node.position) {
htmlRanges.push({ start: node.position.start.offset!, end: node.position.end.offset! });
} else if ("children" in node) node.children.forEach(findHtml);
}
findHtml(
fromMarkdown(source, {
extensions: [gfmTable()],
mdastExtensions: [gfmTableFromMarkdown()],
}),
);
findHtml(fromMarkdown(source));
const codeRanges: { start: number; end: number }[] = [];
// Disable HTML parsing so code and tables inside <details> remain visible.
// Disable HTML parsing so code inside <details> remains visible to the Markdown parser.
const tree = fromMarkdown(source, {
extensions: [{ disable: { null: ["htmlFlow", "htmlText"] } }, gfmTable()],
mdastExtensions: [gfmTableFromMarkdown()],
extensions: [{ disable: { null: ["htmlFlow", "htmlText"] } }],
});
function findMarkdownRanges(node: Nodes) {
if (node.type === "table" && node.position) {
tableRanges.push({ start: node.position.start.offset!, end: node.position.end.offset! });
}
function protectCode(node: Nodes) {
if (node.type === "code" || node.type === "inlineCode") {
const start = node.position?.start.offset;
const end = node.position?.end.offset;
if (start !== undefined && end !== undefined) codeRanges.push({ start, end });
} else if ("children" in node) node.children.forEach(findMarkdownRanges);
} else if ("children" in node) node.children.forEach(protectCode);
}
findMarkdownRanges(tree);
protectCode(tree);
const links: (string | undefined)[] = [];
let previousTag: { name: string; end: number } | null = null;
const convert = (raw: string, offset: number): string => {
@@ -96,13 +84,6 @@ export function normalizeMarkdownHtml(source: string): string {
: /^\s*$/.test(source.slice(0, offset));
previousTag = { name, end: offset + raw.length };
if (EMPHASIS[name]) return EMPHASIS[name];
if (name === "br") {
if (closing) return "";
// A Unicode line separator keeps the row intact; its space ends GFM autolinks.
return tableRanges.some(({ start, end }) => offset >= start && offset < end)
? " \u2028"
: " \n";
}
const boundary = layoutBoundary(name, source, raw, offset, closing, startsAfterBoundary);
if (boundary !== null) return boundary;
if (name === "a") return markdownAnchor(raw, closing, links);
@@ -187,6 +168,7 @@ function layoutBoundary(
closing: boolean,
startsAfterBoundary: boolean,
): string | null {
if (name === "br") return closing ? "" : " \n";
if (name === "summary") return closing ? "**\n\n" : "**";
if (name === "details")
return (closing ? offset + raw.length === source.length : offset === 0) ? "" : "\n\n";
@@ -39,88 +39,6 @@ it("resolves authored root-relative links only when the target is a known comman
});
describe("shared Markdown source adaptation", () => {
it("keeps HTML line breaks inside their Markdown table cells", async () => {
const source =
"| A | B |\n|---|---|\n| 1 | first<br/>second |\n| 2 | first<br />second |\n| 3 | first<br>second |";
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const rows: ASTNode[] = [];
const collect = (node: ASTNode) => {
if (node.type === "TableRow") rows.push(node);
node.children?.forEach(collect);
};
collect(tree);
expect(rows).toHaveLength(4);
const text = (node: ASTNode): string =>
(node.content ?? "") + (node.children?.map(text).join("") ?? "");
expect(rows.map((row) => row.children?.map(text))).toEqual([
["A", "B"],
["1", "first \u2028second"],
["2", "first \u2028second"],
["3", "first \u2028second"],
]);
});
it("keeps table breaks inside a details wrapper without a blank line", async () => {
const source =
"<details><summary>Results</summary>\n| A | B |\n|---|---|\n| 1 | first<br>second |\n</details>";
const tree = await parseMarkdown(prepareMarkdownSource(source).render(), {
hardSoftBreaks: true,
latexMath: false,
});
const tables: ASTNode[] = [];
const collect = (node: ASTNode) => {
if (node.type === "Table") tables.push(node);
node.children?.forEach(collect);
};
collect(tree);
expect(tables).toHaveLength(1);
expect(tables[0].attributes?.bodyRowCount).toBe("1");
expect(tables[0].children?.[1]?.children?.[0]?.children?.[1]?.children).toEqual([
{ type: "Text", content: "first \u2028second" },
]);
});
it.each([
["src/first.ts", "src/second.ts"],
["https://example.com/first", "src/second.ts"],
["https://example.com/first", "https://example.com/second"],
])("keeps %s and %s separate across a table break", async (first, second) => {
const prepared = prepareMarkdownSource(
`| A | B |\n|---|---|\n| 1 | ${first}<br>${second} |`,
"/repo",
);
const tree = recognizeTextLinks(
await parseMarkdown(prepared.render(), { hardSoftBreaks: true, latexMath: false }),
prepared.linkRecognition.text,
prepared.linkRecognition.inlineCode,
);
const links: string[] = [];
const collect = (node: ASTNode) => {
if (node.type === "Link") links.push(String(node.attributes?.url));
node.children?.forEach(collect);
};
collect(tree);
expect(links).toEqual([first, second]);
});
it.each([
["| A<br>B | C |\n|---|---|\n| x | y |", "| A \u2028B | C |\n|---|---|\n| x | y |"],
[
"> | A | B |\n> |---|---|\n> | x | first<br>second |",
"> | A | B |\n> |---|---|\n> | x | first \u2028second |",
],
[
"| A | B |\n|---|---|\n| `<br>` | **first<br><BR />second** |",
"| A | B |\n|---|---|\n| `<br>` | **first \u2028 \u2028second** |",
],
[
"| A | B |\n|---|---|\n| x | \\<br> &lt;br&gt; |",
"| A | B |\n|---|---|\n| x | \\<br> &lt;br&gt; |",
],
["Not a table | first<br>second", "Not a table | first \nsecond"],
])("normalizes table breaks without changing literal tags: %s", (source, expected) => {
expect(normalizeMarkdownHtml(source)).toBe(expected);
});
it("keeps paragraphs, fences and quotes together for the library", () => {
const source = "First paragraph.\n\nSecond paragraph.\n\n```ts\nconst n = 1;\n```\n\n> Quote";
expect(prepareMarkdownSource(source).render()).toBe(source);
@@ -10,10 +10,9 @@ import type { Link, Nodes, Paragraph, PhrasingContent, Root } from "mdast";
// Keep this regex in the syntax shared by JavaScript, ICU and java.util.regex.
// The Unicode flag makes Metro expand it to escapes rejected by native engines.
// U+2028 is an inline line break, including between table-cell file links.
const PATH_CHARACTER = String.raw`[a-zA-Z0-9\u0080-\u2027\u2029-\uFFFF_@.%+-]`;
const PATH_CHARACTER = String.raw`[a-zA-Z0-9\u0080-\uFFFF_@.%+-]`;
const PATH_LETTER = String.raw`[a-zA-Z]`;
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9\u0080-\u2027\u2029-\uFFFF_@%+-]`;
const PATH_SEGMENT = String.raw`${PATH_CHARACTER}*[a-zA-Z0-9\u0080-\uFFFF_@%+-]`;
const LINE_SUFFIX = String.raw`(?::\d+(?::\d+)?(?:-\d+(?::\d+)?)?)?`;
const FILE_EXTENSIONS = [...ASSISTANT_FILE_EXTENSIONS]
.map((extension) => extension.replace(/[a-z]/g, (letter) => `[${letter}${letter.toUpperCase()}]`))
@@ -30,7 +29,7 @@ function createTextPattern(path: string, forgeReferencePattern?: string): RegExp
const forgeReference = forgeReferencePattern ? `|${forgeReferencePattern}` : "";
// The native adapter mistakes a literal + in lookbehind for a quantifier; use its hex escape.
return new RegExp(
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9\u0080-\u2027\u2029-\uFFFF_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9\u0080-\u2027\u2029-\uFFFF_@%+:/\\-]|\.${PATH_CHARACTER}))`,
String.raw`(?:${BARE_URL}${forgeReference}|(?<![a-zA-Z0-9\u0080-\uFFFF_@.%\x2b~:/\\-])(?:${path}|${FILE_NAME})${LINE_SUFFIX}(?![a-zA-Z0-9\u0080-\uFFFF_@%+:/\\-]|\.${PATH_CHARACTER}))`,
"g",
);
}
@@ -216,17 +216,19 @@ export function ModelProviderGlyph({
provider,
serverId,
size,
strokeWidth,
tone = "muted",
}: {
provider: string;
serverId: string | null;
size: number;
strokeWidth?: number;
tone?: ProviderGlyphTone;
}) {
const Icon = useProviderIcon(provider, serverId);
const color =
tone === "foreground" ? styles.providerIconForeground.color : styles.providerIconMuted.color;
return <Icon size={size} color={color} />;
return <Icon size={size} strokeWidth={strokeWidth} color={color} />;
}
function HeaderSettingsIcon({ disabled }: { disabled: boolean }) {
@@ -20,6 +20,8 @@ import { resolveProviderIconName } from "@/components/provider-icon-name";
export interface ProviderIconProps {
size: number;
color: string;
/** Honoured by outline glyphs such as the fallback; brand marks are filled and ignore it. */
strokeWidth?: number;
}
export type ProviderIconComponent = ComponentType<ProviderIconProps>;
@@ -649,6 +649,7 @@ function WorkspaceRowRightGroup({
const {
trailingPresentation,
showKebab: showKebabInSlot,
showArchiveButton,
showScrim,
renderSlot,
reserveSlotWidth,
@@ -675,6 +676,8 @@ function WorkspaceRowRightGroup({
<SidebarWorkspaceTrailingActionOverlay
visible={kebab.showKebab}
scrimBackdrop={showScrim ? backdrop : undefined}
workspaceKey={workspace.workspaceKey}
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
>
{onArchive ? (
<SidebarWorkspaceMenu
@@ -872,6 +872,7 @@ function StatusWorkspaceRowInnerContent({
const {
trailingPresentation,
showKebab: showKebabInSlot,
showArchiveButton,
showScrim,
renderSlot,
reserveSlotWidth,
@@ -951,6 +952,7 @@ function StatusWorkspaceRowInnerContent({
trailing={trailing}
trailingPresentation={trailingPresentation}
showKebab={showKebabInSlot}
showArchiveButton={showArchiveButton}
showScrim={showScrim}
reserveSlotWidth={reserveSlotWidth}
isPinned={isPinned}
@@ -982,6 +984,7 @@ function StatusWorkspaceActionSlot({
trailing,
trailingPresentation,
showKebab,
showArchiveButton,
showScrim,
reserveSlotWidth,
isPinned,
@@ -1002,6 +1005,7 @@ function StatusWorkspaceActionSlot({
trailing: SidebarWorkspaceTrailing;
trailingPresentation: SidebarWorkspaceTrailingPresentation;
showKebab: boolean;
showArchiveButton: boolean;
showScrim: boolean;
reserveSlotWidth: boolean;
isPinned?: boolean;
@@ -1026,6 +1030,8 @@ function StatusWorkspaceActionSlot({
<SidebarWorkspaceTrailingActionOverlay
visible={kebab.showKebab}
scrimBackdrop={showScrim ? backdrop : undefined}
workspaceKey={workspace.workspaceKey}
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
>
{kebab.showKebab && onArchive ? (
<SidebarWorkspaceMenu
@@ -1,6 +1,6 @@
import { useMemo, type ComponentProps, type PropsWithChildren, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { type PressableStateCallbackType } from "react-native";
import type { PressableStateCallbackType } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import {
Archive,
@@ -13,6 +13,7 @@ import {
PinOff,
Tag,
} from "lucide-react-native";
import { PressHighlight } from "@/components/ui/press-highlight";
import { isWeb } from "@/constants/platform";
import { getForgePresentation, normalizeForge } from "@/git/forge";
import type { SidebarWorkspaceEntry } from "@/hooks/use-sidebar-workspaces-list";
@@ -72,6 +73,9 @@ const archiveLeadingIcon = <ThemedArchive size={14} uniProps={foregroundMutedCol
const pinLeadingIcon = <ThemedPin size={14} uniProps={foregroundMutedColorMapping} />;
const unpinLeadingIcon = <ThemedPinOff size={14} uniProps={foregroundMutedColorMapping} />;
/** Pointer-only, so it is always the kebab's pointer size. */
export const ARCHIVE_BUTTON_SIZE = 18;
const triggerIconProps = densityIconProps("sm", foregroundMutedColorMapping);
const triggerIconHoveredProps = densityIconProps("sm", foregroundColorMapping);
@@ -79,6 +83,33 @@ function renderTriggerIcon({ hovered }: { hovered?: boolean }) {
return <ThemedMoreVertical uniProps={hovered ? triggerIconHoveredProps : triggerIconProps} />;
}
function renderArchiveIcon({ hovered }: PressableStateCallbackType & { hovered?: boolean }) {
return <ThemedArchive uniProps={hovered ? triggerIconHoveredProps : triggerIconProps} />;
}
/** One-click archive beside the kebab, for pointer rows that reveal it on hover. */
export function SidebarWorkspaceArchiveButton({
workspaceKey,
onArchive,
}: {
workspaceKey: string;
onArchive: () => void;
}) {
const { t } = useTranslation();
return (
<PressHighlight
hitSlop={4}
style={archiveButtonStyle}
onPress={onArchive}
accessibilityRole={isWeb ? undefined : "button"}
accessibilityLabel={t("sidebar.workspace.actions.archiveWorkspace")}
testID={`sidebar-workspace-archive-button-${workspaceKey}`}
>
{renderArchiveIcon}
</PressHighlight>
);
}
export interface SidebarWorkspaceMenuProps {
workspaceKey: string;
serverId?: string;
@@ -437,6 +468,12 @@ function triggerStyle({ hovered = false }: PressableStateCallbackType & { hovere
return [styles.trigger, hovered && styles.triggerHovered];
}
function archiveButtonStyle({
hovered = false,
}: PressableStateCallbackType & { hovered?: boolean }) {
return [styles.archiveButton, hovered && styles.triggerHovered];
}
const styles = StyleSheet.create((theme) => ({
trigger: {
// Larger on touch so the kebab is an easy tap target.
@@ -455,4 +492,13 @@ const styles = StyleSheet.create((theme) => ({
triggerHovered: {
backgroundColor: theme.colors.surface2,
},
// The kebab's box without its offsets: the archive glyph fills its view box, so it needs
// none of the nudging the three dots do. The kebab's marginLeft is the gap between them.
archiveButton: {
width: ARCHIVE_BUTTON_SIZE,
height: ARCHIVE_BUTTON_SIZE,
alignItems: "center",
justifyContent: "center",
borderRadius: 4,
},
}));
@@ -29,7 +29,11 @@ import { shouldRenderSyncedStatusLoader } from "@/utils/status-loader";
import { StatusRing } from "@/components/status-ring";
import { resolveSidebarWorkspacePrimaryLabel } from "@/components/sidebar/sidebar-workspace-title";
import { DensityIcon } from "@/components/ui/density-icon";
import { TrailingActionScrim } from "@/components/ui/trailing-action-scrim";
import { SCRIM_WIDTH, TrailingActionScrim } from "@/components/ui/trailing-action-scrim";
import {
ARCHIVE_BUTTON_SIZE,
SidebarWorkspaceArchiveButton,
} from "@/components/sidebar/sidebar-workspace-menu";
import { useWorkspaceLabelDefinitions } from "@/workspace-labels";
const needsInputColorMapping = (theme: Theme) => ({
@@ -156,7 +160,11 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
)}
<View style={styles.workspaceContentColumn}>
<View style={styles.workspaceTitleRow}>
<Text style={workspaceBranchTextStyle} numberOfLines={1}>
<Text
style={workspaceBranchTextStyle}
numberOfLines={1}
testID={`sidebar-workspace-title-${workspace.workspaceKey}`}
>
{workspaceLabel}
</Text>
<View style={sidebarWorkspaceRowStyles.rowRight}>{children}</View>
@@ -330,6 +338,8 @@ export const sidebarWorkspaceRowStyles = StyleSheet.create((theme) => ({
position: "absolute",
top: 0,
right: 0,
flexDirection: "row",
alignItems: "flex-start",
},
}));
@@ -370,6 +380,7 @@ export function resolveTrailingActionVisibility({
}): {
trailingPresentation: SidebarWorkspaceTrailingPresentation;
showKebab: boolean;
showArchiveButton: boolean;
showScrim: boolean;
renderSlot: boolean;
reserveSlotWidth: boolean;
@@ -384,6 +395,9 @@ export function resolveTrailingActionVisibility({
return {
trailingPresentation,
showKebab,
// One-click archive is a pointer affordance: on touch it would sit a few pixels from the
// kebab and turn a miss into an archive.
showArchiveButton: showKebab && isHovered && !isTouchPlatform,
// The scrim paints the row's own hover background, so it can only be drawn on a hovered
// row — over an unhovered one the gradient fades to the wrong color. That is also why
// touch, which shows the kebab without ever hovering, never gets one.
@@ -432,23 +446,46 @@ export function SidebarWorkspaceTrailingActionBase({
);
}
// The archive button plus the kebab's marginLeft, which is the gap between them.
const ARCHIVE_BUTTON_SCRIM_WIDTH = ARCHIVE_BUTTON_SIZE + 2;
export function SidebarWorkspaceTrailingActionOverlay({
visible,
scrimBackdrop,
workspaceKey,
onArchiveButtonPress,
children,
}: {
visible: boolean;
/** Fade the row into the kebab when something (the diff stat) is still rendered behind it. */
scrimBackdrop?: SidebarSurfaceBackdrop;
workspaceKey: string;
/**
* Shows the archive button left of the kebab. It overlays the title like the kebab does, so
* the scrim widens to cover it rather than the slot reserving its width.
*/
onArchiveButtonPress?: () => void;
children: ReactNode;
}) {
if (!visible || !children) return null;
return (
<>
{scrimBackdrop ? (
<TrailingActionScrim backdrop={scrimBackdrop} testID="sidebar-workspace-trailing-scrim" />
<TrailingActionScrim
backdrop={scrimBackdrop}
width={onArchiveButtonPress ? SCRIM_WIDTH + ARCHIVE_BUTTON_SCRIM_WIDTH : SCRIM_WIDTH}
testID="sidebar-workspace-trailing-scrim"
/>
) : null}
<View style={sidebarWorkspaceRowStyles.trailingActionOverlay}>{children}</View>
<View style={sidebarWorkspaceRowStyles.trailingActionOverlay}>
{onArchiveButtonPress ? (
<SidebarWorkspaceArchiveButton
workspaceKey={workspaceKey}
onArchive={onArchiveButtonPress}
/>
) : null}
{children}
</View>
</>
);
}
@@ -404,6 +404,7 @@ function WorkspaceRowTrailingActions({
const {
trailingPresentation,
showKebab: showKebabInSlot,
showArchiveButton,
showScrim,
renderSlot,
reserveSlotWidth,
@@ -430,6 +431,8 @@ function WorkspaceRowTrailingActions({
<SidebarWorkspaceTrailingActionOverlay
visible={kebab.showKebab}
scrimBackdrop={showScrim ? backdrop : undefined}
workspaceKey={workspace.workspaceKey}
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
>
{onArchive ? (
<SidebarWorkspaceMenu
+50 -31
View File
@@ -35,6 +35,8 @@ export interface ToastShowOptions {
durationMs?: number | null;
nativeAndroid?: boolean;
testID?: string;
/** Runs once when this toast leaves the screen: timed out, dismissed, or replaced. */
onDismiss?: () => void;
}
export interface ToastState {
@@ -45,6 +47,7 @@ export interface ToastState {
variant: ToastVariant;
durationMs: number | null;
testID?: string;
onDismiss?: () => void;
}
/** Dismisses the toast it was returned for; a no-op once another toast replaced it. */
@@ -78,40 +81,56 @@ export function useToastHost(): {
dismiss: () => void;
} {
const { t } = useTranslation();
const [toast, setToast] = useState<ToastState | null>(null);
const [toast, setToastState] = useState<ToastState | null>(null);
const toastRef = useRef<ToastState | null>(null);
const idRef = useRef(0);
const show = useCallback((content: ReactNode, options?: ToastShowOptions): DismissToast => {
const nativeMessage = typeof content === "string" ? content.trim() : null;
if (!content || nativeMessage === "") {
return noopDismiss;
}
const variant = options?.variant ?? "default";
const durationMs = options?.durationMs === undefined ? DEFAULT_DURATION_MS : options.durationMs;
const nativeAndroid = options?.nativeAndroid ?? false;
if (Platform.OS === "android" && nativeAndroid && nativeMessage) {
const duration =
durationMs !== null && durationMs <= 2500 ? ToastAndroid.SHORT : ToastAndroid.LONG;
ToastAndroid.showWithGravity(nativeMessage, duration, ToastAndroid.TOP);
return noopDismiss;
}
idRef.current += 1;
const id = idRef.current;
setToast({
id,
content,
nativeMessage,
icon: options?.icon,
variant,
durationMs,
testID: options?.testID,
});
return () => setToast((current) => (current?.id === id ? null : current));
const setToast = useCallback((next: ToastState | null) => {
const previous = toastRef.current;
if (previous === next) return;
toastRef.current = next;
setToastState(next);
previous?.onDismiss?.();
}, []);
const show = useCallback(
(content: ReactNode, options?: ToastShowOptions): DismissToast => {
const nativeMessage = typeof content === "string" ? content.trim() : null;
if (!content || nativeMessage === "") {
return noopDismiss;
}
const variant = options?.variant ?? "default";
const durationMs =
options?.durationMs === undefined ? DEFAULT_DURATION_MS : options.durationMs;
const nativeAndroid = options?.nativeAndroid ?? false;
if (Platform.OS === "android" && nativeAndroid && nativeMessage) {
const duration =
durationMs !== null && durationMs <= 2500 ? ToastAndroid.SHORT : ToastAndroid.LONG;
ToastAndroid.showWithGravity(nativeMessage, duration, ToastAndroid.TOP);
return noopDismiss;
}
idRef.current += 1;
const id = idRef.current;
setToast({
id,
content,
nativeMessage,
icon: options?.icon,
variant,
durationMs,
testID: options?.testID,
onDismiss: options?.onDismiss,
});
return () => {
if (toastRef.current?.id === id) setToast(null);
};
},
[setToast],
);
const api = useMemo<ToastApi>(
() => ({
show,
@@ -127,7 +146,7 @@ export function useToastHost(): {
const dismiss = useCallback(() => {
setToast(null);
}, []);
}, [setToast]);
return { api, toast, dismiss };
}
@@ -12,10 +12,19 @@ import {
resolveControlSizing,
switchGeometryForLayout,
getControlInteractionPhase,
TOOLBAR_CONTROL_GAP,
TOOLBAR_CONTROL_GAPS,
TOOLBAR_CONTROL_HEIGHT,
TOOLBAR_CONTROL_SIZES,
TOOLBAR_DISC_GLYPH_SIZES,
TOOLBAR_DISC_SIZE,
TOOLBAR_DISC_SIZES,
TOOLBAR_GLYPH_SIZES,
TOOLBAR_RINGS,
toolbarGlyphColor,
toolbarGlyphsFor,
toolbarGlyphTone,
toolbarSlot,
TOUCH_TARGET,
} from "@/components/ui/control-geometry";
import type { Theme } from "@/styles/theme";
@@ -109,6 +118,62 @@ describe("control sizing gate", () => {
});
});
describe("toolbar glyphs and spacing", () => {
it("spaces touch toolbar controls by what they paint and keeps the pointer's 4px gap", () => {
expect(TOOLBAR_CONTROL_GAPS).toEqual({ touch: 20, pointer: 4 });
expect(TOOLBAR_CONTROL_GAP).toEqual({ xs: 20, md: 4 });
// A 20pt glyph's disc-sized frame reaches 8 into the gap on each side.
expect(toolbarSlot(20)).toEqual({
width: TOOLBAR_DISC_SIZE,
height: TOOLBAR_DISC_SIZE,
marginHorizontal: { xs: -8, md: 0 },
});
});
it("paints touch toolbar glyphs at the header icons' 20pt and 1.5px stroke and leaves pointer unchanged", () => {
const pointerGlyph = { size: 16, strokeWidth: 1.5, tone: "muted" };
expect(toolbarGlyphsFor("touch").icon).toEqual({
size: 20,
strokeWidth: 1.5,
tone: "foreground",
});
expect(toolbarGlyphsFor("pointer")).toEqual({ icon: pointerGlyph, label: pointerGlyph });
expect(TOOLBAR_GLYPH_SIZES.icon).toEqual({ xs: 20, md: 16 });
expect(toolbarGlyphsFor("touch").icon.size).toBeLessThan(TOOLBAR_CONTROL_SIZES.touch);
expect(toolbarGlyphsFor("pointer").icon.size).toBeLessThan(TOOLBAR_CONTROL_SIZES.pointer);
// A disc's solid glyph stays at the `md` size so the stop square does not fill its disc.
expect(TOOLBAR_DISC_GLYPH_SIZES).toEqual({ touch: 20, pointer: 16 });
});
it("keeps a touch glyph beside a label at the label's 20pt scale", () => {
expect(toolbarGlyphsFor("touch").label).toEqual({
size: 20,
strokeWidth: 1.5,
tone: "foreground",
});
expect(TOOLBAR_GLYPH_SIZES.label).toEqual({ xs: 20, md: 16 });
});
it("sizes the touch context ring to the toolbar glyph's ink and keeps the pointer ring", () => {
expect(TOOLBAR_RINGS).toEqual({
touch: { size: 18, strokeWidth: 2 },
pointer: { size: 16, strokeWidth: 2 },
});
});
it("brightens a muted toolbar glyph under a hovering pointer", () => {
const pointer = toolbarGlyphsFor("pointer").icon;
const touch = toolbarGlyphsFor("touch").icon;
expect(toolbarGlyphTone(pointer, false)).toBe("muted");
expect(toolbarGlyphTone(pointer, true)).toBe("foreground");
expect(toolbarGlyphTone(touch, false)).toBe("foreground");
const colors = { foreground: "#fafafa", foregroundMuted: "#a1a5a4" };
const palette = { colors } as unknown as Theme;
expect(toolbarGlyphColor(palette, "foreground")).toBe("#fafafa");
expect(toolbarGlyphColor(palette, "muted")).toBe("#a1a5a4");
});
});
describe("control geometry", () => {
it("keeps resting control borders transparent while preserving border geometry", () => {
const geometry = createControlGeometry(theme);
@@ -1,5 +1,5 @@
import type { StyleProp, ViewStyle } from "react-native";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { ICON_SIZE, ICON_STROKE_WIDTH, type Theme } from "@/styles/theme";
import {
bySizing,
controlSizingForLayout,
@@ -87,20 +87,63 @@ export const ICON_BUTTON_SIZES = {
} satisfies Record<"large" | "small", SizingValue>;
/**
* A control in a dense toolbar row, such as the composer's: an icon-only square or a labelled
* pill. Touch-sized it is one touch target.
* The height of a dense toolbar row, such as the composer's. Touch-sized it is one touch target;
* its controls are disc-sized and centre in it.
*/
export const TOOLBAR_CONTROL_SIZES = { touch: TOUCH_TARGET, pointer: 28 } satisfies SizingValue;
export const TOOLBAR_CONTROL_HEIGHT = bySizing(TOOLBAR_CONTROL_SIZES);
/**
* The painted disc of a filled toolbar control, such as the composer's send and stop. The
* control keeps the full toolbar hit frame and paints this smaller disc centered inside it, so
* touch-sized it does not outweigh its unpainted neighbours. Pointer-sized it fills the frame.
* The disc of a filled toolbar control, such as the composer's send and stop, and the frame and
* highlight of every other toolbar control (`toolbarSlot`). Pointer-sized it fills the row.
*/
export const TOOLBAR_DISC_SIZES = { touch: 36, pointer: 28 } satisfies SizingValue;
export const TOOLBAR_DISC_SIZE = bySizing(TOOLBAR_DISC_SIZES);
/**
* The space between adjacent toolbar controls. Touch-sized it is the visible space between what
* the controls paint, because each control lays out at its painted width (`toolbarSlot`).
*/
export const TOOLBAR_CONTROL_GAPS = { touch: 20, pointer: 4 } satisfies SizingValue;
export const TOOLBAR_CONTROL_GAP = bySizing(TOOLBAR_CONTROL_GAPS);
/**
* A toolbar control's frame: a disc-sized circle, which is also its fully rounded highlight.
* Touch-sized it lays out at the width of the glyph it paints, `shapeWidth`, and the circle reaches
* into the gaps on either side, so the row spaces what you see. Pointer-sized it is the square
* control.
*/
export function toolbarSlot(shapeWidth: number): {
width: LayoutValue;
height: LayoutValue;
marginHorizontal: LayoutValue;
} {
return {
width: TOOLBAR_DISC_SIZE,
height: TOOLBAR_DISC_SIZE,
marginHorizontal: bySizing({
touch: (shapeWidth - TOOLBAR_DISC_SIZES.touch) / 2,
pointer: 0,
}),
};
}
/**
* A toolbar control as wide as its content, such as a labelled picker: a disc-tall pill. Touch-sized
* its padding reaches into the gaps, so its content is what the row spaces.
*/
export function toolbarContentSlot(padding: number): {
height: LayoutValue;
paddingHorizontal: number;
marginHorizontal: LayoutValue;
} {
return {
height: TOOLBAR_DISC_SIZE,
paddingHorizontal: padding,
marginHorizontal: bySizing({ touch: -padding, pointer: 0 }),
};
}
/**
* Glyph sizes. Pointer glyphs sit beside 13-14pt text; touch glyphs sit beside iOS's 17pt body
* text, so each step is larger.
@@ -112,6 +155,81 @@ export function iconSizeFor(size: IconSize): SizingValue {
return { touch: TOUCH_ICON_SIZE[size], pointer: ICON_SIZE[size] };
}
/**
* The glyph a toolbar control paints. Touch-sized every toolbar glyph matches the header icons:
* 20pt at the app's 1.5px stroke, resting at `foreground`. Pointer-sized it is the `md` glyph at
* the same stroke and rests muted until hovered.
*/
export type ToolbarGlyphTone = "foreground" | "muted";
export interface ToolbarGlyph {
size: number;
strokeWidth: number;
/** The tone at rest; a hovering pointer brightens it to `foreground`. */
tone: ToolbarGlyphTone;
}
/** `icon` is an icon-only control's glyph; `label` is a glyph paired with a label. */
export interface ToolbarGlyphs {
icon: ToolbarGlyph;
label: ToolbarGlyph;
}
const POINTER_TOOLBAR_GLYPH: ToolbarGlyph = {
size: ICON_SIZE.md,
strokeWidth: ICON_STROKE_WIDTH,
tone: "muted",
};
const TOOLBAR_GLYPHS: Record<ControlSizing, ToolbarGlyphs> = {
touch: {
icon: { size: TOUCH_ICON_SIZE.md, strokeWidth: ICON_STROKE_WIDTH, tone: "foreground" },
label: { size: TOUCH_ICON_SIZE.md, strokeWidth: ICON_STROKE_WIDTH, tone: "foreground" },
},
pointer: { icon: POINTER_TOOLBAR_GLYPH, label: POINTER_TOOLBAR_GLYPH },
};
export function toolbarGlyphsFor(sizing: ControlSizing): ToolbarGlyphs {
return TOOLBAR_GLYPHS[sizing];
}
/** The slot each toolbar glyph sits in, as stylesheet values. */
export const TOOLBAR_GLYPH_SIZES = {
icon: bySizing({ touch: TOOLBAR_GLYPHS.touch.icon.size, pointer: POINTER_TOOLBAR_GLYPH.size }),
label: bySizing({ touch: TOOLBAR_GLYPHS.touch.label.size, pointer: POINTER_TOOLBAR_GLYPH.size }),
} satisfies Record<keyof ToolbarGlyphs, LayoutValue>;
/**
* The context ring in a toolbar row. A full circle fills its box while an outline glyph's ink
* sits inset, so touch-sized the ring is 18pt, the height of a 20pt glyph's ink. Its 2px stroke
* is half a pixel over the glyphs' so the thin circle does not read lighter than them.
* Pointer-sized it is the `md` glyph.
*/
export interface ToolbarRing {
size: number;
strokeWidth: number;
}
export const TOOLBAR_RINGS = {
touch: { size: 18, strokeWidth: 2 },
pointer: { size: ICON_SIZE.md, strokeWidth: 2 },
} satisfies Record<ControlSizing, ToolbarRing>;
export function toolbarGlyphTone(glyph: ToolbarGlyph, hovered: boolean): ToolbarGlyphTone {
return hovered ? "foreground" : glyph.tone;
}
export function toolbarGlyphColor(theme: Theme, tone: ToolbarGlyphTone): string {
return tone === "foreground" ? theme.colors.foreground : theme.colors.foregroundMuted;
}
/**
* The solid glyph inside a toolbar disc, such as the stop square. It stays at the `md` glyph
* size: at the toolbar glyph size the square would fill half its disc. Send's outline arrow
* takes the toolbar glyph.
*/
export const TOOLBAR_DISC_GLYPH_SIZES = iconSizeFor("md");
/** The height of a control of `size`, for code that has to compute with it outside a stylesheet. */
export function controlHeightForLayout(size: ControlSize, isCompact: boolean): number {
return CONTROL_SIZES[size][controlSizingForLayout(isCompact)];
@@ -0,0 +1,61 @@
import React, { act, useMemo } from "react";
import { createRoot, type Root } from "react-dom/client";
import { View } from "react-native";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { TailEllipsisText } from "./index";
// App sources compile against the classic JSX runtime, which expects React on the global.
beforeEach(() => vi.stubGlobal("React", React));
let root: Root;
let host: HTMLDivElement;
beforeEach(() => {
host = document.createElement("div");
document.body.appendChild(host);
root = createRoot(host);
});
afterEach(() => {
act(() => root.unmount());
host.remove();
});
const TEXT_STYLE = { fontSize: 16, fontFamily: "monospace" } as const;
function LabelRow({ text, width }: { text: string; width: number }) {
const rowStyle = useMemo(() => ({ width, flexDirection: "row" as const }), [width]);
return (
<View style={rowStyle}>
<TailEllipsisText text={text} style={TEXT_STYLE} testID="label" />
</View>
);
}
function renderLabel(text: string, width: number): void {
act(() => root.render(<LabelRow text={text} width={width} />));
}
function shownLabel(): { text: string; visible: boolean } {
const label = host.querySelector<HTMLElement>('[data-testid="label"]');
if (!label) throw new Error("label did not render");
return { text: label.textContent ?? "", visible: getComputedStyle(label).opacity !== "0" };
}
it("shows a replacement label that shares its shortened prefixes with the previous one", async () => {
// Wide enough for "Ten second…" in monospace, too narrow for either full label.
const width = 12 * 10;
renderLabel("Ten second stream", width);
await vi.waitFor(() => expect(shownLabel()).toEqual({ text: "Ten second…", visible: true }));
renderLabel("Ten second thread", width);
await vi.waitFor(() => expect(shownLabel()).toEqual({ text: "Ten second…", visible: true }));
});
it("shows a replacement label as wide as the previous one", async () => {
renderLabel("Opus 4.7", 400);
await vi.waitFor(() => expect(shownLabel()).toEqual({ text: "Opus 4.7", visible: true }));
renderLabel("Opus 4.8", 400);
await vi.waitFor(() => expect(shownLabel()).toEqual({ text: "Opus 4.8", visible: true }));
});
@@ -0,0 +1,145 @@
import { useCallback, useMemo, useState } from "react";
import { Text, View, type LayoutChangeEvent, type StyleProp, type TextStyle } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { readMeasuredWidth } from "@/hooks/use-container-width";
import { resolveTailEllipsis, tailEllipsisCandidates } from "./resolve";
interface MeasuredWidths {
text: string;
full?: number;
candidates: (number | undefined)[];
}
/**
* One line of text that shrinks with its row and, when it does not fit, ends on a whole word
* and an ellipsis ("Ten second…"), never on a space. It measures itself, so it stays invisible
* for the frame before its widths are known.
*/
export function TailEllipsisText({
text,
style,
testID,
}: {
text: string;
/** Text styles; the component owns its layout. */
style: StyleProp<TextStyle>;
testID?: string;
}) {
const candidates = useMemo(() => tailEllipsisCandidates(text), [text]);
const [boxWidth, setBoxWidth] = useState<number | undefined>(undefined);
const [widths, setWidths] = useState<MeasuredWidths>({ text, candidates: [] });
const current = widths.text === text ? widths : { text, candidates: [] };
const onBoxLayout = useCallback((event: LayoutChangeEvent) => {
const width = readMeasuredWidth(event);
if (width !== null) setBoxWidth(width);
}, []);
const measure = useCallback(
(slot: "full" | number) => (event: LayoutChangeEvent) => {
const width = readMeasuredWidth(event);
if (width === null) return;
setWidths((previous) => {
const base = previous.text === text ? previous : { text, candidates: [] };
if (slot === "full") return { ...base, full: width };
const next = [...base.candidates];
next[slot] = width;
return { ...base, candidates: next };
});
},
[text],
);
const decision = resolveTailEllipsis({
candidates,
measurements: { boxWidth, fullWidth: current.full, candidateWidths: current.candidates },
});
const shownText = decision.kind === "truncated" ? decision.text : text;
return (
<View style={styles.box} onLayout={onBoxLayout}>
{/* Sizes the box: as wide as the text, or as the row allows. */}
<Text
style={[style, styles.sizer]}
numberOfLines={1}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
>
{text}
</Text>
<View style={styles.shown} pointerEvents="none">
<Text
style={[style, styles.shownText, decision.kind === "measuring" && styles.measuring]}
numberOfLines={1}
ellipsizeMode="tail"
testID={testID}
>
{shownText}
</Text>
</View>
{/* Keyed by the text, so new text remounts the measurer and every width is measured again.
A retained node whose size does not change emits no new layout event. */}
<View
key={text}
style={styles.measurer}
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
>
<Text style={[style, styles.measured]} numberOfLines={1} onLayout={measure("full")}>
{text}
</Text>
{candidates.map((candidate, index) => (
<Text
key={candidate}
style={[style, styles.measured]}
numberOfLines={1}
onLayout={measure(index)}
>
{candidate}
</Text>
))}
</View>
</View>
);
}
const styles = StyleSheet.create({
// A row, so the absolute measurer below lays its text out at full width on native too.
box: {
minWidth: 0,
flexShrink: 1,
flexDirection: "row",
},
sizer: {
minWidth: 0,
flexShrink: 1,
opacity: 0,
},
shown: {
position: "absolute",
left: 0,
right: 0,
top: 0,
bottom: 0,
flexDirection: "row",
alignItems: "center",
},
shownText: {
minWidth: 0,
flexShrink: 1,
},
measuring: {
opacity: 0,
},
measurer: {
position: "absolute",
left: 0,
top: 0,
flexDirection: "row",
alignItems: "flex-start",
opacity: 0,
},
measured: {
flexShrink: 0,
},
});
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vitest";
import { resolveTailEllipsis, tailEllipsisCandidates } from "./resolve";
const candidates = tailEllipsisCandidates("Ten second stream");
const candidateWidths = [34, 80];
describe("tail ellipsis", () => {
it("cuts at word boundaries, so no whitespace sits before the ellipsis", () => {
expect(candidates).toEqual(["Ten…", "Ten second…"]);
expect(tailEllipsisCandidates(" GPT-5.1 Codex ")).toEqual(["GPT-5.1…"]);
expect(tailEllipsisCandidates("claude-opus-4-5")).toEqual([]);
});
it("shows the full text while it fits", () => {
expect(
resolveTailEllipsis({
candidates,
measurements: { boxWidth: 132, fullWidth: 132.3, candidateWidths },
}),
).toEqual({ kind: "full" });
});
it("keeps the most words that fit with the ellipsis", () => {
expect(
resolveTailEllipsis({
candidates,
measurements: { boxWidth: 98, fullWidth: 132, candidateWidths },
}),
).toEqual({ kind: "truncated", text: "Ten second…" });
expect(
resolveTailEllipsis({
candidates,
measurements: { boxWidth: 60, fullWidth: 132, candidateWidths },
}),
).toEqual({ kind: "truncated", text: "Ten…" });
});
it("lets the platform cut inside a first word too long for the box", () => {
expect(
resolveTailEllipsis({
candidates,
measurements: { boxWidth: 20, fullWidth: 132, candidateWidths },
}),
).toEqual({ kind: "clipped" });
expect(
resolveTailEllipsis({
candidates: [],
measurements: { boxWidth: 60, fullWidth: 132, candidateWidths: [] },
}),
).toEqual({ kind: "clipped" });
});
it("decides nothing until the widths it needs are measured", () => {
expect(resolveTailEllipsis({ candidates, measurements: { candidateWidths } })).toEqual({
kind: "measuring",
});
expect(
resolveTailEllipsis({
candidates,
measurements: { boxWidth: 98, fullWidth: 132, candidateWidths: [34] },
}),
).toEqual({ kind: "measuring" });
});
});
@@ -0,0 +1,47 @@
const ELLIPSIS = "…";
/**
* The word-boundary truncations of `text`, shortest first: "Ten second stream" gives "Ten…" and
* "Ten second…". Cutting at a word keeps whitespace out from before the ellipsis.
*/
export function tailEllipsisCandidates(text: string): string[] {
const words = text.trim().split(/\s+/);
return words.slice(1).map((_, index) => `${words.slice(0, index + 1).join(" ")}${ELLIPSIS}`);
}
export type TailEllipsis =
| { kind: "measuring" }
| { kind: "full" }
| { kind: "truncated"; text: string }
/** Not even the first word fits: the platform ellipsis cuts inside it, where no space can sit. */
| { kind: "clipped" };
/** Widths in points, measured from the rendered text. */
export interface TailEllipsisMeasurements {
/** The space the text may take, up to its full width. */
boxWidth?: number;
fullWidth?: number;
/** One per `tailEllipsisCandidates` entry, in the same order. */
candidateWidths: readonly (number | undefined)[];
}
/** Sub-point slack for widths the layout rounds differently from the text it measures. */
const ROUNDING_SLACK = 0.5;
export function resolveTailEllipsis(input: {
candidates: readonly string[];
measurements: TailEllipsisMeasurements;
}): TailEllipsis {
const { boxWidth, fullWidth, candidateWidths } = input.measurements;
if (boxWidth === undefined || fullWidth === undefined) return { kind: "measuring" };
if (fullWidth <= boxWidth + ROUNDING_SLACK) return { kind: "full" };
if (input.candidates.some((_, index) => candidateWidths[index] === undefined)) {
return { kind: "measuring" };
}
for (let index = input.candidates.length - 1; index >= 0; index -= 1) {
if ((candidateWidths[index] ?? Infinity) <= boxWidth) {
return { kind: "truncated", text: input.candidates[index] };
}
}
return { kind: "clipped" };
}
@@ -6,9 +6,18 @@ import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import type { Theme } from "@/styles/theme";
export const SCRIM_WIDTH = 48;
const SCRIM_SOLID_OFFSET = "55%";
// The fade is a fixed length so a wider scrim only adds solid surface under its actions.
const SCRIM_FADE_WIDTH = SCRIM_WIDTH * 0.55;
function TrailingActionScrimSvg({ gradientId, color }: { gradientId: string; color: string }) {
function TrailingActionScrimSvg({
gradientId,
color,
solidOffset,
}: {
gradientId: string;
color: string;
solidOffset: string;
}) {
return (
<Svg width="100%" height="100%" preserveAspectRatio="none">
<Defs>
@@ -16,7 +25,7 @@ function TrailingActionScrimSvg({ gradientId, color }: { gradientId: string; col
{/* Vary opacity rather than interpolating toward `transparent`, which crosses black in
some engines and leaves a grey fringe. */}
<Stop offset="0%" stopColor={color} stopOpacity={0} />
<Stop offset={SCRIM_SOLID_OFFSET} stopColor={color} stopOpacity={1} />
<Stop offset={solidOffset} stopColor={color} stopOpacity={1} />
<Stop offset="100%" stopColor={color} stopOpacity={1} />
</SvgLinearGradient>
</Defs>
@@ -39,17 +48,22 @@ const backdropColorMappings: Record<SurfaceBackdrop, (theme: Theme) => { color:
/** Fades trailing content into the surface beneath an absolutely overlaid action. */
export function TrailingActionScrim({
backdrop,
width = SCRIM_WIDTH,
testID,
}: {
backdrop: SurfaceBackdrop;
/** Covers more than one trailing action; the fade keeps its length. */
width?: number;
testID?: string;
}) {
// React-generated ids contain characters that are invalid inside SVG fragment references.
const gradientId = `trailing-action-scrim-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
const solidOffset = `${Math.round((SCRIM_FADE_WIDTH / width) * 100)}%`;
return (
<View style={styles.scrim} pointerEvents="none" testID={testID}>
<View style={styles.scrim(width)} pointerEvents="none" testID={testID}>
<ThemedTrailingActionScrimSvg
gradientId={gradientId}
solidOffset={solidOffset}
uniProps={backdropColorMappings[backdrop]}
/>
</View>
@@ -57,11 +71,11 @@ export function TrailingActionScrim({
}
const styles = StyleSheet.create({
scrim: {
scrim: (width: number) => ({
position: "absolute",
top: 0,
bottom: 0,
right: 0,
width: SCRIM_WIDTH,
},
width,
}),
});
@@ -2,7 +2,7 @@ import { forwardRef, useCallback, type ComponentProps } from "react";
import { Text, View, type PressableStateCallbackType } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
import { TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { TOUCH_ICON_SIZE, toolbarContentSlot, toolbarSlot } from "@/components/ui/control-geometry";
import { useComposerControlLayout } from "@/composer/agent-controls/layout-context";
import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
import type { AgentControlIcon } from "@/agent-controls/icons";
@@ -42,10 +42,13 @@ export const AgentControlTrigger = forwardRef<View, AgentControlTriggerProps>(
},
ref,
) {
const { glyphSize } = useComposerControlLayout();
const { glyphs } = useComposerControlLayout();
const glyphRole = showToolbarLabel ? "label" : "icon";
const glyph = glyphs[glyphRole];
const isSheet = surface === "sheet";
const resolvedGlyphSize = isSheet ? 16 : glyphSize;
const resolvedIconColor = iconColor ?? styles.iconColor.color;
const toolbarIconColor =
glyph.tone === "foreground" ? styles.iconColorForeground.color : styles.iconColor.color;
const resolvedIconColor = iconColor ?? (isSheet ? styles.iconColor.color : toolbarIconColor);
const showValue = isSheet || showToolbarLabel;
const triggerStyle = useCallback(
({ pressed, hovered }: PressableStateCallbackType) => [
@@ -73,11 +76,11 @@ export const AgentControlTrigger = forwardRef<View, AgentControlTriggerProps>(
>
{isSheet ? (
<View style={styles.sheetGlyph}>
<Icon size={resolvedGlyphSize} color={resolvedIconColor} />
<Icon size={16} color={resolvedIconColor} />
</View>
) : (
<ComposerToolbarGlyph size={resolvedGlyphSize}>
<Icon size={resolvedGlyphSize} color={resolvedIconColor} />
<ComposerToolbarGlyph role={glyphRole}>
<Icon size={glyph.size} strokeWidth={glyph.strokeWidth} color={resolvedIconColor} />
</ComposerToolbarGlyph>
)}
{isSheet ? (
@@ -97,18 +100,17 @@ export const AgentControlTrigger = forwardRef<View, AgentControlTriggerProps>(
const styles = StyleSheet.create((theme) => ({
toolbarControl: {
height: TOOLBAR_CONTROL_HEIGHT,
minWidth: 0,
flexShrink: 1,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius["2xl"],
...toolbarContentSlot(theme.spacing[2]),
borderRadius: theme.borderRadius.full,
backgroundColor: "transparent",
},
toolbarIconOnly: {
width: TOOLBAR_CONTROL_HEIGHT,
...toolbarSlot(TOUCH_ICON_SIZE.md),
flexShrink: 0,
paddingHorizontal: 0,
justifyContent: "center",
@@ -160,7 +162,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface2,
},
pressed: {
backgroundColor: theme.colors.surface0,
backgroundColor: theme.colors.surface2,
},
disabled: {
opacity: 0.5,
@@ -168,4 +170,7 @@ const styles = StyleSheet.create((theme) => ({
iconColor: {
color: theme.colors.foregroundMuted,
},
iconColorForeground: {
color: theme.colors.foreground,
},
}));
@@ -1,10 +1,22 @@
import type { ReactNode } from "react";
import { StyleSheet, View } from "react-native";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { TOOLBAR_GLYPH_SIZES, type ToolbarGlyphs } from "@/components/ui/control-geometry";
export function ComposerToolbarGlyph({ children, size }: { children: ReactNode; size: number }) {
/**
* The slot a composer toolbar control's glyph sits in; see `toolbarGlyphsFor`. `label` when the
* glyph sits beside a label, `icon` when the glyph is the whole control.
*/
export function ComposerToolbarGlyph({
role,
children,
}: {
role: keyof ToolbarGlyphs;
children: ReactNode;
}) {
return (
<View
style={size >= 20 ? styles.touch : styles.pointer}
style={role === "label" ? styles.labelSlot : styles.iconSlot}
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
pointerEvents="none"
@@ -14,19 +26,9 @@ export function ComposerToolbarGlyph({ children, size }: { children: ReactNode;
);
}
const slot = { flexShrink: 0, alignItems: "center", justifyContent: "center" } as const;
const styles = StyleSheet.create({
pointer: {
width: 16,
height: 16,
flexShrink: 0,
alignItems: "center",
justifyContent: "center",
},
touch: {
width: 20,
height: 20,
flexShrink: 0,
alignItems: "center",
justifyContent: "center",
},
iconSlot: { ...slot, width: TOOLBAR_GLYPH_SIZES.icon, height: TOOLBAR_GLYPH_SIZES.icon },
labelSlot: { ...slot, width: TOOLBAR_GLYPH_SIZES.label, height: TOOLBAR_GLYPH_SIZES.label },
});
@@ -61,7 +61,16 @@ import {
resolveAgentModelSelection,
} from "@/composer/agent-controls/utils";
import { useIsCompactFormFactor } from "@/constants/layout";
import { controlSizingForLayout, TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import {
controlSizingForLayout,
TOOLBAR_CONTROL_GAP,
bySizing,
toolbarGlyphColor,
type ToolbarGlyphs,
TOUCH_ICON_SIZE,
toolbarContentSlot,
toolbarSlot,
} from "@/components/ui/control-geometry";
import { DensityIcon } from "@/components/ui/density-icon";
import { readMeasuredWidth } from "@/hooks/use-container-width";
import { useToast } from "@/contexts/toast-context";
@@ -79,7 +88,10 @@ import {
type ComposerControlDensity,
type ComposerControlPresentation,
} from "@/composer/agent-controls/layout";
import { ComposerControlLayoutProvider } from "@/composer/agent-controls/layout-context";
import {
ComposerControlLayoutProvider,
useComposerControlLayout,
} from "@/composer/agent-controls/layout-context";
import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
import { AgentControlTrigger } from "@/composer/agent-controls/control";
import { CompactModelSheet } from "@/composer/agent-controls/model-sheet";
@@ -219,10 +231,10 @@ function getFeatureIconColor(
green: { 400: string };
yellow: { 400: string };
},
foregroundMuted: string,
restColor: string,
): string {
if (!isFeatureActive(feature)) {
return foregroundMuted;
return restColor;
}
switch (getFeatureHighlightColor(feature.id)) {
@@ -233,7 +245,7 @@ function getFeatureIconColor(
case "yellow":
return palette.yellow[400];
default:
return foregroundMuted;
return restColor;
}
}
@@ -585,7 +597,7 @@ function ControlledAgentControls({
const presentation = useMemo(() => resolveComposerControlPresentation(density), [density]);
const layoutContextValue = useMemo(
() => ({
glyphSize: toolbarGeometry.glyphSize,
glyphs: toolbarGeometry.glyphs,
presentation,
}),
[presentation, toolbarGeometry],
@@ -799,7 +811,7 @@ function ControlledAgentControls({
renderThinkingOption={renderThinkingOption}
modeControl={modeControl}
presentation={presentation}
glyphSize={layoutContextValue.glyphSize}
glyphs={layoutContextValue.glyphs}
activeSheet={activeSheet}
handleOpenSheet={handleOpenSheet}
handleCloseSheet={handleCloseSheet}
@@ -838,7 +850,7 @@ function ControlledAgentControls({
handleOpenChange={handleSheetOpenChange}
renderThinkingOption={renderThinkingOption}
modeControl={modeControl}
glyphSize={layoutContextValue.glyphSize}
glyphs={layoutContextValue.glyphs}
showLabels={presentation.showModelLabel}
modelSelectorServerId={modelSelectorServerId}
canSwitchProvider={Boolean(onSelectProviderAndModel)}
@@ -900,7 +912,7 @@ interface DesktopAgentControlsContentProps {
}) => ReactElement;
modeControl?: AgentModeControlValue | null;
presentation: ComposerControlPresentation;
glyphSize: number;
glyphs: ToolbarGlyphs;
activeSheet: ActiveSheet;
handleOpenSheet: (sheet: Exclude<ActiveSheet, null>) => void;
handleCloseSheet: () => void;
@@ -957,15 +969,15 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
renderThinkingOption,
modeControl,
presentation,
glyphSize,
glyphs,
activeSheet,
handleOpenSheet,
handleCloseSheet,
modelSelectorServerId,
} = props;
const modelToolbar = useMemo(
() => ({ glyphSize, showCaret: presentation.showCarets }),
[glyphSize, presentation.showCarets],
() => ({ glyph: glyphs.label, showCaret: presentation.showCarets }),
[glyphs, presentation.showCarets],
);
const featuresSheetHeader = useMemo<SheetHeader>(
() => ({ title: t("agentControls.features.title") }),
@@ -1086,8 +1098,12 @@ function DesktopAgentControlsContent(props: DesktopAgentControlsContentProps) {
accessibilityLabel={t("agentControls.features.open")}
testID="agent-controls-features"
>
<ComposerToolbarGlyph size={glyphSize}>
<Settings2 size={glyphSize} color={theme.colors.foregroundMuted} />
<ComposerToolbarGlyph role="icon">
<Settings2
size={glyphs.icon.size}
strokeWidth={glyphs.icon.strokeWidth}
color={toolbarGlyphColor(theme, glyphs.icon.tone)}
/>
</ComposerToolbarGlyph>
</Pressable>
<AdaptiveModalSheet
@@ -1162,7 +1178,7 @@ interface SheetAgentControlsContentProps {
onPress: () => void;
}) => ReactElement;
modeControl?: AgentModeControlValue | null;
glyphSize: number;
glyphs: ToolbarGlyphs;
showLabels: boolean;
modelSelectorServerId: string | null;
canSwitchProvider: boolean;
@@ -1202,7 +1218,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
handleOpenChange,
renderThinkingOption,
modeControl,
glyphSize,
glyphs,
showLabels,
modelSelectorServerId,
canSwitchProvider,
@@ -1291,7 +1307,7 @@ function SheetAgentControlsContent(props: SheetAgentControlsContentProps) {
onRetryProvider={onRetryModelProvider}
isRetryingProvider={isRetryingModelProvider}
serverId={modelSelectorServerId}
glyphSize={glyphSize}
glyphs={glyphs}
showLabels={showLabels}
canSwitchProvider={canSwitchProvider}
>
@@ -1316,6 +1332,8 @@ function DesktopFeatureItem({
onActionComplete?: () => void;
}) {
const { theme } = useUnistyles();
const { glyphs } = useComposerControlLayout();
const restColor = toolbarGlyphColor(theme, glyphs.icon.tone);
const featureSelector: AgentControlSelector = `feature-${feature.id}`;
const featureAnchorRef = useRef<View>(null);
@@ -1356,11 +1374,7 @@ function DesktopFeatureItem({
<TooltipTrigger asChild triggerRefProp="ref">
<AgentControlTrigger
icon={FeatureIcon}
iconColor={getFeatureIconColor(
feature,
theme.colors.palette,
theme.colors.foregroundMuted,
)}
iconColor={getFeatureIconColor(feature, theme.colors.palette, restColor)}
surface="toolbar"
label={feature.label}
showToolbarLabel={false}
@@ -1391,11 +1405,7 @@ function DesktopFeatureItem({
<AgentControlTrigger
ref={featureAnchorRef}
icon={FeatureIcon}
iconColor={getFeatureIconColor(
feature,
theme.colors.palette,
theme.colors.foregroundMuted,
)}
iconColor={getFeatureIconColor(feature, theme.colors.palette, restColor)}
surface="toolbar"
label={feature.label}
value={selectedOption?.label ?? feature.label}
@@ -1972,17 +1982,20 @@ const styles = StyleSheet.create((theme) => ({
flexShrink: 1,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
gap: TOOLBAR_CONTROL_GAP,
// Clips pickers that run out of room. Touch-sized the pickers' pills and circles reach 8 past
// what the row spaces, so the clip reaches as far.
overflow: "hidden",
paddingHorizontal: bySizing({ touch: theme.spacing[2], pointer: 0 }),
marginHorizontal: bySizing({ touch: -theme.spacing[2], pointer: 0 }),
},
modeBadge: {
height: TOOLBAR_CONTROL_HEIGHT,
flexDirection: "row",
alignItems: "center",
backgroundColor: "transparent",
gap: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius["2xl"],
...toolbarContentSlot(theme.spacing[2]),
borderRadius: theme.borderRadius.full,
},
modelControl: {
minWidth: 0,
@@ -1994,8 +2007,7 @@ const styles = StyleSheet.create((theme) => ({
flexShrink: 0,
},
modeIconBadge: {
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
...toolbarSlot(TOUCH_ICON_SIZE.md),
alignItems: "center",
justifyContent: "center",
paddingHorizontal: 0,
@@ -2007,7 +2019,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface2,
},
modeBadgePressed: {
backgroundColor: theme.colors.surface0,
backgroundColor: theme.colors.surface2,
},
disabledBadge: {
opacity: 0.5,
@@ -1,16 +1,17 @@
import { createContext, useContext, type ReactNode } from "react";
import { toolbarGlyphsFor, type ToolbarGlyphs } from "@/components/ui/control-geometry";
import {
resolveComposerControlPresentation,
type ComposerControlPresentation,
} from "@/composer/agent-controls/layout";
interface ComposerControlLayoutValue {
glyphSize: number;
glyphs: ToolbarGlyphs;
presentation: ComposerControlPresentation;
}
const DEFAULT_LAYOUT: ComposerControlLayoutValue = {
glyphSize: 16,
glyphs: toolbarGlyphsFor("pointer"),
presentation: resolveComposerControlPresentation("full"),
};
@@ -3,6 +3,7 @@ import {
composerToolbarGeometry,
resolveComposerControlDensity,
resolveComposerControlPresentation,
resolveModelTriggerLabels,
} from "./layout";
const POINTER = composerToolbarGeometry("pointer");
@@ -174,21 +175,29 @@ describe("composer control layout", () => {
).toBe("condensed");
});
it("gives every toolbar control one shell and one glyph per control sizing", () => {
it("gives every toolbar control one shell and one glyph per role and control sizing", () => {
const pointerGlyph = { size: 16, strokeWidth: 1.5, tone: "muted" };
expect(POINTER).toEqual({
controlSize: 28,
glyphSize: 16,
glyphs: { icon: pointerGlyph, label: pointerGlyph },
controlGap: 4,
iconLabelGap: 4,
labelPadding: 8,
caretSize: 14,
});
expect(TOUCH).toMatchObject({ controlSize: 44, glyphSize: 20 });
expect(TOUCH).toMatchObject({
controlSize: 20,
glyphs: {
icon: { size: 20, strokeWidth: 1.5, tone: "foreground" },
label: { size: 20, strokeWidth: 1.5, tone: "foreground" },
},
controlGap: 20,
});
});
it("budgets touch-sized controls, so a touch toolbar condenses at a width a pointer one fits", () => {
const input = {
availableWidth: 420,
availableWidth: 400,
currentDensity: "full" as const,
controls: {
hasModel: true,
@@ -204,8 +213,8 @@ describe("composer control layout", () => {
});
describe("touch toolbar on an iPad in portrait, sidebar docked", () => {
// Codex: model, thinking, mode and two toggle features. The measured toolbar is 272 wide
// with an empty draft and 224 once an attachment brings in the send button.
// Codex: model, thinking, mode and two toggle features. Touch controls lay out at what they
// paint, 20pt apart, so icon-only thinking, mode and features need 200.
const controls = {
hasModel: true,
hasThinking: true,
@@ -217,7 +226,7 @@ describe("composer control layout", () => {
it("keeps the model family label with icon-only controls on an empty draft", () => {
expect(
resolveComposerControlDensity({
availableWidth: 272,
availableWidth: 280,
currentDensity: "full",
geometry: TOUCH,
controls,
@@ -225,10 +234,21 @@ describe("composer control layout", () => {
).toBe("tight");
});
it("folds thinking, mode and features into the model control once an attachment narrows it", () => {
it("keeps the icon-only controls once an attachment brings in send", () => {
expect(
resolveComposerControlDensity({
availableWidth: 224,
availableWidth: 240,
currentDensity: "tight",
geometry: TOUCH,
controls,
}),
).toBe("tight");
});
it("folds thinking, mode and features into the model control below their width", () => {
expect(
resolveComposerControlDensity({
availableWidth: 180,
currentDensity: "tight",
geometry: TOUCH,
controls,
@@ -239,7 +259,7 @@ describe("composer control layout", () => {
it("drops the model label only after the controls are folded", () => {
expect(
resolveComposerControlDensity({
availableWidth: 120,
availableWidth: 64,
currentDensity: "compact",
geometry: TOUCH,
controls,
@@ -263,8 +283,58 @@ describe("composer control layout", () => {
};
expect(resolveComposerControlDensity({ ...input, availableWidth: 600 })).toBe("compact");
// The iPhone toolbar with an attachment: "GPT-6…" beside "Medium" still fits.
expect(resolveComposerControlDensity({ ...input, availableWidth: 159 })).toBe("compact");
expect(resolveComposerControlDensity({ ...input, availableWidth: 120 })).toBe("iconOnly");
// The thinking label is not budgeted: it gives way before the model family label does.
expect(resolveComposerControlDensity({ ...input, availableWidth: 96 })).toBe("compact");
expect(resolveComposerControlDensity({ ...input, availableWidth: 64 })).toBe("iconOnly");
});
});
describe("folded model control labels", () => {
it("shows the thinking label while the model label fits beside it in full", () => {
expect(
resolveModelTriggerLabels({
hasThinking: true,
measurements: { availableWidth: 191, fullWidth: 190 },
}),
).toBe("modelAndThinking");
});
it("hides the thinking label when rounded widths tie", () => {
// On the web, 203.14 of labels and a 203 frame both report 203.
expect(
resolveModelTriggerLabels({
hasThinking: true,
measurements: { availableWidth: 203, fullWidth: 203 },
}),
).toBe("model");
});
it("hides the thinking label before the model label would truncate", () => {
expect(
resolveModelTriggerLabels({
hasThinking: true,
measurements: { availableWidth: 189.5, fullWidth: 190 },
}),
).toBe("model");
expect(
resolveModelTriggerLabels({
hasThinking: true,
measurements: { availableWidth: 90, fullWidth: 190 },
}),
).toBe("model");
});
it("decides nothing until both widths are measured", () => {
expect(resolveModelTriggerLabels({ hasThinking: true, measurements: {} })).toBe("measuring");
expect(
resolveModelTriggerLabels({ hasThinking: true, measurements: { availableWidth: 300 } }),
).toBe("measuring");
expect(resolveModelTriggerLabels({ hasThinking: true, measurements: { fullWidth: 120 } })).toBe(
"measuring",
);
});
it("needs no measurement without a thinking label", () => {
expect(resolveModelTriggerLabels({ hasThinking: false, measurements: {} })).toBe("model");
});
});
@@ -1,7 +1,9 @@
import {
iconSizeFor,
TOOLBAR_CONTROL_GAPS,
TOOLBAR_CONTROL_SIZES,
toolbarGlyphsFor,
type ControlSizing,
type ToolbarGlyphs,
} from "@/components/ui/control-geometry";
/**
@@ -39,23 +41,32 @@ export interface ComposerControlPresentation {
showModelLabel: boolean;
}
/** What each toolbar control takes up in the row, which is what the density budget sums. */
export interface ComposerToolbarGeometry {
/** An icon-only control's width in the row. */
controlSize: number;
glyphSize: number;
glyphs: ToolbarGlyphs;
controlGap: number;
iconLabelGap: number;
/** A labelled control's padding on each side, as far as it takes room in the row. */
labelPadding: number;
caretSize: number;
}
/** The toolbar's measurements under a control sizing; see `resolveControlSizing`. */
/**
* The toolbar's measurements under a control sizing; see `resolveControlSizing`. Touch-sized a
* control lays out at the width of what it paints (`toolbarSlot`, `toolbarContentSlot`), so an
* icon-only control takes its glyph's width and a picker's padding takes no room.
*/
export function composerToolbarGeometry(sizing: ControlSizing): ComposerToolbarGeometry {
const glyphs = toolbarGlyphsFor(sizing);
const isTouch = sizing === "touch";
return {
controlSize: TOOLBAR_CONTROL_SIZES[sizing],
glyphSize: iconSizeFor("md")[sizing],
controlGap: 4,
controlSize: isTouch ? glyphs.icon.size : TOOLBAR_CONTROL_SIZES.pointer,
glyphs,
controlGap: TOOLBAR_CONTROL_GAPS[sizing],
iconLabelGap: 4,
labelPadding: 8,
labelPadding: isTouch ? 0 : 8,
caretSize: 14,
};
}
@@ -63,8 +74,6 @@ export function composerToolbarGeometry(sizing: ControlSizing): ComposerToolbarG
const DENSITY_HYSTERESIS = 12;
/** The model label's narrowest useful width: enough for the model family, such as "GPT-6…". */
const MODEL_FAMILY_LABEL_WIDTH = 56;
/** A thinking label beside the folded model label, such as "Medium". */
const THINKING_LABEL_WIDTH = 48;
function normalizedFontScale(fontScale: number): number {
return Number.isFinite(fontScale) ? Math.max(1, fontScale) : 1;
@@ -83,7 +92,7 @@ function estimateLabelWidth(label: string, fontScale: number): number {
/** A labelled control's fixed chrome: its padding, its glyph, and the gap to its label. */
function labelledChrome(geometry: ComposerToolbarGeometry): number {
return geometry.labelPadding * 2 + geometry.glyphSize + geometry.iconLabelGap;
return geometry.labelPadding * 2 + geometry.glyphs.label.size + geometry.iconLabelGap;
}
function resolveFeatureControlWidth(
@@ -147,16 +156,16 @@ function resolveTightFloor(
return sumControlWidths(widths, geometry);
}
/** One model control carrying the model family label and the thinking label. */
/**
* One model control carrying the model family label. Its thinking label is not budgeted: it is
* the first label to go when the control runs out of room; see `resolveModelTriggerLabels`.
*/
function resolveCompactFloor(
controls: ComposerControlPresence,
geometry: ComposerToolbarGeometry,
): number {
const fontScale = normalizedFontScale(controls.fontScale);
const thinkingLabel = controls.hasThinking
? geometry.iconLabelGap + THINKING_LABEL_WIDTH * fontScale
: 0;
return labelledChrome(geometry) + MODEL_FAMILY_LABEL_WIDTH * fontScale + thinkingLabel;
return labelledChrome(geometry) + MODEL_FAMILY_LABEL_WIDTH * fontScale;
}
function resolveDensityFloor(
@@ -251,3 +260,33 @@ export function resolveComposerControlPresentation(
): ComposerControlPresentation {
return PRESENTATIONS[density];
}
/**
* Which labels the folded model control shows. `measuring` until every width is known, so the
* control never paints a choice made without them.
*/
export type ModelTriggerLabels = "measuring" | "modelAndThinking" | "model";
/** Widths measured from the rendered model control, in points. */
export interface ModelTriggerMeasurements {
/** The width the control may take. */
availableWidth: number;
/** The control with its model and thinking labels side by side, untruncated. */
fullWidth: number;
}
/**
* The thinking label goes first: it shows only while the model label fits beside it in full, so
* the model label truncates only once the thinking label is gone. The web reports layout widths
* rounded to whole pixels, so equal widths can hide a fraction of a pixel of overflow; only a
* full width strictly below the available width is known to fit.
*/
export function resolveModelTriggerLabels(input: {
hasThinking: boolean;
measurements: Partial<ModelTriggerMeasurements>;
}): ModelTriggerLabels {
if (!input.hasThinking) return "model";
const { availableWidth, fullWidth } = input.measurements;
if (availableWidth === undefined || fullWidth === undefined) return "measuring";
return fullWidth < availableWidth ? "modelAndThinking" : "model";
}
@@ -1,7 +1,7 @@
import { useCallback, useMemo, useRef, useState, type ReactElement } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { StyleSheet } from "react-native-unistyles";
import { useShallow } from "zustand/shallow";
import { useStoreWithEqualityFn } from "zustand/traditional";
import { type SheetHeader } from "@/components/adaptive-modal-sheet";
@@ -85,7 +85,6 @@ export function AgentModeControl({
surface = "toolbar",
onClose,
}: AgentModeControlValue & { surface?: "toolbar" | "sheet"; onClose?: () => void }) {
const { theme } = useUnistyles();
const { presentation } = useComposerControlLayout();
const { t } = useTranslation();
const { isActiveComposer } = useComposerKeyboardScope();
@@ -102,7 +101,6 @@ export function AgentModeControl({
}, [modeOptions, selectedModeId]);
const Icon = getAgentModeIcon(provider, selectedMode?.id ?? "", providerDefinitions);
const iconColor = theme.colors.foregroundMuted;
const selectedModeLabel = selectedMode ? formatAgentModeLabel(selectedMode) : "";
const allOptions = useMemo<ComboboxOption[]>(
@@ -197,7 +195,6 @@ export function AgentModeControl({
<AgentControlTrigger
ref={anchorRef}
icon={Icon}
iconColor={iconColor}
surface={surface}
label={t("agentControls.mode.title")}
value={selectedModeLabel}
@@ -1,21 +1,36 @@
import { useCallback, useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Keyboard, ScrollView, Text, View, type PressableStateCallbackType } from "react-native";
import {
Keyboard,
ScrollView,
Text,
View,
type LayoutChangeEvent,
type PressableStateCallbackType,
} from "react-native";
import { StyleSheet } from "react-native-unistyles";
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
import type { AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
import { AdaptiveModalSheet } from "@/components/adaptive-modal-sheet";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
import { TailEllipsisText } from "@/components/ui/tail-ellipsis-text";
import { useProviderIcon } from "@/components/provider-icons";
import { ModelBrowser, useModelBrowser } from "@/components/model-browser";
import { resolveModelBrowserScrolling } from "@/components/model-browser-view";
import { AgentControlTrigger } from "@/composer/agent-controls/control";
import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
import { resolveModelTriggerLabels } from "@/composer/agent-controls/layout";
import { resolveModelSheetOpening } from "@/composer/agent-controls/model-sheet-flow";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { TOOLBAR_CONTROL_HEIGHT } from "@/components/ui/control-geometry";
import { readMeasuredWidth } from "@/hooks/use-container-width";
import {
TOUCH_ICON_SIZE,
toolbarContentSlot,
toolbarSlot,
type ToolbarGlyphs,
} from "@/components/ui/control-geometry";
const SNAP_POINTS = ["80%", "90%"];
const MODEL_LIST_TOP_INSET = 4;
@@ -42,7 +57,7 @@ interface CompactModelSheetProps {
isRetryingProvider?: boolean;
disabled?: boolean;
serverId?: string | null;
glyphSize: number;
glyphs: ToolbarGlyphs;
/** False when the toolbar is too narrow for labels: the trigger shows the provider glyph only. */
showLabels: boolean;
canSwitchProvider: boolean;
@@ -78,6 +93,43 @@ function resolveModelSheetProfileActions(
};
}
/**
* Measures the folded model control and decides which labels it shows; see
* `resolveModelTriggerLabels`. The full width is keyed by what was measured, so a new label is
* `measuring` until its own width is known instead of reusing the previous label's.
*/
function useModelTriggerLabels(input: {
modelLabel: string;
thinkingLabel: string | null;
glyphSize: number;
}) {
const { modelLabel, thinkingLabel, glyphSize } = input;
const measuredKey = `${glyphSize}\n${modelLabel}\n${thinkingLabel ?? ""}`;
const [availableWidth, setAvailableWidth] = useState<number | undefined>(undefined);
const [fullWidth, setFullWidth] = useState<{ key: string; width: number } | null>(null);
const onFrameLayout = useCallback((event: LayoutChangeEvent) => {
const width = readMeasuredWidth(event);
if (width !== null) setAvailableWidth(width);
}, []);
const onFullLayout = useCallback(
(event: LayoutChangeEvent) => {
const width = readMeasuredWidth(event);
if (width !== null) setFullWidth({ key: measuredKey, width });
},
[measuredKey],
);
const labels = resolveModelTriggerLabels({
hasThinking: thinkingLabel !== null,
measurements: {
availableWidth,
fullWidth: fullWidth?.key === measuredKey ? fullWidth.width : undefined,
},
});
return { labels, measuredKey, onFrameLayout, onFullLayout };
}
export function CompactModelSheet({
providers,
selectedProvider,
@@ -96,7 +148,7 @@ export function CompactModelSheet({
isRetryingProvider = false,
disabled = false,
serverId = null,
glyphSize,
glyphs,
showLabels,
canSwitchProvider,
children,
@@ -233,17 +285,6 @@ export function CompactModelSheet({
open();
}, [close, isOpen, open]);
const iconOnly = !showLabels && hasSelectedProvider;
const triggerStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType) => [
styles.trigger,
iconOnly && styles.triggerIconOnly,
hovered && styles.triggerHovered,
(pressed || isOpen) && styles.triggerPressed,
disabled && styles.triggerDisabled,
],
[disabled, iconOnly, isOpen],
);
const mobileRootContent = useMemo(
() => (
<View style={styles.mobileRootContent} testID="agent-controls-settings-list">
@@ -269,36 +310,19 @@ export function CompactModelSheet({
return (
<>
<ComboboxTrigger
collapsable={false}
<ModelSheetTrigger
ModelIcon={hasSelectedProvider ? ModelIcon : null}
modelLabel={shortModelLabel(rootBrowser.triggerLabel)}
thinkingLabel={thinkingLabel}
glyphs={glyphs}
iconOnly={!showLabels && hasSelectedProvider}
isOpen={isOpen}
disabled={disabled}
onPress={toggle}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={t("modelSelector.selectedModel", {
model: rootBrowser.selectedModelLabel,
})}
testID="combined-model-selector"
chevron={null}
>
{hasSelectedProvider ? (
<ComposerToolbarGlyph size={glyphSize}>
<ModelIcon size={glyphSize} color={styles.providerIcon.color} />
</ComposerToolbarGlyph>
) : null}
{!iconOnly ? (
<View style={styles.triggerLabels}>
<Text style={styles.triggerText} numberOfLines={1}>
{shortModelLabel(rootBrowser.triggerLabel)}
</Text>
{thinkingLabel ? (
<Text style={styles.triggerThinking} numberOfLines={1}>
{thinkingLabel}
</Text>
) : null}
</View>
) : null}
</ComboboxTrigger>
/>
<AdaptiveModalSheet
header={rootHeader}
@@ -380,20 +404,137 @@ export function CompactModelSheet({
);
}
/**
* The folded model control in the toolbar: the provider glyph, then the model and thinking
* labels for as long as they fit.
*/
function ModelSheetTrigger({
ModelIcon,
modelLabel,
thinkingLabel,
glyphs,
iconOnly,
isOpen,
disabled,
onPress,
accessibilityLabel,
}: {
/** The selected provider's glyph, or null before a provider is selected. */
ModelIcon: ReturnType<typeof useProviderIcon> | null;
modelLabel: string;
thinkingLabel: string | null;
glyphs: ToolbarGlyphs;
iconOnly: boolean;
isOpen: boolean;
disabled: boolean;
onPress: () => void;
accessibilityLabel: string;
}) {
const glyphRole = iconOnly ? "icon" : "label";
const glyph = glyphs[glyphRole];
const triggerLabels = useModelTriggerLabels({
modelLabel,
thinkingLabel: iconOnly ? null : thinkingLabel,
glyphSize: glyph.size,
});
const providerIconColor =
glyph.tone === "foreground" ? styles.providerIconForeground.color : styles.providerIcon.color;
const triggerStyle = useCallback(
({ hovered, pressed }: PressableStateCallbackType) => [
styles.trigger,
iconOnly && styles.triggerIconOnly,
hovered && styles.triggerHovered,
(pressed || isOpen) && styles.triggerPressed,
disabled && styles.triggerDisabled,
],
[disabled, iconOnly, isOpen],
);
return (
<View style={styles.triggerFrame} onLayout={triggerLabels.onFrameLayout}>
<ComboboxTrigger
collapsable={false}
disabled={disabled}
onPress={onPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
testID="combined-model-selector"
chevron={null}
>
{ModelIcon ? (
<ComposerToolbarGlyph role={glyphRole}>
<ModelIcon
size={glyph.size}
strokeWidth={glyph.strokeWidth}
color={providerIconColor}
/>
</ComposerToolbarGlyph>
) : null}
{!iconOnly ? (
<View
style={[
styles.triggerLabels,
triggerLabels.labels === "measuring" && styles.triggerLabelsMeasuring,
]}
>
<TailEllipsisText
text={modelLabel}
style={styles.triggerText}
testID="combined-model-selector-model-label"
/>
{thinkingLabel && triggerLabels.labels !== "model" ? (
<Text
style={styles.triggerThinking}
numberOfLines={1}
testID="combined-model-selector-thinking-label"
>
{thinkingLabel}
</Text>
) : null}
</View>
) : null}
</ComboboxTrigger>
{!iconOnly && thinkingLabel ? (
<View
// Keyed by what it measures: a retained node whose size does not change emits no new
// layout event, so new labels would never be measured.
key={triggerLabels.measuredKey}
style={[styles.trigger, styles.triggerMeasurer]}
onLayout={triggerLabels.onFullLayout}
pointerEvents="none"
accessibilityElementsHidden
importantForAccessibility="no-hide-descendants"
aria-hidden
>
{ModelIcon ? <ComposerToolbarGlyph role={glyphRole}>{null}</ComposerToolbarGlyph> : null}
<View style={styles.triggerLabels}>
<Text style={[styles.triggerText, styles.triggerMeasuredText]} numberOfLines={1}>
{modelLabel}
</Text>
<Text style={styles.triggerThinking} numberOfLines={1}>
{thinkingLabel}
</Text>
</View>
</View>
) : null}
</View>
);
}
const styles = StyleSheet.create((theme) => ({
trigger: {
height: TOOLBAR_CONTROL_HEIGHT,
minWidth: 0,
flexShrink: 1,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
paddingHorizontal: theme.spacing[2],
borderRadius: theme.borderRadius["2xl"],
...toolbarContentSlot(theme.spacing[2]),
borderRadius: theme.borderRadius.full,
backgroundColor: "transparent",
},
triggerIconOnly: {
width: TOOLBAR_CONTROL_HEIGHT,
...toolbarSlot(TOUCH_ICON_SIZE.md),
flexShrink: 0,
paddingHorizontal: 0,
justifyContent: "center",
@@ -402,7 +543,7 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface2,
},
triggerPressed: {
backgroundColor: theme.colors.surface0,
backgroundColor: theme.colors.surface2,
},
triggerDisabled: {
opacity: 0.5,
@@ -421,6 +562,28 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
gap: theme.spacing[1],
},
triggerLabelsMeasuring: {
opacity: 0,
},
/** The space the trigger may take; the trigger itself stays as wide as its content. */
triggerFrame: {
minWidth: 0,
flexGrow: 1,
flexShrink: 1,
flexDirection: "row",
alignItems: "center",
},
/** An invisible copy of the trigger with both labels untruncated. */
triggerMeasurer: {
position: "absolute",
left: 0,
top: 0,
flexShrink: 0,
opacity: 0,
},
triggerMeasuredText: {
flexShrink: 0,
},
triggerThinking: {
flexShrink: 0,
color: theme.colors.foregroundExtraMuted,
@@ -430,6 +593,9 @@ const styles = StyleSheet.create((theme) => ({
providerIcon: {
color: theme.colors.foregroundMuted,
},
providerIconForeground: {
color: theme.colors.foreground,
},
sheetBody: {
paddingHorizontal: 0,
paddingTop: 0,
@@ -60,17 +60,6 @@ describe("useDraftAgentCreateFlow", () => {
expect(result.current.isSubmitting).toBe(true);
expect(result.current.draftAgent).toEqual({ currentAttempt: attempt });
expect(result.current.submittedStreamItems).toEqual([
{
kind: "user_message",
id: "msg-prepared",
clientMessageId: "msg-prepared",
text: "build this",
timestamp: attempt.timestamp,
images: [image],
attachments: [attachment],
},
]);
expect(createRequest).not.toHaveBeenCalled();
await act(async () => {
+1 -42
View File
@@ -8,15 +8,8 @@ import {
import { isActiveCreateFlowForDraft, useCreateFlowStore } from "@/stores/create-flow-store";
import { handoffCreatedAgentMessageSubmission } from "@/composer/submission/writer";
import { useSessionStore } from "@/stores/session-store";
import {
createUserMessage,
type StreamItem,
type UserMessageImageAttachment,
} from "@/types/stream";
import { createUserMessage, type UserMessageImageAttachment } from "@/types/stream";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import type { PendingMessageSubmission } from "@/composer/submission/model";
const EMPTY_STREAM_ITEMS: StreamItem[] = [];
interface CreateAttempt {
clientMessageId: string;
@@ -153,38 +146,6 @@ export function useDraftAgentCreateFlow<TDraftAgent, TCreateResult>({
const formErrorMessage = machine.tag === "draft" ? machine.errorMessage : "";
const isSubmitting = machine.tag === "creating";
const submittedStreamItems = useMemo<StreamItem[]>(() => {
if (machine.tag !== "creating") {
return EMPTY_STREAM_ITEMS;
}
if (
!machine.attempt.text &&
(!machine.attempt.images || machine.attempt.images.length === 0) &&
(!machine.attempt.attachments || machine.attempt.attachments.length === 0)
) {
return EMPTY_STREAM_ITEMS;
}
return [
createUserMessage({
clientMessageId: machine.attempt.clientMessageId,
text: machine.attempt.text,
timestamp: machine.attempt.timestamp,
images: machine.attempt.images,
attachments: machine.attempt.attachments,
}),
];
}, [machine]);
const pendingMessageSubmissions = useMemo<readonly PendingMessageSubmission[]>(() => {
if (machine.tag !== "creating") return [];
return [
{
clientMessageId: machine.attempt.clientMessageId,
},
];
}, [machine]);
const draftAgent = machine.tag === "creating" ? machine.draftAgent : null;
const startCreateAttempt = useCallback(
(attempt: CreateAttempt) => {
@@ -365,8 +326,6 @@ export function useDraftAgentCreateFlow<TDraftAgent, TCreateResult>({
machine,
formErrorMessage,
isSubmitting,
submittedStreamItems,
pendingMessageSubmissions,
draftAgent,
handleCreateFromInput,
continueCreateFromAttempt,
@@ -0,0 +1,103 @@
import { describe, expect, it } from "vitest";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import type { PendingCreateAttempt } from "@/stores/create-flow-store";
import type { UserMessageImageAttachment } from "@/types/stream";
import { DRAFT_CAPABILITIES, resolveDraftTimeline } from "./timeline";
const image: UserMessageImageAttachment = {
id: "image-1",
mimeType: "image/png",
storageType: "web-indexeddb",
storageKey: "image-key",
createdAt: 123,
};
const attachment = {
type: "review",
cwd: "/repo",
summary: "Review",
} as unknown as AgentAttachment;
function pendingAttempt(overrides: Partial<PendingCreateAttempt> = {}): PendingCreateAttempt {
return {
draftId: "draft-1",
serverId: "server-1",
agentId: null,
clientMessageId: "draft-1:initial-message",
text: "build this",
timestamp: Date.parse("2026-05-25T00:00:00.000Z"),
lifecycle: "active",
images: [image],
attachments: [attachment],
...overrides,
};
}
describe("resolveDraftTimeline", () => {
it("shows the sent prompt pending with the turn working", () => {
const timeline = resolveDraftTimeline({
pending: pendingAttempt(),
serverId: "server-1",
tabId: "tab-1",
cwd: "/repo",
});
expect(timeline?.agent).toEqual({
serverId: "server-1",
id: "tab-1",
status: "running",
cwd: "/repo",
capabilities: DRAFT_CAPABILITIES,
});
expect(timeline?.streamItems).toEqual([
{
kind: "user_message",
id: "draft-1:initial-message",
clientMessageId: "draft-1:initial-message",
text: "build this",
timestamp: new Date("2026-05-25T00:00:00.000Z"),
images: [image],
attachments: [attachment],
},
]);
expect(timeline?.pendingMessageSubmissions).toEqual([
{ clientMessageId: "draft-1:initial-message" },
]);
expect(timeline?.turnPresentation.isActive).toBe(true);
});
it("keeps the prompt once the agent is created, until the tab retargets", () => {
const timeline = resolveDraftTimeline({
pending: pendingAttempt({ lifecycle: "sent", agentId: "agent-1" }),
serverId: "server-1",
tabId: "tab-1",
cwd: "/repo",
});
expect(timeline?.streamItems).toHaveLength(1);
});
it("shows only the working turn for a prompt without content", () => {
const timeline = resolveDraftTimeline({
pending: pendingAttempt({ text: "", images: undefined, attachments: undefined }),
serverId: "server-1",
tabId: "tab-1",
cwd: "/repo",
});
expect(timeline?.streamItems).toEqual([]);
expect(timeline?.turnPresentation.isActive).toBe(true);
});
it("shows no timeline before a prompt is sent, after it fails, or on another host", () => {
const base = { serverId: "server-1", tabId: "tab-1", cwd: "/repo" };
expect(resolveDraftTimeline({ ...base, pending: undefined })).toBeNull();
expect(
resolveDraftTimeline({ ...base, pending: pendingAttempt({ lifecycle: "abandoned" }) }),
).toBeNull();
expect(
resolveDraftTimeline({ ...base, pending: pendingAttempt({ serverId: "server-2" }) }),
).toBeNull();
expect(resolveDraftTimeline({ ...base, cwd: null, pending: pendingAttempt() })).toBeNull();
});
});
+102
View File
@@ -0,0 +1,102 @@
import { useMemo } from "react";
import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types";
import type { PendingMessageSubmission } from "@/composer/submission/model";
import type { AgentScreenAgent } from "@/hooks/use-agent-screen-state-machine";
import { type PendingCreateAttempt, useCreateFlowStore } from "@/stores/create-flow-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import {
resolveTurnPresentation,
TURN_LIVENESS_IDLE,
type TurnPresentation,
} from "@/timeline/turn-liveness";
import { createUserMessage, type StreamItem } from "@/types/stream";
import type { WorkspaceDraftTabSetup } from "@/workspace-tabs/model";
import { resolveDraftWorkingDirectory } from "@/composer/draft/workspace-tab-core";
export const DRAFT_CAPABILITIES: AgentCapabilityFlags = {
supportsStreaming: true,
supportsSessionPersistence: false,
supportsDynamicModes: false,
supportsMcpServers: false,
supportsReasoningStream: false,
supportsToolInvocations: false,
};
export interface DraftConversation {
tabId: string;
workspaceId: string;
draftId: string;
setup?: WorkspaceDraftTabSetup;
}
/** The timeline a draft shows while its first prompt creates the agent. */
export interface DraftTimeline {
agent: AgentScreenAgent;
streamItems: StreamItem[];
pendingMessageSubmissions: readonly PendingMessageSubmission[];
turnPresentation: TurnPresentation;
}
const EMPTY_STREAM_ITEMS: StreamItem[] = [];
/**
* The sent prompt, pending, with the turn working. The created agent's timeline carries the same
* row (same client message id), so the handoff only changes who owns it.
*/
export function resolveDraftTimeline(input: {
pending: PendingCreateAttempt | undefined;
serverId: string;
tabId: string;
cwd: string | null;
}): DraftTimeline | null {
const { pending, serverId, tabId, cwd } = input;
if (!pending || pending.serverId !== serverId || pending.lifecycle === "abandoned" || !cwd) {
return null;
}
const hasContent =
pending.text.length > 0 ||
(pending.images?.length ?? 0) > 0 ||
(pending.attachments?.length ?? 0) > 0;
return {
agent: { serverId, id: tabId, status: "running", cwd, capabilities: DRAFT_CAPABILITIES },
streamItems: hasContent
? [
createUserMessage({
clientMessageId: pending.clientMessageId,
text: pending.text,
timestamp: new Date(pending.timestamp),
images: pending.images,
attachments: pending.attachments,
}),
]
: EMPTY_STREAM_ITEMS,
pendingMessageSubmissions: [{ clientMessageId: pending.clientMessageId }],
turnPresentation: resolveTurnPresentation(TURN_LIVENESS_IDLE, true),
};
}
export function useDraftTimeline(input: {
serverId: string;
draft: DraftConversation | null;
}): DraftTimeline | null {
const { serverId, draft } = input;
const pending = useCreateFlowStore((state) =>
draft ? state.pendingByDraftId[draft.draftId] : undefined,
);
const workspaceDirectory = useWorkspaceFields(
serverId,
draft?.workspaceId ?? null,
(workspace) => workspace.workspaceDirectory,
);
const cwd = draft
? resolveDraftWorkingDirectory({
workspaceDirectory: workspaceDirectory || null,
initialSetup: draft.setup ?? null,
})
: null;
const tabId = draft?.tabId ?? "";
return useMemo(
() => resolveDraftTimeline({ pending, serverId, tabId, cwd }),
[cwd, pending, serverId, tabId],
);
}
@@ -1,4 +1,5 @@
import { resolveSubmissionReadiness } from "@/provider-selection/provider-selection";
import type { WorkspaceDraftTabSetup } from "@/workspace-tabs/model";
export interface WorkspaceDraftAutoSubmitConfig {
provider: string;
@@ -50,3 +51,13 @@ export function validateDraftSubmission(input: {
});
return readiness.ok ? null : (readiness.reason ?? null);
}
export function resolveDraftWorkingDirectory(input: {
workspaceDirectory: string | null;
initialSetup: WorkspaceDraftTabSetup | null;
}): string | null {
if (input.initialSetup) {
return input.initialSetup.cwd;
}
return input.workspaceDirectory;
}
+124 -198
View File
@@ -1,21 +1,17 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import { Keyboard, ScrollView, StyleSheet as RNStyleSheet, Text, View } from "react-native";
import { Keyboard, StyleSheet as RNStyleSheet, Text, View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { ComposerDock } from "@/composer/dock";
import { useContainerWidthBelow } from "@/hooks/use-container-width";
import invariant from "tiny-invariant";
import { Composer } from "@/composer";
import { useComposerEditingSession, useComposerFullscreen } from "@/composer/editing-session";
import { FileDropZone } from "@/components/file-drop/file-drop-zone";
import { type ComposerEditingSession, useComposerFullscreen } from "@/composer/editing-session";
import { ComposerImportPill } from "@/composer/draft/import-pill";
import { COMPOSER_PILL_CLEARANCE } from "@/composer/pill-styles";
import { AgentStreamView } from "@/agent-stream/view";
import { composerWorkspaceAttachment } from "@/composer/attachments/workspace";
import { useAgentInputDraft } from "@/composer/draft/input-draft";
import type { CreateAgentInitialValues } from "@/hooks/use-agent-form-state";
import { useDraftAgentCreateFlow, type DraftCreateAttempt } from "@/composer/draft/create-flow";
import { resolveTurnPresentation, TURN_LIVENESS_IDLE } from "@/timeline/turn-liveness";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { buildWorkspaceDraftAgentConfig } from "@/screens/workspace/workspace-draft-agent-config";
import { buildDraftStoreKey } from "@/stores/draft-keys";
@@ -25,13 +21,13 @@ import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { useWorkspaceDraftSubmissionStore } from "@/stores/workspace-draft-submission-store";
import { useAgentControlCommandCenterActions } from "@/command-center/agent-control-registration";
import { encodeImages } from "@/utils/encode-images";
import type { WorkspaceFileOpenRequest } from "@/workspace/file-open";
import { shouldAutoFocusWorkspaceDraftComposer } from "@/screens/workspace/workspace-draft-pane-focus";
import {
resolveDraftWorkingDirectory,
shouldAllowEmptyDraftText,
validateDraftSubmission,
} from "@/composer/draft/workspace-tab-core";
import type { AgentCapabilityFlags } from "@getpaseo/protocol/agent-types";
import { DRAFT_CAPABILITIES } from "@/composer/draft/timeline";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { WorkspaceComposerAttachment } from "@/attachments/types";
@@ -50,16 +46,6 @@ import {
import { openWorkspaceChanges } from "@/workspace-tabs/open-supporting-view";
import { useSettings } from "@/hooks/use-settings";
const EMPTY_PENDING_PERMISSIONS = new Map();
const DRAFT_CAPABILITIES: AgentCapabilityFlags = {
supportsStreaming: true,
supportsSessionPersistence: false,
supportsDynamicModes: false,
supportsMcpServers: false,
supportsReasoningStream: false,
supportsToolInvocations: false,
};
interface AutoSubmitConfig {
provider: string;
modeId: string | null;
@@ -260,25 +246,15 @@ function buildDraftInitialValues(input: {
};
}
function resolveDraftWorkingDirectory(input: {
workspaceDirectory: string | null;
initialSetup: WorkspaceDraftTabSetup | null;
}): string | null {
if (input.initialSetup) {
return input.initialSetup.cwd;
}
return input.workspaceDirectory;
}
interface WorkspaceDraftAgentTabProps {
interface WorkspaceDraftComposerProps {
serverId: string;
workspaceId: string;
tabId: string;
draftId: string;
initialSetup?: WorkspaceDraftTabSetup;
isPaneFocused: boolean;
editingSession: ComposerEditingSession;
onCreated: (snapshot: AgentSnapshotPayload) => void;
onOpenWorkspaceFile: (request: WorkspaceFileOpenRequest) => void;
onOpenImportSheet?: () => void;
}
@@ -292,17 +268,21 @@ function resolveImportPillPress(
return onOpenImportSheet ?? null;
}
export function WorkspaceDraftAgentTab({
/**
* Creates the agent from the draft's first prompt. The conversation panel shows that prompt in
* the timeline from the create-flow store while the agent is created.
*/
export function WorkspaceDraftComposer({
serverId,
workspaceId,
tabId,
draftId,
initialSetup = undefined,
isPaneFocused,
editingSession,
onCreated,
onOpenWorkspaceFile,
onOpenImportSheet,
}: WorkspaceDraftAgentTabProps) {
}: WorkspaceDraftComposerProps) {
const { t } = useTranslation();
const client = useHostRuntimeClient(serverId);
const isConnected = useHostRuntimeIsConnected(serverId);
@@ -387,7 +367,6 @@ export function WorkspaceDraftAgentTab({
}, [pendingCreateAttempt]);
const allowsEmptyAutoSubmit = pendingAutoSubmit?.allowEmptyText === true;
const isCompactFormFactor = useIsCompactFormFactor();
const editingSession = useComposerEditingSession("chat");
const isComposerFullscreen = useComposerFullscreen(editingSession);
const { onLayout: onInputAreaLayout, isBelow: isCompactComposerLayout } = useContainerWidthBelow(
COMPACT_CONTENT_WIDTH,
@@ -421,82 +400,71 @@ export function WorkspaceDraftAgentTab({
[isCompactFormFactor, openInSidePane, serverId, workspaceId],
);
const {
formErrorMessage,
isSubmitting,
submittedStreamItems,
pendingMessageSubmissions,
draftAgent,
handleCreateFromInput,
continueCreateFromAttempt,
} = useDraftAgentCreateFlow<Agent, AgentSnapshotPayload>({
draftId,
getPendingServerId: () => serverId,
initialAttempt: initialCreateAttempt,
allowEmptyText: allowsEmptyAutoSubmit,
validateBeforeSubmit: ({ text, attachments }) => {
const allowsEmptyDraftText = shouldAllowEmptyDraftText({
allowsEmptyAutoSubmit,
attachments,
});
return validateDraftSubmission({
text,
allowsEmptyAutoSubmit: allowsEmptyDraftText,
composerState,
autoSubmitConfig,
workspaceDirectory: draftWorkingDirectory,
isConnected,
});
},
onBeforeSubmit: async () => {
await composerState.persistFormPreferences();
if (isWeb) {
(document.activeElement as HTMLElement | null)?.blur?.();
}
Keyboard.dismiss();
},
buildDraftAgent: (attempt) =>
buildDraftAgentSnapshot({
attempt,
serverId,
tabId,
workspaceDirectory: draftWorkingDirectory,
autoSubmitConfig,
composerState,
selectModelMessage: t("workspaceSetup.errors.selectModel"),
}),
createRequest: async ({ attempt, text, images, attachments, cwd }) => {
if (pendingAutoSubmit?.agentCreation) {
const result = await pendingAutoSubmit.agentCreation.result;
return { agentId: result.id, result };
}
return submitDraftCreateRequest({
draftId,
attempt,
text,
images,
attachments,
cwd,
client,
workspaceDirectory: draftWorkingDirectory,
workspaceId: workspaceFields?.id ?? null,
autoSubmitConfig,
composerState,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
selectModelMessage: t("workspaceSetup.errors.selectModel"),
});
},
onCreateSuccess: ({ result }) => {
clearDraftInput("sent");
clearWorkspaceAttachments({ scopeKey: draftAttachmentScopeKey });
useWorkspaceDraftSubmissionStore.getState().clearDraftSetup({ draftId });
onCreated(result);
},
});
const turnPresentation = useMemo(
() => resolveTurnPresentation(TURN_LIVENESS_IDLE, pendingMessageSubmissions.length > 0),
[pendingMessageSubmissions],
);
const { formErrorMessage, isSubmitting, handleCreateFromInput, continueCreateFromAttempt } =
useDraftAgentCreateFlow<Agent, AgentSnapshotPayload>({
draftId,
getPendingServerId: () => serverId,
initialAttempt: initialCreateAttempt,
allowEmptyText: allowsEmptyAutoSubmit,
validateBeforeSubmit: ({ text, attachments }) => {
const allowsEmptyDraftText = shouldAllowEmptyDraftText({
allowsEmptyAutoSubmit,
attachments,
});
return validateDraftSubmission({
text,
allowsEmptyAutoSubmit: allowsEmptyDraftText,
composerState,
autoSubmitConfig,
workspaceDirectory: draftWorkingDirectory,
isConnected,
});
},
onBeforeSubmit: async () => {
await composerState.persistFormPreferences();
if (isWeb) {
(document.activeElement as HTMLElement | null)?.blur?.();
}
Keyboard.dismiss();
},
buildDraftAgent: (attempt) =>
buildDraftAgentSnapshot({
attempt,
serverId,
tabId,
workspaceDirectory: draftWorkingDirectory,
autoSubmitConfig,
composerState,
selectModelMessage: t("workspaceSetup.errors.selectModel"),
}),
createRequest: async ({ attempt, text, images, attachments, cwd }) => {
if (pendingAutoSubmit?.agentCreation) {
const result = await pendingAutoSubmit.agentCreation.result;
return { agentId: result.id, result };
}
return submitDraftCreateRequest({
draftId,
attempt,
text,
images,
attachments,
cwd,
client,
workspaceDirectory: draftWorkingDirectory,
workspaceId: workspaceFields?.id ?? null,
autoSubmitConfig,
composerState,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
selectModelMessage: t("workspaceSetup.errors.selectModel"),
});
},
onCreateSuccess: ({ result }) => {
clearDraftInput("sent");
clearWorkspaceAttachments({ scopeKey: draftAttachmentScopeKey });
useWorkspaceDraftSubmissionStore.getState().clearDraftSetup({ draftId });
onCreated(result);
},
});
useAgentControlCommandCenterActions({
sourceId: `draft:${serverId}:${tabId}`,
enabled: isPaneFocused && !isSubmitting,
@@ -600,75 +568,48 @@ export function WorkspaceDraftAgentTab({
}),
[composerState.agentControls, handleDropdownCloseFocus, isSubmitting],
);
const dockContent = (
<View style={styles.contentContainer}>
{isSubmitting && draftAgent ? (
<View style={styles.streamContainer}>
<AgentStreamView
agentId={tabId}
serverId={serverId}
context={draftAgent}
streamItems={submittedStreamItems}
pendingMessageSubmissions={pendingMessageSubmissions}
turnPresentation={turnPresentation}
pendingPermissions={EMPTY_PENDING_PERMISSIONS}
onOpenWorkspaceFile={onOpenWorkspaceFile}
/>
</View>
) : (
<ScrollView style={styles.scrollView} contentContainerStyle={styles.configScrollContent}>
<View style={styles.configSection}>
{formErrorMessage ? (
<View style={styles.errorContainer}>
<Text style={styles.errorText}>{formErrorMessage}</Text>
</View>
) : null}
</View>
</ScrollView>
)}
</View>
);
return (
<FileDropZone style={styles.container}>
<ComposerDock fullscreen={isComposerFullscreen}>
{dockContent}
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
{importPillPress && !isComposerFullscreen ? (
<View style={styles.importPillRow}>
<View style={styles.importPillContent}>
<ComposerImportPill onPress={importPillPress} />
</View>
</View>
) : null}
<Composer
agentId={tabId}
serverId={serverId}
workspaceId={workspaceId}
isPaneFocused={isPaneFocused}
onSubmitMessage={handleCreateFromInput}
isSubmitLoading={isSubmitting}
blurOnSubmit={true}
textSource={draftInput.textSource}
onChangeText={draftInput.editText}
textReplacement={draftInput.textReplacement}
attachments={draftInput.attachments}
attachmentScopeKeys={attachmentScopeKeys}
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
onChangeAttachments={draftInput.setAttachments}
cwd={composerState.workingDir}
clearDraft={draftInput.clear}
editingSession={editingSession}
autoFocus={shouldAutoFocusWorkspaceDraftComposer({ isPaneFocused, isSubmitting })}
autoFocusKey={String(draftInput.attachmentFocusRequestId)}
onFocusInput={handleFocusInputCallback}
commandDraft={composerState.commandDraft}
agentControls={composerAgentControls}
isCompactLayout={isCompactComposerLayout}
/>
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
{formErrorMessage ? (
<View style={styles.formErrorRow}>
<View style={styles.formError}>
<Text style={styles.errorText}>{formErrorMessage}</Text>
</View>
</View>
</ComposerDock>
</FileDropZone>
) : null}
{importPillPress && !isComposerFullscreen ? (
<View style={styles.importPillRow}>
<View style={styles.importPillContent}>
<ComposerImportPill onPress={importPillPress} />
</View>
</View>
) : null}
<Composer
agentId={tabId}
serverId={serverId}
workspaceId={workspaceId}
isPaneFocused={isPaneFocused}
onSubmitMessage={handleCreateFromInput}
isSubmitLoading={isSubmitting}
blurOnSubmit={true}
textSource={draftInput.textSource}
onChangeText={draftInput.editText}
textReplacement={draftInput.textReplacement}
attachments={draftInput.attachments}
attachmentScopeKeys={attachmentScopeKeys}
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
onChangeAttachments={draftInput.setAttachments}
cwd={composerState.workingDir}
clearDraft={draftInput.clear}
editingSession={editingSession}
autoFocus={shouldAutoFocusWorkspaceDraftComposer({ isPaneFocused, isSubmitting })}
autoFocusKey={String(draftInput.attachmentFocusRequestId)}
onFocusInput={handleFocusInputCallback}
commandDraft={composerState.commandDraft}
agentControls={composerAgentControls}
isCompactLayout={isCompactComposerLayout}
/>
</View>
);
}
@@ -682,27 +623,10 @@ const animatedStaticStyles = RNStyleSheet.create({
});
const styles = StyleSheet.create((theme) => ({
container: {
flex: 1,
formErrorRow: {
width: "100%",
backgroundColor: theme.colors.surface0,
},
contentContainer: {
flex: 1,
},
streamContainer: {
flex: 1,
},
scrollView: {
flex: 1,
},
configScrollContent: {
paddingHorizontal: theme.spacing[4],
paddingTop: theme.spacing[4],
paddingBottom: theme.spacing[6],
},
configSection: {
gap: theme.spacing[3],
alignItems: "center",
},
importPillRow: {
width: "100%",
@@ -722,8 +646,10 @@ const styles = StyleSheet.create((theme) => ({
maxWidth: theme.contentMaxWidth,
flexDirection: "row",
},
errorContainer: {
marginTop: theme.spacing[2],
formError: {
width: "100%",
maxWidth: theme.contentMaxWidth,
marginBottom: theme.spacing[2],
paddingHorizontal: theme.spacing[3],
paddingVertical: theme.spacing[2],
borderRadius: theme.borderRadius.md,
+101 -88
View File
@@ -33,10 +33,16 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import {
controlSizingForLayout,
iconSizeFor,
TOOLBAR_CONTROL_HEIGHT,
TOOLBAR_CONTROL_GAP,
TOOLBAR_DISC_GLYPH_SIZES,
TOOLBAR_DISC_SIZE,
TOOLBAR_RINGS,
toolbarGlyphsFor,
toolbarGlyphTone,
type ToolbarGlyph,
toolbarSlot,
} from "@/components/ui/control-geometry";
import { COMPOSER_TOOLBAR_SHAPES } from "@/composer/input/toolbar-rails";
import { usePanelStore } from "@/stores/panel-store";
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
import { useShallow } from "zustand/shallow";
@@ -260,20 +266,22 @@ function resolveCheckoutRemoteUrl(
return checkoutStatus?.remoteUrl ?? null;
}
function buildCancelButtonStyle(isConnected: boolean, isCancellingAgent: boolean): object[] {
function buildCancelButtonStyle(
pressed: boolean,
isConnected: boolean,
isCancellingAgent: boolean,
): object[] {
const pressedStyle = pressed ? styles.discPressed : undefined;
const disabled = !isConnected || isCancellingAgent ? styles.buttonDisabled : undefined;
return [styles.cancelButton, disabled].filter((value): value is object => Boolean(value));
return [styles.cancelButton, pressedStyle, disabled].filter((value): value is object =>
Boolean(value),
);
}
function buildRealtimeVoiceButtonStyle(
hovered: boolean | undefined,
voiceButtonDisabled: boolean,
reserveLeadingSpace: boolean,
): object[] {
const hoveredStyle = hovered ? styles.iconButtonHovered : undefined;
function buildRealtimeVoiceButtonStyle(pressed: boolean, voiceButtonDisabled: boolean): object[] {
const pressedStyle = pressed ? styles.discPressed : undefined;
const disabledStyle = voiceButtonDisabled ? styles.buttonDisabled : undefined;
const reserveStyle = reserveLeadingSpace ? styles.realtimeVoiceButtonCompactReserve : undefined;
return [styles.realtimeVoiceButton, reserveStyle, hoveredStyle, disabledStyle].filter(
return [styles.realtimeVoiceButton, pressedStyle, disabledStyle].filter(
(value): value is object => Boolean(value),
);
}
@@ -1082,8 +1090,8 @@ function ComposerForgeBinding({
}
interface ComposerCancelButtonProps {
buttonIconSize: number;
cancelButtonStyle: (object | undefined)[];
discGlyphSize: number;
cancelButtonStyle: (state: PressableStateCallbackType) => object[];
handleCancelAgent: () => void;
isConnected: boolean;
isCancellingAgent: boolean;
@@ -1092,7 +1100,7 @@ interface ComposerCancelButtonProps {
}
function ComposerCancelButton({
buttonIconSize,
discGlyphSize,
cancelButtonStyle,
handleCancelAgent,
isConnected,
@@ -1106,7 +1114,7 @@ function ComposerCancelButton({
const icon = isCancellingAgent ? (
<LoadingSpinner size="small" color="white" />
) : (
<Square size={buttonIconSize} color="white" fill="white" />
<Square size={discGlyphSize} color="white" fill="white" />
);
const shortcutNode = agentInterruptKeys ? <Shortcut chord={agentInterruptKeys} /> : null;
return (
@@ -1131,7 +1139,7 @@ function ComposerCancelButton({
}
interface ComposerVoiceModeButtonProps {
buttonIconSize: number;
glyph: ToolbarGlyph;
handleToggleRealtimeVoice: () => void;
isConnected: boolean;
isVoiceSwitching: boolean;
@@ -1142,37 +1150,25 @@ interface ComposerVoiceModeButtonProps {
t: TFunction;
}
interface ComposerRightControlsSlotProps extends ComposerVoiceModeButtonProps {
function showsVoiceModeButton(input: {
isVoiceModeForAgent: boolean;
hasAgent: boolean;
isAgentRunning: boolean;
hasSendableContent: boolean;
isCompact: boolean;
showVoice: boolean;
}
function ComposerRightControlsSlot({
isVoiceModeForAgent,
hasAgent,
isAgentRunning,
hasSendableContent,
isCompact,
showVoice,
...voiceProps
}: ComposerRightControlsSlotProps) {
const hideVoiceForCompactInput = isCompact && hasSendableContent;
const showVoiceModeButton =
showVoice && !isVoiceModeForAgent && hasAgent && !isAgentRunning && !hideVoiceForCompactInput;
if (!showVoiceModeButton) return null;
}): boolean {
// Voice mode holds the trailing disc until there is something to send, then Send takes it.
return (
<View style={styles.rightControls}>
<ComposerVoiceModeButton {...voiceProps} />
</View>
input.showVoice &&
!input.isVoiceModeForAgent &&
input.hasAgent &&
!input.isAgentRunning &&
!input.hasSendableContent
);
}
function ComposerVoiceModeButton({
buttonIconSize,
glyph,
handleToggleRealtimeVoice,
isConnected,
isVoiceSwitching,
@@ -1183,13 +1179,25 @@ function ComposerVoiceModeButton({
const shortcutNode = voiceToggleKeys ? <Shortcut chord={voiceToggleKeys} /> : null;
const renderTriggerContent = useCallback(
({ hovered }: PressableStateCallbackType & { hovered?: boolean }) => {
if (isVoiceSwitching) {
return <LoadingSpinner size="small" color="white" />;
}
const colorMapping = hovered ? iconForegroundMapping : iconForegroundMutedMapping;
return <ThemedAudioLines size={buttonIconSize} uniProps={colorMapping} />;
const colorMapping =
toolbarGlyphTone(glyph, Boolean(hovered)) === "foreground"
? iconForegroundMapping
: iconForegroundMutedMapping;
return (
<View style={styles.voiceModeDisc}>
{isVoiceSwitching ? (
<LoadingSpinner size="small" color="white" />
) : (
<ThemedAudioLines
size={glyph.size}
strokeWidth={glyph.strokeWidth}
uniProps={colorMapping}
/>
)}
</View>
);
},
[buttonIconSize, isVoiceSwitching],
[glyph, isVoiceSwitching],
);
return (
<Tooltip delayDuration={0} enabledOnDesktop enabledOnMobile={false}>
@@ -1311,7 +1319,9 @@ function ComposerContentImpl({
const isCompactFormFactor = useIsCompactFormFactor();
const isCompactLayout = resolveCompactLayout(isCompactLayoutOverride, isCompactFormFactor);
const buttonIconSize = iconSizeFor("md")[controlSizingForLayout(isCompactFormFactor)];
const controlSizing = controlSizingForLayout(isCompactFormFactor);
const toolbarGlyph = toolbarGlyphsFor(controlSizing).icon;
const discGlyphSize = TOOLBAR_DISC_GLYPH_SIZES[controlSizing];
const isDesktopWebBreakpoint = resolveIsDesktopWebBreakpoint(isCompactFormFactor);
const { finePointer: hasFinePointer } = usePointerCapabilities();
const isDesktopLayout = resolveIsDesktopWebBreakpoint(isCompactLayout);
@@ -2012,8 +2022,9 @@ function ComposerContentImpl({
[agentId, recall, replaceUserInput, serverId],
);
const cancelButtonStyle = useMemo(
() => buildCancelButtonStyle(isConnected, isCancellingAgent),
const cancelButtonStyle = useCallback(
(state: PressableStateCallbackType) =>
buildCancelButtonStyle(state.pressed, isConnected, isCancellingAgent),
[isConnected, isCancellingAgent],
);
@@ -2021,14 +2032,14 @@ function ComposerContentImpl({
const voiceButtonDisabled = !isConnected || isVoiceSwitching;
const realtimeVoiceButtonStyle = useCallback(
(state: PressableStateCallbackType & { hovered?: boolean }) =>
buildRealtimeVoiceButtonStyle(state.hovered, voiceButtonDisabled, isCompactLayout),
[isCompactLayout, voiceButtonDisabled],
buildRealtimeVoiceButtonStyle(state.pressed, voiceButtonDisabled),
[voiceButtonDisabled],
);
const activeActionContent = useMemo(
() => (
<ComposerCancelButton
buttonIconSize={buttonIconSize}
discGlyphSize={discGlyphSize}
cancelButtonStyle={cancelButtonStyle}
handleCancelAgent={handleCancelAgent}
isConnected={isConnected}
@@ -2039,7 +2050,7 @@ function ComposerContentImpl({
),
[
agentInterruptKeys,
buttonIconSize,
discGlyphSize,
cancelButtonStyle,
handleCancelAgent,
isCancellingAgent,
@@ -2048,32 +2059,34 @@ function ComposerContentImpl({
],
);
const rightContent = useMemo(
() => (
<ComposerRightControlsSlot
isVoiceModeForAgent={isVoiceModeForAgent}
hasAgent={hasAgent}
isAgentRunning={isAgentRunning}
hasSendableContent={hasSendableContent}
isCompact={isCompactLayout}
showVoice={mode.showVoice}
buttonIconSize={buttonIconSize}
handleToggleRealtimeVoice={handleToggleRealtimeVoice}
isConnected={isConnected}
isVoiceSwitching={isVoiceSwitching}
realtimeVoiceButtonStyle={realtimeVoiceButtonStyle}
voiceToggleKeys={voiceToggleKeys}
t={t}
/>
),
const voiceModeContent = useMemo(
() =>
showsVoiceModeButton({
isVoiceModeForAgent,
hasAgent,
isAgentRunning,
hasSendableContent,
showVoice: mode.showVoice,
}) ? (
<View style={styles.rightControls}>
<ComposerVoiceModeButton
glyph={toolbarGlyph}
handleToggleRealtimeVoice={handleToggleRealtimeVoice}
isConnected={isConnected}
isVoiceSwitching={isVoiceSwitching}
realtimeVoiceButtonStyle={realtimeVoiceButtonStyle}
voiceToggleKeys={voiceToggleKeys}
t={t}
/>
</View>
) : null,
[
buttonIconSize,
toolbarGlyph,
handleToggleRealtimeVoice,
hasAgent,
hasSendableContent,
isAgentRunning,
isConnected,
isCompactLayout,
isVoiceModeForAgent,
isVoiceSwitching,
mode.showVoice,
@@ -2093,7 +2106,7 @@ function ComposerContentImpl({
maxTokens={agentState.contextWindowMaxTokens}
usedTokens={agentState.contextWindowUsedTokens}
totalCostUsd={agentState.totalCostUsd}
glyphSize={buttonIconSize}
toolbarRing={TOOLBAR_RINGS[controlSizing]}
/>
</View>
) : null,
@@ -2104,7 +2117,7 @@ function ComposerContentImpl({
agentState.contextWindowMaxTokens,
agentState.contextWindowUsedTokens,
agentState.totalCostUsd,
buttonIconSize,
controlSizing,
],
);
@@ -2490,7 +2503,7 @@ function ComposerContentImpl({
disabled={isSubmitLoading}
leftContent={leftContent}
beforeVoiceContent={beforeVoiceContent}
rightContent={rightContent}
voiceModeContent={voiceModeContent}
activeActionContent={activeActionContent}
voiceServerId={serverId}
voiceAgentId={agentId}
@@ -2596,13 +2609,10 @@ const styles = StyleSheet.create((theme: Theme) => ({
width: "100%",
gap: theme.spacing[3],
},
// The trigger is the hit frame and stays unpainted; the disc inside it carries the fill.
cancelButton: {
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
...toolbarSlot(COMPOSER_TOOLBAR_SHAPES.disc),
alignItems: "center",
justifyContent: "center",
marginLeft: theme.spacing[1],
},
cancelButtonDisc: {
width: TOOLBAR_DISC_SIZE,
@@ -2615,31 +2625,34 @@ const styles = StyleSheet.create((theme: Theme) => ({
rightControls: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
gap: TOOLBAR_CONTROL_GAP,
},
contextWindowMeterSlot: {
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
...toolbarSlot(COMPOSER_TOOLBAR_SHAPES.ring),
flexShrink: 0,
alignItems: "center",
justifyContent: "center",
},
realtimeVoiceButton: {
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
voiceModeDisc: {
width: TOOLBAR_DISC_SIZE,
height: TOOLBAR_DISC_SIZE,
borderRadius: theme.borderRadius.full,
backgroundColor: theme.colors.surface3,
alignItems: "center",
justifyContent: "center",
},
realtimeVoiceButtonCompactReserve: {
marginLeft: theme.spacing[1],
realtimeVoiceButton: {
...toolbarSlot(COMPOSER_TOOLBAR_SHAPES.disc),
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
},
realtimeVoiceButtonActive: {
backgroundColor: theme.colors.palette.green[600],
borderColor: theme.colors.palette.green[800],
},
iconButtonHovered: {
backgroundColor: theme.colors.surface2,
discPressed: {
opacity: 0.7,
},
attachmentTray: {
flexDirection: "row",
+138 -77
View File
@@ -31,10 +31,24 @@ import { useTranslation } from "react-i18next";
import type { Theme } from "@/styles/theme";
import {
controlSizingForLayout,
iconSizeFor,
TOOLBAR_CONTROL_GAP,
TOOLBAR_CONTROL_HEIGHT,
TOOLBAR_DISC_GLYPH_SIZES,
TOOLBAR_DISC_SIZE,
toolbarGlyphsFor,
toolbarGlyphTone,
type ToolbarGlyph,
toolbarSlot,
} from "@/components/ui/control-geometry";
import {
COMPOSER_PADDING_BOTTOM,
COMPOSER_PADDING_HORIZONTAL,
COMPOSER_CORNER_RADIUS,
COMPOSER_PADDING_TOP,
COMPOSER_TOOLBAR_SHAPES,
composerToolbarOverhang,
resolveComposerLeadingEdge,
} from "@/composer/input/toolbar-rails";
import { ArrowUp, Mic, MicOff, CornerDownLeft, Plus, Square } from "lucide-react-native";
import * as Haptics from "expo-haptics";
import { useDictation } from "@/hooks/use-dictation";
@@ -170,8 +184,8 @@ export interface MessageInputProps {
leftContent?: React.ReactNode;
/** Content to render on the right side before the voice button (e.g., context window meter) */
beforeVoiceContent?: React.ReactNode;
/** Auxiliary content to render on the right side after the voice button. */
rightContent?: React.ReactNode;
/** The realtime voice mode button after the dictation button, or null when the row hides it. */
voiceModeContent?: React.ReactNode;
/** Primary action to render when the agent is active and the composer has no sendable content. */
activeActionContent?: React.ReactNode;
voiceServerId?: string;
@@ -252,19 +266,28 @@ interface TextAreaHandle {
};
}
function glyphColorMapping(glyph: ToolbarGlyph, hovered: boolean) {
return toolbarGlyphTone(glyph, hovered) === "foreground"
? iconForegroundMapping
: iconForegroundMutedMapping;
}
function AttachButtonIcon({
hovered,
onAttachButtonRef,
buttonIconSize,
glyph,
}: {
hovered: boolean;
onAttachButtonRef: ((node: View | null) => void) | undefined;
buttonIconSize: number;
glyph: ToolbarGlyph;
}) {
const colorMapping = hovered ? iconForegroundMapping : iconForegroundMutedMapping;
return (
<View ref={onAttachButtonRef} collapsable={false} style={styles.attachButtonAnchor}>
<ThemedPlus size={buttonIconSize} uniProps={colorMapping} />
<ThemedPlus
size={glyph.size}
strokeWidth={glyph.strokeWidth}
uniProps={glyphColorMapping(glyph, hovered)}
/>
</View>
);
}
@@ -342,25 +365,25 @@ function VoiceButtonIcon({
hovered,
isDictating,
isMutedRealtime,
buttonIconSize,
glyph,
discGlyphSize,
}: {
hovered: boolean;
isDictating: boolean;
isMutedRealtime: boolean;
buttonIconSize: number;
glyph: ToolbarGlyph;
discGlyphSize: number;
}) {
if (isDictating) {
return (
<View style={styles.voiceButtonRecordingDisc}>
<Square size={buttonIconSize} color="white" fill="white" />
<Square size={discGlyphSize} color="white" fill="white" />
</View>
);
}
const colorMapping = hovered ? iconForegroundMapping : iconForegroundMutedMapping;
if (isMutedRealtime) {
return <ThemedMicOff size={buttonIconSize} uniProps={colorMapping} />;
}
return <ThemedMic size={buttonIconSize} uniProps={colorMapping} />;
const colorMapping = glyphColorMapping(glyph, hovered);
const Icon = isMutedRealtime ? ThemedMicOff : ThemedMic;
return <Icon size={glyph.size} strokeWidth={glyph.strokeWidth} uniProps={colorMapping} />;
}
type ShortcutChord = NonNullable<React.ComponentProps<typeof Shortcut>["chord"]>;
@@ -399,12 +422,12 @@ function SendButtonContent({
isSubmitLoading,
submitIcon,
submitLabel,
buttonIconSize,
glyph,
}: {
isSubmitLoading: boolean;
submitIcon: "arrow" | "return";
submitLabel: string | undefined;
buttonIconSize: number;
glyph: ToolbarGlyph;
}) {
if (isSubmitLoading) {
return <ThemedLoadingSpinner size="small" uniProps={iconAccentForegroundMapping} />;
@@ -413,9 +436,21 @@ function SendButtonContent({
return <Text style={styles.sendButtonLabel}>{submitLabel}</Text>;
}
if (submitIcon === "return") {
return <ThemedCornerDownLeft size={buttonIconSize} uniProps={iconAccentForegroundMapping} />;
return (
<ThemedCornerDownLeft
size={glyph.size}
strokeWidth={glyph.strokeWidth}
uniProps={iconAccentForegroundMapping}
/>
);
}
return <ThemedArrowUp size={buttonIconSize} uniProps={iconAccentForegroundMapping} />;
return (
<ThemedArrowUp
size={glyph.size}
strokeWidth={glyph.strokeWidth}
uniProps={iconAccentForegroundMapping}
/>
);
}
interface DesktopKeyPressContext {
@@ -808,7 +843,7 @@ function SendButtonTooltip({
submitIcon,
submitLabel,
submitButtonTestID,
buttonIconSize,
glyph,
sendKeys,
sendTooltipLabel,
}: {
@@ -825,7 +860,7 @@ function SendButtonTooltip({
submitIcon: "arrow" | "return";
submitLabel: string | undefined;
submitButtonTestID: string | undefined;
buttonIconSize: number;
glyph: ToolbarGlyph;
sendKeys: ShortcutChord | null | undefined;
sendTooltipLabel: string;
}) {
@@ -847,7 +882,7 @@ function SendButtonTooltip({
isSubmitLoading={isSubmitLoading}
submitIcon={submitIcon}
submitLabel={submitLabel}
buttonIconSize={buttonIconSize}
glyph={glyph}
/>
</View>
</TooltipTrigger>
@@ -1140,7 +1175,7 @@ interface ResolvedMessageInputProps {
disabled: boolean;
leftContent: React.ReactNode;
beforeVoiceContent: React.ReactNode;
rightContent: React.ReactNode;
voiceModeContent: React.ReactNode;
activeActionContent: React.ReactNode;
voiceServerId: string | undefined;
voiceAgentId: string | undefined;
@@ -1188,7 +1223,7 @@ function resolveMessageInputProps(props: MessageInputProps): ResolvedMessageInpu
disabled: props.disabled ?? false,
leftContent: props.leftContent,
beforeVoiceContent: props.beforeVoiceContent,
rightContent: props.rightContent,
voiceModeContent: props.voiceModeContent,
activeActionContent: props.activeActionContent,
voiceServerId: props.voiceServerId,
voiceAgentId: props.voiceAgentId,
@@ -1216,8 +1251,12 @@ function extractErrorMessage(error: unknown): string | null {
return null;
}
/**
* Send that stands in for the trailing disc, in fullscreen or while there is nothing to send, is
* disabled until there is content.
*/
function resolvePresentationSendDisabled(input: {
fullscreen: boolean;
standsIn: boolean;
disabled: boolean;
hasText: boolean;
attachments: ComposerAttachment[];
@@ -1225,7 +1264,7 @@ function resolvePresentationSendDisabled(input: {
allowEmpty: boolean;
}): boolean {
return (
input.disabled || (input.fullscreen && !input.allowEmpty && !hasSendableComposerContent(input))
input.disabled || (input.standsIn && !input.allowEmpty && !hasSendableComposerContent(input))
);
}
@@ -1266,7 +1305,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
disabled,
leftContent,
beforeVoiceContent,
rightContent,
voiceModeContent,
activeActionContent,
voiceServerId,
voiceAgentId,
@@ -1296,7 +1335,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
const [renderedLines, setRenderedLines] = useState(1);
const maxInputHeight = resolveMaxInputHeight(windowHeight, isCompact);
const controlSizing = controlSizingForLayout(isCompact);
const buttonIconSize = iconSizeFor("md")[controlSizing];
const toolbarGlyph = toolbarGlyphsFor(controlSizing).icon;
const discGlyphSize = TOOLBAR_DISC_GLYPH_SIZES[controlSizing];
const toast = useToast();
const voice = useVoiceOptional();
const voiceMuteToggleKeys = useShortcutKeys("voice-mute-toggle");
@@ -1919,18 +1959,20 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
);
const attachButtonStyle = useCallback(
({ hovered }: { hovered?: boolean }) => [
({ hovered, pressed }: { hovered?: boolean; pressed?: boolean }) => [
styles.attachButton,
Boolean(hovered) && styles.iconButtonHovered,
Boolean(hovered || pressed) && styles.iconButtonHovered,
(!isConnected || disabled) && styles.buttonDisabled,
],
[isConnected, disabled],
);
const voiceButtonStyle = useCallback(
({ hovered }: { hovered?: boolean }) => [
({ hovered, pressed }: { hovered?: boolean; pressed?: boolean }) => [
styles.voiceButton,
Boolean(hovered) && !isDictating && styles.iconButtonHovered,
isDictating && styles.voiceButtonRecording,
Boolean(hovered || pressed) && !isDictating && styles.iconButtonHovered,
Boolean(pressed) && isDictating && styles.discPressed,
!isDictationStartEnabled && styles.buttonDisabled,
],
[isDictating, isDictationStartEnabled],
@@ -1971,16 +2013,24 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
[mode.isMonospace],
);
// Fullscreen always shows Send; without content it is disabled, and looks it.
// With nothing to send and no voice mode, a disabled Send holds the trailing disc so the row
// does not shift when typing starts.
const sendStandsIn = isFullscreen || (primaryActionKind === "none" && voiceModeContent == null);
const presentedActionKind: PrimaryActionKind = sendStandsIn ? "send" : primaryActionKind;
const isPresentedSendDisabled = resolvePresentationSendDisabled({
fullscreen: isFullscreen,
standsIn: sendStandsIn,
disabled: isSendButtonDisabled,
hasText: hasLiveText,
attachments,
hasExternalContent,
allowEmpty: allowEmptySubmit,
});
const sendButtonCombinedStyle = useMemo(
() => [styles.sendButton, isPresentedSendDisabled && styles.buttonDisabled],
const sendButtonCombinedStyle = useCallback(
({ pressed }: { pressed?: boolean }) => [
styles.sendButton,
Boolean(pressed) && styles.discPressed,
isPresentedSendDisabled && styles.buttonDisabled,
],
[isPresentedSendDisabled],
);
const overlayContainerStyle = useMemo(
@@ -1993,10 +2043,10 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
<AttachButtonIcon
hovered={Boolean(hovered)}
onAttachButtonRef={onAttachButtonRef}
buttonIconSize={buttonIconSize}
glyph={toolbarGlyph}
/>
),
[onAttachButtonRef, buttonIconSize],
[onAttachButtonRef, toolbarGlyph],
);
const renderVoiceButtonIcon = useCallback(
@@ -2005,16 +2055,17 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
hovered={Boolean(hovered)}
isDictating={isDictating}
isMutedRealtime={Boolean(isRealtimeVoiceForCurrentAgent && voice?.isMuted)}
buttonIconSize={buttonIconSize}
glyph={toolbarGlyph}
discGlyphSize={discGlyphSize}
/>
),
[isDictating, isRealtimeVoiceForCurrentAgent, voice?.isMuted, buttonIconSize],
[isDictating, isRealtimeVoiceForCurrentAgent, voice?.isMuted, toolbarGlyph, discGlyphSize],
);
const sendButton = useMemo(
() => (
<PrimaryAction
kind={isFullscreen ? "send" : primaryActionKind}
kind={presentedActionKind}
activeActionContent={activeActionContent}
shouldShow
canPressLoadingButton={canPressLoadingButton}
@@ -2029,14 +2080,13 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
submitIcon={submitIcon}
submitLabel={submitLabel}
submitButtonTestID={submitButtonTestID}
buttonIconSize={buttonIconSize}
glyph={toolbarGlyph}
sendKeys={resolveSendKeys(sendShortcut)}
sendTooltipLabel={sendTooltipLabel}
/>
),
[
isFullscreen,
primaryActionKind,
presentedActionKind,
activeActionContent,
canPressLoadingButton,
onSubmitLoadingPress,
@@ -2050,7 +2100,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
submitIcon,
submitLabel,
submitButtonTestID,
buttonIconSize,
toolbarGlyph,
sendShortcut,
sendTooltipLabel,
],
@@ -2124,9 +2174,25 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
focusInputKeys,
],
);
const leadingEdge = resolveComposerLeadingEdge({
showsAttach: mode.showAttachments,
showsAgentControls: leftContent != null,
});
// The trailing control is always a disc: voice mode, then Send or Stop.
const trailingEdge = "disc";
const buttonRowStyle = useMemo(
() => [
styles.buttonRow,
{
marginLeft: -composerToolbarOverhang(leadingEdge, controlSizing),
marginRight: -composerToolbarOverhang(trailingEdge, controlSizing),
},
],
[controlSizing, leadingEdge, trailingEdge],
);
const toolbar = useMemo(
() => (
<View style={styles.buttonRow}>
<View style={buttonRowStyle}>
{/* Toolbar left: attachment button + agent controls */}
<View style={styles.leftButtonGroup}>
<AttachmentDropdown
@@ -2156,12 +2222,13 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
voiceMuteToggleKeys={voiceMuteToggleKeys}
dictationToggleKeys={dictationToggleKeys}
/>
{rightContent}
{voiceModeContent}
{sendButton}
</View>
</View>
),
[
buttonRowStyle,
mode.showAttachments,
isConnected,
disabled,
@@ -2181,7 +2248,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
isRealtimeVoiceForCurrentAgent,
voiceMuteToggleKeys,
dictationToggleKeys,
rightContent,
voiceModeContent,
sendButton,
],
);
@@ -2249,7 +2316,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
<ComposerInputPresentation
fullscreen={isFullscreen}
controlSizing={controlSizing}
sendIconSize={buttonIconSize}
sendIconSize={toolbarGlyph.size}
surface={textSurface}
toolbar={toolbar}
send={sendButton}
@@ -2290,20 +2357,10 @@ const styles = StyleSheet.create((theme: Theme) => ({
backgroundColor: theme.colors.surface1,
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.borderAccent,
borderRadius: theme.borderRadius["2xl"],
paddingTop: {
xs: theme.spacing[2],
md: theme.spacing[4],
},
// The button row bleeds 6px horizontally, so match its corner inset at the bottom.
paddingBottom: {
xs: theme.spacing[2],
md: theme.spacing[3],
},
paddingHorizontal: {
xs: theme.spacing[3],
md: theme.spacing[4],
},
borderRadius: COMPOSER_CORNER_RADIUS,
paddingTop: COMPOSER_PADDING_TOP,
paddingBottom: COMPOSER_PADDING_BOTTOM,
paddingHorizontal: COMPOSER_PADDING_HORIZONTAL,
...(isWeb
? {
transitionProperty: "border-color",
@@ -2377,47 +2434,49 @@ const styles = StyleSheet.create((theme: Theme) => ({
minHeight: MIN_INPUT_HEIGHT,
color: theme.colors.foregroundMuted,
},
// The row keeps a full touch target's height; its disc-sized controls centre in it.
buttonRow: {
minHeight: TOOLBAR_CONTROL_HEIGHT,
flexShrink: 0,
flexDirection: "row",
alignItems: "flex-end",
alignItems: "center",
justifyContent: "space-between",
marginHorizontal: -6,
},
leftButtonGroup: {
minWidth: 0,
flexShrink: 1,
flexGrow: 1,
flexDirection: "row",
alignItems: "flex-end",
gap: theme.spacing[0],
alignItems: "center",
gap: TOOLBAR_CONTROL_GAP,
},
rightButtonGroup: {
flexShrink: 0,
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[1],
gap: TOOLBAR_CONTROL_GAP,
},
attachButton: {
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
...toolbarSlot(COMPOSER_TOOLBAR_SHAPES.attach),
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
},
attachButtonAnchor: {
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
width: TOOLBAR_DISC_SIZE,
height: TOOLBAR_DISC_SIZE,
alignItems: "center",
justifyContent: "center",
},
voiceButton: {
width: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
...toolbarSlot(COMPOSER_TOOLBAR_SHAPES.dictation),
borderRadius: theme.borderRadius.full,
alignItems: "center",
justifyContent: "center",
},
voiceButtonRecording: {
marginHorizontal: toolbarSlot(COMPOSER_TOOLBAR_SHAPES.disc).marginHorizontal,
},
voiceButtonRecordingDisc: {
width: TOOLBAR_DISC_SIZE,
height: TOOLBAR_DISC_SIZE,
@@ -2426,13 +2485,12 @@ const styles = StyleSheet.create((theme: Theme) => ({
alignItems: "center",
justifyContent: "center",
},
// The trigger is the hit frame and stays unpainted; the disc inside it carries the fill.
sendButton: {
minWidth: TOOLBAR_CONTROL_HEIGHT,
height: TOOLBAR_CONTROL_HEIGHT,
minWidth: TOOLBAR_DISC_SIZE,
marginHorizontal: toolbarSlot(COMPOSER_TOOLBAR_SHAPES.disc).marginHorizontal,
height: TOOLBAR_DISC_SIZE,
alignItems: "center",
justifyContent: "center",
marginLeft: theme.spacing[1],
},
sendButtonDisc: {
width: TOOLBAR_DISC_SIZE,
@@ -2459,6 +2517,9 @@ const styles = StyleSheet.create((theme: Theme) => ({
iconButtonHovered: {
backgroundColor: theme.colors.surface2,
},
discPressed: {
opacity: 0.7,
},
tooltipRow: {
flexDirection: "row",
alignItems: "center",
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { composerToolbarOverhang, resolveComposerLeadingEdge } from "./toolbar-rails";
describe("composer toolbar rails", () => {
it("keeps touch glyphs and labels on the text rails and nests a trailing disc into the corner", () => {
for (const edge of ["attach", "dictation", "voiceMode", "label", "none"] as const) {
expect(composerToolbarOverhang(edge, "touch")).toBe(0);
}
// A 36pt disc centred in the 44pt row sits 8 from the bottom edge, so it sits 8 from the side.
expect(composerToolbarOverhang("disc", "touch")).toBe(8);
});
it("keeps the pointer row's flat overhang", () => {
for (const edge of ["attach", "dictation", "voiceMode", "disc", "label", "none"] as const) {
expect(composerToolbarOverhang(edge, "pointer")).toBe(6);
}
});
it("starts the row on attach, else on the agent controls", () => {
expect(resolveComposerLeadingEdge({ showsAttach: true, showsAgentControls: true })).toBe(
"attach",
);
expect(resolveComposerLeadingEdge({ showsAttach: false, showsAgentControls: true })).toBe(
"label",
);
expect(resolveComposerLeadingEdge({ showsAttach: false, showsAgentControls: false })).toBe(
"none",
);
});
});
@@ -0,0 +1,85 @@
import {
TOOLBAR_CONTROL_SIZES,
TOOLBAR_DISC_SIZES,
TOOLBAR_RINGS,
toolbarGlyphsFor,
type ControlSizing,
} from "@/components/ui/control-geometry";
import { bySizing } from "@/components/ui/control-sizing";
/** The control at one end of the composer toolbar, which decides how far the row hangs out. */
export type ComposerToolbarEdge = "attach" | "label" | "dictation" | "voiceMode" | "disc" | "none";
/**
* The composer's padding. Its sides are the rails: the text column and the toolbar's outer
* controls both start there.
*/
const COMPOSER_PADDING = {
touch: { top: 12, horizontal: 16, bottom: 4 },
pointer: { top: 16, horizontal: 16, bottom: 12 },
} as const;
export const COMPOSER_PADDING_TOP = bySizing({
touch: COMPOSER_PADDING.touch.top,
pointer: COMPOSER_PADDING.pointer.top,
});
export const COMPOSER_PADDING_HORIZONTAL = bySizing({
touch: COMPOSER_PADDING.touch.horizontal,
pointer: COMPOSER_PADDING.pointer.horizontal,
});
export const COMPOSER_PADDING_BOTTOM = bySizing({
touch: COMPOSER_PADDING.touch.bottom,
pointer: COMPOSER_PADDING.pointer.bottom,
});
/** How much of Lucide's 24-unit grid each toolbar glyph's ink spans, centred in its box. */
const GLYPH_INK_SPANS = { plus: 14, mic: 14, audioLines: 20 } as const;
function touchGlyphInkWidth(span: number): number {
const glyph = toolbarGlyphsFor("touch").icon;
return (span * glyph.size) / 24 + glyph.strokeWidth;
}
/** The width each toolbar control paints when touch-sized; the row spaces these. */
export const COMPOSER_TOOLBAR_SHAPES = {
attach: touchGlyphInkWidth(GLYPH_INK_SPANS.plus),
dictation: touchGlyphInkWidth(GLYPH_INK_SPANS.mic),
voiceMode: touchGlyphInkWidth(GLYPH_INK_SPANS.audioLines),
ring: TOOLBAR_RINGS.touch.size,
disc: TOOLBAR_DISC_SIZES.touch,
} as const;
/** Pointer-sized the row hangs a flat 6px into the padding, which puts each 16pt glyph box on the rail. */
const POINTER_OVERHANG = 6;
/** How far a touch-sized disc sits from the composer's bottom edge, centred in the toolbar row. */
const DISC_EDGE_INSET =
COMPOSER_PADDING.touch.bottom + (TOOLBAR_CONTROL_SIZES.touch - TOOLBAR_DISC_SIZES.touch) / 2;
/**
* A trailing disc nests into the composer's corner: it reaches past the rail until it sits as far
* from the right edge as from the bottom edge.
*/
const DISC_CORNER_NEST = COMPOSER_PADDING.touch.horizontal - DISC_EDGE_INSET;
/** Touch-sized the composer's corner is concentric with the disc nested in it. */
export const COMPOSER_CORNER_RADIUS = bySizing({
touch: TOOLBAR_DISC_SIZES.touch / 2 + DISC_EDGE_INSET,
pointer: 16,
});
/** How far the composer toolbar hangs past the text column at one end. */
export function composerToolbarOverhang(edge: ComposerToolbarEdge, sizing: ControlSizing): number {
if (sizing === "pointer") return POINTER_OVERHANG;
return edge === "disc" ? DISC_CORNER_NEST : 0;
}
/** The control that starts the toolbar on the left. */
export function resolveComposerLeadingEdge(input: {
showsAttach: boolean;
showsAgentControls: boolean;
}): ComposerToolbarEdge {
if (input.showsAttach) return "attach";
if (input.showsAgentControls) return "label";
return "none";
}
@@ -4,7 +4,10 @@ import {
clearWorkspaceArchivePending,
isWorkspaceArchivePending,
markWorkspaceArchivePending,
markWorkspaceArchiveUndoPending,
shouldSuppressWorkspaceForLocalArchive,
settleWorkspaceArchiveIntent,
shouldSuppressWorkspaceRemovalForLocalUndo,
} from "@/contexts/session-workspace-upserts";
const baseWorkspace: WorkspaceDescriptor = {
@@ -116,3 +119,41 @@ describe("workspace archive pending suppression", () => {
clearWorkspaceArchivePending({ serverId: "server-1", workspaceId: "/repo/worktree" });
});
});
describe("workspace archive undo intent", () => {
const target = { serverId: "server-1", workspaceId: "/repo/worktree" };
it("lets host upserts through and holds host removes while an undo is pending", () => {
markWorkspaceArchivePending(target);
const undo = markWorkspaceArchiveUndoPending(target);
expect({
upsertSuppressed: shouldSuppressWorkspaceForLocalArchive({
serverId: target.serverId,
workspace: workspace({ archivingAt: null }),
}),
removeSuppressed: shouldSuppressWorkspaceRemovalForLocalUndo(target),
}).toEqual({ upsertSuppressed: false, removeSuppressed: true });
settleWorkspaceArchiveIntent(undo);
expect(shouldSuppressWorkspaceRemovalForLocalUndo(target)).toBe(false);
});
it("keeps a newer intent when the request behind an older one settles late", () => {
const firstArchive = markWorkspaceArchivePending(target);
const firstUndo = markWorkspaceArchiveUndoPending(target);
settleWorkspaceArchiveIntent(firstArchive);
clearWorkspaceArchivePending(target);
expect(shouldSuppressWorkspaceRemovalForLocalUndo(target)).toBe(true);
markWorkspaceArchivePending(target);
settleWorkspaceArchiveIntent(firstUndo);
expect(isWorkspaceArchivePending(target)).toBe(true);
const secondUndo = markWorkspaceArchiveUndoPending(target);
settleWorkspaceArchiveIntent(firstUndo);
expect(shouldSuppressWorkspaceRemovalForLocalUndo(target)).toBe(true);
settleWorkspaceArchiveIntent(secondUndo);
});
});
@@ -1,77 +1,142 @@
import type { WorkspaceDescriptor } from "@/stores/session-store";
import { normalizeWorkspaceOpaqueId } from "@/utils/workspace-identity";
interface PendingWorkspaceArchive {
workspaceId: string;
/**
* What this client last asked the host to do with a workspace, while the host catches up.
*
* - `archive`: the row is hidden; host upserts for it are dropped until its remove arrives.
* - `undo`: the row is back; host removes for it are dropped until the undo response arrives.
*
* Each request gets its own intent. A request settles or checks only the intent it set, so a
* late response for an earlier request never touches the intent of a newer one.
*/
export interface WorkspaceArchiveIntent {
readonly kind: "archive" | "undo";
}
const pendingWorkspaceArchivesByServer = new Map<string, Map<string, PendingWorkspaceArchive>>();
const intentsByServer = new Map<string, Map<string, WorkspaceArchiveIntent>>();
const intentListeners = new Set<() => void>();
const targetByIntent = new WeakMap<
WorkspaceArchiveIntent,
{ serverId: string; workspaceId: string }
>();
function pendingArchiveKey(input: { serverId: string; workspaceId: string }): string {
return `${input.serverId.trim()}::${input.workspaceId.trim()}`;
interface WorkspaceIntentTarget {
serverId: string;
workspaceId?: string | null;
}
function resolveTarget(
input: WorkspaceIntentTarget,
): { serverId: string; workspaceId: string } | null {
const serverId = input.serverId.trim();
const workspaceId = normalizeWorkspaceOpaqueId(input.workspaceId);
if (!serverId || !workspaceId) return null;
return { serverId, workspaceId };
}
function readIntent(input: WorkspaceIntentTarget): WorkspaceArchiveIntent | null {
const target = resolveTarget(input);
if (!target) return null;
return intentsByServer.get(target.serverId)?.get(target.workspaceId) ?? null;
}
function setIntent(
input: WorkspaceIntentTarget,
kind: WorkspaceArchiveIntent["kind"],
): WorkspaceArchiveIntent {
const intent: WorkspaceArchiveIntent = { kind };
const target = resolveTarget(input);
if (!target) return intent;
targetByIntent.set(intent, target);
const intents = intentsByServer.get(target.serverId) ?? new Map();
intents.set(target.workspaceId, intent);
intentsByServer.set(target.serverId, intents);
notifyIntentListeners();
return intent;
}
function deleteIntent(target: { serverId: string; workspaceId: string }): void {
const intents = intentsByServer.get(target.serverId);
if (!intents) return;
intents.delete(target.workspaceId);
if (intents.size === 0) intentsByServer.delete(target.serverId);
notifyIntentListeners();
}
function notifyIntentListeners(): void {
for (const listener of intentListeners) listener();
}
/** Calls `listener` whenever any workspace's archive intent changes. */
export function subscribeWorkspaceArchiveIntents(listener: () => void): () => void {
intentListeners.add(listener);
return () => {
intentListeners.delete(listener);
};
}
function clearIntentOfKind(
input: WorkspaceIntentTarget,
kind: WorkspaceArchiveIntent["kind"],
): void {
const target = resolveTarget(input);
if (!target || readIntent(target)?.kind !== kind) return;
deleteIntent(target);
}
/** True while `intent` is still the latest thing this client asked for its workspace. */
export function isWorkspaceArchiveIntentCurrent(intent: WorkspaceArchiveIntent): boolean {
const target = targetByIntent.get(intent);
return target !== undefined && readIntent(target) === intent;
}
/** The request behind `intent` settled. A newer request's intent stays in place. */
export function settleWorkspaceArchiveIntent(intent: WorkspaceArchiveIntent): void {
const target = targetByIntent.get(intent);
if (target && readIntent(target) === intent) deleteIntent(target);
}
export function markWorkspaceArchivePending(input: {
serverId: string;
workspaceId: string;
}): void {
const serverId = input.serverId.trim();
const workspaceId = normalizeWorkspaceOpaqueId(input.workspaceId);
if (!serverId || !workspaceId) {
return;
}
const archives = pendingWorkspaceArchivesByServer.get(serverId) ?? new Map();
archives.set(pendingArchiveKey({ serverId, workspaceId }), {
workspaceId,
});
pendingWorkspaceArchivesByServer.set(serverId, archives);
}): WorkspaceArchiveIntent {
return setIntent(input, "archive");
}
/** The host removed the workspace, which settles whichever archive this client has pending. */
export function clearWorkspaceArchivePending(input: {
serverId: string;
workspaceId: string;
}): void {
const serverId = input.serverId.trim();
const workspaceId = normalizeWorkspaceOpaqueId(input.workspaceId);
if (!serverId || !workspaceId) {
return;
}
const archives = pendingWorkspaceArchivesByServer.get(serverId);
if (!archives) {
return;
}
archives.delete(pendingArchiveKey({ serverId, workspaceId }));
if (archives.size === 0) {
pendingWorkspaceArchivesByServer.delete(serverId);
}
clearIntentOfKind(input, "archive");
}
export function isWorkspaceArchivePending(input: {
export function isWorkspaceArchivePending(input: WorkspaceIntentTarget): boolean {
return readIntent(input)?.kind === "archive";
}
export function markWorkspaceArchiveUndoPending(input: {
serverId: string;
workspaceId?: string | null;
}): boolean {
const serverId = input.serverId.trim();
if (!serverId) {
return false;
}
workspaceId: string;
}): WorkspaceArchiveIntent {
return setIntent(input, "undo");
}
const archives = pendingWorkspaceArchivesByServer.get(serverId);
if (!archives) {
return false;
}
const workspaceId = normalizeWorkspaceOpaqueId(input.workspaceId);
return Boolean(workspaceId && archives.has(pendingArchiveKey({ serverId, workspaceId })));
export function isWorkspaceArchiveUndoPending(input: WorkspaceIntentTarget): boolean {
return readIntent(input)?.kind === "undo";
}
export function shouldSuppressWorkspaceForLocalArchive(input: {
serverId: string;
workspace: WorkspaceDescriptor;
}): boolean {
return isWorkspaceArchivePending({
serverId: input.serverId,
workspaceId: input.workspace.id,
});
return isWorkspaceArchivePending({ serverId: input.serverId, workspaceId: input.workspace.id });
}
export function shouldSuppressWorkspaceRemovalForLocalUndo(input: {
serverId: string;
workspaceId: string;
}): boolean {
return isWorkspaceArchiveUndoPending(input);
}
+3
View File
@@ -1341,6 +1341,9 @@ export const ar: TranslationResources = {
hostDisconnected: "Host غير متصل",
hideFailed: "فشل في إخفاء مساحة العمل",
archiveFailed: "فشل في أرشفة مساحة العمل",
archived: "تمت أرشفة مساحة العمل",
undoArchive: "تراجع",
undoArchiveFailed: "تعذّر التراجع عن الأرشفة",
},
},
},
+3
View File
@@ -1349,6 +1349,9 @@ export const en = {
hostDisconnected: "Host is not connected",
hideFailed: "Failed to hide workspace",
archiveFailed: "Failed to archive workspace",
archived: "Workspace archived",
undoArchive: "Undo",
undoArchiveFailed: "Couldn't undo the archive",
},
},
},
+3
View File
@@ -1377,6 +1377,9 @@ export const es: TranslationResources = {
hostDisconnected: "Hostno está conectado",
hideFailed: "No se pudo ocultar el espacio de trabajo",
archiveFailed: "No se pudo archivar el espacio de trabajo",
archived: "Espacio de trabajo archivado",
undoArchive: "Deshacer",
undoArchiveFailed: "No se pudo deshacer el archivado",
},
},
},
+3
View File
@@ -1371,6 +1371,9 @@ export const fr: TranslationResources = {
hostDisconnected: "L’hôte n’est pas connecté",
hideFailed: "Impossible de masquer l’espace de travail",
archiveFailed: "Impossible d’archiver l’espace de travail",
archived: "Espace de travail archivé",
undoArchive: "Annuler",
undoArchiveFailed: "Impossible d’annuler l’archivage",
},
},
},
+3
View File
@@ -1355,6 +1355,9 @@ export const ja: TranslationResources = {
hostDisconnected: "ホストが接続されていません",
hideFailed: "ワークスペースの非表示に失敗しました",
archiveFailed: "ワークスペースのアーカイブに失敗しました",
archived: "ワークスペースをアーカイブしました",
undoArchive: "元に戻す",
undoArchiveFailed: "アーカイブを元に戻せませんでした",
},
},
},
+3
View File
@@ -1348,6 +1348,9 @@ export const ko: TranslationResources = {
hostDisconnected: "호스트가 연결되어 있지 않습니다",
hideFailed: "워크스페이스를 숨기지 못했습니다",
archiveFailed: "워크스페이스를 보관하지 못했습니다.",
archived: "워크스페이스를 보관했습니다",
undoArchive: "실행 취소",
undoArchiveFailed: "보관을 취소하지 못했습니다",
},
},
},
+3
View File
@@ -1367,6 +1367,9 @@ export const ptBR: TranslationResources = {
hostDisconnected: "Host não está conectado",
hideFailed: "Falha ao ocultar workspace",
archiveFailed: "Falha ao arquivar workspace",
archived: "Workspace arquivado",
undoArchive: "Desfazer",
undoArchiveFailed: "Não foi possível desfazer o arquivamento",
},
},
},
+3
View File
@@ -1359,6 +1359,9 @@ export const ru: TranslationResources = {
hostDisconnected: "Хост не подключён",
hideFailed: "Не удалось скрыть рабочее пространство",
archiveFailed: "Не удалось архивировать рабочее пространство",
archived: "Рабочее пространство архивировано",
undoArchive: "Отменить",
undoArchiveFailed: "Не удалось отменить архивацию",
},
},
},
+3
View File
@@ -1330,6 +1330,9 @@ export const zhCN: TranslationResources = {
hostDisconnected: "Host 未连接",
hideFailed: "隐藏 workspace 失败",
archiveFailed: "归档工作区失败",
archived: "工作区已归档",
undoArchive: "撤销",
undoArchiveFailed: "无法撤销归档",
},
},
},
+1
View File
@@ -52,6 +52,7 @@ export type KeyboardActionId =
| "workspace.project.pick"
| "worktree.new"
| "workspace.archive"
| "workspace.archive.undo"
| "workspace.pin"
| "view.toggle.focus"
| "theme.cycle"
@@ -51,6 +51,7 @@ export type KeyboardActionId =
| "workspace.project.pick"
| "worktree.new"
| "workspace.archive"
| "workspace.archive.undo"
| "workspace.pin"
// Command-center only: no keybind, so these are absent from route-shortcut.ts.
| "workspace.rename"
@@ -109,6 +110,7 @@ export type KeyboardActionDefinition =
| { id: "workspace.project.pick"; scope: KeyboardActionScope }
| { id: "worktree.new"; scope: KeyboardActionScope }
| { id: "workspace.archive"; scope: KeyboardActionScope }
| { id: "workspace.archive.undo"; scope: KeyboardActionScope }
| { id: "workspace.pin"; scope: KeyboardActionScope }
| { id: "workspace.rename"; scope: KeyboardActionScope }
| { id: "workspace.setup.show"; scope: KeyboardActionScope };
@@ -408,6 +408,25 @@ describe("keyboard-shortcuts", () => {
},
);
describe("undo archive workspace", () => {
it.each([
{ isMac: true, event: { key: "z", code: "KeyZ", metaKey: true } },
{ isMac: false, event: { key: "z", code: "KeyZ", ctrlKey: true } },
])("routes Cmd/Ctrl+Z outside text and terminals (mac: $isMac)", ({ isMac, event }) => {
expectShortcutResolution({ event, context: { isMac }, action: "workspace.archive.undo" });
});
it.each(["editable", "message-input", "terminal"] as const)(
"leaves Cmd+Z to the focused %s",
(focusScope) => {
expectNoShortcutResolution({
event: { key: "z", code: "KeyZ", metaKey: true },
context: { isMac: true, focusScope },
});
},
);
});
it("leaves Escape to an editable field", () => {
expectNoShortcutResolution({
event: { key: "Escape", code: "Escape" },
@@ -169,6 +169,7 @@ export const SHORTCUT_HELP_ROW_ORDER: Record<ShortcutSectionId, readonly string[
"workspace-next",
"pin-workspace",
"archive-workspace",
"undo-archive-workspace",
],
"tabs-panes": [
"workspace-tab-new",
@@ -361,6 +362,31 @@ const SHORTCUT_BINDINGS: readonly ShortcutBinding[] = [
},
},
// --- Undo archive workspace ---
// Only claims the key while an archive can be undone; otherwise text undo runs as usual.
{
id: "workspace-archive-undo-cmd-z-mac",
action: "workspace.archive.undo",
combo: "Cmd+Z",
when: { mac: true, commandCenter: false, editable: false, terminal: false },
help: {
id: "undo-archive-workspace",
section: "workspaces",
label: "Undo archive workspace",
},
},
{
id: "workspace-archive-undo-ctrl-z-non-mac",
action: "workspace.archive.undo",
combo: "Ctrl+Z",
when: { mac: false, commandCenter: false, editable: false, terminal: false },
help: {
id: "undo-archive-workspace",
section: "workspaces",
label: "Undo archive workspace",
},
},
// --- Pin workspace ---
{
id: "workspace-pin-cmd-shift-p-mac",
@@ -48,6 +48,7 @@ const PASSTHROUGH_DISPATCH: Record<string, KeyboardActionDefinition> = {
"workspace.new": { id: "workspace.new", scope: "sidebar" },
"workspace.project.pick": { id: "workspace.project.pick", scope: "workspace" },
"workspace.archive": { id: "workspace.archive", scope: "sidebar" },
"workspace.archive.undo": { id: "workspace.archive.undo", scope: "global" },
"workspace.pin": { id: "workspace.pin", scope: "sidebar" },
"worktree.new": { id: "worktree.new", scope: "sidebar" },
"workspace.terminal.new": { id: "workspace.terminal.new", scope: "workspace" },
+158 -94
View File
@@ -78,7 +78,8 @@ import {
deriveRouteBottomAnchorIntent,
deriveRouteBottomAnchorRequest,
} from "@/screens/agent/agent-ready-screen-bottom-anchor";
import { WorkspaceDraftAgentTab } from "@/composer/draft/workspace-tab";
import { WorkspaceDraftComposer } from "@/composer/draft/workspace-tab";
import { type DraftConversation, useDraftTimeline } from "@/composer/draft/timeline";
import { AgentTracks } from "@/panels/agent-tracks";
import { ParentAgentCallout, useParentAgentId } from "@/subagents/parent";
import { useCreateFlowStore } from "@/stores/create-flow-store";
@@ -90,14 +91,13 @@ import {
useSessionStore,
} from "@/stores/session-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import { buildWorkspaceTabPersistenceKey, type WorkspaceTabTarget } from "@/workspace-tabs/model";
import { openWorkspaceChanges } from "@/workspace-tabs/open-supporting-view";
import { useSettings } from "@/hooks/use-settings";
import type { Theme } from "@/styles/theme";
import type { PendingPermission } from "@/types/shared";
import type { StreamItem, TodoEntry } from "@/types/stream";
import type { StreamItem } from "@/types/stream";
import type { ViewedTimelineStatus, ViewedTimelineUiBridge } from "@/timeline/viewed-timeline-sync";
import { useArchiveFinishedSubagents, useSubagentsForParent } from "@/subagents";
import { getInitDeferred, getInitKey } from "@/utils/agent-initialization";
import { derivePendingPermissionKey, normalizeAgentSnapshot } from "@/utils/agent-snapshots";
import { applyLegacyDaemonWorkspaceOwnership } from "@/workspace/legacy-daemon-workspaces";
@@ -225,6 +225,29 @@ function AgentLoadErrorView({ message, onRetry }: { message: string; onRetry: ()
);
}
/** A draft has no agent to wait for; an agent shows its loading and error states until ready. */
function renderConversationNonReadyView(args: {
draft: DraftConversation | null;
agentId: string | undefined;
cwd: string | null;
viewState: AgentScreenViewState;
effectiveAgent: AgentScreenAgent | null;
t: TFunction;
onRetryLoad: () => void;
}): React.ReactElement | null {
if (args.draft) {
return null;
}
const nonReadyView = renderChatAgentNonReadyView(args);
if (nonReadyView) {
return nonReadyView;
}
invariant(args.agentId, "agent id is defined when agent content is ready");
invariant(args.effectiveAgent, "effectiveAgent is defined when the non-ready view is absent");
invariant(args.cwd, "agent cwd is defined when agent content is ready");
return null;
}
function renderChatAgentNonReadyView(args: {
viewState: AgentScreenViewState;
effectiveAgent: AgentScreenAgent | null;
@@ -303,17 +326,31 @@ function storeFetchedAgentDetail(input: {
return hydrated;
}
function AgentPanel() {
type ConversationTarget = Extract<WorkspaceTabTarget, { kind: "agent" } | { kind: "draft" }>;
/** The agent a conversation shows; a draft has none until its first prompt creates one. */
function resolveConversationAgentId(target: ConversationTarget): string | undefined {
return target.kind === "agent" ? target.agentId.trim() || undefined : undefined;
}
/**
* Drafts and agents render through one chain so the timeline stays mounted when the draft's
* first prompt creates the agent and the tab retargets. The agent gates are idle for a draft.
*/
export function AgentConversationPanel() {
const { serverId, workspaceId, target, openFileInWorkspace } = usePaneContext();
const { isInteractive } = usePaneFocus();
invariant(target.kind === "agent", "AgentPanel requires agent target");
invariant(
target.kind === "agent" || target.kind === "draft",
"AgentConversationPanel requires an agent or draft target",
);
return (
<RetainedChatContent>
<AgentPanelContent
serverId={serverId}
workspaceId={workspaceId}
agentId={target.agentId}
target={target}
isPaneFocused={isInteractive}
onOpenWorkspaceFile={openFileInWorkspace}
/>
@@ -321,55 +358,6 @@ function AgentPanel() {
);
}
function DraftPanel() {
const {
serverId,
workspaceId,
tabId,
target,
openFileInWorkspace,
openImportSheet,
retargetCurrentTab,
} = usePaneContext();
const { isInteractive } = usePaneFocus();
invariant(target.kind === "draft", "DraftPanel requires draft target");
const handleCreated = useCallback(
(agentSnapshot: Parameters<typeof normalizeAgentSnapshot>[0]) => {
const normalized = normalizeAgentSnapshot(agentSnapshot, serverId);
const agent = applyLegacyDaemonWorkspaceOwnership({ serverId, agent: normalized });
getHostRuntimeStore().acceptAgentSnapshot(serverId, agent);
retargetCurrentTab({ kind: "agent", agentId: agentSnapshot.id });
},
[retargetCurrentTab, serverId],
);
return (
<WorkspaceDraftAgentTab
serverId={serverId}
workspaceId={workspaceId}
tabId={tabId}
draftId={target.draftId}
initialSetup={target.setup}
isPaneFocused={isInteractive}
onOpenWorkspaceFile={openFileInWorkspace}
onCreated={handleCreated}
onOpenImportSheet={openImportSheet}
/>
);
}
export function AgentConversationPanel() {
const { target } = usePaneContext();
if (target.kind === "draft") {
return <DraftPanel />;
}
if (target.kind === "agent") {
return <AgentPanel />;
}
invariant(false, "AgentConversationPanel requires an agent or draft target");
}
export const agentPanelRegistration = definePanel("agent", {
component: AgentConversationPanel,
useDescriptor: useAgentDescriptor,
@@ -444,18 +432,18 @@ type AgentLookupState =
function AgentPanelContent({
serverId,
workspaceId,
agentId,
target,
isPaneFocused,
onOpenWorkspaceFile,
}: {
serverId: string;
workspaceId: string;
agentId: string;
target: ConversationTarget;
isPaneFocused: boolean;
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const { t } = useTranslation();
const resolvedAgentId = agentId.trim() || undefined;
const resolvedAgentId = resolveConversationAgentId(target);
const resolvedServerId = serverId.trim() || undefined;
const daemons = useHosts();
const runtimeServerId = resolvedServerId ?? "";
@@ -484,7 +472,7 @@ function AgentPanelContent({
: runtimeConnectionStatus;
const lastConnectionError = runtimeLastError;
if (!resolvedServerId || (!runtimeClient && !hasCachedAgent)) {
if (target.kind === "agent" && (!resolvedServerId || (!runtimeClient && !hasCachedAgent))) {
return (
<AgentSessionUnavailableState
serverLabel={serverLabel}
@@ -498,9 +486,9 @@ function AgentPanelContent({
return (
<AgentPanelBody
serverId={resolvedServerId}
serverId={resolvedServerId ?? serverId}
workspaceId={workspaceId}
agentId={resolvedAgentId}
target={target}
isPaneFocused={isPaneFocused}
client={runtimeClient}
isConnected={runtimeIsConnected}
@@ -512,7 +500,7 @@ function AgentPanelContent({
function AgentPanelBody({
serverId,
workspaceId,
agentId,
target,
isPaneFocused,
client,
isConnected,
@@ -520,13 +508,14 @@ function AgentPanelBody({
}: {
serverId: string;
workspaceId: string;
agentId?: string;
target: ConversationTarget;
isPaneFocused: boolean;
client: ReturnType<typeof useHostRuntimeClient>;
isConnected: boolean;
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const { t } = useTranslation();
const agentId = resolveConversationAgentId(target);
const { isArchivingAgent: _isArchivingAgent } = useArchiveAgent();
const hasSession = useSessionStore((state) => Boolean(state.sessions[serverId]));
const projectPlacement = useStoreWithEqualityFn(
@@ -641,7 +630,7 @@ function AgentPanelBody({
}
: null;
if (!agent) {
if (target.kind === "agent" && !agent) {
return (
<View style={styles.container} testID="agent-loading">
<View style={styles.errorContainer}>
@@ -655,7 +644,7 @@ function AgentPanelBody({
<ChatAgentContent
serverId={serverId}
workspaceId={workspaceId}
agentId={agentId}
target={target}
isPaneFocused={isPaneFocused}
client={client}
isConnected={isConnected}
@@ -667,7 +656,7 @@ function AgentPanelBody({
function ChatAgentContent({
serverId,
workspaceId,
agentId,
target,
isPaneFocused,
client,
isConnected,
@@ -675,13 +664,15 @@ function ChatAgentContent({
}: {
serverId: string;
workspaceId: string;
agentId?: string;
target: ConversationTarget;
isPaneFocused: boolean;
client: ReturnType<typeof useHostRuntimeClient>;
isConnected: boolean;
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const { t } = useTranslation();
const { tabId } = usePaneContext();
const agentId = resolveConversationAgentId(target);
const isPaneVisible = useRetainedPanelActive();
const { api: toastApi, toast: toastState, dismiss: dismissToast } = useToastHost();
const { isArchivingAgent } = useArchiveAgent();
@@ -988,17 +979,23 @@ function ChatAgentContent({
visibilityCatchUpStatus,
]);
const nonReadyView = renderChatAgentNonReadyView({
const draft = useMemo<DraftConversation | null>(
() =>
target.kind === "draft"
? { tabId, workspaceId, draftId: target.draftId, setup: target.setup }
: null,
[tabId, target, workspaceId],
);
const nonReadyView = renderConversationNonReadyView({
draft,
agentId,
cwd: agentState.cwd,
viewState,
effectiveAgent,
t,
onRetryLoad: retryAgentLoad,
});
if (nonReadyView) return nonReadyView;
invariant(agentId, "agent id is defined when agent content is ready");
invariant(effectiveAgent, "effectiveAgent is defined when the non-ready view is absent");
const agentCwd = agentState.cwd;
invariant(agentCwd, "agent cwd is defined when agent content is ready");
const showHistorySyncOverlay =
viewState.tag === "ready" &&
viewState.sync.status === "catching_up" &&
@@ -1013,7 +1010,8 @@ function ChatAgentContent({
<ChatAgentReadyContent
serverId={serverId}
workspaceId={workspaceId}
agentId={agentId}
agentId={agentId ?? tabId}
draft={draft}
isPaneFocused={isPaneFocused}
isArchivingCurrentAgent={isArchivingCurrentAgent}
agentState={agentState}
@@ -1031,7 +1029,7 @@ function ChatAgentContent({
showHistorySyncOverlay={showHistorySyncOverlay}
showHistorySyncError={showHistorySyncError}
isRetryingHistorySync={isRetryingHistorySync}
cwd={agentCwd}
cwd={agentState.cwd ?? ""}
retryTimelineSync={retryTimelineSync}
onAttentionInputFocus={attentionController.clearOnInputFocus}
onAttentionPromptSend={attentionController.clearOnPromptSend}
@@ -1044,6 +1042,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
serverId,
workspaceId,
agentId,
draft,
isPaneFocused,
isArchivingCurrentAgent,
agentState,
@@ -1069,11 +1068,13 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
}: {
serverId: string;
workspaceId: string;
/** The agent's id, or the tab id while a draft has no agent yet. */
agentId: string;
draft: DraftConversation | null;
isPaneFocused: boolean;
isArchivingCurrentAgent: boolean;
agentState: ChatAgentSelectedState;
effectiveAgent: AgentScreenAgent;
effectiveAgent: AgentScreenAgent | null;
routeBottomAnchorRequest: RouteBottomAnchorRequest;
hasAppliedAuthoritativeHistory: boolean;
toastApi: ToastApi;
@@ -1095,19 +1096,11 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
}) {
const { t } = useTranslation();
// The workspace sheet is for looking; Open as tab brings the agent back with its composer.
const showsComposer = usePaneContext().host !== "sheet";
const paneHost = usePaneContext().host;
const showsComposer = draft !== null || paneHost !== "sheet";
// The dock lays out fullscreen for the same session the composer edits in.
const composerEditingSession = useComposerEditingSession("chat");
const isComposerFullscreen = useComposerFullscreen(composerEditingSession);
const subagentRows = useSubagentsForParent({ serverId, parentAgentId: agentId });
const tasks = useSessionStore((state): TodoEntry[] | undefined =>
state.sessions[serverId]?.agentTasks.get(agentId),
);
const archiveFinishedSubagents = useArchiveFinishedSubagents({
serverId,
parentAgentId: agentId,
rows: subagentRows,
});
const hasActiveComposer = !agentState.archivedAt && !isArchivingCurrentAgent;
const parentAgentId = useParentAgentId(serverId, agentId);
// With a composer the parent is a pill above it; without one, the box takes the composer's place.
@@ -1161,7 +1154,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
const parentCallout = parentAgentId ? (
<ParentAgentCallout serverId={serverId} parentAgentId={parentAgentId} />
) : null;
const composerSection = showsComposer ? (
const agentComposerSection = showsComposer ? (
<RenderProfile id={`AgentComposerSection:${agentId}`}>
<AgentComposerSection
agentId={agentId}
@@ -1182,6 +1175,16 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
) : (
parentCallout
);
const composerSection = draft ? (
<DraftComposerSection
serverId={serverId}
draft={draft}
isPaneFocused={isPaneFocused}
editingSession={composerEditingSession}
/>
) : (
agentComposerSection
);
const streamContent = (
<View style={animatedStaticStyles.content}>
{showsComposer ? null : <SheetAgentFacts serverId={serverId} agentId={agentId} />}
@@ -1191,6 +1194,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
serverId={serverId}
agentId={agentId}
agent={effectiveAgent}
draft={draft}
routeBottomAnchorRequest={routeBottomAnchorRequest}
hasAppliedAuthoritativeHistory={hasAppliedAuthoritativeHistory}
hasActiveComposer={hasActiveComposer}
@@ -1198,16 +1202,12 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
onOpenWorkspaceFile={onOpenWorkspaceFile}
/>
</RenderProfile>
{hasActiveComposer ? (
{hasActiveComposer && !draft ? (
<AgentTracks
serverId={serverId}
workspaceId={workspaceId}
agentId={agentId}
parentAgentId={parentPillAgentId}
subagentRows={subagentRows}
tasks={tasks}
archiveFinishedStatus={archiveFinishedSubagents.status}
onArchiveFinished={archiveFinishedSubagents.archiveFinished}
/>
) : null}
</View>
@@ -1263,7 +1263,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
</RewindComposerRestoreProvider>
);
return wrapAgentCommandProvider({
enabled: showsComposer && hasActiveComposer,
enabled: showsComposer && hasActiveComposer && !draft,
serverId,
agentId,
editingSession: composerEditingSession,
@@ -1355,6 +1355,7 @@ const AgentStreamSection = memo(function AgentStreamSection({
serverId,
agentId,
agent,
draft,
routeBottomAnchorRequest,
hasAppliedAuthoritativeHistory,
hasActiveComposer,
@@ -1364,7 +1365,8 @@ const AgentStreamSection = memo(function AgentStreamSection({
streamViewRef: React.RefObject<AgentStreamViewHandle | null>;
serverId: string;
agentId?: string;
agent: AgentScreenAgent;
agent: AgentScreenAgent | null;
draft: DraftConversation | null;
routeBottomAnchorRequest: RouteBottomAnchorRequest;
hasAppliedAuthoritativeHistory: boolean;
hasActiveComposer: boolean;
@@ -1422,7 +1424,31 @@ const AgentStreamSection = memo(function AgentStreamSection({
}
return new Map(pendingPermissionList.map((permission) => [permission.key, permission]));
}, [pendingPermissionList]);
// A draft's timeline exists only while its first prompt creates the agent. The created agent's
// timeline then replaces this input in the same mounted view.
const draftTimeline = useDraftTimeline({ serverId, draft });
if (draftTimeline) {
return (
<AgentStreamView
ref={streamViewRef}
agentId={draftTimeline.agent.id}
serverId={serverId}
context={draftTimeline.agent}
streamItems={draftTimeline.streamItems}
pendingPermissions={EMPTY_PENDING_PERMISSIONS}
bottomOverlayTailClearance={bottomOverlayTailClearance}
bottomOverlayControlClearance={bottomOverlayControlClearance}
toast={toast}
pendingMessageSubmissions={draftTimeline.pendingMessageSubmissions}
turnPresentation={draftTimeline.turnPresentation}
onOpenWorkspaceFile={onOpenWorkspaceFile}
/>
);
}
if (!agent) {
return null;
}
return (
<AgentStreamView
ref={streamViewRef}
@@ -1443,6 +1469,44 @@ const AgentStreamSection = memo(function AgentStreamSection({
);
});
/** The draft's composer, which creates the agent and retargets this tab to it. */
function DraftComposerSection({
serverId,
draft,
isPaneFocused,
editingSession,
}: {
serverId: string;
draft: DraftConversation;
isPaneFocused: boolean;
editingSession: ComposerEditingSession;
}) {
const { openImportSheet, retargetCurrentTab } = usePaneContext();
const handleCreated = useCallback(
(agentSnapshot: Parameters<typeof normalizeAgentSnapshot>[0]) => {
const normalized = normalizeAgentSnapshot(agentSnapshot, serverId);
const agent = applyLegacyDaemonWorkspaceOwnership({ serverId, agent: normalized });
getHostRuntimeStore().acceptAgentSnapshot(serverId, agent);
retargetCurrentTab({ kind: "agent", agentId: agentSnapshot.id });
},
[retargetCurrentTab, serverId],
);
return (
<WorkspaceDraftComposer
serverId={serverId}
workspaceId={draft.workspaceId}
tabId={draft.tabId}
draftId={draft.draftId}
initialSetup={draft.setup}
isPaneFocused={isPaneFocused}
editingSession={editingSession}
onCreated={handleCreated}
onOpenImportSheet={openImportSheet}
/>
);
}
const AgentComposerSection = memo(function AgentComposerSection({
agentId,
serverId,
+13 -12
View File
@@ -9,11 +9,11 @@ import { useSettings } from "@/hooks/use-settings";
import { PluginComposerPills } from "@/plugins";
import { useSessionStore } from "@/stores/session-store";
import {
type ArchiveFinishedStatus,
useArchiveFinishedSubagents,
useArchiveSubagent,
useDetachSubagent,
useSubagentSheetTab,
type SubagentRow,
useSubagentsForParent,
} from "@/subagents";
import { ParentAgentPill } from "@/subagents/parent";
import { SubagentsTrack } from "@/subagents/track";
@@ -35,20 +35,21 @@ export const AgentTracks = memo(function AgentTracks({
workspaceId,
agentId,
parentAgentId,
subagentRows,
tasks,
archiveFinishedStatus,
onArchiveFinished,
}: {
serverId: string;
workspaceId: string;
agentId: string;
parentAgentId: string | null;
subagentRows: SubagentRow[];
tasks: TodoEntry[] | undefined;
archiveFinishedStatus: ArchiveFinishedStatus;
onArchiveFinished: () => void;
}): ReactElement {
const subagentRows = useSubagentsForParent({ serverId, parentAgentId: agentId });
const tasks = useSessionStore((state): TodoEntry[] | undefined =>
state.sessions[serverId]?.agentTasks.get(agentId),
);
const archiveFinishedSubagents = useArchiveFinishedSubagents({
serverId,
parentAgentId: agentId,
rows: subagentRows,
});
const { tabId } = usePaneContext();
const isCompact = useIsCompactFormFactor();
const openInSidePane = useSettings((settings) => settings.openInSidePane);
@@ -119,8 +120,8 @@ export const AgentTracks = memo(function AgentTracks({
onOpenProviderSubagent={handleOpenProviderSubagent}
sheetTabFor={sheetTabFor}
onArchiveSubagent={archiveSubagent}
onArchiveFinished={onArchiveFinished}
archiveFinishedStatus={archiveFinishedStatus}
onArchiveFinished={archiveFinishedSubagents.archiveFinished}
archiveFinishedStatus={archiveFinishedSubagents.status}
onDetachSubagent={canDetachSubagents ? detachSubagent : undefined}
/>
<PluginComposerPills
@@ -390,4 +390,39 @@ describe("AgentDirectoryReplica", () => {
expect(useSessionStore.getState().sessions[serverId]?.agents.has("agent")).toBe(true);
store.clearSession(serverId);
});
it("keeps unchanged agent fields when an update changes only the status", () => {
const serverId = "agent-replica-unchanged-fields";
const store = useSessionStore.getState();
store.initializeSession(serverId, null as unknown as DaemonClient);
const replica = new AgentDirectoryReplica(
serverId,
() => undefined,
() => undefined,
);
const agentInStore = () => useSessionStore.getState().sessions[serverId]?.agents.get("agent");
replica.commitSnapshot([entry(payload("agent"))], []);
const before = agentInStore();
replica.applyDelta({
kind: "upsert",
agent: { ...payload("agent"), status: "running", updatedAt: "2026-07-17T00:02:00.000Z" },
project: entry(payload("agent")).project,
});
const afterDelta = agentInStore();
replica.commitSnapshot(
[entry({ ...payload("agent"), status: "idle", updatedAt: "2026-07-17T00:03:00.000Z" })],
[],
);
const afterSnapshot = agentInStore();
expect(afterDelta?.status).toBe("running");
expect(afterSnapshot?.status).toBe("idle");
for (const agent of [afterDelta, afterSnapshot]) {
expect(agent?.capabilities).toBe(before?.capabilities);
expect(agent?.availableModes).toBe(before?.availableModes);
expect(agent?.labels).toBe(before?.labels);
expect(agent?.projectPlacement).toBe(before?.projectPlacement);
}
store.clearSession(serverId);
});
});
@@ -21,6 +21,26 @@ function withoutAgent(agentId: string) {
};
}
/**
* Every update arrives as a whole new agent, so each nested value (capabilities, modes, labels) is
* a new object even when it did not change. Keep the stored value for every field that is equal,
* and the stored agent when nothing changed, so a reader of one field sees a new value only when
* that field changes.
*/
function keepUnchangedFields(stored: Agent, incoming: Agent): Agent {
const next = { ...incoming };
let changed = Object.keys(stored).length !== Object.keys(next).length;
for (const key of Object.keys(next) as (keyof Agent)[]) {
if (next[key] === stored[key]) continue;
if (key in stored && equal(next[key], stored[key])) {
Object.assign(next, { [key]: stored[key] });
} else {
changed = true;
}
}
return changed ? next : stored;
}
function mergeSnapshotTurn(previous: Agent | undefined, incoming: Agent): Agent {
if (!previous) return incoming;
const activeTurn =
@@ -59,7 +79,8 @@ export class AgentStoreProjection {
let accepted = agent;
useSessionStore.getState().setAgents(this.serverId, (current) => {
const previous = current.get(agent.id);
accepted = acceptAgentDirectoryUpdate(previous, mergeSnapshotTurn(previous, agent));
const winner = acceptAgentDirectoryUpdate(previous, mergeSnapshotTurn(previous, agent));
accepted = previous ? keepUnchangedFields(previous, winner) : winner;
if (accepted === previous) return current;
const next = new Map(current);
next.set(agent.id, accepted);
@@ -117,7 +138,7 @@ export class AgentStoreProjection {
for (const [agentId, fetchedAgent] of fetched) {
const existing = current.get(agentId);
const merged = mergeSnapshotTurn(existing, fetchedAgent);
agents.set(agentId, existing && equal(existing, merged) ? existing : merged);
agents.set(agentId, existing ? keepUnchangedFields(existing, merged) : merged);
if (fetchedAgent.archivedAt) {
clearArchiveAgentPending({ queryClient, serverId: this.serverId, agentId });
}
@@ -9,6 +9,8 @@ import {
import {
clearWorkspaceArchivePending,
markWorkspaceArchivePending,
markWorkspaceArchiveUndoPending,
settleWorkspaceArchiveIntent,
} from "@/contexts/session-workspace-upserts";
import { useWorkspaceSetupStore } from "@/stores/workspace-setup-store";
import { WorkspaceDirectoryReplica } from "./workspace-replica";
@@ -378,3 +380,53 @@ it("restores a missing workspace after an archive failure without replacing a li
store.clearSession(serverId);
}
});
it("keeps a workspace whose archive is being undone when the host reports its removal", () => {
const serverId = "workspace-archive-undo";
const store = useSessionStore.getState();
store.initializeSession(serverId, null as unknown as DaemonClient);
const replica = new WorkspaceDirectoryReplica(serverId);
const restored = normalizeWorkspaceDescriptor(workspace("restored"));
const undo = markWorkspaceArchiveUndoPending({ serverId, workspaceId: restored.id });
try {
replica.acceptWorkspaces([restored]);
expect(replica.applyDelta({ kind: "remove", id: restored.id })).toEqual([]);
expect(useSessionStore.getState().sessions[serverId]?.workspaces.has(restored.id)).toBe(true);
settleWorkspaceArchiveIntent(undo);
replica.applyDelta({ kind: "remove", id: restored.id });
expect(useSessionStore.getState().sessions[serverId]?.workspaces.has(restored.id)).toBe(false);
} finally {
settleWorkspaceArchiveIntent(undo);
store.clearSession(serverId);
}
});
it("keeps a workspace whose archive is being undone when a refresh snapshot omits it", () => {
const serverId = "workspace-archive-undo-refresh";
const store = useSessionStore.getState();
store.initializeSession(serverId, null as unknown as DaemonClient);
const replica = new WorkspaceDirectoryReplica(serverId);
const restored = normalizeWorkspaceDescriptor(workspace("restored"));
const other = normalizeWorkspaceDescriptor(workspace("other"));
const workspaceIds = () => [
...(useSessionStore.getState().sessions[serverId]?.workspaces.keys() ?? []),
];
const undo = markWorkspaceArchiveUndoPending({ serverId, workspaceId: restored.id });
try {
replica.acceptWorkspaces([restored]);
replica.commitSnapshot({ workspaces: new Map([[other.id, other]]), projects: new Map() }, []);
expect(workspaceIds().sort()).toEqual(["other", "restored"]);
settleWorkspaceArchiveIntent(undo);
replica.commitSnapshot({ workspaces: new Map([[other.id, other]]), projects: new Map() }, []);
expect(workspaceIds()).toEqual(["other"]);
} finally {
settleWorkspaceArchiveIntent(undo);
store.clearSession(serverId);
}
});
@@ -14,6 +14,7 @@ import { useWorkspaceSetupStore } from "@/stores/workspace-setup-store";
import {
clearWorkspaceArchivePending,
shouldSuppressWorkspaceForLocalArchive,
shouldSuppressWorkspaceRemovalForLocalUndo,
} from "@/contexts/session-workspace-upserts";
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
import type { DirectoryReplicaMutation } from "@/runtime/replica-cache";
@@ -107,6 +108,15 @@ export class WorkspaceDirectoryReplica {
workspaces.set(workspaceId, workspace);
}
}
// A snapshot taken while an undo runs can predate the restore; the host publishes the row.
for (const [workspaceId, workspace] of this.workspaces) {
if (
!workspaces.has(workspaceId) &&
shouldSuppressWorkspaceRemovalForLocalUndo({ serverId: this.serverId, workspaceId })
) {
workspaces.set(workspaceId, workspace);
}
}
for (const workspace of workspaces.values()) this.applySetupStatus(workspace);
this.workspaces = workspaces;
this.projects = new Map(snapshot.projects);
@@ -173,6 +183,12 @@ export class WorkspaceDirectoryReplica {
kind: "remove";
},
): DirectoryReplicaMutation[] {
// The archive this remove reports is being undone; the host publishes the restored row.
if (
shouldSuppressWorkspaceRemovalForLocalUndo({ serverId: this.serverId, workspaceId: delta.id })
) {
return [];
}
this.deleteWorkspace(delta.id);
const mutations: DirectoryReplicaMutation[] = [
{ kind: "workspace", type: "delete", id: delta.id },
@@ -137,6 +137,7 @@ import { useWorkspace } from "@/stores/session-store-hooks";
import type { CheckoutStatusPayload } from "@/git/use-status-query";
import { confirmDialog } from "@/utils/confirm-dialog";
import { useArchiveAgent } from "@/hooks/use-archive-agent";
import { useWorkspaceArchiveUndoRunning } from "@/workspace/archive-undo";
import { useStableEvent } from "@/hooks/use-stable-event";
import { removeResidentBrowserWebview } from "@/desktop/browser/resident-webviews";
import { createWorkspaceBrowser, useBrowserStore } from "@/desktop/browser/store";
@@ -870,8 +871,12 @@ function WorkspaceDocumentTitleEffectSlot({
);
}
/**
* The header floats over a conversation's timeline. A draft and the agent it creates share one
* timeline, so their surfaces match and the timeline does not move when the tab retargets.
*/
function floatsHeaderOverContent(activeTab: WorkspaceTabDescriptor | null): boolean {
return supportsStreamTopOverlay && activeTab?.kind === "agent";
return supportsStreamTopOverlay && (activeTab?.kind === "agent" || activeTab?.kind === "draft");
}
/** A fullscreen composer covers the compact header; the column lays out without it. */
@@ -1245,6 +1250,11 @@ function WorkspaceScreenContent({
const hasHydratedAgents = useSessionStore(
(state) => state.sessions[normalizedServerId]?.hasHydratedAgents ?? false,
);
// An undo puts the row back before the host restores its agents. Their tabs stay until it settles.
const isArchiveUndoRunning = useWorkspaceArchiveUndoRunning({
serverId: normalizedServerId,
workspaceId: normalizedWorkspaceId,
});
const workspaceRouteState = useResolvedWorkspaceRouteState({
serverId: normalizedServerId,
workspace: workspaceDescriptor,
@@ -1545,7 +1555,7 @@ function WorkspaceScreenContent({
persistenceKey,
buildWorkspaceTabSnapshot({
agentVisibility: workspaceAgentVisibility,
agentsHydrated: hasHydratedAgents,
agentsHydrated: hasHydratedAgents && !isArchiveUndoRunning,
terminalsHydrated: terminalsQuery.isSuccess,
knownTerminalIds,
standaloneTerminalIds,
@@ -1556,6 +1566,7 @@ function WorkspaceScreenContent({
);
}, [
hasHydratedAgents,
isArchiveUndoRunning,
hasHydratedWorkspaceLayoutStore,
pendingTerminalCreateInput,
createTerminalMutation.isPending,
@@ -126,6 +126,23 @@ describe("agent directory reconciliation", () => {
}).toEqual({ title: "newer page", status: "running", projectName: "repo" });
});
it("takes the project of a newer buffered upsert", () => {
const snapshotEntry = entry("agent", "idle");
const newerProject = { ...snapshotEntry.project, projectName: "renamed project" };
const result = reconcileAgentDirectory({
snapshot: [snapshotEntry],
deltas: [
{
kind: "upsert",
agent: { ...snapshot("agent", "idle"), updatedAt: "2026-07-12T11:00:00.000Z" },
project: newerProject,
},
],
});
expect(result[0]?.project.projectName).toBe("renamed project");
});
it("clears a snapshot stop when a newer buffered upsert is running", () => {
const result = reconcileAgentDirectory({
snapshot: [entry("agent", "idle")],
@@ -0,0 +1,8 @@
export {
archiveWorkspaceWithUndo,
undoLatestWorkspaceArchive,
type UndoableWorkspaceArchiveClient,
} from "./internal/undo-window";
export { WorkspaceArchiveUndoShortcutHost } from "./internal/undo-shortcut-host";
export { supportsWorkspaceArchiveUndo } from "./internal/capability";
export { useWorkspaceArchiveUndoRunning } from "./internal/use-workspace-archive-undo-running";
@@ -0,0 +1,8 @@
import { useSessionStore } from "@/stores/session-store";
export function supportsWorkspaceArchiveUndo(serverId: string): boolean {
return (
useSessionStore.getState().sessions[serverId]?.serverInfo?.features?.workspaceArchiveUndo ===
true
);
}
@@ -0,0 +1,22 @@
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
import { hasUndoableWorkspaceArchive, undoLatestWorkspaceArchive } from "./undo-window";
const UNDO_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive.undo"];
/**
* Cmd/Ctrl+Z for the archive toast. Mounted once at the app root because the row that started
* the archive unmounts as soon as its workspace hides. It claims the key only while an archive
* can be undone, so the key falls through to text undo the rest of the time.
*/
export function WorkspaceArchiveUndoShortcutHost(): null {
useKeyboardActionHandler({
handlerId: "workspace-archive-undo-global",
actions: UNDO_ARCHIVE_ACTIONS,
enabled: true,
priority: 0,
isActive: hasUndoableWorkspaceArchive,
handle: undoLatestWorkspaceArchive,
});
return null;
}
@@ -0,0 +1,301 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import type { ToastApi, ToastShowOptions } from "@/components/toast-host";
import { clearWorkspaceArchivePending } from "@/contexts/session-workspace-upserts";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import { seedSessionHosts } from "@/test/seed-session";
import {
archiveWorkspaceWithUndo,
undoLatestWorkspaceArchive,
type UndoableWorkspaceArchiveClient,
} from "@/workspace/archive-undo";
const SERVER_ID = "workspace-archive-undo-window";
interface Deferred<T> {
promise: Promise<T>;
resolve: (value: T) => void;
reject: (error: unknown) => void;
}
function deferred<T>(): Deferred<T> {
let resolve!: (value: T) => void;
let reject!: (error: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
function workspace(id: string): WorkspaceDescriptor {
return {
createdAt: null,
lastUserMessageAt: null,
id,
projectId: "project",
projectDisplayName: "Project",
projectRootPath: "/repo/project",
workspaceDirectory: `/repo/project/${id}`,
projectKind: "git",
workspaceKind: "worktree",
name: id,
status: "done",
archivingAt: null,
statusEnteredAt: null,
diffStat: null,
scripts: [],
};
}
/** A toast host with one slot, like the app's: a new toast replaces the shown one. */
function createToastHost() {
let shown: { content: ReactNode; options?: ToastShowOptions; dismiss: () => void } | null = null;
const errors: string[] = [];
const api: ToastApi = {
show: (content, options) => {
const previous = shown;
const entry = {
content,
options,
dismiss: () => {
if (shown !== entry) return;
shown = null;
options?.onDismiss?.();
},
};
shown = entry;
previous?.options?.onDismiss?.();
return entry.dismiss;
},
copied: () => {},
error: (message) => {
errors.push(message);
api.show(message);
},
};
return {
api,
errors,
get shownTestID() {
return shown?.options?.testID ?? null;
},
timeOut: () => shown?.dismiss(),
};
}
type ArchivePayload = Awaited<ReturnType<UndoableWorkspaceArchiveClient["archiveWorkspace"]>>;
function createClient() {
const archives = new Map<string, Deferred<ArchivePayload>>();
const undos = new Map<string, Deferred<void>>();
const client: UndoableWorkspaceArchiveClient = {
archiveWorkspace: (workspaceId) => {
const response = deferred<ArchivePayload>();
archives.set(workspaceId, response);
return response.promise;
},
undoWorkspaceArchive: (workspaceId) => {
const response = deferred<void>();
undos.set(workspaceId, response);
return response.promise;
},
};
return {
client,
finishArchive: (workspaceId: string, payload: Partial<ArchivePayload> = {}) =>
archives.get(workspaceId)?.resolve({ error: null, ...payload }),
undoRequested: (workspaceId: string) => undos.has(workspaceId),
finishUndo: (workspaceId: string) => undos.get(workspaceId)?.resolve(),
failUndo: (workspaceId: string, error: Error) => undos.get(workspaceId)?.reject(error),
};
}
function storedWorkspace(id: string): WorkspaceDescriptor | undefined {
return useSessionStore.getState().sessions[SERVER_ID]?.workspaces.get(id);
}
function startArchive(input: {
host: ReturnType<typeof createClient>;
toast: ReturnType<typeof createToastHost>;
workspaceId: string;
committed: string[];
}) {
return archiveWorkspaceWithUndo({
client: input.host.client,
workspace: { serverId: SERVER_ID, workspaceId: input.workspaceId },
toast: input.toast.api,
onArchiveCommitted: () => input.committed.push(input.workspaceId),
});
}
beforeEach(() => {
seedSessionHosts([SERVER_ID]);
useSessionStore.getState().initializeSession(SERVER_ID, {} as DaemonClient);
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [workspace("a"), workspace("b")]);
});
afterEach(() => {
undoLatestWorkspaceArchive();
clearWorkspaceArchivePending({ serverId: SERVER_ID, workspaceId: "a" });
clearWorkspaceArchivePending({ serverId: SERVER_ID, workspaceId: "b" });
seedSessionHosts([]);
useSessionStore.setState((state) => ({ ...state, sessions: {} }));
});
describe("archiveWorkspaceWithUndo", () => {
it("commits the archive only once its toast is gone", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const archive = startArchive({ host, toast, workspaceId: "a", committed });
expect(toast.shownTestID).toBe("workspace-archived-toast");
host.finishArchive("a");
await archive;
expect(committed).toEqual([]);
toast.timeOut();
expect({ committed, undone: undoLatestWorkspaceArchive() }).toEqual({
committed: ["a"],
undone: false,
});
});
it("keeps the layout when another client restores the workspace before the toast closes", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const archive = startArchive({ host, toast, workspaceId: "a", committed });
host.finishArchive("a");
await archive;
clearWorkspaceArchivePending({ serverId: SERVER_ID, workspaceId: "a" });
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [workspace("a")]);
toast.timeOut();
expect({ committed, row: storedWorkspace("a") }).toEqual({
committed: [],
row: workspace("a"),
});
});
it("commits when the archive finishes after its toast already timed out", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const archive = startArchive({ host, toast, workspaceId: "a", committed });
toast.timeOut();
expect(committed).toEqual([]);
host.finishArchive("a");
await archive;
expect(committed).toEqual(["a"]);
});
it("undo during a running archive brings the row back and never commits", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const archive = startArchive({ host, toast, workspaceId: "a", committed });
expect(storedWorkspace("a")).toBeUndefined();
expect(undoLatestWorkspaceArchive()).toBe(true);
expect({
row: storedWorkspace("a"),
undoRequested: host.undoRequested("a"),
toast: toast.shownTestID,
}).toEqual({ row: workspace("a"), undoRequested: true, toast: null });
host.finishArchive("a", { canceled: true, error: "Workspace archive was undone" });
await archive;
host.finishUndo("a");
toast.timeOut();
expect({ committed, errors: toast.errors, row: storedWorkspace("a") }).toEqual({
committed: [],
errors: [],
row: workspace("a"),
});
});
it("does not claim Cmd+Z when no archive can be undone", async () => {
const host = createClient();
const toast = createToastHost();
expect(undoLatestWorkspaceArchive()).toBe(false);
const archive = startArchive({ host, toast, workspaceId: "a", committed: [] });
host.finishArchive("a");
await archive;
toast.timeOut();
expect(undoLatestWorkspaceArchive()).toBe(false);
expect(host.undoRequested("a")).toBe(false);
});
it("a newer archive takes over undo and commits the older one", async () => {
const host = createClient();
const toast = createToastHost();
const committed: string[] = [];
const first = startArchive({ host, toast, workspaceId: "a", committed });
host.finishArchive("a");
await first;
const second = startArchive({ host, toast, workspaceId: "b", committed });
expect(committed).toEqual(["a"]);
expect(undoLatestWorkspaceArchive()).toBe(true);
expect({ undoA: host.undoRequested("a"), undoB: host.undoRequested("b") }).toEqual({
undoA: false,
undoB: true,
});
host.finishArchive("b", { canceled: true });
await second;
});
it("reports a failed undo and hides the row again", async () => {
const host = createClient();
const toast = createToastHost();
const archive = startArchive({ host, toast, workspaceId: "a", committed: [] });
host.finishArchive("a");
await archive;
undoLatestWorkspaceArchive();
host.failUndo("a", new Error("Branch is gone"));
await expect.poll(() => toast.errors).toEqual(["Couldn't undo the archive"]);
expect(storedWorkspace("a")).toBeUndefined();
});
it("stays quiet about an archive that failed after the user undid it", async () => {
const host = createClient();
const toast = createToastHost();
const archive = startArchive({ host, toast, workspaceId: "a", committed: [] });
undoLatestWorkspaceArchive();
host.finishArchive("a", { error: "registry unavailable" });
await expect(archive).resolves.toBeUndefined();
expect(toast.errors).toEqual([]);
});
it("rejects a failed archive, closes its toast and puts the row back", async () => {
const host = createClient();
const toast = createToastHost();
const archive = startArchive({ host, toast, workspaceId: "a", committed: [] });
host.finishArchive("a", { error: "registry unavailable" });
await expect(archive).rejects.toThrow("registry unavailable");
expect({
toast: toast.shownTestID,
undone: undoLatestWorkspaceArchive(),
row: storedWorkspace("a"),
}).toEqual({ toast: null, undone: false, row: workspace("a") });
});
});
@@ -0,0 +1,129 @@
import type { DismissToast, ToastApi } from "@/components/toast-host";
import { i18n } from "@/i18n/i18next";
import type { WorkspaceDescriptor } from "@/stores/session-store";
import {
beginOptimisticWorkspaceArchive,
isWorkspaceListed,
undoWorkspaceArchiveOptimistically,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
import { WorkspaceArchivedToast } from "./workspace-archived-toast";
/** How long the archived toast, and with it the chance to undo, stays up. */
export const WORKSPACE_ARCHIVE_UNDO_WINDOW_MS = 6000;
export interface UndoableWorkspaceArchiveClient {
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
}
interface UndoWindowInput {
client: UndoableWorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
toast: ToastApi;
hidden: WorkspaceDescriptor | null;
onArchiveCommitted: () => void;
}
let latest: UndoWindow | null = null;
/**
* One archive's chance to be undone. It opens when the row hides and closes when its toast
* leaves the screen (timeout, replaced by another toast, or undo).
*
* - `open`: undo is offered.
* - `closed`: undo is no longer offered; the archive stands.
* - `undone`: the user took the archive back.
*/
class UndoWindow {
phase: "open" | "closed" | "undone" = "open";
private archived = false;
private readonly dismissToast: DismissToast;
constructor(private readonly input: UndoWindowInput) {
this.dismissToast = input.toast.show(<WorkspaceArchivedToast onUndo={this.undo} />, {
durationMs: WORKSPACE_ARCHIVE_UNDO_WINDOW_MS,
testID: "workspace-archived-toast",
onDismiss: this.close,
});
}
/** The host finished the archive. It commits now if undo is no longer offered. */
archiveFinished(): void {
this.archived = true;
if (this.phase === "closed") this.commit();
}
/** The archive failed on the host, so there is nothing left to undo. */
archiveFailed(): void {
this.close();
this.dismissToast();
}
readonly close = (): void => {
if (this.phase !== "open") return;
this.phase = "closed";
this.release();
if (this.archived) this.commit();
};
/** Commits unless the workspace is back by now, for example restored from another client. */
private commit(): void {
if (isWorkspaceListed(this.input.workspace)) return;
this.input.onArchiveCommitted();
}
readonly undo = (): boolean => {
if (this.phase !== "open") return false;
this.phase = "undone";
this.release();
this.dismissToast();
void undoWorkspaceArchiveOptimistically(this.input).catch((error: unknown) => {
console.warn("[workspace-archive-undo] undo failed", error);
this.input.toast.error(i18n.t("sidebar.workspace.toasts.undoArchiveFailed"));
});
return true;
};
private release(): void {
if (latest === this) latest = null;
}
}
/**
* Archives a workspace and offers to undo it until the toast goes away.
*
* `onArchiveCommitted` runs once the archive both finished on the host and can no longer be
* undone, and only if the workspace is still gone then. Local state the undo would want back
* (tabs, layout) survives the window, and survives a restore from another client.
* Rejects when the archive fails and was not undone; the row is back by then.
*/
export async function archiveWorkspaceWithUndo(input: {
client: UndoableWorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
toast: ToastApi;
onArchiveCommitted: () => void;
}): Promise<void> {
const archive = beginOptimisticWorkspaceArchive(input);
const window = new UndoWindow({ ...input, hidden: archive.hidden });
latest = window;
let outcome: Awaited<typeof archive.done>;
try {
outcome = await archive.done;
} catch (error) {
if (window.phase === "undone") return;
window.archiveFailed();
throw error;
}
if (outcome === "archived") window.archiveFinished();
}
/** Undoes the most recent archive while its toast is up. Returns false when there is none. */
export function undoLatestWorkspaceArchive(): boolean {
return latest ? latest.undo() : false;
}
export function hasUndoableWorkspaceArchive(): boolean {
return latest !== null;
}
@@ -0,0 +1,21 @@
import { useCallback, useSyncExternalStore } from "react";
import {
isWorkspaceArchiveUndoPending,
subscribeWorkspaceArchiveIntents,
} from "@/contexts/session-workspace-upserts";
/**
* True while this client's undo of the workspace's archive is running on the host. Until it
* settles, the workspace's agents may still read as archived even though they are coming back.
*/
export function useWorkspaceArchiveUndoRunning(input: {
serverId: string;
workspaceId: string | null;
}): boolean {
const { serverId, workspaceId } = input;
const read = useCallback(
() => isWorkspaceArchiveUndoPending({ serverId, workspaceId }),
[serverId, workspaceId],
);
return useSyncExternalStore(subscribeWorkspaceArchiveIntents, read, read);
}
@@ -0,0 +1,41 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Button } from "@/components/ui/button";
import { Shortcut } from "@/components/ui/shortcut";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
export function WorkspaceArchivedToast({ onUndo }: { onUndo: () => void }) {
const { t } = useTranslation();
const undoKeys = useShortcutKeys("undo-archive-workspace");
const undoShortcut = useMemo(() => (undoKeys ? <Shortcut chord={undoKeys} /> : null), [undoKeys]);
return (
<View style={styles.row}>
<Text style={styles.message}>{t("sidebar.workspace.toasts.archived")}</Text>
<Button
size="sm"
onPress={onUndo}
testID="workspace-archived-toast-undo"
trailing={undoShortcut}
>
{t("sidebar.workspace.toasts.undoArchive")}
</Button>
</View>
);
}
const styles = StyleSheet.create((theme) => ({
row: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
},
message: {
flexShrink: 1,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.normal,
},
}));
@@ -10,6 +10,7 @@ import {
import type { WorkspaceDescriptor } from "@/stores/session-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
import { archiveWorkspaceWithUndo, supportsWorkspaceArchiveUndo } from "@/workspace/archive-undo";
import { archiveWorkspaceOptimistically } from "@/workspace/workspace-archive";
function purgeArchivedWorkspaceState(input: { serverId: string; workspaceId: string }): void {
@@ -58,17 +59,22 @@ export function useWorkspaceArchive(input: ArchiveWorkspaceInput): WorkspaceArch
toast.error(t("sidebar.workspace.toasts.hostDisconnected"));
return;
}
const workspace = { serverId, workspaceId };
onSetHiding?.(true);
try {
onArchiveStarted();
await archiveWorkspaceOptimistically({
client,
workspace: {
serverId,
workspaceId,
},
});
purgeArchivedWorkspaceState({ serverId, workspaceId });
if (supportsWorkspaceArchiveUndo(serverId)) {
await archiveWorkspaceWithUndo({
client,
workspace,
toast,
onArchiveCommitted: () => purgeArchivedWorkspaceState(workspace),
});
} else {
// COMPAT(workspaceArchiveUndo): hosts before v0.15.3 cannot undo; remove after 2027-05-06.
await archiveWorkspaceOptimistically({ client, workspace });
purgeArchivedWorkspaceState(workspace);
}
} catch (error) {
toast.error(
error instanceof Error ? error.message : t("sidebar.workspace.toasts.archiveFailed"),
@@ -5,11 +5,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
clearWorkspaceArchivePending,
isWorkspaceArchivePending,
isWorkspaceArchiveUndoPending,
} from "@/contexts/session-workspace-upserts";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import {
archiveWorkspaceOptimistically,
archiveWorkspacesOptimistically,
beginOptimisticWorkspaceArchive,
undoWorkspaceArchiveOptimistically,
type WorkspaceArchiveTarget,
} from "@/workspace/workspace-archive";
@@ -21,12 +24,14 @@ type ArchiveWorkspacePayload = Awaited<ReturnType<DaemonClient["archiveWorkspace
function archivePayload(input: {
workspaceId: string;
error?: string | null;
canceled?: boolean;
}): ArchiveWorkspacePayload {
return {
requestId: "request",
workspaceId: input.workspaceId,
archivedAt: null,
error: input.error ?? null,
...(input.canceled ? { canceled: true } : {}),
};
}
@@ -224,3 +229,140 @@ describe("archiveWorkspacesOptimistically", () => {
expect(storedWorkspaceOn(SECOND_SERVER_ID, second.id)).toBeUndefined();
});
});
describe("undoWorkspaceArchiveOptimistically", () => {
it("brings the row back while the host undoes the archive it is still running", async () => {
const archived = workspace();
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [archived]);
const archiveResponse = deferred<ArchiveWorkspacePayload>();
const undoResponse = deferred<void>();
const archive = beginOptimisticWorkspaceArchive({
client: createClient(async () => archiveResponse.promise),
workspace: target(),
});
const undo = undoWorkspaceArchiveOptimistically({
client: { undoWorkspaceArchive: async () => undoResponse.promise },
workspace: target(),
hidden: archive.hidden,
});
expect(storedWorkspace(archived.id)).toEqual(archived);
// The host answers the canceled archive before the undo.
archiveResponse.resolve(archivePayload({ workspaceId: archived.id, canceled: true }));
await expect(archive.done).resolves.toBe("canceled");
undoResponse.resolve();
await undo;
expect({
row: storedWorkspace(archived.id),
archivePending: isWorkspaceArchivePending(target()),
undoPending: isWorkspaceArchiveUndoPending(target()),
}).toEqual({ row: archived, archivePending: false, undoPending: false });
});
it("hides the row again when the host cannot undo the archive", async () => {
const archived = workspace();
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [archived]);
const archive = beginOptimisticWorkspaceArchive({
client: createClient(async () => archivePayload({ workspaceId: archived.id })),
workspace: target(),
});
await archive.done;
await expect(
undoWorkspaceArchiveOptimistically({
client: {
undoWorkspaceArchive: async () => {
throw new Error("Branch is gone");
},
},
workspace: target(),
hidden: archive.hidden,
}),
).rejects.toThrow("Branch is gone");
expect(storedWorkspace(archived.id)).toBeUndefined();
expect(isWorkspaceArchiveUndoPending(target())).toBe(false);
});
it("leaves a re-archived row hidden when the earlier undo settles", async () => {
const archived = workspace();
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [archived]);
const undoResponse = deferred<void>();
const first = beginOptimisticWorkspaceArchive({
client: createClient(async () => archivePayload({ workspaceId: archived.id })),
workspace: target(),
});
await first.done;
const undo = undoWorkspaceArchiveOptimistically({
client: { undoWorkspaceArchive: async () => undoResponse.promise },
workspace: target(),
hidden: first.hidden,
});
const rearchive = beginOptimisticWorkspaceArchive({
client: createClient(async () => new Promise<ArchiveWorkspacePayload>(() => {})),
workspace: target(),
});
undoResponse.resolve();
await undo;
expect(rearchive.hidden).toEqual(archived);
expect(storedWorkspace(archived.id)).toBeUndefined();
expect(isWorkspaceArchivePending(target())).toBe(true);
});
it("puts the row back when another client's undo cancels this archive", async () => {
const archived = workspace();
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [archived]);
const archive = beginOptimisticWorkspaceArchive({
client: createClient(async () =>
archivePayload({ workspaceId: archived.id, canceled: true, error: "undone" }),
),
workspace: target(),
});
await expect(archive.done).resolves.toBe("canceled");
expect({
row: storedWorkspace(archived.id),
archivePending: isWorkspaceArchivePending(target()),
}).toEqual({ row: archived, archivePending: false });
});
it("an earlier undo settling keeps holding the row for a later undo", async () => {
const archived = workspace();
getHostRuntimeStore().acceptWorkspaceSnapshots(SERVER_ID, [archived]);
const firstUndoResponse = deferred<void>();
const secondUndoResponse = deferred<void>();
const first = beginOptimisticWorkspaceArchive({
client: createClient(async () => archivePayload({ workspaceId: archived.id })),
workspace: target(),
});
await first.done;
const firstUndo = undoWorkspaceArchiveOptimistically({
client: { undoWorkspaceArchive: async () => firstUndoResponse.promise },
workspace: target(),
hidden: first.hidden,
});
const second = beginOptimisticWorkspaceArchive({
client: createClient(async () => new Promise<ArchiveWorkspacePayload>(() => {})),
workspace: target(),
});
const secondUndo = undoWorkspaceArchiveOptimistically({
client: { undoWorkspaceArchive: async () => secondUndoResponse.promise },
workspace: target(),
hidden: second.hidden,
});
firstUndoResponse.resolve();
await firstUndo;
expect({
row: storedWorkspace(archived.id),
undoPending: isWorkspaceArchiveUndoPending(target()),
}).toEqual({ row: archived, undoPending: true });
secondUndoResponse.resolve();
await secondUndo;
});
});
+96 -25
View File
@@ -1,7 +1,10 @@
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import {
clearWorkspaceArchivePending,
isWorkspaceArchiveIntentCurrent,
markWorkspaceArchivePending,
markWorkspaceArchiveUndoPending,
settleWorkspaceArchiveIntent,
type WorkspaceArchiveIntent,
} from "@/contexts/session-workspace-upserts";
import { useSessionStore, type WorkspaceDescriptor } from "@/stores/session-store";
import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
@@ -13,11 +16,25 @@ export interface WorkspaceArchiveTarget {
}
interface WorkspaceArchiveClient {
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null }>;
archiveWorkspace: (workspaceId: string) => Promise<{ error: string | null; canceled?: boolean }>;
}
interface WorkspaceArchiveUndoClient {
undoWorkspaceArchive: (workspaceId: string) => Promise<void>;
}
/** `canceled`: an undo stopped the archive on the host before it finished. */
export type WorkspaceArchiveOutcome = "archived" | "canceled";
export interface OptimisticWorkspaceArchive {
/** The row as it was before the archive hid it, for undo to put back. */
hidden: WorkspaceDescriptor | null;
done: Promise<WorkspaceArchiveOutcome>;
}
interface OptimisticWorkspaceArchiveSnapshot {
workspace: WorkspaceDescriptor | null;
intent: WorkspaceArchiveIntent;
}
export interface WorkspaceArchiveFailure {
@@ -38,32 +55,42 @@ function isWorkspaceArchiveFailure(error: unknown): error is WorkspaceArchiveFai
);
}
function hideWorkspaceOptimistically(
workspace: WorkspaceArchiveTarget,
): OptimisticWorkspaceArchiveSnapshot {
function findListedWorkspace(workspace: WorkspaceArchiveTarget): WorkspaceDescriptor | null {
const workspaces = useSessionStore.getState().sessions[workspace.serverId]?.workspaces;
const workspaceKey = resolveWorkspaceMapKeyByIdentity({
workspaces,
workspaceId: workspace.workspaceId,
});
const snapshot = workspaceKey ? (workspaces?.get(workspaceKey) ?? null) : null;
markWorkspaceArchivePending({
return workspaceKey ? (workspaces?.get(workspaceKey) ?? null) : null;
}
/** True when the workspace is in this client's list, for example after another client restored it. */
export function isWorkspaceListed(workspace: WorkspaceArchiveTarget): boolean {
return findListedWorkspace(workspace) !== null;
}
function hideWorkspaceOptimistically(
workspace: WorkspaceArchiveTarget,
): OptimisticWorkspaceArchiveSnapshot {
const snapshot = findListedWorkspace(workspace);
const intent = markWorkspaceArchivePending({
serverId: workspace.serverId,
workspaceId: workspace.workspaceId,
});
getHostRuntimeStore().removeWorkspaceSnapshot(workspace.serverId, workspace.workspaceId);
return { workspace: snapshot };
return { workspace: snapshot, intent };
}
/**
* Puts back a row whose archive did not happen. Skipped when a newer request on this client
* (an undo, or another archive) owns the row by now.
*/
function restoreOptimisticallyHiddenWorkspace(input: {
serverId: string;
workspaceId: string;
snapshot: OptimisticWorkspaceArchiveSnapshot;
}): void {
clearWorkspaceArchivePending({
serverId: input.serverId,
workspaceId: input.workspaceId,
});
if (!isWorkspaceArchiveIntentCurrent(input.snapshot.intent)) return;
settleWorkspaceArchiveIntent(input.snapshot.intent);
if (input.snapshot.workspace) {
getHostRuntimeStore().acceptWorkspaceSnapshots(input.serverId, [input.snapshot.workspace]);
}
@@ -72,31 +99,75 @@ function restoreOptimisticallyHiddenWorkspace(input: {
async function archiveWorkspaceOrThrow(input: {
client: WorkspaceArchiveClient;
workspaceId: string;
}): Promise<void> {
}): Promise<WorkspaceArchiveOutcome> {
const payload = await input.client.archiveWorkspace(input.workspaceId);
if (payload.canceled) {
return "canceled";
}
if (payload.error) {
throw new Error(payload.error);
}
return "archived";
}
/**
* Hides the row now and archives it on the host. A failed archive puts the row back, and so
* does a canceled one: an undo from another client stopped it, so the workspace stays.
*/
export function beginOptimisticWorkspaceArchive(input: {
client: WorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
}): OptimisticWorkspaceArchive {
const snapshot = hideWorkspaceOptimistically(input.workspace);
const done = (async () => {
try {
const outcome = await archiveWorkspaceOrThrow({
client: input.client,
workspaceId: input.workspace.workspaceId,
});
if (outcome === "canceled") {
restoreOptimisticallyHiddenWorkspace({ serverId: input.workspace.serverId, snapshot });
}
return outcome;
} catch (error) {
restoreOptimisticallyHiddenWorkspace({ serverId: input.workspace.serverId, snapshot });
throw error;
}
})();
return { hidden: snapshot.workspace, done };
}
export async function archiveWorkspaceOptimistically(input: {
client: WorkspaceArchiveClient;
workspace: WorkspaceArchiveTarget;
}): Promise<void> {
const snapshot = hideWorkspaceOptimistically(input.workspace);
}): Promise<WorkspaceArchiveOutcome> {
return beginOptimisticWorkspaceArchive(input).done;
}
/**
* Puts the archived row back now and asks the host to undo the archive, whether it is still
* running or already finished. A failed undo hides the row again, unless the user archived
* it again in the meantime.
*/
export async function undoWorkspaceArchiveOptimistically(input: {
client: WorkspaceArchiveUndoClient;
workspace: WorkspaceArchiveTarget;
hidden: WorkspaceDescriptor | null;
}): Promise<void> {
const { serverId, workspaceId } = input.workspace;
const intent = markWorkspaceArchiveUndoPending({ serverId, workspaceId });
if (input.hidden) {
getHostRuntimeStore().acceptWorkspaceSnapshots(serverId, [input.hidden]);
}
try {
await archiveWorkspaceOrThrow({
client: input.client,
workspaceId: input.workspace.workspaceId,
});
await input.client.undoWorkspaceArchive(workspaceId);
} catch (error) {
restoreOptimisticallyHiddenWorkspace({
serverId: input.workspace.serverId,
workspaceId: input.workspace.workspaceId,
snapshot,
});
if (isWorkspaceArchiveIntentCurrent(intent)) {
getHostRuntimeStore().removeWorkspaceSnapshot(serverId, workspaceId);
}
throw error;
} finally {
settleWorkspaceArchiveIntent(intent);
}
}
+17
View File
@@ -3628,6 +3628,23 @@ export class DaemonClient {
}
}
/** Rejects when the host could not put the workspace back; an old host has no such RPC. */
async undoWorkspaceArchive(workspaceId: string, requestId?: string): Promise<void> {
const payload =
await this.sendNamespacedCorrelatedSessionRequest<"workspace.archive.undo.response">({
requestId,
message: {
type: "workspace.archive.undo.request",
workspaceId,
},
// Undoing a finished worktree archive recreates the worktree, like recovery does.
timeout: 150_000,
});
if (!payload.accepted) {
throw new Error(payload.error ?? "The host could not undo the workspace archive");
}
}
async resumeAgent(
handle: AgentPersistenceHandle,
overrides?: Partial<AgentSessionConfig>,
+26
View File
@@ -1105,6 +1105,14 @@ export const WorkspaceRecoveryRestoreRequestSchema = z.object({
requestId: z.string(),
});
// Undoes the latest archive of a workspace: cancels it if it is still running, otherwise
// restores the workspace, then unarchives the agents that archive took down.
export const WorkspaceArchiveUndoRequestSchema = z.object({
type: z.literal("workspace.archive.undo.request"),
workspaceId: z.string(),
requestId: z.string(),
});
export const SetVoiceModeMessageSchema = z.object({
type: z.literal("set_voice_mode"),
enabled: z.boolean(),
@@ -2249,6 +2257,16 @@ export const WorkspaceRecoveryRestoreResponseSchema = z.object({
}),
});
export const WorkspaceArchiveUndoResponseSchema = z.object({
type: z.literal("workspace.archive.undo.response"),
payload: z.object({
requestId: z.string(),
workspaceId: z.string(),
accepted: z.boolean(),
error: z.string().nullable(),
}),
});
export const SetVoiceModeResponseMessageSchema = z.object({
type: z.literal("set_voice_mode_response"),
payload: z.object({
@@ -3355,6 +3373,7 @@ export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
WorkspaceLabelDeleteInspectRequestSchema,
WorkspaceRecoveryInspectRequestSchema,
WorkspaceRecoveryRestoreRequestSchema,
WorkspaceArchiveUndoRequestSchema,
SetVoiceModeMessageSchema,
SendAgentMessageRequestSchema,
WaitForFinishRequestSchema,
@@ -3820,6 +3839,8 @@ export const ServerInfoStatusPayloadSchema = z
worktreeRestore: z.boolean().optional(),
// COMPAT(workspaceRecovery): added in v0.1.105, remove after 2027-01-11 once daemon floor >= v0.1.105.
workspaceRecovery: z.boolean().optional(),
// COMPAT(workspaceArchiveUndo): added in v0.15.3, remove gate after 2027-05-06.
workspaceArchiveUndo: z.boolean().optional(),
// COMPAT(workspaceFileEditing): added in v0.2.0, remove after 2027-01-18 once daemon floor >= v0.2.0.
workspaceFileEditing: z.boolean().optional(),
// COMPAT(fileByteWrites): added in v0.13.0, remove gate after 2027-04-20.
@@ -4796,6 +4817,8 @@ export const ArchiveWorkspaceResponseMessageSchema = z.object({
workspaceId: z.string(),
archivedAt: z.string().nullable(),
error: z.string().nullable(),
// An undo stopped this archive before it finished; `error` carries the reason.
canceled: z.boolean().optional(),
}),
});
@@ -7231,6 +7254,7 @@ export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
WorkspaceBaseBranchSetResponseSchema,
WorkspaceRecoveryInspectResponseSchema,
WorkspaceRecoveryRestoreResponseSchema,
WorkspaceArchiveUndoResponseSchema,
WaitForFinishResponseMessageSchema,
AgentPermissionRequestMessageSchema,
AgentPermissionResolvedMessageSchema,
@@ -7444,6 +7468,7 @@ export type WorkspaceRecoveryInspectResponse = z.infer<
export type WorkspaceRecoveryRestoreResponse = z.infer<
typeof WorkspaceRecoveryRestoreResponseSchema
>;
export type WorkspaceArchiveUndoResponse = z.infer<typeof WorkspaceArchiveUndoResponseSchema>;
export type WorkspaceCreateRequest = z.infer<typeof WorkspaceCreateRequestSchema>;
export type WorkspaceCreateResponse = z.infer<typeof WorkspaceCreateResponseSchema>;
export type ProjectRenameResponsePayload = z.infer<typeof ProjectRenameResponsePayloadSchema>;
@@ -7593,6 +7618,7 @@ export type WorkspacePinSetRequest = z.infer<typeof WorkspacePinSetRequestSchema
export type WorkspaceBaseBranchSetRequest = z.infer<typeof WorkspaceBaseBranchSetRequestSchema>;
export type WorkspaceRecoveryInspectRequest = z.infer<typeof WorkspaceRecoveryInspectRequestSchema>;
export type WorkspaceRecoveryRestoreRequest = z.infer<typeof WorkspaceRecoveryRestoreRequestSchema>;
export type WorkspaceArchiveUndoRequest = z.infer<typeof WorkspaceArchiveUndoRequestSchema>;
export type SetAgentModeRequestMessage = z.infer<typeof SetAgentModeRequestMessageSchema>;
export type SetAgentModelRequestMessage = z.infer<typeof SetAgentModelRequestMessageSchema>;
export type SetAgentThinkingRequestMessage = z.infer<typeof SetAgentThinkingRequestMessageSchema>;
@@ -6,7 +6,7 @@ import {
} from "./agent-messages/index.js";
import { expect, test, vi, onTestFinished } from "vitest";
import { spawn } from "node:child_process";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import { randomUUID } from "node:crypto";
@@ -9466,6 +9466,68 @@ test("archiveAgent detaches a cross-workspace child even when its tab is closed"
expect(storedChild?.labels[PARENT_AGENT_ID_LABEL]).toBeUndefined();
});
test.each([
{ workspaceId: "workspace-b", open: "false" },
{ workspaceId: "workspace-a", open: "true" },
])(
"archiveAgent publishes stored survivor detach updates ($workspaceId, open=$open)",
async ({ workspaceId, open }) => {
const artifacts = join(process.cwd(), ".artifacts");
mkdirSync(artifacts, { recursive: true });
const workdir = mkdtempSync(join(artifacts, "stored-child-detach-"));
onTestFinished(() => rmSync(workdir, { recursive: true, force: true }));
const storage = new AgentStorage(join(workdir, "agents"), logger);
const manager = new AgentManager({
clients: { codex: new TestAgentClient() },
registry: storage,
logger,
});
const parent = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Parent" },
undefined,
{ workspaceId: "workspace-a" },
);
const child = await manager.createAgent(
{ provider: "codex", cwd: workdir, title: "Closed cross-workspace child" },
undefined,
{
workspaceId,
labels: {
[PARENT_AGENT_ID_LABEL]: parent.id,
[DESKTOP_OPEN_AGENT_TAB_LABEL]: open,
team: "ios",
},
},
);
await manager.closeAgent(child.id);
// Unfiltered, as a session subscribes: a closed survivor's update must reach every client.
const emittedLabels: Array<Record<string, string>> = [];
const unsubscribe = manager.subscribe(
(event) => {
if (event.type === "agent_state" && event.agent.id === child.id) {
emittedLabels.push(event.agent.labels);
}
},
{ replayState: false },
);
await manager.archiveAgent(parent.id);
await manager.flush();
unsubscribe();
const expectedLabels = { team: "ios" };
const storedChild = await storage.get(child.id);
expect(storedChild?.archivedAt).toBeUndefined();
expect(storedChild?.labels).toEqual(expectedLabels);
expect(emittedLabels).toEqual([expectedLabels]);
// The child is already detached; repeating detach has nothing to sever.
const detached = await manager.detachAgent(child.id);
expect(detached.previousParentAgentId).toBeNull();
expect(detached.record.labels).toEqual(expectedLabels);
},
);
test("archiveAgent re-reads a child before deciding whether to cascade", async () => {
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-cascade-fresh-child-"));
@@ -2112,7 +2112,10 @@ export class AgentManager {
return;
}
if (shouldDetachFromArchivedParent(parent, currentChild)) {
await this.detachAgentUnlocked(currentChild.id);
const detached = await this.detachAgentUnlocked(currentChild.id);
if (!detached.live) {
this.dispatchStoredAgentState(detached.record);
}
} else if (this.agents.has(currentChild.id)) {
await this.archiveAgentUnlocked(currentChild.id);
} else {
@@ -2198,7 +2201,7 @@ export class AgentManager {
session: null,
capabilities: STORED_AGENT_CAPABILITIES,
config: buildStoredAgentConfig(record),
runtimeInfo: undefined,
runtimeInfo: record.runtimeInfo,
lifecycle: "closed",
createdAt: new Date(record.createdAt),
updatedAt,
@@ -2540,16 +2543,20 @@ export class AgentManager {
if (this.agents.has(agentId)) await this.closeAgentRuntime(agentId);
await this.syncNativeArchiveState(record.provider, record.persistence, "restore");
await registry.upsert({
const nextRecord: StoredAgentRecord = {
...record,
...(updates?.workspaceId ? { workspaceId: updates.workspaceId } : {}),
...(updates?.labels ? { labels: applyLabelPatch(record.labels, updates.labels) } : {}),
archivedAt: null,
updatedAt: new Date().toISOString(),
});
};
await registry.upsert(nextRecord);
if (this.getAgent(agentId)) {
this.notifyAgentState(agentId);
} else if (!nextRecord.internal) {
// Same publication archiveSnapshot makes, so a stored-only agent reappears for every client.
this.dispatchStoredAgentState(nextRecord);
}
return true;
}
@@ -219,6 +219,7 @@ const INBOUND_PERMISSION = {
"workspace.base_branch.set.request": "workspace.write",
"workspace.recovery.inspect.request": ["workspace.read", "hub.execute"],
"workspace.recovery.restore.request": ["workspace.manage", "hub.execute"],
"workspace.archive.undo.request": ["workspace.manage", "hub.execute"],
"workspace.script.list.request": "workspace.read",
"workspace.script.start.request": "workspace.write",
"workspace.script.stop.request": "workspace.write",
@@ -462,6 +463,7 @@ const OUTBOUND_PERMISSION = {
"workspace.base_branch.set.response": "workspace.write",
"workspace.recovery.inspect.response": ["workspace.read", "hub.execute"],
"workspace.recovery.restore.response": ["workspace.manage", "hub.execute"],
"workspace.archive.undo.response": ["workspace.manage", "hub.execute"],
"workspace.script.list.response": "workspace.read",
"workspace.script.start.response": "workspace.write",
"workspace.script.stop.response": "workspace.write",
@@ -0,0 +1,162 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import path from "node:path";
import { expect, test } from "vitest";
import type { AgentSnapshotPayload, SessionOutboundMessage } from "@getpaseo/protocol/messages";
import { PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestPaseoDaemon, type TestPaseoDaemon } from "../test-utils/paseo-daemon.js";
const CREATED_AT = "2026-11-04T08:00:00.000Z";
const UPDATED_AT = "2026-11-04T09:00:00.000Z";
const RUNTIME_INFO = {
provider: "codex",
sessionId: null,
model: "provider-default",
thinkingOptionId: "medium",
};
test.each([false, true])(
"parent archive preserves a stored survivor for subscribers (filtered=%s)",
async (filtered) => {
const fixture = seedFixture();
let daemon: TestPaseoDaemon | null = null;
let observer: DaemonClient | null = null;
let actor: DaemonClient | null = null;
try {
daemon = await createTestPaseoDaemon({
paseoHomeRoot: fixture.paseoHomeRoot,
staticDir: fixture.staticDir,
cleanup: false,
});
const url = `ws://127.0.0.1:${daemon.port}/ws`;
observer = new DaemonClient({ url });
actor = new DaemonClient({ url });
await observer.connect();
await actor.connect();
const updates: AgentSnapshotPayload[] = [];
const removed: string[] = [];
observer.subscribeRawMessages((message: SessionOutboundMessage) => {
if (message.type === "agent_update" && message.payload.kind === "upsert") {
updates.push(message.payload.agent);
} else if (message.type === "agent_update" && message.payload.kind === "remove") {
removed.push(message.payload.agentId);
}
});
const initial = await observer.fetchAgents({
filter: { includeBackground: true, ...(filtered ? { thinkingOptionId: "medium" } : {}) },
subscribe: {},
});
const initialSurvivor = initial.entries.find(
(entry) => entry.agent.id === "child-survivor",
)?.agent;
expect(initialSurvivor?.runtimeInfo).toEqual(RUNTIME_INFO);
expect(initialSurvivor?.effectiveThinkingOptionId).toBe("medium");
// A child already detached by hand remains independent of the parent archive.
await actor.detachAgent("child-manual");
await actor.archiveAgent("parent");
const survivor = await actor.fetchAgent({ agentId: "child-survivor" });
expect(survivor?.agent.archivedAt).toBeNull();
expect(survivor?.agent.labels).toEqual({});
await expect
.poll(() => updates.findLast((update) => update.id === "child-survivor")?.labels)
.toEqual({});
const update = updates.findLast((item) => item.id === "child-survivor");
expect(update?.runtimeInfo).toEqual(RUNTIME_INFO);
expect(update?.effectiveThinkingOptionId).toBe("medium");
expect(removed).not.toContain("child-survivor");
const manual = await actor.fetchAgent({ agentId: "child-manual" });
expect(manual?.agent.archivedAt).toBeNull();
expect(manual?.agent.labels).toEqual({});
} finally {
await observer?.close().catch(() => undefined);
await actor?.close().catch(() => undefined);
await daemon?.close().catch(() => undefined);
for (const target of fixture.cleanupPaths) rmSync(target, { recursive: true, force: true });
}
},
);
function seedFixture() {
const artifacts = path.join(process.cwd(), ".artifacts");
mkdirSync(artifacts, { recursive: true });
const root = mkdtempSync(path.join(artifacts, "archive-detach-"));
const parentCwd = path.join(root, "parent");
const childCwd = path.join(root, "child");
const paseoHomeRoot = path.join(root, "home");
const staticDir = path.join(root, "static");
mkdirSync(staticDir);
mkdirSync(parentCwd);
mkdirSync(childCwd);
const paseoHome = path.join(paseoHomeRoot, ".paseo");
const projectsDir = path.join(paseoHome, "projects");
const agentsDir = path.join(paseoHome, "agents");
mkdirSync(projectsDir, { recursive: true });
mkdirSync(agentsDir, { recursive: true });
const project = (projectId: string, rootPath: string) => ({
projectId,
rootPath,
kind: "non_git",
displayName: projectId,
customName: null,
createdAt: CREATED_AT,
updatedAt: UPDATED_AT,
archivedAt: null,
});
const workspace = (workspaceId: string, projectId: string, cwd: string) => ({
workspaceId,
projectId,
cwd,
kind: "directory",
displayName: workspaceId,
title: null,
branch: null,
baseBranch: null,
createdAt: CREATED_AT,
updatedAt: UPDATED_AT,
archivedAt: null,
});
writeJson(path.join(projectsDir, "projects.json"), [
project("proj-parent", parentCwd),
project("proj-child", childCwd),
]);
writeJson(path.join(projectsDir, "workspaces.json"), [
workspace("ws-parent", "proj-parent", parentCwd),
workspace("ws-child", "proj-child", childCwd),
]);
const agent = (id: string, cwd: string, workspaceId: string, labels: Record<string, string>) => ({
id,
provider: "codex",
cwd,
workspaceId,
createdAt: CREATED_AT,
updatedAt: UPDATED_AT,
lastActivityAt: UPDATED_AT,
lastUserMessageAt: null,
title: id,
labels,
lastStatus: "closed",
lastModeId: "full-access",
config: null,
...(id === "child-survivor" ? { runtimeInfo: RUNTIME_INFO } : {}),
persistence: null,
});
// Both children live in another workspace, so the parent's archive detaches rather than archives them.
writeJson(path.join(agentsDir, "parent.json"), agent("parent", parentCwd, "ws-parent", {}));
writeJson(
path.join(agentsDir, "child-survivor.json"),
agent("child-survivor", childCwd, "ws-child", { [PARENT_AGENT_ID_LABEL]: "parent" }),
);
writeJson(
path.join(agentsDir, "child-manual.json"),
agent("child-manual", childCwd, "ws-child", { [PARENT_AGENT_ID_LABEL]: "parent" }),
);
return { paseoHomeRoot, staticDir, cleanupPaths: [root] };
}
function writeJson(filePath: string, value: unknown): void {
writeFileSync(filePath, `${JSON.stringify(value, null, 2)}\n`);
}
@@ -0,0 +1,124 @@
import { execFileSync } from "node:child_process";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import path from "node:path";
import { isDeepStrictEqual } from "node:util";
import { expect, test } from "vitest";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import { DaemonClient } from "../test-utils/daemon-client.js";
import type { SessionOutboundMessage } from "../messages.js";
test("a warm reconnect does not resend the unchanged workspace snapshot", async () => {
const artifacts = path.resolve(".artifacts");
await mkdir(artifacts, { recursive: true });
const root = await mkdtemp(path.join(artifacts, "workspace-reconnect-"));
const cwd = path.join(root, "repo");
await mkdir(cwd);
execFileSync("git", ["init", "-b", "main"], { cwd, stdio: "ignore" });
await writeFile(path.join(cwd, "README.md"), "initial\n");
execFileSync("git", ["add", "README.md"], { cwd });
execFileSync(
"git",
[
"-c",
"user.name=Test",
"-c",
"user.email=test@example.com",
"-c",
"commit.gpgsign=false",
"commit",
"-m",
"Initial",
],
{ cwd, stdio: "ignore" },
);
const homeRoot = path.join(root, "home");
const registry = path.join(homeRoot, ".paseo", "projects");
await mkdir(registry, { recursive: true });
const timestamps = {
createdAt: "2026-10-01T00:00:00.000Z",
updatedAt: "2026-10-01T00:00:00.000Z",
archivedAt: null,
};
await writeFile(
path.join(registry, "projects.json"),
JSON.stringify([
{
projectId: "prj_reconnect",
rootPath: cwd,
kind: "git",
displayName: "Reconnect",
...timestamps,
},
]),
);
await writeFile(
path.join(registry, "workspaces.json"),
JSON.stringify(
Array.from({ length: 3 }, (_, index) => ({
workspaceId: `wks_reconnect_${index}`,
projectId: "prj_reconnect",
cwd,
kind: "local_checkout",
displayName: `Workspace ${index}`,
title: `Workspace ${index}`,
...timestamps,
})),
),
);
const daemon = await createTestPaseoDaemon({
paseoHomeRoot: homeRoot,
staticDir: path.join(root, "static"),
cleanup: false,
agentClients: {},
pluginsEnabled: false,
});
const clients: DaemonClient[] = [];
try {
const warm = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
clients.push(warm);
await warm.connect();
await warm.getCheckoutStatus(cwd);
await warm.close();
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
clients.push(client);
await client.connect();
const updates: Extract<SessionOutboundMessage, { type: "workspace_update" }>[] = [];
const events = client.observeEvents(["checkout_status_update"]);
events.subscribe({ snapshot: () => {}, update: () => {} });
await events.ready;
const snapshot = await client.fetchWorkspaces({ sync: {}, subscribe: {} });
snapshot.subscription.subscribe({
snapshot() {},
update(message) {
if (message.type === "workspace_update") updates.push(message);
},
});
expect(snapshot.entries).toHaveLength(3);
expect(snapshot.entries[0]?.gitRuntime?.currentBranch).toBe("main");
await client.getCheckoutStatus(cwd);
await new Promise((resolve) => setTimeout(resolve, 1000));
await writeFile(
path.join(root, "observed.json"),
JSON.stringify({ snapshot, updates }, null, 2),
);
const values = new Map(
snapshot.entries.map(({ syncSeq: _, ...workspace }) => [
workspace.id,
JSON.parse(JSON.stringify(workspace)),
]),
);
const identical = updates.filter(
({ payload }) =>
payload.kind === "upsert" &&
isDeepStrictEqual(
JSON.parse(JSON.stringify(payload.workspace)),
values.get(payload.workspace.id),
),
);
expect(identical, "workspace_update duplicates the snapshot without a data change").toEqual([]);
} finally {
await Promise.all(clients.map((client) => client.close()));
await daemon.close();
}
}, 30_000);
+137 -32
View File
@@ -278,6 +278,10 @@ import {
handleWorkspaceSetupRunRequest as handleWorkspaceSetupRunRequestMessage,
} from "./worktree-session.js";
import { archiveByScope, type ActiveWorkspaceRef } from "./workspace-archive-service.js";
import {
WorkspaceArchiveOperations,
type WorkspaceArchiveUndoInput,
} from "./workspace-archive-operations.js";
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
import { SessionAuthorization, type DaemonPermission } from "./authorization/index.js";
@@ -286,6 +290,12 @@ function resolveWorkspaceSetupRuntime(
): WorkspaceSetupRuntime {
return runtime ?? new WorkspaceSetupRuntime();
}
function resolveWorkspaceArchiveOperations(
operations: WorkspaceArchiveOperations | undefined,
): WorkspaceArchiveOperations {
return operations ?? new WorkspaceArchiveOperations();
}
import { WorktreeRequestError, toWorktreeWireError } from "./worktree-errors.js";
import { parseGitRemoteLocation } from "@getpaseo/protocol/git-remote";
import {
@@ -566,6 +576,8 @@ export interface SessionOptions {
scriptRuntimeStore?: WorkspaceScriptRuntimeStore;
workspaceSetupObservation?: WorkspaceSetupObservation;
workspaceSetupRuntime?: WorkspaceSetupRuntime;
/** Shared by every session so an undo from any connection reaches the archive it cancels. */
workspaceArchiveOperations?: WorkspaceArchiveOperations;
onBranchChanged?: (
workspaceId: string,
oldBranch: string | null,
@@ -837,6 +849,7 @@ export class Session {
private readonly workspaceSetupObservation: WorkspaceSetupObservation;
private readonly unsubscribeSetupObservation: () => void;
private readonly workspaceSetupRuntime: WorkspaceSetupRuntime;
private readonly workspaceArchiveOperations: WorkspaceArchiveOperations;
private readonly workspaceGitObserver: WorkspaceGitObserverService;
private readonly workspaceDirectory: WorkspaceDirectory;
private readonly voiceSessions: VoiceSessions;
@@ -902,6 +915,7 @@ export class Session {
scriptRuntimeStore,
workspaceSetupObservation,
workspaceSetupRuntime,
workspaceArchiveOperations,
onBranchChanged,
getDaemonTcpPort,
getDaemonTcpHost,
@@ -1249,6 +1263,7 @@ export class Session {
},
);
this.workspaceSetupRuntime = resolveWorkspaceSetupRuntime(workspaceSetupRuntime);
this.workspaceArchiveOperations = resolveWorkspaceArchiveOperations(workspaceArchiveOperations);
this.getDaemonTcpPort = getDaemonTcpPort ?? null;
this.getDaemonTcpHost = getDaemonTcpHost ?? null;
this.serviceProxyPublicBaseUrl = serviceProxyPublicBaseUrl ?? null;
@@ -3306,6 +3321,8 @@ export class Session {
return this.handleWorkspaceRecoveryInspectRequest(msg);
case "workspace.recovery.restore.request":
return this.handleWorkspaceRecoveryRestoreRequest(msg);
case "workspace.archive.undo.request":
return this.handleWorkspaceArchiveUndoRequest(msg);
case "workspace.clear_attention.request":
return this.handleWorkspaceClearAttentionRequest(msg);
case "workspace.mark_unread.request":
@@ -6180,6 +6197,10 @@ export class Session {
private async restoreWorkspaceAndEmit(workspaceId: string): Promise<void> {
await this.workspaceRecovery.restore(workspaceId);
await this.publishRecoveredWorkspace(workspaceId);
}
private async publishRecoveredWorkspace(workspaceId: string): Promise<void> {
const workspace = await this.workspaceRegistry.get(workspaceId);
if (!workspace) {
throw new Error(`Recovered workspace record not found: ${workspaceId}`);
@@ -7786,41 +7807,62 @@ export class Session {
request: Extract<SessionInboundMessage, { type: "archive_workspace_request" }>,
): Promise<void> {
try {
const existing = await this.workspaceRegistry.get(request.workspaceId);
if (!existing) {
throw new Error(`Workspace not found: ${request.workspaceId}`);
}
await archiveByScope(
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
agentStorage: this.agentStorage,
findWorkspaceIdForCwd: (cwd) => this.findWorkspaceIdForCwd(cwd),
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
listActiveWorkspaces: () => this.listActiveWorkspaceRefs(),
archiveWorkspaceRecord: (workspaceId) => this.archiveWorkspaceRecord(workspaceId),
emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds) =>
this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds),
markWorkspaceArchiving: (workspaceIds, archivingAt) =>
this.markWorkspaceArchiving(workspaceIds, archivingAt),
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
stopWorkspaceSetup: (workspaceId) => this.workspaceSetupRuntime.stop(workspaceId),
sessionLogger: this.sessionLogger,
},
{
scope: { kind: "workspace", workspaceId: existing.workspaceId },
requestId: request.requestId,
// Claim the archive queue before any await, so an undo sent right behind this request
// queues after it and cancels it instead of running first.
const outcome = await this.workspaceArchiveOperations.archive(
request.workspaceId,
async (signal) => {
const existing = await this.workspaceRegistry.get(request.workspaceId);
if (!existing) {
throw new Error(`Workspace not found: ${request.workspaceId}`);
}
return archiveByScope(
{
paseoHome: this.paseoHome,
paseoWorktreesBaseRoot: this.worktreesRoot,
github: this.github,
workspaceGitService: this.workspaceGitService,
agentManager: this.agentManager,
agentStorage: this.agentStorage,
findWorkspaceIdForCwd: (cwd) => this.findWorkspaceIdForCwd(cwd),
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
listActiveWorkspaces: () => this.listActiveWorkspaceRefs(),
archiveWorkspaceRecord: (workspaceId) => this.archiveWorkspaceRecord(workspaceId),
emitWorkspaceUpdatesForWorkspaceIds: (workspaceIds) =>
this.emitWorkspaceUpdatesForWorkspaceIds(workspaceIds),
markWorkspaceArchiving: (workspaceIds, archivingAt) =>
this.markWorkspaceArchiving(workspaceIds, archivingAt),
clearWorkspaceArchiving: (workspaceIds) => this.clearWorkspaceArchiving(workspaceIds),
assertWorkspaceAutomationAllowed: (workspaceId) =>
assertWorkspaceAutomationAllowedForWorkspace(this.workspaceRegistry, workspaceId),
killTerminalsForWorkspace: (workspaceId) =>
this.terminalController.killTerminalsForWorkspace(workspaceId),
stopWorkspaceSetup: (workspaceId) => this.workspaceSetupRuntime.stop(workspaceId),
sessionLogger: this.sessionLogger,
},
{
scope: { kind: "workspace", workspaceId: existing.workspaceId },
requestId: request.requestId,
signal,
},
);
},
);
if (outcome.kind === "canceled") {
this.emit({
type: "archive_workspace_response",
payload: {
requestId: request.requestId,
workspaceId: request.workspaceId,
archivedAt: null,
error: "Workspace archive was undone",
canceled: true,
},
});
return;
}
const archivedWorkspace = await this.workspaceRegistry.get(request.workspaceId);
const archivedAt = archivedWorkspace?.archivedAt ?? new Date().toISOString();
this.emit({
@@ -7850,6 +7892,69 @@ export class Session {
}
}
private async handleWorkspaceArchiveUndoRequest(
request: Extract<SessionInboundMessage, { type: "workspace.archive.undo.request" }>,
): Promise<void> {
try {
await this.workspaceArchiveOperations.undo(request.workspaceId, (input) =>
this.restoreArchivedWorkspaceAndAgents(request.workspaceId, input),
);
this.emit({
type: "workspace.archive.undo.response",
payload: {
requestId: request.requestId,
workspaceId: request.workspaceId,
accepted: true,
error: null,
},
});
} catch (error) {
this.sessionLogger.warn(
{ err: error, workspaceId: request.workspaceId, requestId: request.requestId },
"session: workspace.archive.undo.request rejected",
);
this.emit({
type: "workspace.archive.undo.response",
payload: {
requestId: request.requestId,
workspaceId: request.workspaceId,
accepted: false,
error: getErrorMessageOr(error, "Failed to undo the workspace archive"),
},
});
}
}
// Runs on the archive lane after any in-flight archive has stopped, so the record reflects how
// far it got: still active when it was canceled early, archived (directory kept or removed)
// otherwise.
private async restoreArchivedWorkspaceAndAgents(
workspaceId: string,
input: WorkspaceArchiveUndoInput,
): Promise<void> {
const workspace = await this.workspaceRegistry.get(workspaceId);
if (!workspace) {
throw new Error(`Workspace not found: ${workspaceId}`);
}
if (workspace.archivedAt) {
await this.workspaceRecovery.restore(workspaceId);
}
const results = await Promise.allSettled(
input.agentIds.map((agentId) =>
unarchiveAgentState(this.agentStorage, this.agentManager, agentId),
),
);
for (const [index, result] of results.entries()) {
if (result.status === "rejected") {
this.sessionLogger.warn(
{ err: result.reason, workspaceId, agentId: input.agentIds[index] },
"Failed to unarchive agent while undoing workspace archive",
);
}
}
await this.publishRecoveredWorkspace(workspaceId);
}
private async handleWorkspaceClearAttentionRequest(
request: Extract<SessionInboundMessage, { type: "workspace.clear_attention.request" }>,
): Promise<void> {
@@ -65,6 +65,7 @@ import {
import type { HubRelationshipManagement } from "./hub/relationship-controller.js";
import { WorkspaceSetupObservation } from "./workspace-setup-observation.js";
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
import type { HubExecutionAgents } from "./hub/daemon-executions.js";
import type { AgentProvider } from "./agent/agent-sdk-types.js";
import { ProviderSnapshotManager } from "./agent/provider-snapshot-manager.js";
@@ -609,6 +610,9 @@ export class VoiceAssistantWebSocketServer {
private readonly voiceCallerContexts = new Map<string, VoiceCallerContext>();
private readonly workspaceSetupObservation = new WorkspaceSetupObservation();
private readonly workspaceSetupRuntime: WorkspaceSetupRuntime;
// One lane per workspace across every connection, so an undo from any client can cancel an
// archive another connection started.
private readonly workspaceArchiveOperations = new WorkspaceArchiveOperations();
private readonly providerSnapshotManager: ProviderSnapshotManager;
private onLifecycleIntent!: ((intent: SessionLifecycleIntent) => void) | null;
private onBranchChanged!:
@@ -1697,6 +1701,7 @@ export class VoiceAssistantWebSocketServer {
scriptRuntimeStore: this.scriptRuntimeStore ?? undefined,
workspaceSetupObservation: this.workspaceSetupObservation,
workspaceSetupRuntime: this.workspaceSetupRuntime,
workspaceArchiveOperations: this.workspaceArchiveOperations,
onBranchChanged: this.onBranchChanged ?? undefined,
getDaemonTcpPort: this.getDaemonTcpPort ?? undefined,
getDaemonTcpHost: this.getDaemonTcpHost ?? undefined,
@@ -2120,6 +2125,8 @@ export class VoiceAssistantWebSocketServer {
worktreeRestore: true,
// COMPAT(workspaceRecovery): added in v0.1.105, remove after 2027-01-11 once daemon floor >= v0.1.105.
workspaceRecovery: true,
// COMPAT(workspaceArchiveUndo): added in v0.15.3, remove gate after 2027-05-06.
workspaceArchiveUndo: true,
// COMPAT(workspaceFileEditing): added in v0.2.0, remove after 2027-01-18 once daemon floor >= v0.2.0.
workspaceFileEditing: true,
// COMPAT(fileByteWrites): added in v0.13.0, remove gate after 2027-04-20.

Some files were not shown because too many files have changed in this diff Show More