Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fea3de73c3 | ||
|
|
e8f28ef6f6 | ||
|
|
5e9e07450e |
@@ -1,63 +0,0 @@
|
||||
# Brand assets
|
||||
|
||||
Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets that will replace the existing icons across the app, desktop client, website, docs, and Hub in follow-up work.
|
||||
|
||||
## Brand architecture
|
||||
|
||||
- **Paseo** (butterfly mark): the local client, daemon, CLI, SDK, and small account features (sign-in, share links, tunnels).
|
||||
- **Paseo Hub** (flower mark): the software factory, team features, hosted service, and paid plans (`Hub Free`, `Hub Solo`, `Hub Team`).
|
||||
- **Hub** (flower mark + `Hub`): used only where Paseo is already on screen, such as inside the Hub dashboard header.
|
||||
|
||||
## Specifications
|
||||
|
||||
### Marks
|
||||
|
||||
Both marks are single-line stroked paths on a `700 × 700` viewBox with `stroke-width="50"`, `stroke-linecap="round"`, and `stroke-linejoin="round"`. Both are optically centered to a `527`-unit ink footprint:
|
||||
|
||||
- **Paseo (`marks/paseo-*.svg`)**: refit of the hand-drawn butterfly (redraw B) with smooth curvature on the large wing and lower loop and a uniform `50` stroke width.
|
||||
- **Paseo Hub (`marks/paseo-hub-*.svg`)**: five-petal looped flower (variant A) with a `12°` clockwise petal lean, sized up to match the butterfly's `527` footprint with the same `50` stroke.
|
||||
|
||||
Colors:
|
||||
|
||||
- `white` (`#FFFFFF`) for dark surfaces (`#101615`, `#101010`, `#000000`)
|
||||
- `black` (`#000000`) for light surfaces
|
||||
- `green` (`#20744A`) brand accent
|
||||
|
||||
### Lockups
|
||||
|
||||
All lockups (`lockups/*.svg`) share a `144`-unit height (`140`-unit flower ink height with a `2`-unit margin on all sides) so stacked lockups align cleanly:
|
||||
|
||||
- **Font**: Plus Jakarta Sans SemiBold (`600`), bundled in `fonts/PlusJakartaSans-SemiBold.ttf` under the SIL Open Font License 1.1 (`fonts/OFL.txt`).
|
||||
- **Outlined text**: lockup SVGs outline the wordmark to `<path>` elements so they render identically everywhere without the font installed.
|
||||
- **Proportions**: marks are `15%` larger against text and `20%` closer than the original website header baseline (`24 px` box, `12 px` gap, `18 px` text).
|
||||
- **Optical balance**: in the `paseo` lockup, the butterfly is scaled to `94%` (`stroke-width` proportional) so `Paseo`, `Paseo Hub`, and `Hub` sit at equal visual weight when shown together.
|
||||
|
||||
## Files
|
||||
|
||||
```text
|
||||
assets/brand/
|
||||
build.mjs Regenerates all marks and lockups
|
||||
fonts/
|
||||
PlusJakartaSans-SemiBold.ttf
|
||||
OFL.txt
|
||||
marks/
|
||||
paseo-white.svg
|
||||
paseo-black.svg
|
||||
paseo-green.svg
|
||||
paseo-hub-white.svg
|
||||
paseo-hub-black.svg
|
||||
paseo-hub-green.svg
|
||||
lockups/
|
||||
paseo-white.svg
|
||||
paseo-black.svg
|
||||
paseo-hub-white.svg
|
||||
paseo-hub-black.svg
|
||||
hub-white.svg
|
||||
hub-black.svg
|
||||
```
|
||||
|
||||
## Regenerate
|
||||
|
||||
```sh
|
||||
node assets/brand/build.mjs
|
||||
```
|
||||
@@ -1,93 +0,0 @@
|
||||
Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
|
Before Width: | Height: | Size: 7.9 KiB |
|
Before Width: | Height: | Size: 7.9 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 5.9 KiB |
|
Before Width: | Height: | Size: 5.9 KiB |
|
Before Width: | Height: | Size: 6.7 KiB |
|
Before Width: | Height: | Size: 6.7 KiB |
|
Before Width: | Height: | Size: 6.7 KiB |
|
Before Width: | Height: | Size: 5.9 KiB |
@@ -186,13 +186,11 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
Single file, validated with `PersistedConfigSchema`.
|
||||
|
||||
`agents.skills.selection` stores the orchestration-skill preference for the daemon host, and a
|
||||
missing value defaults to `{ mode: "all" }`. The daemon does not persist installed state. It
|
||||
derives installed state from `~/.agents/skills`, `~/.claude/skills`, and `~/.gemini/config/skills`,
|
||||
and serializes configuration and filesystem convergence through one owner. Codex and Gemini CLI
|
||||
discover `~/.agents/skills`, while Antigravity discovers `~/.gemini/config/skills`. Updates retire
|
||||
unchanged files from Paseo-managed copies in `~/.codex/skills` and preserve user edits and
|
||||
untracked files.
|
||||
`agents.skills.selection` is the daemon host's orchestration-skill preference. Missing means
|
||||
`{ mode: "all" }`. Installed state is not persisted; the daemon derives it from the shared
|
||||
`~/.agents/skills` and Claude skill directories and keeps config plus filesystem convergence behind
|
||||
one serialized owner. Codex discovers the shared directory. Updates retire unchanged files from
|
||||
Paseo-managed copies in `~/.codex/skills`, preserving user edits and untracked files.
|
||||
|
||||
`paseo reload` reads and validates this file once inside the daemon. That snapshot drives resolution,
|
||||
classification, application, and reload bookkeeping. `DaemonConfigStore` owns applying runtime-safe
|
||||
|
||||
@@ -29,12 +29,7 @@ const ACP_PROVIDER = {
|
||||
|
||||
interface ProviderCatalogDaemonClient {
|
||||
getLastServerInfoMessage(): {
|
||||
features?: {
|
||||
gooseProvider?: boolean;
|
||||
fxProvider?: boolean;
|
||||
hopliteProvider?: boolean;
|
||||
plugins?: boolean;
|
||||
};
|
||||
features?: { fxProvider?: boolean; hopliteProvider?: boolean; plugins?: boolean };
|
||||
} | null;
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
@@ -209,47 +204,3 @@ test("model selector excludes Hoplite before opt-in", async ({ page }, testInfo)
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("adds bundled goose from the catalog", async ({ page }) => {
|
||||
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
|
||||
clientIdPrefix: "goose-catalog-e2e",
|
||||
});
|
||||
try {
|
||||
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(true);
|
||||
await client.patchDaemonConfig({ removeProviders: ["goose"] });
|
||||
await gotoAppShell(page);
|
||||
await addGooseFromSettings(page, getServerId());
|
||||
expect((await client.getDaemonConfig()).config.providers?.goose).toEqual({ enabled: true });
|
||||
} finally {
|
||||
await client.patchDaemonConfig({ removeProviders: ["goose"] });
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("adds goose through ACP on an older host", async ({ page, outdatedDaemon }) => {
|
||||
const client = await connectDaemonClient<ProviderCatalogDaemonClient>({
|
||||
clientIdPrefix: "goose-catalog-old-host",
|
||||
port: Number(new URL(`http://${outdatedDaemon.endpoint}`).port),
|
||||
});
|
||||
try {
|
||||
expect(client.getLastServerInfoMessage()?.features?.gooseProvider).toBe(false);
|
||||
await seedSavedSettingsHosts(page, [outdatedDaemon]);
|
||||
await page.reload();
|
||||
await addGooseFromSettings(page, outdatedDaemon.serverId);
|
||||
expect((await client.getDaemonConfig()).config.providers?.goose).toMatchObject({
|
||||
extends: "acp",
|
||||
command: ["goose", "acp"],
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
});
|
||||
|
||||
async function addGooseFromSettings(page: import("@playwright/test").Page, serverId: string) {
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, serverId);
|
||||
await openSettingsHostSection(page, serverId, "providers");
|
||||
await openAddProvider(page);
|
||||
await installAcpCatalogProvider(page, "goose");
|
||||
await expectProviderInstalledInSettings(page, "goose");
|
||||
}
|
||||
|
||||
@@ -1598,237 +1598,6 @@ test("canvas diff replaces a selection with forward and backward drags", async (
|
||||
}
|
||||
});
|
||||
|
||||
test("canvas diff double-click selects the grapheme under the pointer, not the nearest caret", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = "call(foo bar)";
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
clickCount: 2,
|
||||
fraction: 0.75,
|
||||
start: { line: 0, offset: 3 },
|
||||
end: { line: 0, offset: 3 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "call");
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
clickCount: 2,
|
||||
fraction: 0.1,
|
||||
start: { line: 0, offset: 4 },
|
||||
end: { line: 0, offset: 4 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "(");
|
||||
});
|
||||
|
||||
test("canvas diff double-click selects the clicked word and replaces an existing selection", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = "alpha bravo charlie delta";
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
start: { line: 0, offset: 0 },
|
||||
end: { line: 0, offset: 4 },
|
||||
});
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
clickCount: 2,
|
||||
start: { line: 0, offset: 8 },
|
||||
end: { line: 0, offset: 8 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "bravo");
|
||||
});
|
||||
|
||||
test("canvas diff double-click drag extends the selection word by word in both directions", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = "alpha bravo charlie delta";
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
for (const [start, end, expectedText] of [
|
||||
[{ line: 0, offset: 8 }, { line: 0, offset: 14 }, "bravo charlie"],
|
||||
[{ line: 0, offset: 14 }, { line: 0, offset: 2 }, "alpha bravo charlie"],
|
||||
] as const) {
|
||||
await dragAddedTextRange(page, { lines: [content], clickCount: 2, start, end });
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, expectedText);
|
||||
}
|
||||
});
|
||||
|
||||
test("canvas diff double-click drag extends word by word across lines and wrapped lines", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const lines = ["alpha bravo", "charlie delta"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
for (const [start, end, expectedText] of [
|
||||
[{ line: 0, offset: 8 }, { line: 1, offset: 10 }, "bravo\ncharlie delta"],
|
||||
[{ line: 1, offset: 10 }, { line: 0, offset: 2 }, "alpha bravo\ncharlie delta"],
|
||||
] as const) {
|
||||
await dragAddedTextRange(page, { lines, clickCount: 2, start, end });
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, expectedText);
|
||||
}
|
||||
|
||||
const wrapped = `${"alpha ".repeat(40)}bravo charlie`;
|
||||
const wrappedWorkspace = await createWorkspaceWithExactSelectionDiff(wrapped);
|
||||
await configureDiffPresentation(page, { layout: "unified", wrapLines: true });
|
||||
await openSelectionWorkspaceChanges(page, wrappedWorkspace);
|
||||
await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true });
|
||||
const bravoStart = 40 * "alpha ".length;
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [wrapped],
|
||||
wrapped: true,
|
||||
clickCount: 2,
|
||||
start: { line: 0, offset: bravoStart + 2 },
|
||||
end: { line: 0, offset: bravoStart + 9 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "bravo charlie");
|
||||
});
|
||||
|
||||
test("canvas diff double-click drag keeps word selection on the split side", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const lines = ["RIGHT-ONE", "RIGHT-TWO"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await configureDiffPresentation(page, { layout: "split", wrapLines: false });
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
await setOpenChangesPresentation(page, { layout: "split", wrapLines: false });
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines,
|
||||
side: "right",
|
||||
clickCount: 2,
|
||||
start: { line: 0, offset: 7 },
|
||||
end: { line: 1, offset: 3 },
|
||||
});
|
||||
await page.keyboard.press("ControlOrMeta+C");
|
||||
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("ONE\nRIGHT");
|
||||
});
|
||||
|
||||
test("canvas diff triple-click selects the whole source line and replaces an existing selection", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = "alpha bravo";
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
start: { line: 0, offset: 0 },
|
||||
end: { line: 0, offset: 3 },
|
||||
});
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
clickCount: 3,
|
||||
start: { line: 0, offset: 8 },
|
||||
end: { line: 0, offset: 8 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, content);
|
||||
});
|
||||
|
||||
test("canvas diff triple-click drag extends whole source lines in both directions", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const lines = ["alpha", "bravo", "charlie"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await useUnwrappedDiffLines(page);
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
|
||||
for (const [start, end] of [
|
||||
[
|
||||
{ line: 0, offset: 2 },
|
||||
{ line: 2, offset: 3 },
|
||||
],
|
||||
[
|
||||
{ line: 2, offset: 3 },
|
||||
{ line: 0, offset: 1 },
|
||||
],
|
||||
] as const) {
|
||||
await dragAddedTextRange(page, { lines, clickCount: 3, start, end });
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, "alpha\nbravo\ncharlie");
|
||||
}
|
||||
});
|
||||
|
||||
test("canvas diff triple-click selects every wrapped fragment of a source line", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const content = `${"alpha ".repeat(80)}omega`;
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(content);
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await configureDiffPresentation(page, { layout: "unified", wrapLines: true });
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
await setOpenChangesPresentation(page, { layout: "unified", wrapLines: true });
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines: [content],
|
||||
wrapped: true,
|
||||
clickCount: 3,
|
||||
start: { line: 0, offset: 20 },
|
||||
end: { line: 0, offset: 20 },
|
||||
});
|
||||
await copyDiffSelectionWithKeyboard(page);
|
||||
await expectClipboardText(page, content);
|
||||
});
|
||||
|
||||
test("canvas diff triple-click drag keeps whole source lines on the split side", async ({
|
||||
context,
|
||||
page,
|
||||
}) => {
|
||||
const lines = ["RIGHT-ONE", "RIGHT-TWO"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
await configureDiffPresentation(page, { layout: "split", wrapLines: false });
|
||||
await openSelectionWorkspaceChanges(page, workspace);
|
||||
await setOpenChangesPresentation(page, { layout: "split", wrapLines: false });
|
||||
|
||||
await dragAddedTextRange(page, {
|
||||
lines,
|
||||
side: "right",
|
||||
clickCount: 3,
|
||||
start: { line: 1, offset: 3 },
|
||||
end: { line: 0, offset: 4 },
|
||||
});
|
||||
await page.keyboard.press("ControlOrMeta+C");
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => navigator.clipboard.readText()))
|
||||
.toBe("RIGHT-ONE\nRIGHT-TWO");
|
||||
});
|
||||
|
||||
test("canvas diff copies only the selected split side", async ({ context, page }) => {
|
||||
const lines = ["RIGHT-ONE", "RIGHT-TWO"];
|
||||
const workspace = await createWorkspaceWithExactSelectionDiff(lines.join("\n"));
|
||||
@@ -2713,8 +2482,6 @@ async function dragAddedTextRange(
|
||||
side?: "left" | "right";
|
||||
wrapped?: boolean;
|
||||
horizontalOffset?: number;
|
||||
clickCount?: 1 | 2 | 3;
|
||||
fraction?: number;
|
||||
},
|
||||
): Promise<void> {
|
||||
const body = page.getByTestId("diff-file-0-body");
|
||||
@@ -2753,38 +2520,14 @@ async function dragAddedTextRange(
|
||||
columnLeft +
|
||||
gutterWidth +
|
||||
8 +
|
||||
(localOffset + (input.fraction ?? 0)) * metrics.characterWidth -
|
||||
localOffset * metrics.characterWidth -
|
||||
(input.horizontalOffset ?? 0),
|
||||
y: bounds.y + (1 + fragmentsBefore(line) + fragment + 0.5) * lineHeight,
|
||||
};
|
||||
};
|
||||
const start = point(input.start);
|
||||
const end = point(input.end);
|
||||
const clickCount = input.clickCount ?? 1;
|
||||
await page.mouse.move(start.x, start.y);
|
||||
if (clickCount > 1) {
|
||||
const isSinglePoint =
|
||||
input.start.line === input.end.line && input.start.offset === input.end.offset;
|
||||
if (isSinglePoint && clickCount === 2) {
|
||||
await page.mouse.dblclick(start.x, start.y);
|
||||
return;
|
||||
}
|
||||
if (isSinglePoint) {
|
||||
for (let count = 1; count <= clickCount; count += 1) {
|
||||
await page.mouse.down({ clickCount: count });
|
||||
await page.mouse.up({ clickCount: count });
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (let count = 1; count < clickCount; count += 1) {
|
||||
await page.mouse.down({ clickCount: count });
|
||||
await page.mouse.up({ clickCount: count });
|
||||
}
|
||||
await page.mouse.down({ clickCount });
|
||||
await page.mouse.move(end.x, end.y, { steps: 12 });
|
||||
await page.mouse.up({ clickCount });
|
||||
return;
|
||||
}
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(end.x, end.y, { steps: 12 });
|
||||
await page.mouse.up();
|
||||
|
||||
@@ -10,19 +10,16 @@ import {
|
||||
expectColumnAtLeftGutter,
|
||||
expectColumnClearOfOutline,
|
||||
expectContentColumnWidth,
|
||||
expectSharedHorizontalRail,
|
||||
} from "../support/helpers/content-width";
|
||||
import { openFileExplorer, openFileFromExplorer } from "../support/helpers/file-explorer";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
const ULTRAWIDE_VIEWPORT = { width: 2560, height: 1080 };
|
||||
const DESKTOP_VIEWPORT = { width: 1440, height: 900 };
|
||||
const TRANSITION_VIEWPORT = { width: 1250, height: 900 };
|
||||
const DEFAULT_COLUMN = { min: 800, max: 820 };
|
||||
const WIDE_COLUMN = { min: 1180, max: 1200 };
|
||||
const FULL_COLUMN = { min: 2000, max: ULTRAWIDE_VIEWPORT.width };
|
||||
|
||||
test("resizes mounted chat content and keeps timeline and composer on one rail beside the outline", async ({
|
||||
test("resizes mounted chat content and leaves room for the outline at full width", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
@@ -40,46 +37,26 @@ test("resizes mounted chat content and keeps timeline and composer on one rail b
|
||||
await openAgentRoute(page, agent);
|
||||
await expectChatOutlinePrompts(page, 2);
|
||||
const reply = page.getByTestId("assistant-message").first();
|
||||
const turnFooter = page.getByTestId("turn-footer").first();
|
||||
const composer = page.getByTestId("message-input-root");
|
||||
await expectContentColumnWidth(reply, DEFAULT_COLUMN);
|
||||
await expectSharedHorizontalRail(turnFooter, composer);
|
||||
const originalReply = await reply.elementHandle();
|
||||
|
||||
// In the transition band (pane ~930px >= 918px, < 820 + 120), Default clears the outline on one rail.
|
||||
await page.setViewportSize(TRANSITION_VIEWPORT);
|
||||
await expectColumnClearOfOutline(composer, chatOutlineRail(page));
|
||||
await expectSharedHorizontalRail(turnFooter, composer);
|
||||
|
||||
await page.setViewportSize(ULTRAWIDE_VIEWPORT);
|
||||
await chooseContentWidth(page, "Wide");
|
||||
await expectContentColumnWidth(reply, WIDE_COLUMN);
|
||||
await expectContentColumnWidth(composer, WIDE_COLUMN);
|
||||
await expectSharedHorizontalRail(turnFooter, composer);
|
||||
|
||||
// At 1440px (pane ~1120px < 1200 + 120), Wide clears the outline and keeps timeline and composer aligned.
|
||||
await page.setViewportSize(DESKTOP_VIEWPORT);
|
||||
await expectColumnClearOfOutline(composer, chatOutlineRail(page));
|
||||
await expectSharedHorizontalRail(turnFooter, composer);
|
||||
|
||||
await page.setViewportSize(ULTRAWIDE_VIEWPORT);
|
||||
await chooseContentWidth(page, "Full");
|
||||
await expectContentColumnWidth(reply, FULL_COLUMN);
|
||||
await expectContentColumnWidth(composer, FULL_COLUMN);
|
||||
await expectColumnClearOfOutline(reply, chatOutlineRail(page));
|
||||
await expectColumnClearOfOutline(composer, chatOutlineRail(page));
|
||||
await expectSharedHorizontalRail(turnFooter, composer);
|
||||
|
||||
await disableChatOutline(page);
|
||||
await expectNoChatOutline(page);
|
||||
await expectColumnAtLeftGutter(page, reply);
|
||||
await expectColumnAtLeftGutter(page, composer);
|
||||
await expectSharedHorizontalRail(turnFooter, composer);
|
||||
|
||||
await chooseContentWidth(page, "Default");
|
||||
await expectContentColumnWidth(reply, DEFAULT_COLUMN);
|
||||
await expectContentColumnWidth(composer, DEFAULT_COLUMN);
|
||||
await expectSharedHorizontalRail(turnFooter, composer);
|
||||
expect(await originalReply?.evaluate((node) => node.isConnected)).toBe(true);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
|
||||
import { selectSidebarStatusGrouping } from "../support/helpers/sidebar";
|
||||
import {
|
||||
createGatedTeardown,
|
||||
pressArchiveShortcut,
|
||||
workspaceRow,
|
||||
} from "../support/helpers/workspace-archive-undo";
|
||||
|
||||
// The archive shortcut used to be registered by the sidebar row itself, so it did nothing whenever
|
||||
// the row was unmounted — a collapsed project section being the common case. It now lives in a
|
||||
// single always-mounted handler keyed on the active route selection, like the pin shortcut.
|
||||
// Returns the workspace route, so the test can assert archiving redirected off it.
|
||||
async function openWorkspace(page: Page, workspaceId: string): Promise<string> {
|
||||
const row = workspaceRow(page, workspaceId);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await row.click();
|
||||
await expect(page).toHaveURL((url) => url.pathname.endsWith(`/workspace/${workspaceId}`), {
|
||||
timeout: 30_000,
|
||||
});
|
||||
return page.url();
|
||||
}
|
||||
|
||||
async function collapseProjectSection(page: Page, project: SeededWorkspace): Promise<void> {
|
||||
const header = page
|
||||
.locator('[data-testid^="sidebar-project-row-"]')
|
||||
.filter({ hasText: project.projectDisplayName });
|
||||
await expect(header).toHaveCount(1, { timeout: 30_000 });
|
||||
|
||||
await header.click();
|
||||
await expect(workspaceRow(page, project.workspaceId)).toHaveCount(0, { timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function collapseStatusGroupContaining(page: Page, workspaceId: string): Promise<void> {
|
||||
const rows = page
|
||||
.locator('[data-testid^="sidebar-status-group-rows-"]')
|
||||
.filter({ has: workspaceRow(page, workspaceId) });
|
||||
await expect(rows).toHaveCount(1, { timeout: 30_000 });
|
||||
|
||||
const rowsTestId = await rows.getAttribute("data-testid");
|
||||
const bucket = rowsTestId?.replace("sidebar-status-group-rows-", "");
|
||||
expect(bucket).toBeTruthy();
|
||||
|
||||
await page.getByTestId(`sidebar-status-group-${bucket}`).click();
|
||||
await expect(workspaceRow(page, workspaceId)).toHaveCount(0, { timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function expectArchived(page: Page, workspace: SeededWorkspace, workspaceUrl: string) {
|
||||
await expect(page).not.toHaveURL(workspaceUrl);
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const { entries } = await workspace.client.fetchWorkspaces();
|
||||
return entries.some((entry) => entry.id === workspace.workspaceId);
|
||||
})
|
||||
.toBe(false);
|
||||
}
|
||||
|
||||
test.describe("Archive workspace shortcut", () => {
|
||||
test("archives the active workspace while its row is rendered", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-expanded-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives the active workspace while its project section is collapsed", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-collapsed-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
await collapseProjectSection(page, workspace);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives the active workspace while its status group is collapsed", async ({ page }) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "archive-shortcut-status-" });
|
||||
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const workspaceUrl = await openWorkspace(page, workspace.workspaceId);
|
||||
await selectSidebarStatusGrouping(page);
|
||||
await expect(page.getByTestId("sidebar-status-list-scroll")).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await collapseStatusGroupContaining(page, workspace.workspaceId);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
|
||||
await expectArchived(page, workspace, workspaceUrl);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("archives a different workspace while the first worktree is still tearing down", async ({
|
||||
page,
|
||||
}) => {
|
||||
const teardown = createGatedTeardown();
|
||||
const project = await seedWorkspace({
|
||||
repoPrefix: "archive-shortcut-teardown-",
|
||||
repo: { paseoConfig: teardown.paseoConfig },
|
||||
});
|
||||
const next = await seedWorkspace({ repoPrefix: "archive-shortcut-next-" });
|
||||
|
||||
try {
|
||||
const { workspace: worktree, error } = await project.client.createWorkspace({
|
||||
source: {
|
||||
kind: "worktree",
|
||||
cwd: project.repoPath,
|
||||
worktreeSlug: "archive-shortcut-teardown",
|
||||
},
|
||||
});
|
||||
if (!worktree) throw new Error(error ?? "Could not seed the worktree");
|
||||
await gotoAppShell(page);
|
||||
|
||||
await test.step("start the first archive and wait for its teardown", async () => {
|
||||
await openWorkspace(page, worktree.id);
|
||||
await pressArchiveShortcut(page);
|
||||
await teardown.expectStarted();
|
||||
});
|
||||
|
||||
await test.step("archive the second workspace before the first archive finishes", async () => {
|
||||
const workspaceUrl = await openWorkspace(page, next.workspaceId);
|
||||
await pressArchiveShortcut(page);
|
||||
await expectArchived(page, next, workspaceUrl);
|
||||
});
|
||||
} finally {
|
||||
teardown.release();
|
||||
await project.cleanup();
|
||||
await next.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -503,34 +503,6 @@ test.describe("terminal history with a finger", () => {
|
||||
await expectMouseWheelScrollsHistory(page);
|
||||
});
|
||||
|
||||
test("finger scrolling leaves terminal input unfocused until a tap", async ({ page }) => {
|
||||
await openPhoneTerminalHistory(page);
|
||||
await blurTerminalInput(page);
|
||||
|
||||
await expectSingleFingerScroll(page, 24);
|
||||
await expect(input(page)).not.toBeFocused();
|
||||
await expectSingleFingerScroll(page, 1);
|
||||
await expect(input(page)).not.toBeFocused();
|
||||
|
||||
await tapTerminalScreen(page);
|
||||
await expect(input(page)).toBeFocused();
|
||||
});
|
||||
|
||||
test("finger scrolling keeps a floating keyboard's input focused", async ({ page }) => {
|
||||
await openPhoneTerminalHistory(page);
|
||||
await tapTerminalScreen(page);
|
||||
await expect(input(page)).toBeFocused();
|
||||
|
||||
// A floating keyboard leaves the visual viewport unchanged.
|
||||
await expectSingleFingerScroll(page, 24);
|
||||
await expect(input(page)).toBeFocused();
|
||||
await expect(input(page)).toHaveAttribute("virtualkeyboardpolicy", "manual");
|
||||
|
||||
// Android Back also leaves the input focused. A tap restores automatic keyboard opening.
|
||||
await tapTerminalScreen(page);
|
||||
await expect(input(page)).not.toHaveAttribute("virtualkeyboardpolicy");
|
||||
});
|
||||
|
||||
for (const mode of ["alternate", "mouse"] as const) {
|
||||
test(`preserves finger navigation in ${mode} input mode`, async ({ page }) => {
|
||||
await openPhoneInputCapture(page, mode);
|
||||
@@ -559,26 +531,6 @@ async function openPhoneTerminalHistory(page: Page) {
|
||||
});
|
||||
await openPhoneTerminal(page);
|
||||
await expect.poll(() => getTerminalBufferText(page)).toContain("HISTORY_150");
|
||||
await expect
|
||||
.poll(() => page.evaluate(() => window.__paseoTerminal!.buffer.active.baseY))
|
||||
.toBeGreaterThan(0);
|
||||
await page.evaluate(() => window.__paseoTerminal!.scrollToBottom());
|
||||
await expect.poll(() => viewport(page)).toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
function terminalScreen(page: Page) {
|
||||
return page.getByTestId("terminal-surface").filter({ visible: true }).locator(".xterm-screen");
|
||||
}
|
||||
|
||||
async function tapTerminalScreen(page: Page) {
|
||||
const box = await terminalScreen(page).boundingBox();
|
||||
expect(box).not.toBeNull();
|
||||
await page.touchscreen.tap(box!.x + box!.width / 2, box!.y + box!.height / 3);
|
||||
}
|
||||
|
||||
async function blurTerminalInput(page: Page) {
|
||||
await input(page).evaluate((element) => element.blur());
|
||||
await expect(input(page)).not.toBeFocused();
|
||||
}
|
||||
|
||||
async function openPhoneInputCapture(page: Page, mode: "alternate" | "mouse") {
|
||||
@@ -618,20 +570,6 @@ async function openPhoneTerminal(page: Page) {
|
||||
await page.getByTestId(`sidebar-workspace-row-${getServerId()}:${harness.workspaceId}`).click();
|
||||
await expect(page.getByRole("textbox", { name: "Terminal input" })).toBeVisible();
|
||||
await expect(page.getByTestId("terminal-surface").filter({ visible: true })).toBeVisible();
|
||||
// The terminal stays mounted while the sidebar's closing backdrop still intercepts input.
|
||||
await expect
|
||||
.poll(() =>
|
||||
page
|
||||
.getByTestId("terminal-surface")
|
||||
.filter({ visible: true })
|
||||
.evaluate((root) => {
|
||||
const box = root.querySelector(".xterm-screen")!.getBoundingClientRect();
|
||||
return root.contains(
|
||||
document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 3),
|
||||
);
|
||||
}),
|
||||
)
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function expectMouseWheelScrollsHistory(page: Page) {
|
||||
|
||||
@@ -2,14 +2,13 @@ import { tmpdir } from "node:os";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { UsageReport, UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { addConnectedHostAndReload } from "../support/helpers/hosts";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import { openSettingsSection } from "../support/helpers/settings";
|
||||
import { gate } from "../support/helpers/context-window";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
|
||||
import {
|
||||
@@ -46,7 +45,6 @@ import {
|
||||
refreshAllUsage,
|
||||
togglePin,
|
||||
usageItem,
|
||||
usageModal,
|
||||
} from "../support/helpers/usage-sidebar-item";
|
||||
|
||||
const emptyHome = path.join(tmpdir(), `paseo-usage-empty-${randomUUID()}`);
|
||||
@@ -235,8 +233,8 @@ test.describe("usage modal", () => {
|
||||
],
|
||||
});
|
||||
await gotoAppShell(page);
|
||||
// Three Weekly labels overflow the summary, so it falls back to compact shorthands.
|
||||
await expectPinnedUsage(page, ["31% wk", "20% wk", "12% wk"]);
|
||||
// Three windows leave no room for labels in the summary, so it reads percents.
|
||||
await expectPinnedUsage(page, ["31%", "20%", "12%"]);
|
||||
await openUsageFromItem(page);
|
||||
await expectUsageCardOrder(page, ["alpha:a", "beta:home", "beta:work"]);
|
||||
|
||||
@@ -867,106 +865,6 @@ test("open usage clocks advance without refreshing or reopening", async ({ page
|
||||
}
|
||||
});
|
||||
|
||||
test("Refresh all keeps quota visible and restores the forecast after a timeout", async ({
|
||||
page,
|
||||
}) => {
|
||||
const reading = new Date();
|
||||
const login = await installLoginUsage(usageReading(reading, 40));
|
||||
try {
|
||||
const transport = await installDaemonWebSocketGate(page);
|
||||
await openCompactUsageWithClock(page, reading);
|
||||
await expectQuota(page, "40% used", /runs out in /);
|
||||
|
||||
await timeOutUsageRefresh(page, transport);
|
||||
await expectQuota(page, "40% used", null);
|
||||
await expectUsageRefreshError(page).toBeVisible();
|
||||
|
||||
await login.setReport(usageReading(reading, 10));
|
||||
transport.releaseHeldClientRequest();
|
||||
await refreshAllUsage(page);
|
||||
await expectQuota(page, "10% used", "~50% left at reset");
|
||||
await expectUsageRefreshError(page).toBeHidden();
|
||||
} finally {
|
||||
await login.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a card refresh timeout is visible alongside a newer quota forecast", async ({ page }) => {
|
||||
const reading = new Date();
|
||||
const login = await installLoginUsage(usageReading(reading, 40));
|
||||
try {
|
||||
const transport = await installDaemonWebSocketGate(page);
|
||||
await openCompactUsageWithClock(page, reading);
|
||||
await expectQuota(page, "40% used", /runs out in /);
|
||||
|
||||
await delayCardRefreshResponse(page, transport);
|
||||
await login.setReport(usageReading(reading, 10));
|
||||
await refreshAllUsage(page);
|
||||
await expectQuota(page, "10% used", "~50% left at reset");
|
||||
|
||||
await advanceUsageClock(page, 61_000);
|
||||
await expectUsageRefreshError(page).toBeVisible();
|
||||
await expectQuota(page, "10% used", "~50% left at reset");
|
||||
} finally {
|
||||
await login.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
function expectUsageRefreshError(page: Page) {
|
||||
return expect(usageModal(page).getByText("Unable to refresh usage", { exact: true }));
|
||||
}
|
||||
|
||||
async function delayCardRefreshResponse(
|
||||
page: Page,
|
||||
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
|
||||
) {
|
||||
await expect(page.getByRole("button", { name: "Refresh all", exact: true })).toBeEnabled();
|
||||
transport.holdNextServerMessage("usage.list_reports.response");
|
||||
await refreshLoginUsage(page);
|
||||
await transport.waitForHeldServerMessage("usage.list_reports.response");
|
||||
}
|
||||
|
||||
function usageReading(observed: Date, usedPct: number): UsageReport {
|
||||
return {
|
||||
status: "available",
|
||||
observedAt: observed.toISOString(),
|
||||
windows: [
|
||||
{
|
||||
id: "session",
|
||||
label: "Session",
|
||||
usedPct,
|
||||
durationSeconds: 18_000,
|
||||
resetsAt: new Date(observed.getTime() + 4 * 3_600_000).toISOString(),
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
async function expectQuota(page: Page, amount: string, forecast: string | RegExp | null) {
|
||||
const usage = usageModal(page);
|
||||
await expect(usage.getByText(amount, { exact: true })).toBeVisible();
|
||||
await expect(usage.getByText(/^resets in /)).toBeVisible();
|
||||
if (forecast === null) {
|
||||
await expect(usage.getByText(/^runs out in /)).toBeHidden();
|
||||
return;
|
||||
}
|
||||
await expect(usage.getByText(forecast)).toBeVisible();
|
||||
}
|
||||
|
||||
async function timeOutUsageRefresh(
|
||||
page: Page,
|
||||
transport: Awaited<ReturnType<typeof installDaemonWebSocketGate>>,
|
||||
) {
|
||||
const refresh = page.getByRole("button", { name: "Refresh all", exact: true });
|
||||
await expect(refresh).toBeEnabled();
|
||||
transport.holdNextClientRequest("usage.list_reports.request");
|
||||
await refreshAllUsage(page);
|
||||
await transport.waitForHeldClientRequest();
|
||||
await expect(refresh).toBeDisabled();
|
||||
await advanceUsageClock(page, 61_000);
|
||||
await expect(refresh).toBeEnabled();
|
||||
}
|
||||
|
||||
async function openCompactUsageWithClock(page: Page, now: Date) {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.clock.install({ time: now });
|
||||
|
||||
@@ -40,7 +40,6 @@ import {
|
||||
usageModal,
|
||||
installTallUsageSource,
|
||||
} from "../support/helpers/usage-sidebar-item";
|
||||
import { seedDockedSidebarWidth } from "../support/helpers/sidebar-footer-overflow";
|
||||
import { seedSidebarFooterPreferences } from "../support/helpers/sidebar-nav-settings";
|
||||
import { waitForSettledPosition } from "../support/helpers/sheet-layout";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
@@ -578,97 +577,3 @@ test("visible usage summary requests reports on load", async ({ page }) => {
|
||||
await expectPinnedUsage(page, ["31% 5h", "54% wk", "7% 5h", "12% wk"]);
|
||||
expect(usage.listRequests()).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("sidebar usage falls back to period shorthands before dropping all labels", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const [claude, codex] = claudeAndCodexReports();
|
||||
const fetchedAt = new Date().toISOString();
|
||||
await installUsageReportsFixture(page, {
|
||||
lists: [
|
||||
() => [
|
||||
{
|
||||
...codex!,
|
||||
report: {
|
||||
status: "available",
|
||||
windows: [
|
||||
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 97 },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
...claude!,
|
||||
report: {
|
||||
status: "available",
|
||||
windows: [
|
||||
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 100 },
|
||||
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 14 },
|
||||
{
|
||||
id: "weekly_model_opus",
|
||||
label: "Weekly · Opus",
|
||||
shortLabel: "wk Opus",
|
||||
summary: true,
|
||||
usedPct: 22,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "antigravity:default",
|
||||
account: {},
|
||||
fetchedAt,
|
||||
sourceId: "antigravity",
|
||||
sourceLabel: "Antigravity",
|
||||
report: {
|
||||
status: "available",
|
||||
windows: [
|
||||
{
|
||||
id: "gemini-weekly",
|
||||
label: "Gemini Models · Weekly",
|
||||
shortLabel: "Gemini wk",
|
||||
summary: true,
|
||||
usedPct: 6,
|
||||
},
|
||||
{
|
||||
id: "gemini-5h",
|
||||
label: "Gemini Models · 5h",
|
||||
shortLabel: "Gemini 5h",
|
||||
summary: true,
|
||||
usedPct: 20,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
});
|
||||
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
|
||||
await seedDockedSidebarWidth(page, 432);
|
||||
await page.setViewportSize(WIDE);
|
||||
await gotoAppShell(page);
|
||||
|
||||
await expectPinnedUsage(page, ["6% wk", "20% 5h", "100% 5h", "14% wk", "22% wk", "97% wk"]);
|
||||
|
||||
const handle = page.getByTestId("left-sidebar-resize-handle");
|
||||
const dragSidebarTo = async (targetX: number) => {
|
||||
const box = (await handle.boundingBox())!;
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(targetX, box.y + box.height / 2, { steps: 10 });
|
||||
await page.mouse.up();
|
||||
};
|
||||
|
||||
await dragSidebarTo(600);
|
||||
await expectPinnedUsage(page, [
|
||||
"6% Gemini wk",
|
||||
"20% Gemini 5h",
|
||||
"100% 5h",
|
||||
"14% wk",
|
||||
"22% wk Opus",
|
||||
"97% wk",
|
||||
]);
|
||||
|
||||
await dragSidebarTo(300);
|
||||
await expectPinnedUsage(page, ["6%", "20%", "100%", "14%", "22%", "97%"]);
|
||||
});
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "../support/helpers/sidebar";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
import {
|
||||
pressArchiveShortcut,
|
||||
rowArchiveButton,
|
||||
undoButton,
|
||||
workspaceRow,
|
||||
@@ -211,18 +212,28 @@ async function relayDaemon(
|
||||
* Holds the app's next checkout status request for `directory` once armed, so a test can act
|
||||
* while the archive waits for the host's answer.
|
||||
*/
|
||||
async function holdCheckoutStatusRequest(page: Page, directory: string) {
|
||||
async function holdCheckoutStatusRequest(
|
||||
page: Page,
|
||||
worktree: { workspaceDirectory: string; workspaceId: string },
|
||||
) {
|
||||
let armed = false;
|
||||
let held: (() => void) | null = null;
|
||||
let archiveRequests = 0;
|
||||
await page.routeWebSocket(daemonWsRoutePattern(), (browser) => {
|
||||
const server = browser.connectToServer();
|
||||
browser.onMessage((message) => {
|
||||
const request = typeof message === "string" ? parseSessionEnvelope(message)?.message : null;
|
||||
if (
|
||||
request?.type === "archive_workspace_request" &&
|
||||
request.workspaceId === worktree.workspaceId
|
||||
) {
|
||||
archiveRequests += 1;
|
||||
}
|
||||
if (
|
||||
armed &&
|
||||
!held &&
|
||||
request?.type === "checkout_status_request" &&
|
||||
request.cwd === directory
|
||||
request.cwd === worktree.workspaceDirectory
|
||||
) {
|
||||
held = () => server.send(message);
|
||||
return;
|
||||
@@ -236,6 +247,7 @@ async function holdCheckoutStatusRequest(page: Page, directory: string) {
|
||||
armed = true;
|
||||
},
|
||||
waitForHeld: () => expect.poll(() => held !== null).toBe(true),
|
||||
archiveRequests: () => archiveRequests,
|
||||
release: () => {
|
||||
if (!held) throw new Error("No checkout status request is held");
|
||||
held();
|
||||
@@ -388,7 +400,7 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
): Promise<string> {
|
||||
const serverId = getServerId();
|
||||
const worktree = await createWorktree(slug);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree.workspaceDirectory);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(serverId, worktree.workspaceId));
|
||||
@@ -432,6 +444,58 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
await expectAppRoute(page, openedRoute);
|
||||
});
|
||||
|
||||
async function openWorktreeWithCheckoutHeld(page: Page, slug: string) {
|
||||
const worktree = await createWorktree(slug);
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
// Opening the workspace can start a checkout read that the archive reuses.
|
||||
statusRequest.arm();
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await workspaceRow(page, worktree.workspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), worktree.workspaceId));
|
||||
return { worktree, statusRequest };
|
||||
}
|
||||
|
||||
test("the archive shortcut works in another workspace while a checkout check is pending", async ({
|
||||
page,
|
||||
}) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-switch-shortcut",
|
||||
);
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
const otherWorkspaceId = worktree.project.workspaceId;
|
||||
await workspaceRow(page, otherWorkspaceId).click();
|
||||
await expectAppRoute(page, buildHostWorkspaceRoute(getServerId(), otherWorkspaceId));
|
||||
|
||||
await pressArchiveShortcut(page);
|
||||
await expect.poll(() => hostListsWorkspace(otherWorkspaceId)).toBe(false);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
});
|
||||
|
||||
test("the row button and shortcut send one archive for the same worktree", async ({ page }) => {
|
||||
const { worktree, statusRequest } = await openWorktreeWithCheckoutHeld(
|
||||
page,
|
||||
"archive-risk-repeat-shortcut",
|
||||
);
|
||||
|
||||
await clickRowArchiveButton(page, worktree.workspaceId);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
await pressArchiveShortcut(page);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
|
||||
await expect.poll(() => hostListsWorkspace(worktree.workspaceId)).toBe(false);
|
||||
expect(statusRequest.archiveRequests()).toBe(1);
|
||||
});
|
||||
|
||||
test("archiving the open worktree from its git actions leaves it for a new workspace", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -22,7 +22,7 @@ type AgentSkillsClient = Pick<
|
||||
"close" | "connect" | "getAgentSkillsStatus" | "saveAgentSkillsSelection"
|
||||
>;
|
||||
|
||||
export type SkillTargetName = "agents" | "claude" | "antigravity";
|
||||
export type SkillTargetName = "agents" | "claude";
|
||||
|
||||
export interface AgentSkillsSandbox {
|
||||
available: string[];
|
||||
@@ -64,7 +64,6 @@ export async function startAgentSkillsSandbox(): Promise<AgentSkillsSandbox> {
|
||||
const targets = {
|
||||
agents: path.join(home, ".agents", "skills"),
|
||||
claude: path.join(home, ".claude", "skills"),
|
||||
antigravity: path.join(home, ".gemini", "config", "skills"),
|
||||
};
|
||||
const codexSkillsDir = path.join(home, ".codex", "skills");
|
||||
|
||||
|
||||
@@ -51,18 +51,3 @@ export async function expectColumnAtLeftGutter(page: Page, column: Locator): Pro
|
||||
})
|
||||
.toBeLessThanOrEqual(24);
|
||||
}
|
||||
|
||||
/** Checks that two column surfaces sit on the same left and right vertical rails. */
|
||||
export async function expectSharedHorizontalRail(first: Locator, second: Locator): Promise<void> {
|
||||
await expect(first).toBeVisible({ timeout: 30_000 });
|
||||
await expect(second).toBeVisible({ timeout: 30_000 });
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const [a, b] = await Promise.all([first.boundingBox(), second.boundingBox()]);
|
||||
if (!a || !b) return Infinity;
|
||||
const leftDelta = Math.abs(a.x - b.x);
|
||||
const rightDelta = Math.abs(a.x + a.width - (b.x + b.width));
|
||||
return Math.max(leftDelta, rightDelta);
|
||||
})
|
||||
.toBeLessThanOrEqual(1);
|
||||
}
|
||||
|
||||
@@ -185,15 +185,13 @@ function onLogin(report: UsageReportEntry, login: string): UsageReportEntry {
|
||||
}
|
||||
|
||||
export function expiredLogin(report: UsageReportEntry): UsageReportEntry {
|
||||
const fetchedAt = Date.now();
|
||||
return {
|
||||
...report,
|
||||
fetchedAt: new Date(fetchedAt).toISOString(),
|
||||
report: {
|
||||
status: "unavailable",
|
||||
problem: {
|
||||
kind: "expired",
|
||||
expiresAt: new Date(fetchedAt - 2 * 60 * 60_000).toISOString(),
|
||||
expiresAt: new Date(Date.now() - 2 * 60 * 60_000).toISOString(),
|
||||
refreshedBy: "claude",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -196,7 +196,7 @@ export interface SetupHost {
|
||||
/**
|
||||
* An isolated host whose only agent history is the Claude sessions given here, so suggestions
|
||||
* never depend on the machine running the test. Its HOME is a scratch folder, so the skills setup
|
||||
* installs never land in the real ~/.agents, ~/.claude, ~/.codex, or ~/.gemini/config. `withBrokenProvider` adds a
|
||||
* installs never land in the real ~/.agents, ~/.claude or ~/.codex. `withBrokenProvider` adds a
|
||||
* provider that cannot start.
|
||||
*/
|
||||
export async function startSetupHost(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { openChangesPanel } from "./branch-switcher";
|
||||
|
||||
export async function restoreArchivedWorkspace(page: Page): Promise<void> {
|
||||
@@ -32,11 +32,7 @@ export async function expectCommittedFile(page: Page, filename: string): Promise
|
||||
}
|
||||
|
||||
export async function expectCommittedFileAfterReload(page: Page, filename: string): Promise<void> {
|
||||
await test.step("See the committed file immediately after Restore", async () => {
|
||||
await expectCommittedFile(page, filename);
|
||||
});
|
||||
await test.step("Reload and see the same committed file", async () => {
|
||||
await page.reload();
|
||||
await expectCommittedFile(page, filename);
|
||||
});
|
||||
await expectCommittedFile(page, filename);
|
||||
await page.reload();
|
||||
await expectCommittedFile(page, filename);
|
||||
}
|
||||
|
||||
@@ -66,7 +66,6 @@
|
||||
[role="slider"],
|
||||
[role="menuitem"],
|
||||
[tabindex],
|
||||
[data-window-no-drag],
|
||||
[contenteditable="true"] {
|
||||
-webkit-app-region: no-drag !important;
|
||||
}
|
||||
|
||||
@@ -66,23 +66,4 @@ describe("fetchAgentCommands", () => {
|
||||
|
||||
expect(client.calls).toEqual([{ agentId: "agent-1", draftConfig: undefined }]);
|
||||
});
|
||||
|
||||
it("deduplicates duplicate command names from the daemon, keeping the first entry", async () => {
|
||||
const client = createClient(
|
||||
commandsPayload([
|
||||
{ name: "goal", description: "Run until goal is finished", argumentHint: "" },
|
||||
{ name: "plan", description: "Plan carefully before executing a task.", argumentHint: "" },
|
||||
{ name: "plan", description: "Local plan skill description", argumentHint: "" },
|
||||
{ name: "review", description: "Review changes", argumentHint: "" },
|
||||
]),
|
||||
);
|
||||
|
||||
const commands = await fetchAgentCommands({ client, agentId: "agent-1" });
|
||||
|
||||
expect(commands).toEqual([
|
||||
{ name: "goal", description: "Run until goal is finished", argumentHint: "" },
|
||||
{ name: "plan", description: "Plan carefully before executing a task.", argumentHint: "" },
|
||||
{ name: "review", description: "Review changes", argumentHint: "" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -37,18 +37,6 @@ export interface AgentCommandsClient {
|
||||
listCommands(options: ListAgentCommandsOptions): ReturnType<DaemonClient["listCommands"]>;
|
||||
}
|
||||
|
||||
// COMPAT(dedupeListCommands): added in v0.17.0, remove after 2027-05-20 once daemon floor >= v0.17.0.
|
||||
function dedupeSlashCommands(commands: readonly AgentSlashCommand[]): AgentSlashCommand[] {
|
||||
const seen = new Set<string>();
|
||||
const unique: AgentSlashCommand[] = [];
|
||||
for (const command of commands) {
|
||||
if (seen.has(command.name)) continue;
|
||||
seen.add(command.name);
|
||||
unique.push(command);
|
||||
}
|
||||
return unique;
|
||||
}
|
||||
|
||||
export async function fetchAgentCommands(input: {
|
||||
client: AgentCommandsClient;
|
||||
agentId: string;
|
||||
@@ -59,7 +47,7 @@ export async function fetchAgentCommands(input: {
|
||||
draftConfig: input.draftConfig,
|
||||
});
|
||||
if (response.error) throw new Error(response.error);
|
||||
return dedupeSlashCommands(response.commands as AgentSlashCommand[]);
|
||||
return response.commands as AgentSlashCommand[];
|
||||
}
|
||||
|
||||
interface UseAgentCommandsQueryOptions {
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { SPACING } from "@/styles/theme";
|
||||
|
||||
// Outline rail geometry shared between the rail overlay and the chat pane's column rail.
|
||||
export const CHAT_OUTLINE_RAIL_WIDTH = 36;
|
||||
export const CHAT_OUTLINE_RAIL_LEFT = SPACING[2];
|
||||
export const CHAT_OUTLINE_MIN_PANEL_WIDTH = 918;
|
||||
export const CHAT_OUTLINE_GUTTER_INSET = CHAT_OUTLINE_RAIL_LEFT + CHAT_OUTLINE_RAIL_WIDTH;
|
||||
@@ -11,3 +11,7 @@ export interface ChatOutlineRailProps {
|
||||
export function ChatOutlineRail(_props: ChatOutlineRailProps): null {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useChatOutlineRailLayout(_enabled: boolean) {
|
||||
return { onLayout: undefined, inset: 0 };
|
||||
}
|
||||
|
||||
@@ -2,17 +2,19 @@ import { memo, useCallback, useEffect, useMemo, useState, useSyncExternalStore }
|
||||
import { Pressable, Text, View, type PointerEvent as RNPointerEvent } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { useReducedMotion } from "react-native-reanimated";
|
||||
import { useContainerWidthBelow } from "@/hooks/use-container-width";
|
||||
import { SPACING } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
import { CHAT_OUTLINE_RAIL_LEFT, CHAT_OUTLINE_RAIL_WIDTH } from "./geometry";
|
||||
import { createChatOutlineHoverIntent } from "./hover-intent";
|
||||
import { promptTickMagnification } from "./model";
|
||||
import type { ChatOutlineRailProps } from "./rail";
|
||||
|
||||
// Hover tracking lives on the rail and the slots, never on the Pressable inside them:
|
||||
// magnifying a slot must not move the box the pointer is resting on. See docs/hover.md.
|
||||
const RAIL_WIDTH = CHAT_OUTLINE_RAIL_WIDTH;
|
||||
const RAIL_LEFT = CHAT_OUTLINE_RAIL_LEFT;
|
||||
const RAIL_WIDTH = 36;
|
||||
const RAIL_LEFT = SPACING[2];
|
||||
const SLOT_HEIGHT = 8;
|
||||
const MIN_PANEL_WIDTH = 918;
|
||||
const RESTING_PILL_HEIGHT = 2;
|
||||
const MAGNIFIED_PILL_HEIGHT = 4;
|
||||
const RESTING_PILL_WIDTH = 10;
|
||||
@@ -22,6 +24,11 @@ const PREVIEW_WIDTH = 260;
|
||||
const PREVIEW_HEIGHT = 48;
|
||||
const PREVIEW_GAP = 4;
|
||||
|
||||
export function useChatOutlineRailLayout(enabled: boolean) {
|
||||
const { onLayout, isBelow } = useContainerWidthBelow(MIN_PANEL_WIDTH);
|
||||
return { onLayout, inset: enabled && !isBelow ? RAIL_LEFT + RAIL_WIDTH : 0 };
|
||||
}
|
||||
|
||||
export const ChatOutlineRail = memo(function ChatOutlineRail({
|
||||
prompts,
|
||||
activePrompt,
|
||||
|
||||
@@ -40,7 +40,6 @@ import {
|
||||
type HistoryStartSettleScheduler,
|
||||
} from "./history-start-settle-scheduler";
|
||||
import { useChatFindSelectedMessageId } from "@/agent-stream/chat-find";
|
||||
import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "@/chat-rail/gutters";
|
||||
import { useScrollToMessage } from "./use-scroll-to-message.web";
|
||||
|
||||
interface CreateWebStreamStrategyInput {
|
||||
@@ -1229,20 +1228,21 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
]);
|
||||
|
||||
const contentContainerStyle = useMemo((): CSSProperties => {
|
||||
const gutter = isMobileBreakpoint ? 8 : CHAT_COLUMN_BASE_GUTTER;
|
||||
const { paddingLeft, paddingRight } = resolveChatColumnGutters({
|
||||
gutter,
|
||||
outlineInset,
|
||||
contentMaxWidth,
|
||||
});
|
||||
const gutter = isMobileBreakpoint ? 8 : 16;
|
||||
const leftGutter = gutter + outlineInset;
|
||||
// Balance the outline gutter using only the space the capped column has left over.
|
||||
const rightGutter =
|
||||
outlineInset > 0 && contentMaxWidth !== undefined
|
||||
? `clamp(${gutter}px, calc(100% - ${leftGutter + contentMaxWidth}px), ${leftGutter}px)`
|
||||
: gutter;
|
||||
return {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
minHeight: "100%",
|
||||
paddingTop: CONTENT_PADDING_TOP_PX,
|
||||
paddingBottom: 16,
|
||||
paddingLeft,
|
||||
paddingRight,
|
||||
paddingLeft: leftGutter,
|
||||
paddingRight: rightGutter,
|
||||
boxSizing: "border-box",
|
||||
};
|
||||
}, [contentMaxWidth, isMobileBreakpoint, outlineInset]);
|
||||
|
||||
@@ -80,9 +80,8 @@ import { resolveStreamRenderStrategy } from "./strategy-resolver";
|
||||
import { type StreamSegmentRenderers, type StreamViewportHandle } from "./strategy";
|
||||
import { renderStreamRow, type RenderStreamItem } from "./stream-row";
|
||||
import { type NearBottom, useIsNearBottom, useNearBottom } from "./near-bottom";
|
||||
import { ChatOutlineRail } from "@/agent-stream/chat-outline/rail";
|
||||
import { ChatOutlineRail, useChatOutlineRailLayout } from "@/agent-stream/chat-outline/rail";
|
||||
import { useChatOutline } from "@/agent-stream/chat-outline/use-chat-outline";
|
||||
import { CHAT_COLUMN_RAIL_DATASET, useChatOutlineRail } from "@/chat-rail";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { planTimelineTailFetch } from "@/timeline/timeline-sync-plan";
|
||||
import {
|
||||
@@ -323,7 +322,7 @@ function ScrollToBottomButton({
|
||||
);
|
||||
if (isNearBottom && !isTimelineDetached) return null;
|
||||
return (
|
||||
<View style={containerStyle} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
|
||||
<View style={containerStyle} pointerEvents="box-none">
|
||||
<Animated.View entering={scrollIndicatorFadeIn} exiting={scrollIndicatorFadeOut}>
|
||||
<Pressable
|
||||
style={stylesheet.scrollToBottomButton}
|
||||
@@ -366,6 +365,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
const { t } = useTranslation();
|
||||
const autoExpandReasoning = useSettings((settings) => settings.autoExpandReasoning);
|
||||
const chatDisplay = useSettings((settings) => settings.chatDisplay);
|
||||
const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled);
|
||||
const contentMaxWidth = useSettings(resolveContentMaxWidth);
|
||||
const viewportRef = useRef<StreamViewportHandle | null>(null);
|
||||
const pendingClientMessageIds = useMemo(
|
||||
@@ -404,6 +404,10 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
(state) =>
|
||||
state.sessions[resolvedServerId]?.serverInfo?.features?.agentForkContextCursor === true,
|
||||
);
|
||||
const supportsChatOutline = useSessionStore(
|
||||
(state) =>
|
||||
state.sessions[resolvedServerId]?.serverInfo?.features?.agentTimelinePromptIndex === true,
|
||||
);
|
||||
const timelineEpoch = useSessionStore(
|
||||
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
|
||||
);
|
||||
@@ -613,21 +617,22 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
mountedHistoryMessageIds.has(messageId) || liveHeadMessageIds.has(messageId),
|
||||
};
|
||||
}, [baseRenderModel.segments.liveHead, mountedHistoryMessageIds]);
|
||||
const outlineRail = useChatOutlineRail();
|
||||
const outlineInset = outlineRail.inset;
|
||||
const outlineEnabled = supportsChatOutline && chatOutlineEnabled;
|
||||
const chatOutline = useChatOutline({
|
||||
agentId,
|
||||
serverId: resolvedServerId,
|
||||
timelineEpoch,
|
||||
tail: effectiveStreamItems,
|
||||
head: effectiveStreamHead,
|
||||
enabled: outlineRail.enabled,
|
||||
enabled: outlineEnabled,
|
||||
viewportRef,
|
||||
onJumpError: handleTimelineHistoryLoadError,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage: revealLoadedHistory,
|
||||
});
|
||||
|
||||
const outlineLayout = useChatOutlineRailLayout(outlineEnabled);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
@@ -1171,7 +1176,10 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
visibleMessageIds={mountedMessageIds}
|
||||
>
|
||||
<ToolCallSheetProvider>
|
||||
<AssistantSelectionCopySurface style={stylesheet.container}>
|
||||
<AssistantSelectionCopySurface
|
||||
style={stylesheet.container}
|
||||
onLayout={outlineLayout.onLayout}
|
||||
>
|
||||
<MessageOuterSpacingProvider disableOuterSpacing>
|
||||
<ToolCallExpansionContext.Provider value={toolCallExpansion}>
|
||||
<UserMessageExpansionContext.Provider value={userMessageExpansion}>
|
||||
@@ -1200,12 +1208,12 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
baseListContentContainerStyle: stylesheet.listContentContainer,
|
||||
forwardListContentContainerStyle: stylesheet.forwardListContentContainer,
|
||||
contentMaxWidth,
|
||||
outlineInset,
|
||||
outlineInset: outlineLayout.inset,
|
||||
})}
|
||||
</UserMessageExpansionContext.Provider>
|
||||
</ToolCallExpansionContext.Provider>
|
||||
</MessageOuterSpacingProvider>
|
||||
{outlineInset > 0 && chatOutline.prompts.length >= 2 ? (
|
||||
{outlineLayout.inset > 0 && chatOutline.prompts.length >= 2 ? (
|
||||
<ChatOutlineRail
|
||||
prompts={chatOutline.prompts}
|
||||
activePrompt={chatOutline.activePrompt}
|
||||
|
||||
@@ -54,6 +54,7 @@ import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggl
|
||||
import { DesktopWindowControls } from "@/components/desktop/window-controls";
|
||||
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
|
||||
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
|
||||
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
|
||||
import { WorkspaceRenameHost } from "@/components/workspace-rename-host";
|
||||
import { WorkspaceArchiveUndoShortcutHost } from "@/workspace/archive-undo";
|
||||
import { WorkspaceExplorerOpenGesture } from "@/mobile-panels/explorer-open-gesture";
|
||||
@@ -568,6 +569,7 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<CommandCenterWorkspaceActions />
|
||||
<PluginCommandCenterActions />
|
||||
<WorkspacePinShortcutHandler />
|
||||
<WorkspaceArchiveShortcutHandler />
|
||||
<WorkspaceRenameHost />
|
||||
<WorkspaceArchiveUndoShortcutHost />
|
||||
<CommandCenter />
|
||||
|
||||
@@ -1,14 +1,20 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native";
|
||||
|
||||
interface AssistantSelectionCopySurfaceProps {
|
||||
children: ReactNode;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
onLayout?: (event: LayoutChangeEvent) => void;
|
||||
}
|
||||
|
||||
export function AssistantSelectionCopySurface({
|
||||
children,
|
||||
style,
|
||||
onLayout,
|
||||
}: AssistantSelectionCopySurfaceProps) {
|
||||
return <View style={style}>{children}</View>;
|
||||
return (
|
||||
<View style={style} onLayout={onLayout}>
|
||||
{children}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { useCallback, type ClipboardEvent, type CSSProperties, type ReactNode } from "react";
|
||||
import { View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { createAssistantSelectionClipboardContent } from "./content.web";
|
||||
|
||||
interface AssistantSelectionCopySurfaceProps {
|
||||
children: ReactNode;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
onLayout?: (event: LayoutChangeEvent) => void;
|
||||
}
|
||||
|
||||
const DISPLAY_CONTENTS: CSSProperties = { display: "contents" };
|
||||
@@ -12,6 +13,7 @@ const DISPLAY_CONTENTS: CSSProperties = { display: "contents" };
|
||||
export function AssistantSelectionCopySurface({
|
||||
children,
|
||||
style,
|
||||
onLayout,
|
||||
}: AssistantSelectionCopySurfaceProps) {
|
||||
const handleCopy = useCallback((event: ClipboardEvent<HTMLDivElement>) => {
|
||||
const content = createAssistantSelectionClipboardContent(window.getSelection());
|
||||
@@ -26,7 +28,9 @@ export function AssistantSelectionCopySurface({
|
||||
|
||||
return (
|
||||
<div onCopy={handleCopy} style={DISPLAY_CONTENTS}>
|
||||
<View style={style}>{children}</View>
|
||||
<View style={style} onLayout={onLayout}>
|
||||
{children}
|
||||
</View>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,77 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { CHAT_OUTLINE_GUTTER_INSET } from "@/agent-stream/chat-outline/geometry";
|
||||
import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "./gutters";
|
||||
import {
|
||||
CHAT_COLUMN_RAIL_DATASET as NATIVE_CHAT_COLUMN_RAIL_DATASET,
|
||||
ChatColumnRailSurface as NativeChatColumnRailSurface,
|
||||
useChatOutlineRail as useNativeChatOutlineRail,
|
||||
} from "./index.native";
|
||||
import { CHAT_COLUMN_RAIL_DATASET as WEB_CHAT_COLUMN_RAIL_DATASET } from "./index.web";
|
||||
|
||||
describe("resolveChatColumnGutters", () => {
|
||||
it("uses symmetric base gutters when no outline inset is reserved", () => {
|
||||
expect(
|
||||
resolveChatColumnGutters({
|
||||
gutter: CHAT_COLUMN_BASE_GUTTER,
|
||||
outlineInset: 0,
|
||||
contentMaxWidth: 820,
|
||||
}),
|
||||
).toEqual({ paddingLeft: 16, paddingRight: 16 });
|
||||
|
||||
expect(
|
||||
resolveChatColumnGutters({
|
||||
gutter: CHAT_COLUMN_BASE_GUTTER,
|
||||
outlineInset: 0,
|
||||
contentMaxWidth: undefined,
|
||||
}),
|
||||
).toEqual({ paddingLeft: 16, paddingRight: 16 });
|
||||
});
|
||||
|
||||
it("reserves only the left outline gutter when content width is Full", () => {
|
||||
expect(
|
||||
resolveChatColumnGutters({
|
||||
gutter: CHAT_COLUMN_BASE_GUTTER,
|
||||
outlineInset: CHAT_OUTLINE_GUTTER_INSET,
|
||||
contentMaxWidth: undefined,
|
||||
}),
|
||||
).toEqual({ paddingLeft: 60, paddingRight: 16 });
|
||||
});
|
||||
|
||||
it("balances capped columns with a clamped right gutter from the remaining width", () => {
|
||||
expect(
|
||||
resolveChatColumnGutters({
|
||||
gutter: CHAT_COLUMN_BASE_GUTTER,
|
||||
outlineInset: CHAT_OUTLINE_GUTTER_INSET,
|
||||
contentMaxWidth: 820,
|
||||
}),
|
||||
).toEqual({
|
||||
paddingLeft: 60,
|
||||
paddingRight: "clamp(16px, calc(100% - 880px), 60px)",
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveChatColumnGutters({
|
||||
gutter: CHAT_COLUMN_BASE_GUTTER,
|
||||
outlineInset: CHAT_OUTLINE_GUTTER_INSET,
|
||||
contentMaxWidth: 1200,
|
||||
}),
|
||||
).toEqual({
|
||||
paddingLeft: 60,
|
||||
paddingRight: "clamp(16px, calc(100% - 1260px), 60px)",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("native and web chat-rail boundaries", () => {
|
||||
it("keeps native as a zero-overhead pass-through with no dataset or outline inset", () => {
|
||||
const sentinel = "child";
|
||||
expect(NATIVE_CHAT_COLUMN_RAIL_DATASET).toBeUndefined();
|
||||
expect(useNativeChatOutlineRail()).toEqual({ enabled: false, inset: 0 });
|
||||
expect(NativeChatColumnRailSurface({ serverId: "srv-1", children: sentinel })).toBe(sentinel);
|
||||
});
|
||||
|
||||
it("tags web rail lanes with a frozen dataset reference", () => {
|
||||
expect(WEB_CHAT_COLUMN_RAIL_DATASET).toEqual({ chatRailLane: "true" });
|
||||
expect(Object.isFrozen(WEB_CHAT_COLUMN_RAIL_DATASET)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,30 +0,0 @@
|
||||
import { SPACING } from "@/styles/theme";
|
||||
|
||||
export const CHAT_COLUMN_BASE_GUTTER = SPACING[4];
|
||||
|
||||
export interface ChatColumnGutters {
|
||||
paddingLeft: number;
|
||||
paddingRight: number | string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Horizontal padding for a chat column on web.
|
||||
*
|
||||
* When the chat outline reserves `outlineInset` on the left, a capped column matches
|
||||
* that inset on the right using only the horizontal slack left over after fitting
|
||||
* `contentMaxWidth`. Default and Wide stay centered while the pane has room, shift
|
||||
* smoothly away from the outline as the pane narrows, and fall back to the base gutter
|
||||
* on the right when uncapped (`Full`) or tight.
|
||||
*/
|
||||
export function resolveChatColumnGutters(input: {
|
||||
gutter: number;
|
||||
outlineInset: number;
|
||||
contentMaxWidth: number | undefined;
|
||||
}): ChatColumnGutters {
|
||||
const paddingLeft = input.gutter + input.outlineInset;
|
||||
const paddingRight =
|
||||
input.outlineInset > 0 && input.contentMaxWidth !== undefined
|
||||
? `clamp(${input.gutter}px, calc(100% - ${paddingLeft + input.contentMaxWidth}px), ${paddingLeft}px)`
|
||||
: input.gutter;
|
||||
return { paddingLeft, paddingRight };
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
export interface ChatColumnRailSurfaceProps {
|
||||
serverId: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export interface ChatOutlineRailState {
|
||||
/** Whether the chat outline feature is enabled for this pane (independent of pane width). */
|
||||
readonly enabled: boolean;
|
||||
/** Left gutter inset currently reserved for the outline rail (`0` or `44` on web). */
|
||||
readonly inset: number;
|
||||
}
|
||||
|
||||
const DISABLED_CHAT_OUTLINE_RAIL: ChatOutlineRailState = Object.freeze({
|
||||
enabled: false,
|
||||
inset: 0,
|
||||
});
|
||||
|
||||
/**
|
||||
* Marker for chat surfaces (composer, track bar, callouts) that share the pane's
|
||||
* horizontal column rail. On web, an active `ChatColumnRailSurface` applies the
|
||||
* pane's outline-aware gutters via CSS custom properties without re-rendering
|
||||
* children. Native never reserves an outline gutter, so this is undefined.
|
||||
*/
|
||||
export const CHAT_COLUMN_RAIL_DATASET: Record<string, string> | undefined = undefined;
|
||||
|
||||
/**
|
||||
* Native pass-through: the chat outline is a wide-layout web affordance, so native
|
||||
* renders no wrapper view, registers no subscriptions, and reserves no outline inset.
|
||||
*/
|
||||
export function ChatColumnRailSurface({ children }: ChatColumnRailSurfaceProps) {
|
||||
return children;
|
||||
}
|
||||
|
||||
/** Chat outline state for this pane (always disabled with 0 inset on native). */
|
||||
export function useChatOutlineRail(): ChatOutlineRailState {
|
||||
return DISABLED_CHAT_OUTLINE_RAIL;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
export {
|
||||
CHAT_COLUMN_RAIL_DATASET,
|
||||
ChatColumnRailSurface,
|
||||
useChatOutlineRail,
|
||||
type ChatColumnRailSurfaceProps,
|
||||
type ChatOutlineRailState,
|
||||
} from "./index.native";
|
||||
@@ -1,143 +0,0 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type CSSProperties,
|
||||
} from "react";
|
||||
import {
|
||||
CHAT_OUTLINE_GUTTER_INSET,
|
||||
CHAT_OUTLINE_MIN_PANEL_WIDTH,
|
||||
} from "@/agent-stream/chat-outline/geometry";
|
||||
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { CHAT_COLUMN_BASE_GUTTER, resolveChatColumnGutters } from "./gutters";
|
||||
import type { ChatColumnRailSurfaceProps, ChatOutlineRailState } from "./index";
|
||||
|
||||
export type { ChatColumnRailSurfaceProps, ChatOutlineRailState };
|
||||
|
||||
const STYLE_ID = "paseo-chat-column-rail";
|
||||
// React Native Web turns `dataSet={{ chatRailLane: "true" }}` into `data-chat-rail-lane="true"`.
|
||||
// When the enclosing pane reserves an outline gutter, every tagged rail consumer receives
|
||||
// the same horizontal gutters in the browser's layout pass without re-rendering React subtrees
|
||||
// or growing Unistyles' CSS registry.
|
||||
const RAIL_RULE =
|
||||
'[data-chat-rail-active="true"] [data-chat-rail-lane="true"]{padding-left:var(--paseo-chat-rail-left)!important;padding-right:var(--paseo-chat-rail-right)!important;}';
|
||||
|
||||
const BASE_SURFACE_STYLE: CSSProperties = {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
minHeight: 0,
|
||||
};
|
||||
|
||||
const DISABLED_CHAT_OUTLINE_RAIL: ChatOutlineRailState = Object.freeze({
|
||||
enabled: false,
|
||||
inset: 0,
|
||||
});
|
||||
|
||||
const ChatOutlineRailContext = createContext<ChatOutlineRailState>(DISABLED_CHAT_OUTLINE_RAIL);
|
||||
|
||||
export const CHAT_COLUMN_RAIL_DATASET: Record<string, string> | undefined = Object.freeze({
|
||||
chatRailLane: "true",
|
||||
});
|
||||
|
||||
function ensureChatColumnRailStyle(): void {
|
||||
if (typeof document === "undefined") return;
|
||||
if (document.getElementById(STYLE_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = STYLE_ID;
|
||||
style.textContent = RAIL_RULE;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function cssLength(value: number | string): string {
|
||||
return typeof value === "number" ? `${value}px` : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Pane-level owner of the chat column rail on web.
|
||||
*
|
||||
* Measures the pane width once against `CHAT_OUTLINE_MIN_PANEL_WIDTH` (ignoring 0px
|
||||
* measurements from hidden retained tabs) and publishes the resolved horizontal gutters
|
||||
* via CSS custom properties to the composer, track bar, and callouts. Only the outline
|
||||
* enabled flag and reserved inset (`0` or `44`) enter React context for `AgentStreamView`.
|
||||
*/
|
||||
export function ChatColumnRailSurface({ serverId, children }: ChatColumnRailSurfaceProps) {
|
||||
const surfaceRef = useRef<HTMLDivElement | null>(null);
|
||||
const [isBelow, setIsBelow] = useState(true);
|
||||
const chatOutlineEnabled = useSettings((settings) => settings.chatOutlineEnabled);
|
||||
const contentMaxWidth = useSettings(resolveContentMaxWidth);
|
||||
const supportsChatOutline = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.agentTimelinePromptIndex === true,
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const node = surfaceRef.current;
|
||||
if (!node) return;
|
||||
const update = (width: number) => {
|
||||
// Retained inactive tabs sit under `display: none` and report 0; ignore them.
|
||||
if (width <= 0) return;
|
||||
const next = width < CHAT_OUTLINE_MIN_PANEL_WIDTH;
|
||||
setIsBelow((current) => (current === next ? current : next));
|
||||
};
|
||||
update(node.getBoundingClientRect().width);
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver((entries) => {
|
||||
const width =
|
||||
entries[entries.length - 1]?.contentRect.width ?? node.getBoundingClientRect().width;
|
||||
update(width);
|
||||
});
|
||||
observer.observe(node);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
const enabled = supportsChatOutline && chatOutlineEnabled;
|
||||
const inset = enabled && !isBelow ? CHAT_OUTLINE_GUTTER_INSET : 0;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (inset > 0) {
|
||||
ensureChatColumnRailStyle();
|
||||
}
|
||||
}, [inset]);
|
||||
|
||||
const outlineRail = useMemo<ChatOutlineRailState>(
|
||||
() => (enabled ? { enabled, inset } : DISABLED_CHAT_OUTLINE_RAIL),
|
||||
[enabled, inset],
|
||||
);
|
||||
|
||||
const surfaceStyle = useMemo((): CSSProperties => {
|
||||
if (inset === 0) {
|
||||
return BASE_SURFACE_STYLE;
|
||||
}
|
||||
const gutters = resolveChatColumnGutters({
|
||||
gutter: CHAT_COLUMN_BASE_GUTTER,
|
||||
outlineInset: inset,
|
||||
contentMaxWidth,
|
||||
});
|
||||
return {
|
||||
...BASE_SURFACE_STYLE,
|
||||
"--paseo-chat-rail-left": cssLength(gutters.paddingLeft),
|
||||
"--paseo-chat-rail-right": cssLength(gutters.paddingRight),
|
||||
} as CSSProperties;
|
||||
}, [contentMaxWidth, inset]);
|
||||
|
||||
return (
|
||||
<ChatOutlineRailContext.Provider value={outlineRail}>
|
||||
<div
|
||||
ref={surfaceRef}
|
||||
style={surfaceStyle}
|
||||
data-chat-rail-active={inset > 0 ? "true" : undefined}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</ChatOutlineRailContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useChatOutlineRail(): ChatOutlineRailState {
|
||||
return useContext(ChatOutlineRailContext);
|
||||
}
|
||||
@@ -2,7 +2,6 @@ import { useCallback, useState } from "react";
|
||||
import { View, Text } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
|
||||
import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { KeyboardTranslateView } from "@/keyboard/shift";
|
||||
@@ -36,7 +35,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
<View style={styles.inputAreaContainer} dataSet={CHAT_COLUMN_RAIL_DATASET}>
|
||||
<View style={styles.inputAreaContainer}>
|
||||
<View style={styles.inputAreaContent}>
|
||||
<View style={styles.calloutStack}>
|
||||
<View style={styles.callout}>
|
||||
|
||||
@@ -24,9 +24,6 @@ import { isNative } from "@/constants/platform";
|
||||
*/
|
||||
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
|
||||
|
||||
/** Reserves a clickable area for a control mounted outside the titlebar rail. */
|
||||
export const WINDOW_NO_DRAG_DATASET = { "window-no-drag": "" };
|
||||
|
||||
export const titlebarDragSurfaceStyle: React.CSSProperties = {
|
||||
cursor: "default",
|
||||
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
|
||||
|
||||
@@ -27,7 +27,6 @@ const NO_SHORTCUT: ShortcutKey[] = [];
|
||||
interface CompactHeaderProps {
|
||||
/** The leading island: the sidebar menu, or a back button. */
|
||||
navigation: "menu" | "back";
|
||||
inDesktopTitlebar?: boolean;
|
||||
/** Back button action. Defaults to navigating back. */
|
||||
onBack?: () => void;
|
||||
title?: string;
|
||||
@@ -50,7 +49,6 @@ interface CompactHeaderProps {
|
||||
*/
|
||||
export function CompactHeader({
|
||||
navigation,
|
||||
inDesktopTitlebar = false,
|
||||
onBack,
|
||||
title,
|
||||
titleTestID,
|
||||
@@ -60,28 +58,22 @@ export function CompactHeader({
|
||||
}: CompactHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const inTopBand = useTopBand() !== null;
|
||||
const usesTitlebarHeight = inTopBand || inDesktopTitlebar;
|
||||
const rootStyle = useMemo(
|
||||
() => [
|
||||
styles.root,
|
||||
{
|
||||
paddingTop: insets.top + (usesTitlebarHeight ? 0 : HEADER_TOP_PADDING_MOBILE),
|
||||
paddingTop: insets.top + (inTopBand ? 0 : HEADER_TOP_PADDING_MOBILE),
|
||||
marginLeft: insets.left,
|
||||
marginRight: insets.right,
|
||||
},
|
||||
],
|
||||
[usesTitlebarHeight, insets.top, insets.left, insets.right],
|
||||
[inTopBand, insets.top, insets.left, insets.right],
|
||||
);
|
||||
|
||||
return (
|
||||
<IconButtonChromeProvider value="header-island">
|
||||
<View style={rootStyle}>
|
||||
<View
|
||||
style={[
|
||||
usesTitlebarHeight ? styles.titlebarRow : styles.row,
|
||||
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
|
||||
]}
|
||||
>
|
||||
<View style={inTopBand ? styles.topBandRow : styles.row}>
|
||||
<View style={styles.island}>
|
||||
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
|
||||
</View>
|
||||
@@ -163,16 +155,12 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
titlebarRow: {
|
||||
topBandRow: {
|
||||
height: HEADER_INNER_HEIGHT,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
desktopTitlebarDividerSpace: {
|
||||
borderBottomWidth: theme.borderWidth[1],
|
||||
borderBottomColor: "transparent",
|
||||
},
|
||||
titleGroup: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
|
||||
@@ -128,7 +128,6 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import type { PrHint } from "@/git/use-pr-status-query";
|
||||
import {
|
||||
@@ -1298,17 +1297,6 @@ function WorkspaceRowWithMenu({
|
||||
});
|
||||
}, [markUnread, toast]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: `workspace-archive-${workspace.workspaceKey}`,
|
||||
actions: ["workspace.archive"],
|
||||
enabled: selected && !isArchiving,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
handleArchive();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<WorkspaceRowInner
|
||||
|
||||
@@ -42,7 +42,6 @@ import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-ar
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import { useWorkspaceReadState } from "@/hooks/use-workspace-read-state";
|
||||
import {
|
||||
SidebarWorkspaceRowFrame,
|
||||
@@ -702,17 +701,6 @@ function StatusWorkspaceRowWithMenu({
|
||||
});
|
||||
}, [markUnread, toast]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: `workspace-archive-${workspace.workspaceKey}`,
|
||||
actions: ["workspace.archive"],
|
||||
enabled: selected && !isArchiving,
|
||||
priority: 0,
|
||||
handle: () => {
|
||||
handleArchive();
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<StatusWorkspaceRowInner
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
useRef,
|
||||
type CSSProperties,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import type { DOMProps } from "expo/dom";
|
||||
@@ -64,12 +63,6 @@ const HOST_DIV_STYLE: CSSProperties = {
|
||||
paddingRight: 0,
|
||||
};
|
||||
|
||||
interface TerminalTouchFocus {
|
||||
pointerId: number;
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
function buildXtermThemeKey(theme: ITheme): string {
|
||||
const values: Array<string> = [
|
||||
theme.background,
|
||||
@@ -560,46 +553,10 @@ export default function TerminalEmulator({
|
||||
});
|
||||
}, []);
|
||||
|
||||
const touchFocusRef = useRef<TerminalTouchFocus | null>(null);
|
||||
|
||||
const handleRootPointerDown = useCallback(
|
||||
(event: ReactPointerEvent) => {
|
||||
onFocus?.();
|
||||
touchFocusRef.current = null;
|
||||
if (event.pointerType !== "touch") {
|
||||
runtimeRef.current?.focus();
|
||||
return;
|
||||
}
|
||||
// Focusing before a touch becomes a tap opens the keyboard during a scroll.
|
||||
if (event.isPrimary) {
|
||||
touchFocusRef.current = {
|
||||
pointerId: event.pointerId,
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
};
|
||||
}
|
||||
},
|
||||
[onFocus],
|
||||
);
|
||||
|
||||
const handleRootPointerMove = useCallback((event: ReactPointerEvent) => {
|
||||
const touch = touchFocusRef.current;
|
||||
if (touch?.pointerId !== event.pointerId) return;
|
||||
if (Math.hypot(event.clientX - touch.x, event.clientY - touch.y) > 8) {
|
||||
touchFocusRef.current = null;
|
||||
runtimeRef.current?.suppressAutomaticKeyboard();
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleRootPointerUp = useCallback((event: ReactPointerEvent) => {
|
||||
const touch = touchFocusRef.current;
|
||||
touchFocusRef.current = null;
|
||||
if (touch?.pointerId === event.pointerId) runtimeRef.current?.focus();
|
||||
}, []);
|
||||
|
||||
const handleRootPointerCancel = useCallback(() => {
|
||||
touchFocusRef.current = null;
|
||||
}, []);
|
||||
const handleRootPointerDown = useCallback(() => {
|
||||
onFocus?.();
|
||||
runtimeRef.current?.focus();
|
||||
}, [onFocus]);
|
||||
|
||||
const handleRootContextMenu = useCallback(
|
||||
(event: ReactMouseEvent) => {
|
||||
@@ -631,9 +588,6 @@ export default function TerminalEmulator({
|
||||
data-terminal-scrollbar-root="true"
|
||||
style={rootDivStyle}
|
||||
onPointerDown={handleRootPointerDown}
|
||||
onPointerMove={handleRootPointerMove}
|
||||
onPointerUp={handleRootPointerUp}
|
||||
onPointerCancel={handleRootPointerCancel}
|
||||
onContextMenu={handleRootContextMenu}
|
||||
>
|
||||
<div ref={hostRef} style={HOST_DIV_STYLE} />
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useGlobalWorkspaceArchiveAction } from "@/hooks/use-global-workspace-archive-action";
|
||||
|
||||
// Headless host for the archive shortcut, kept out of the root layout for the same reason as
|
||||
// WorkspacePinShortcutHandler: the hook subscribes to the active workspace's fields.
|
||||
export function WorkspaceArchiveShortcutHandler() {
|
||||
useGlobalWorkspaceArchiveAction();
|
||||
return null;
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import { Keyboard, StyleSheet as RNStyleSheet, Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
|
||||
import { useContainerWidthBelow } from "@/hooks/use-container-width";
|
||||
import invariant from "tiny-invariant";
|
||||
import { Composer } from "@/composer";
|
||||
@@ -537,17 +536,14 @@ export function WorkspaceDraftComposer({
|
||||
return (
|
||||
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
|
||||
{formErrorMessage ? (
|
||||
<View
|
||||
style={styles.formErrorRow}
|
||||
dataSet={isComposerFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
|
||||
>
|
||||
<View style={styles.formErrorRow}>
|
||||
<View style={styles.formError}>
|
||||
<Text style={styles.errorText}>{formErrorMessage}</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
{importPillPress && !isComposerFullscreen ? (
|
||||
<View style={styles.importPillRow} dataSet={CHAT_COLUMN_RAIL_DATASET}>
|
||||
<View style={styles.importPillRow}>
|
||||
<View style={styles.importPillContent}>
|
||||
<ComposerImportPill onPress={importPillPress} />
|
||||
</View>
|
||||
|
||||
@@ -30,7 +30,6 @@ import {
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import {
|
||||
controlSizingForLayout,
|
||||
@@ -2576,10 +2575,7 @@ function ComposerContentImpl({
|
||||
>
|
||||
<AttachmentLightbox source={lightboxSource} onClose={handleLightboxClose} />
|
||||
{/* Input area */}
|
||||
<View
|
||||
style={inputAreaContainerStyle}
|
||||
dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
|
||||
>
|
||||
<View style={inputAreaContainerStyle}>
|
||||
<View style={inputAreaContentStyle}>
|
||||
{isFullscreen ? null : queueList}
|
||||
{!isFullscreen && sendErrorNode}
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
useHorizontalScrollBoundary,
|
||||
} from "@/components/ui/horizontal-scroll-boundary";
|
||||
import { STATUS_RING_HALO_INSET } from "@/components/status-ring/geometry";
|
||||
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { usePanelAwareHorizontalScrollGesture } from "@/mobile-panels/gestures";
|
||||
import { getStatusDotColor } from "@/utils/status-dot-color";
|
||||
@@ -46,7 +45,7 @@ export function ComposerTrackBar({ children }: { children: ReactNode }): ReactEl
|
||||
const scrollGesture = usePanelAwareHorizontalScrollGesture();
|
||||
const scrollBoundary = useHorizontalScrollBoundary();
|
||||
return (
|
||||
<View style={styles.bar} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
|
||||
<View style={styles.bar} pointerEvents="box-none">
|
||||
<View style={styles.trackViewport} pointerEvents="box-none">
|
||||
<GestureDetector gesture={scrollGesture}>
|
||||
<Animated.ScrollView
|
||||
|
||||
@@ -224,7 +224,6 @@ const CATALOG_DATA = [
|
||||
},
|
||||
{
|
||||
id: "goose",
|
||||
bundledProvider: { hostFeature: "gooseProvider" },
|
||||
title: "goose",
|
||||
description: "A local, extensible, open source AI agent that automates engineering tasks",
|
||||
version: "1.33.1",
|
||||
|
||||
@@ -2,7 +2,6 @@ import type { ParsedDiffFile } from "@getpaseo/protocol/messages";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
characterOffsetAtPoint,
|
||||
graphemeOffsetAtPoint,
|
||||
hitTestDiffDocument,
|
||||
orderedSelection,
|
||||
selectAllSource,
|
||||
@@ -44,49 +43,6 @@ describe("diff hit testing", () => {
|
||||
).toBe(combining?.end);
|
||||
});
|
||||
|
||||
it("keeps the nearest caret for character drags but hits the grapheme under word gestures", () => {
|
||||
const cell = changedCell(buildModel("call(foo)", { wrapLines: false, viewportWidth: 300 }));
|
||||
const graphemes = cell.fragments[0]!.graphemes;
|
||||
const lastOfWord = graphemes[3]!;
|
||||
const punctuation = graphemes[4]!;
|
||||
const beforeLastOfWord = graphemes
|
||||
.slice(0, 3)
|
||||
.reduce((width, grapheme) => width + grapheme.width, 0);
|
||||
const rightHalfOfWord = beforeLastOfWord + lastOfWord.width * 0.75;
|
||||
const leftHalfOfPunctuation = beforeLastOfWord + lastOfWord.width + punctuation.width * 0.1;
|
||||
|
||||
expect(characterOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe(
|
||||
punctuation.start,
|
||||
);
|
||||
expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfWord, y: 0, lineHeight: 18 })).toBe(
|
||||
lastOfWord.start,
|
||||
);
|
||||
expect(characterOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe(
|
||||
punctuation.start,
|
||||
);
|
||||
expect(graphemeOffsetAtPoint({ cell, x: leftHalfOfPunctuation, y: 0, lineHeight: 18 })).toBe(
|
||||
punctuation.start,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps wrapped fragment boundaries from stealing the grapheme under the pointer", () => {
|
||||
const cell = changedCell(buildModel("abcdef", { viewportWidth: 90 }));
|
||||
const firstFragment = cell.fragments[0]!;
|
||||
expect(cell.fragments.length).toBeGreaterThan(1);
|
||||
const lastGrapheme = firstFragment.graphemes.at(-1)!;
|
||||
const beforeLastGrapheme = firstFragment.graphemes
|
||||
.slice(0, -1)
|
||||
.reduce((width, grapheme) => width + grapheme.width, 0);
|
||||
const rightHalfOfLastGrapheme = beforeLastGrapheme + lastGrapheme.width * 0.75;
|
||||
|
||||
expect(characterOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe(
|
||||
firstFragment.end,
|
||||
);
|
||||
expect(graphemeOffsetAtPoint({ cell, x: rightHalfOfLastGrapheme, y: 0, lineHeight: 18 })).toBe(
|
||||
lastGrapheme.start,
|
||||
);
|
||||
});
|
||||
|
||||
it("normalizes backwards selection and copies exact source including empty lines", () => {
|
||||
const model = buildModel("", { wrapLines: false });
|
||||
const cell = changedCell(model);
|
||||
|
||||
@@ -3,7 +3,6 @@ import type {
|
||||
DiffCell,
|
||||
DiffCharacterPosition,
|
||||
DiffDocumentModel,
|
||||
DiffFragment,
|
||||
DiffHit,
|
||||
DiffSelection,
|
||||
} from "./types";
|
||||
@@ -34,7 +33,12 @@ export function hitTestDiffDocument(input: {
|
||||
localX - file.gutterWidth - CODE_LEFT_PADDING + input.horizontalOffset,
|
||||
);
|
||||
const textY = input.documentY - row.top;
|
||||
const point = { cell, x: contentX, y: textY, lineHeight: input.model.lineHeight };
|
||||
const sourceOffset = characterOffsetAtPoint({
|
||||
cell,
|
||||
x: contentX,
|
||||
y: textY,
|
||||
lineHeight: input.model.lineHeight,
|
||||
});
|
||||
return {
|
||||
kind: "cell",
|
||||
target: cell.reviewTarget,
|
||||
@@ -43,9 +47,8 @@ export function hitTestDiffDocument(input: {
|
||||
rowIndex: row.index,
|
||||
cellIndex,
|
||||
side: cell.reviewTarget?.side ?? (cellIndex === 0 ? "old" : "new"),
|
||||
sourceOffset: characterOffsetAtPoint(point),
|
||||
sourceOffset,
|
||||
},
|
||||
graphemeOffset: graphemeOffsetAtPoint(point),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -55,7 +58,11 @@ export function characterOffsetAtPoint(input: {
|
||||
y: number;
|
||||
lineHeight: number;
|
||||
}): number {
|
||||
const fragment = fragmentAtPoint(input);
|
||||
const fragmentIndex = Math.min(
|
||||
input.cell.fragments.length - 1,
|
||||
Math.max(0, Math.floor(input.y / input.lineHeight)),
|
||||
);
|
||||
const fragment = input.cell.fragments[fragmentIndex];
|
||||
if (!fragment) return 0;
|
||||
let width = 0;
|
||||
for (const grapheme of fragment.graphemes) {
|
||||
@@ -65,36 +72,6 @@ export function characterOffsetAtPoint(input: {
|
||||
return fragment.end;
|
||||
}
|
||||
|
||||
/** The grapheme under the pointer, unlike `characterOffsetAtPoint`, which snaps to the nearest caret. */
|
||||
export function graphemeOffsetAtPoint(input: {
|
||||
cell: DiffCell;
|
||||
x: number;
|
||||
y: number;
|
||||
lineHeight: number;
|
||||
}): number {
|
||||
const fragment = fragmentAtPoint(input);
|
||||
if (!fragment) return 0;
|
||||
let width = 0;
|
||||
for (const grapheme of fragment.graphemes) {
|
||||
if (input.x < width + grapheme.width) return grapheme.start;
|
||||
width += grapheme.width;
|
||||
}
|
||||
const lastGrapheme = fragment.graphemes.at(-1);
|
||||
return lastGrapheme ? lastGrapheme.start : fragment.start;
|
||||
}
|
||||
|
||||
function fragmentAtPoint(input: {
|
||||
cell: DiffCell;
|
||||
y: number;
|
||||
lineHeight: number;
|
||||
}): DiffFragment | null {
|
||||
const fragmentIndex = Math.min(
|
||||
input.cell.fragments.length - 1,
|
||||
Math.max(0, Math.floor(input.y / input.lineHeight)),
|
||||
);
|
||||
return input.cell.fragments[fragmentIndex] ?? null;
|
||||
}
|
||||
|
||||
function rowAtOffset(
|
||||
rows: readonly DiffDocumentModel["rows"][number][],
|
||||
start: number,
|
||||
@@ -186,7 +163,7 @@ export function selectAllSource(
|
||||
return first && last ? { anchor: first, focus: last } : null;
|
||||
}
|
||||
|
||||
export function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number {
|
||||
function comparePosition(left: DiffCharacterPosition, right: DiffCharacterPosition): number {
|
||||
return (
|
||||
left.rowIndex - right.rowIndex ||
|
||||
left.cellIndex - right.cellIndex ||
|
||||
|
||||
@@ -1,38 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
hasPointerDragStarted,
|
||||
lineSelectionForDrag,
|
||||
wordSelectionForDrag,
|
||||
type LineAtPosition,
|
||||
type WordAtPosition,
|
||||
} from "./pointer-gesture";
|
||||
import type { DiffCharacterPosition } from "./types";
|
||||
|
||||
function positionAt(offset: number, rowIndex = 1, cellIndex = 0): DiffCharacterPosition {
|
||||
return { fileIndex: 0, rowIndex, cellIndex, side: "new", sourceOffset: offset };
|
||||
}
|
||||
|
||||
function wordAt(
|
||||
input: { offset: number; start: number; end: number },
|
||||
rowIndex = 1,
|
||||
cellIndex = 0,
|
||||
): WordAtPosition {
|
||||
return {
|
||||
position: positionAt(input.offset, rowIndex, cellIndex),
|
||||
word: { start: input.start, end: input.end },
|
||||
};
|
||||
}
|
||||
|
||||
function lineAt(
|
||||
input: { offset: number; end: number },
|
||||
rowIndex = 1,
|
||||
cellIndex = 0,
|
||||
): LineAtPosition {
|
||||
return {
|
||||
position: positionAt(input.offset, rowIndex, cellIndex),
|
||||
end: input.end,
|
||||
};
|
||||
}
|
||||
import { hasPointerDragStarted } from "./pointer-gesture";
|
||||
|
||||
describe("diff pointer gesture", () => {
|
||||
it("classifies pointer movement as a drag without requiring a character change", () => {
|
||||
@@ -59,99 +26,3 @@ describe("diff pointer gesture", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("diff word drag selection", () => {
|
||||
it("extends forward from the start of the anchor word to the end of the focus word", () => {
|
||||
expect(
|
||||
wordSelectionForDrag({
|
||||
anchor: wordAt({ offset: 8, start: 6, end: 11 }),
|
||||
focus: wordAt({ offset: 14, start: 12, end: 19 }),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(6),
|
||||
focus: positionAt(19),
|
||||
});
|
||||
});
|
||||
|
||||
it("extends backward from the end of the anchor word to the start of the focus word", () => {
|
||||
expect(
|
||||
wordSelectionForDrag({
|
||||
anchor: wordAt({ offset: 15, start: 13, end: 20 }),
|
||||
focus: wordAt({ offset: 7, start: 6, end: 11 }),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(6),
|
||||
focus: positionAt(20),
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the anchor word whole while the pointer stays inside it", () => {
|
||||
const anchor = wordAt({ offset: 10, start: 6, end: 11 });
|
||||
const expected = { anchor: positionAt(6), focus: positionAt(11) };
|
||||
expect(
|
||||
wordSelectionForDrag({ anchor, focus: wordAt({ offset: 7, start: 6, end: 11 }) }),
|
||||
).toEqual(expected);
|
||||
expect(
|
||||
wordSelectionForDrag({ anchor, focus: wordAt({ offset: 9, start: 6, end: 11 }) }),
|
||||
).toEqual(expected);
|
||||
});
|
||||
|
||||
it("snaps both ends to word boundaries across rows", () => {
|
||||
expect(
|
||||
wordSelectionForDrag({
|
||||
anchor: wordAt({ offset: 3, start: 2, end: 5 }, 1),
|
||||
focus: wordAt({ offset: 2, start: 0, end: 4 }, 3),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(2, 1),
|
||||
focus: positionAt(4, 3),
|
||||
});
|
||||
expect(
|
||||
wordSelectionForDrag({
|
||||
anchor: wordAt({ offset: 2, start: 0, end: 4 }, 3),
|
||||
focus: wordAt({ offset: 3, start: 2, end: 5 }, 1),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(2, 1),
|
||||
focus: positionAt(4, 3),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("diff line drag selection", () => {
|
||||
it("selects the whole clicked source line", () => {
|
||||
expect(
|
||||
lineSelectionForDrag({
|
||||
anchor: lineAt({ offset: 3, end: 12 }),
|
||||
focus: lineAt({ offset: 3, end: 12 }),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(0),
|
||||
focus: positionAt(12),
|
||||
});
|
||||
});
|
||||
|
||||
it("extends forward to the end of the focus line while keeping the anchor line", () => {
|
||||
expect(
|
||||
lineSelectionForDrag({
|
||||
anchor: lineAt({ offset: 3, end: 12 }),
|
||||
focus: lineAt({ offset: 1, end: 7 }, 3),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(0),
|
||||
focus: positionAt(7, 3),
|
||||
});
|
||||
});
|
||||
|
||||
it("extends backward from the start of the focus line to the end of the anchor line", () => {
|
||||
expect(
|
||||
lineSelectionForDrag({
|
||||
anchor: lineAt({ offset: 5, end: 9 }, 3),
|
||||
focus: lineAt({ offset: 2, end: 12 }, 1),
|
||||
}),
|
||||
).toEqual({
|
||||
anchor: positionAt(0, 1),
|
||||
focus: positionAt(9, 3),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,46 +1,5 @@
|
||||
import { comparePosition } from "./hit-testing";
|
||||
import type { DiffCharacterPosition, DiffSelection } from "./types";
|
||||
import type { SourceWordRange } from "./word-boundaries";
|
||||
|
||||
const DRAG_THRESHOLD = 4;
|
||||
|
||||
export interface WordAtPosition {
|
||||
position: DiffCharacterPosition;
|
||||
word: SourceWordRange;
|
||||
}
|
||||
|
||||
export interface LineAtPosition {
|
||||
position: DiffCharacterPosition;
|
||||
/** UTF-16 length of the canonical source line. */
|
||||
end: number;
|
||||
}
|
||||
|
||||
export function wordSelectionForDrag(input: {
|
||||
anchor: WordAtPosition;
|
||||
focus: WordAtPosition;
|
||||
}): DiffSelection {
|
||||
const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0;
|
||||
const start = isBackward ? input.focus : input.anchor;
|
||||
const end = isBackward ? input.anchor : input.focus;
|
||||
return {
|
||||
anchor: { ...start.position, sourceOffset: start.word.start },
|
||||
focus: { ...end.position, sourceOffset: end.word.end },
|
||||
};
|
||||
}
|
||||
|
||||
export function lineSelectionForDrag(input: {
|
||||
anchor: LineAtPosition;
|
||||
focus: LineAtPosition;
|
||||
}): DiffSelection {
|
||||
const isBackward = comparePosition(input.focus.position, input.anchor.position) < 0;
|
||||
const start = isBackward ? input.focus : input.anchor;
|
||||
const end = isBackward ? input.anchor : input.focus;
|
||||
return {
|
||||
anchor: { ...start.position, sourceOffset: 0 },
|
||||
focus: { ...end.position, sourceOffset: end.end },
|
||||
};
|
||||
}
|
||||
|
||||
export function hasPointerDragStarted(input: {
|
||||
startX: number;
|
||||
startY: number;
|
||||
|
||||
@@ -35,13 +35,7 @@ import {
|
||||
resolveRelayoutScrollTop,
|
||||
} from "./model";
|
||||
import { paintWebFileHeader, paintWebViewport } from "./paint.web";
|
||||
import {
|
||||
hasPointerDragStarted,
|
||||
lineSelectionForDrag,
|
||||
wordSelectionForDrag,
|
||||
type LineAtPosition,
|
||||
type WordAtPosition,
|
||||
} from "./pointer-gesture";
|
||||
import { hasPointerDragStarted } from "./pointer-gesture";
|
||||
import {
|
||||
createMeasuredAdvances,
|
||||
createAdditiveAdvances,
|
||||
@@ -50,8 +44,6 @@ import {
|
||||
} from "./text-measurement";
|
||||
import { retainDiffViewport } from "./viewport";
|
||||
import type {
|
||||
DiffCell,
|
||||
DiffCharacterPosition,
|
||||
DiffHit,
|
||||
DiffFileSection,
|
||||
DiffSelection,
|
||||
@@ -59,7 +51,6 @@ import type {
|
||||
DiffTypography,
|
||||
TextMeasurer,
|
||||
} from "./types";
|
||||
import { wordRangeAtOffset } from "./word-boundaries";
|
||||
import { useDiffDocumentWorkspaceCache } from "./workspace-cache";
|
||||
|
||||
const DEFAULT_MONO_STACK = "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace";
|
||||
@@ -113,11 +104,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
startY: number;
|
||||
moved: boolean;
|
||||
dismissSelectionOnClick: boolean;
|
||||
granularity:
|
||||
| { kind: "character" }
|
||||
| { kind: "word"; anchor: WordAtPosition }
|
||||
| { kind: "line"; anchor: LineAtPosition };
|
||||
pointerType: string;
|
||||
} | null>(null);
|
||||
const frameRef = useRef<number | null>(null);
|
||||
const activeHeaderPathRef = useRef<string | null>(null);
|
||||
@@ -605,31 +591,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
desiredTypography,
|
||||
setSelection,
|
||||
]);
|
||||
const cellAt = useCallback((position: DiffCharacterPosition): DiffCell | null => {
|
||||
const currentModel = modelRef.current;
|
||||
if (!currentModel) return null;
|
||||
const row = currentModel.rows[position.rowIndex];
|
||||
return row?.kind === "line" ? row.cells[position.cellIndex] : null;
|
||||
}, []);
|
||||
const wordAt = useCallback(
|
||||
(hit: Extract<DiffHit, { kind: "cell" }>): WordAtPosition | null => {
|
||||
const cell = cellAt(hit.position);
|
||||
if (!cell) return null;
|
||||
return {
|
||||
position: { ...hit.position, sourceOffset: hit.graphemeOffset },
|
||||
word: wordRangeAtOffset(cell.content, hit.graphemeOffset),
|
||||
};
|
||||
},
|
||||
[cellAt],
|
||||
);
|
||||
const lineAt = useCallback(
|
||||
(hit: Extract<DiffHit, { kind: "cell" }>): LineAtPosition | null => {
|
||||
const cell = cellAt(hit.position);
|
||||
if (!cell) return null;
|
||||
return { position: hit.position, end: cell.content.length };
|
||||
},
|
||||
[cellAt],
|
||||
);
|
||||
const pointerDown = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (event.button !== 0) return;
|
||||
@@ -641,18 +602,18 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
)
|
||||
)
|
||||
return;
|
||||
const dismissSelectionOnClick = selectionRef.current !== null;
|
||||
if (dismissSelectionOnClick) {
|
||||
setSelection(null);
|
||||
}
|
||||
const hit = pointHit(event);
|
||||
const hadSelection = selectionRef.current !== null;
|
||||
if (hadSelection) setSelection(null);
|
||||
if (hit?.kind !== "cell") return;
|
||||
dragRef.current = {
|
||||
anchor: hit.position,
|
||||
startX: event.clientX,
|
||||
startY: event.clientY,
|
||||
moved: false,
|
||||
dismissSelectionOnClick: hadSelection,
|
||||
granularity: { kind: "character" },
|
||||
pointerType: event.pointerType,
|
||||
dismissSelectionOnClick,
|
||||
};
|
||||
setSelection({ anchor: hit.position, focus: hit.position });
|
||||
event.currentTarget.focus();
|
||||
@@ -660,38 +621,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
},
|
||||
[pointHit, setSelection],
|
||||
);
|
||||
// The native click count honors the OS double-click setting and arrives on the
|
||||
// second mousedown, after pointerdown has opened the character drag.
|
||||
const mouseDown = useCallback(
|
||||
(event: React.MouseEvent<HTMLDivElement>) => {
|
||||
const drag = dragRef.current;
|
||||
if (!drag || event.button !== 0 || event.detail < 2 || drag.pointerType === "touch") return;
|
||||
const target = event.target;
|
||||
if (
|
||||
target instanceof Element &&
|
||||
target.closest(
|
||||
'[data-diff-header="true"], [data-diff-review="true"], [role="menuitem"], button, input, textarea',
|
||||
)
|
||||
)
|
||||
return;
|
||||
const hit = pointHitAt(event.clientX, event.clientY);
|
||||
if (hit?.kind !== "cell") return;
|
||||
if (event.detail >= 3) {
|
||||
const lineAnchor = lineAt(hit);
|
||||
if (!lineAnchor) return;
|
||||
drag.granularity = { kind: "line", anchor: lineAnchor };
|
||||
drag.dismissSelectionOnClick = false;
|
||||
setSelection(lineSelectionForDrag({ anchor: lineAnchor, focus: lineAnchor }));
|
||||
return;
|
||||
}
|
||||
const wordAnchor = wordAt(hit);
|
||||
if (!wordAnchor) return;
|
||||
drag.granularity = { kind: "word", anchor: wordAnchor };
|
||||
drag.dismissSelectionOnClick = false;
|
||||
setSelection(wordSelectionForDrag({ anchor: wordAnchor, focus: wordAnchor }));
|
||||
},
|
||||
[lineAt, pointHitAt, setSelection, wordAt],
|
||||
);
|
||||
const updateActiveHeader = useCallback(
|
||||
(target: EventTarget | null) => {
|
||||
const header =
|
||||
@@ -705,32 +634,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
},
|
||||
[paintStickyHeaderPool, schedulePaint],
|
||||
);
|
||||
const updateHoveredAffordance = useCallback(
|
||||
(hit: Extract<DiffHit, { kind: "cell" }>, clientX: number) => {
|
||||
const row = modelRef.current?.rows[hit.position.rowIndex];
|
||||
const file = modelRef.current?.files[hit.position.fileIndex];
|
||||
const sideIndex =
|
||||
row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0;
|
||||
if (row && file) {
|
||||
const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1);
|
||||
const gutterBorder = sideIndex * columnWidth + file.gutterWidth;
|
||||
const rootBounds = rootRef.current?.getBoundingClientRect();
|
||||
const pointerX = rootBounds ? clientX - rootBounds.left : Number.NaN;
|
||||
if (hit.target && Number.isFinite(pointerX)) {
|
||||
hasHoveredAffordanceRef.current = true;
|
||||
setHoveredAffordance({
|
||||
hit,
|
||||
left: gutterBorder - 12,
|
||||
top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
hasHoveredAffordanceRef.current = false;
|
||||
setHoveredAffordance(null);
|
||||
},
|
||||
[viewport.width],
|
||||
);
|
||||
const pointerMove = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
updateActiveHeader(event.target);
|
||||
@@ -746,29 +649,35 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
}
|
||||
const hit = pointHit(event);
|
||||
if (hit?.kind === "cell") {
|
||||
updateHoveredAffordance(hit, event.clientX);
|
||||
const row = modelRef.current?.rows[hit.position.rowIndex];
|
||||
const file = modelRef.current?.files[hit.position.fileIndex];
|
||||
const sideIndex =
|
||||
row?.kind === "line" && row.cells.length === 2 && hit.position.side === "new" ? 1 : 0;
|
||||
if (row && file) {
|
||||
const columnWidth = viewport.width / (row.kind === "line" ? row.cells.length : 1);
|
||||
const gutterBorder = sideIndex * columnWidth + file.gutterWidth;
|
||||
const rootBounds = rootRef.current?.getBoundingClientRect();
|
||||
const pointerX = rootBounds ? event.clientX - rootBounds.left : Number.NaN;
|
||||
if (hit.target && Number.isFinite(pointerX)) {
|
||||
hasHoveredAffordanceRef.current = true;
|
||||
setHoveredAffordance({
|
||||
hit,
|
||||
left: gutterBorder - 12,
|
||||
top: row.top - scrollTopRef.current + (modelRef.current!.lineHeight - 22) / 2,
|
||||
});
|
||||
} else {
|
||||
hasHoveredAffordanceRef.current = false;
|
||||
setHoveredAffordance(null);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
hasHoveredAffordanceRef.current = false;
|
||||
setHoveredAffordance(null);
|
||||
}
|
||||
if (!drag || hit?.kind !== "cell") return;
|
||||
if (drag.granularity.kind === "word") {
|
||||
const focusWord = wordAt(hit);
|
||||
if (focusWord) {
|
||||
setSelection(wordSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusWord }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (drag.granularity.kind === "line") {
|
||||
const focusLine = lineAt(hit);
|
||||
if (focusLine) {
|
||||
setSelection(lineSelectionForDrag({ anchor: drag.granularity.anchor, focus: focusLine }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
setSelection({ anchor: drag.anchor, focus: hit.position });
|
||||
},
|
||||
[lineAt, pointHit, setSelection, updateActiveHeader, updateHoveredAffordance, wordAt],
|
||||
[pointHit, setSelection, updateActiveHeader, viewport.width],
|
||||
);
|
||||
const pointerUp = useCallback(
|
||||
(event: React.PointerEvent<HTMLDivElement>) => {
|
||||
@@ -913,7 +822,6 @@ export function DiffSurface(props: DiffSurfaceProps) {
|
||||
data-overlay-scrollbar="true"
|
||||
tabIndex={0}
|
||||
onPointerDown={pointerDown}
|
||||
onMouseDown={mouseDown}
|
||||
onPointerMove={pointerMove}
|
||||
onPointerUp={pointerUp}
|
||||
onPointerCancel={cancelPointer}
|
||||
|
||||
@@ -208,8 +208,6 @@ export type DiffHit =
|
||||
kind: "cell";
|
||||
target: ReviewableDiffTarget | null;
|
||||
position: DiffCharacterPosition;
|
||||
/** The grapheme under the pointer, which word gestures select from. */
|
||||
graphemeOffset: number;
|
||||
};
|
||||
|
||||
export interface DiffSelection {
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
import { CharCategory, EditorState } from "@codemirror/state";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { wordRangeAtOffset } from "./word-boundaries";
|
||||
|
||||
describe("diff word boundaries", () => {
|
||||
it("selects the identifier under the offset", () => {
|
||||
expect(wordRangeAtOffset("alpha bravo charlie", 8)).toEqual({ start: 6, end: 11 });
|
||||
});
|
||||
|
||||
it("selects the surrounding whitespace when the offset is inside a run of spaces", () => {
|
||||
expect(wordRangeAtOffset("alpha bravo", 6)).toEqual({ start: 5, end: 8 });
|
||||
});
|
||||
|
||||
it("selects a run of punctuation without merging it into neighboring words", () => {
|
||||
expect(wordRangeAtOffset("call(foo, bar)", 4)).toEqual({ start: 4, end: 5 });
|
||||
expect(wordRangeAtOffset("call(foo, bar)", 6)).toEqual({ start: 5, end: 8 });
|
||||
expect(wordRangeAtOffset("fn()", 3)).toEqual({ start: 2, end: 4 });
|
||||
expect(wordRangeAtOffset("foo.bar", 3)).toEqual({ start: 3, end: 4 });
|
||||
expect(wordRangeAtOffset("foo.bar", 5)).toEqual({ start: 4, end: 7 });
|
||||
});
|
||||
|
||||
it("selects the final word when the offset reaches the end of the line", () => {
|
||||
expect(wordRangeAtOffset("alpha bravo", 11)).toEqual({ start: 6, end: 11 });
|
||||
expect(wordRangeAtOffset("alpha bravo", 99)).toEqual({ start: 6, end: 11 });
|
||||
});
|
||||
|
||||
it("selects the leading word when the offset is clamped at the start", () => {
|
||||
expect(wordRangeAtOffset("alpha bravo", 0)).toEqual({ start: 0, end: 5 });
|
||||
});
|
||||
|
||||
it("keeps combining sequences and emoji clusters whole", () => {
|
||||
const combining = "ai\u0301b";
|
||||
expect(wordRangeAtOffset(combining, 1)).toEqual({ start: 0, end: 4 });
|
||||
expect(wordRangeAtOffset(combining, 2)).toEqual({ start: 0, end: 4 });
|
||||
|
||||
const emoji = "hi 👨👩👧👦 there";
|
||||
const emojiStart = emoji.indexOf("👨");
|
||||
expect(wordRangeAtOffset(emoji, emojiStart)).toEqual({
|
||||
start: emojiStart,
|
||||
end: emojiStart + "👨👩👧👦".length,
|
||||
});
|
||||
});
|
||||
|
||||
it("treats tabs as whitespace and returns an empty range for empty content", () => {
|
||||
expect(wordRangeAtOffset("\tfoo", 0)).toEqual({ start: 0, end: 1 });
|
||||
expect(wordRangeAtOffset("", 0)).toEqual({ start: 0, end: 0 });
|
||||
});
|
||||
|
||||
it("matches CodeMirror word runs for offsets inside a word", () => {
|
||||
const content = "alpha bravo charlie";
|
||||
const state = EditorState.create({ doc: content });
|
||||
for (const offset of [0, 2, 8, 14, 18]) {
|
||||
const word = state.wordAt(offset);
|
||||
expect(word).not.toBeNull();
|
||||
expect(wordRangeAtOffset(content, offset)).toEqual({ start: word!.from, end: word!.to });
|
||||
}
|
||||
});
|
||||
|
||||
it("classifies leading graphemes with CodeMirror character categories", () => {
|
||||
const categorize = EditorState.create({ doc: "" }).charCategorizer(0);
|
||||
const clusters = ["a", "1", "_", "中", "👨👩👧👦", "\u0301", "\ufe0f", "\u00a0"];
|
||||
for (const cluster of clusters) {
|
||||
const isWord = categorize(cluster) === CharCategory.Word;
|
||||
expect(wordRangeAtOffset(`${cluster}x`, 0)).toEqual({
|
||||
start: 0,
|
||||
end: isWord ? cluster.length + 1 : cluster.length,
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,88 +0,0 @@
|
||||
import { CharCategory, EditorState } from "@codemirror/state";
|
||||
import { graphemeBoundaries } from "./model";
|
||||
|
||||
export interface SourceWordRange {
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
|
||||
interface SourceText {
|
||||
state: EditorState;
|
||||
boundaries: number[];
|
||||
categorize: (cluster: string) => CharCategory;
|
||||
}
|
||||
|
||||
// Word gestures query the same line repeatedly while dragging. Keep a bounded
|
||||
// set of parsed sources instead of rebuilding an EditorState on every move.
|
||||
const SOURCE_CACHE_LIMIT = 8;
|
||||
const sources = new Map<string, SourceText>();
|
||||
|
||||
/**
|
||||
* The run around `offset` that a double click selects: a word, a run of
|
||||
* whitespace, or a run of punctuation. Runs never cross grapheme boundaries.
|
||||
*/
|
||||
export function wordRangeAtOffset(content: string, offset: number): SourceWordRange {
|
||||
if (content.length === 0) return { start: 0, end: 0 };
|
||||
const source = sourceText(content);
|
||||
const { boundaries } = source;
|
||||
const clusterIndex = clusterIndexAt(boundaries, offset);
|
||||
const category = source.categorize(clusterText(content, boundaries, clusterIndex));
|
||||
if (category === CharCategory.Word) {
|
||||
const word = source.state.wordAt(boundaries[clusterIndex]);
|
||||
if (word) return { start: word.from, end: word.to };
|
||||
}
|
||||
let first = clusterIndex;
|
||||
while (first > 0 && categoryAt(source, content, boundaries, first - 1) === category) first -= 1;
|
||||
let last = clusterIndex;
|
||||
while (
|
||||
last < boundaries.length - 2 &&
|
||||
categoryAt(source, content, boundaries, last + 1) === category
|
||||
)
|
||||
last += 1;
|
||||
return { start: boundaries[first], end: boundaries[last + 1] };
|
||||
}
|
||||
|
||||
function sourceText(content: string): SourceText {
|
||||
const cached = sources.get(content);
|
||||
if (cached) {
|
||||
sources.delete(content);
|
||||
sources.set(content, cached);
|
||||
return cached;
|
||||
}
|
||||
const state = EditorState.create({ doc: content });
|
||||
const source: SourceText = {
|
||||
state,
|
||||
boundaries: graphemeBoundaries(content),
|
||||
categorize: state.charCategorizer(0),
|
||||
};
|
||||
sources.set(content, source);
|
||||
if (sources.size > SOURCE_CACHE_LIMIT) {
|
||||
const oldest = sources.keys().next();
|
||||
if (!oldest.done) sources.delete(oldest.value);
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function clusterIndexAt(boundaries: readonly number[], offset: number): number {
|
||||
let low = 0;
|
||||
let high = boundaries.length - 2;
|
||||
while (low < high) {
|
||||
const middle = (low + high + 1) >>> 1;
|
||||
if (boundaries[middle] <= offset) low = middle;
|
||||
else high = middle - 1;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
function categoryAt(
|
||||
source: SourceText,
|
||||
content: string,
|
||||
boundaries: readonly number[],
|
||||
index: number,
|
||||
): CharCategory {
|
||||
return source.categorize(clusterText(content, boundaries, index));
|
||||
}
|
||||
|
||||
function clusterText(content: string, boundaries: readonly number[], index: number): string {
|
||||
return content.slice(boundaries[index], boundaries[index + 1]);
|
||||
}
|
||||
@@ -150,21 +150,3 @@ describe("ACP provider catalog", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("adds bundled goose on capable hosts and uses the ACP config on older hosts", () => {
|
||||
const goose = findProvider("goose");
|
||||
expect(buildAcpProviderConfigPatch(goose, (feature) => feature === "gooseProvider")).toEqual({
|
||||
providers: { goose: { enabled: true } },
|
||||
});
|
||||
expect(buildAcpProviderConfigPatch(goose)).toEqual({
|
||||
providers: {
|
||||
goose: {
|
||||
extends: "acp",
|
||||
label: "goose",
|
||||
description: goose.description,
|
||||
command: ["goose", "acp"],
|
||||
env: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,16 +19,12 @@ export function buildAcpProviderConfigPatch(
|
||||
hostSupports: (feature: HostFeatureName) => boolean = () => false,
|
||||
): MutableDaemonConfigPatch {
|
||||
if (entry.bundledProvider) {
|
||||
const feature = entry.bundledProvider.hostFeature;
|
||||
if (hostSupports(feature)) {
|
||||
return { providers: { [entry.id]: { enabled: true } } };
|
||||
}
|
||||
// COMPAT(gooseProvider): added in v0.17.0, remove after 2027-05-20 once host floor includes the bundled adapter.
|
||||
// COMPAT(hopliteProvider): added after v0.11.2, remove after 2027-04-15 once host floor includes the bundled adapter.
|
||||
// COMPAT(fxProvider): added after v0.15.3, remove after 2027-05-09 once host floor includes the bundled adapter.
|
||||
if (feature !== "gooseProvider") {
|
||||
if (!hostSupports(entry.bundledProvider.hostFeature)) {
|
||||
throw new Error(`Update the host to add ${entry.title}.`);
|
||||
}
|
||||
return { providers: { [entry.id]: { enabled: true } } };
|
||||
}
|
||||
return {
|
||||
providers: {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useCallback } from "react";
|
||||
import { useKeyboardActionHandler } from "@/hooks/use-keyboard-action-handler";
|
||||
import type { KeyboardActionId } from "@/keyboard/keyboard-action-dispatcher";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
import { redirectIfArchivingActiveWorkspace } from "@/utils/sidebar-workspace-archive-redirect";
|
||||
import { useWorkspaceArchive } from "@/workspace/use-workspace-archive";
|
||||
import { isWorkspaceListed, type WorkspaceArchiveTarget } from "@/workspace/workspace-archive";
|
||||
|
||||
const WORKSPACE_ARCHIVE_ACTIONS: readonly KeyboardActionId[] = ["workspace.archive"];
|
||||
|
||||
// The archive shortcut used to live on the sidebar row, so it did nothing whenever the row was not
|
||||
// rendered — a collapsed project or status group, a collapsed Pinned section, or focus mode. Like
|
||||
// the pin shortcut (see use-global-workspace-pin-action.ts), it is one registration keyed on the
|
||||
// active route selection.
|
||||
export function useGlobalWorkspaceArchiveAction() {
|
||||
const selection = useActiveWorkspaceSelection();
|
||||
const serverId = selection?.serverId ?? null;
|
||||
const routeWorkspaceId = selection?.workspaceId ?? null;
|
||||
// `id` is the descriptor id, not the route id; see use-global-workspace-pin-action.ts.
|
||||
const fields = useWorkspaceFields(serverId, routeWorkspaceId, (workspace) => ({
|
||||
id: workspace.id,
|
||||
workspaceKind: workspace.workspaceKind,
|
||||
workspaceDirectory: workspace.workspaceDirectory,
|
||||
name: workspace.name,
|
||||
archivingAt: workspace.archivingAt,
|
||||
diffStat: workspace.diffStat,
|
||||
}));
|
||||
|
||||
// useWorkspaceArchive calls the latest render's callback, so `activeWorkspaceId` is whatever is
|
||||
// routed when the archive starts, after any confirmation. It is the descriptor id, which is what
|
||||
// the redirect compares against.
|
||||
const activeWorkspaceId = fields?.id ?? null;
|
||||
const redirectAfterArchive = useCallback(
|
||||
(workspace: WorkspaceArchiveTarget) => {
|
||||
redirectIfArchivingActiveWorkspace({
|
||||
...workspace,
|
||||
activeWorkspaceSelection:
|
||||
serverId && activeWorkspaceId ? { serverId, workspaceId: activeWorkspaceId } : null,
|
||||
});
|
||||
},
|
||||
[activeWorkspaceId, serverId],
|
||||
);
|
||||
|
||||
const archiveController = useWorkspaceArchive({
|
||||
serverId: serverId ?? "",
|
||||
workspaceId: fields?.id ?? "",
|
||||
workspaceKind: fields?.workspaceKind ?? "directory",
|
||||
workspaceDirectory: fields?.workspaceDirectory ?? "",
|
||||
name: fields?.name ?? "",
|
||||
diffStat: fields?.diffStat,
|
||||
onArchiveStarted: redirectAfterArchive,
|
||||
});
|
||||
|
||||
const canArchive = fields !== null && fields.archivingAt === null;
|
||||
|
||||
const handle = useCallback(() => {
|
||||
if (!canArchive || !serverId) {
|
||||
return false;
|
||||
}
|
||||
// Archiving hides its target immediately. Read the store in case the shortcut
|
||||
// runs again before React renders that update.
|
||||
if (!isWorkspaceListed({ serverId, workspaceId: fields.id })) {
|
||||
return false;
|
||||
}
|
||||
archiveController.archive();
|
||||
return true;
|
||||
}, [archiveController, canArchive, fields, serverId]);
|
||||
|
||||
useKeyboardActionHandler({
|
||||
handlerId: "workspace-archive-global",
|
||||
actions: WORKSPACE_ARCHIVE_ACTIONS,
|
||||
enabled: canArchive,
|
||||
priority: 0,
|
||||
handle,
|
||||
});
|
||||
}
|
||||
@@ -2323,9 +2323,6 @@ export const ar: TranslationResources = {
|
||||
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}، {{time}}",
|
||||
projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين",
|
||||
limitReached: "تم بلوغ الحد",
|
||||
mayHaveRunOut: "ربما نفدت الحصة",
|
||||
runsOutNow: "ينفد الآن",
|
||||
runsOutIn: "ينفد خلال {{duration}}",
|
||||
justNow: "الآن",
|
||||
@@ -2895,8 +2892,7 @@ export const ar: TranslationResources = {
|
||||
updateAvailable: "التحديث متاح",
|
||||
updateTitle: "تحديث مهارات Paseo ؟",
|
||||
uninstallTitle: "إلغاء تثبيت مهارات Paseo ؟",
|
||||
uninstallMessage:
|
||||
"يزيل جميع مهارات تنسيق Paseo من ~/.agents و~/.claude و~/.codex و~/.gemini/config.",
|
||||
uninstallMessage: "يزيل جميع مهارات تنسيق Paseo من ~/.agents ، ~/.claude ، ~/.codex.",
|
||||
choose: "اختيار المهارات",
|
||||
chooseAll: "كل المهارات",
|
||||
chooseAllHint: "أبقِ جميع المهارات المرفقة مثبتة، بما فيها ما يُضاف لاحقًا.",
|
||||
@@ -2904,7 +2900,7 @@ export const ar: TranslationResources = {
|
||||
chooseEmpty: "لا تتضمن هذه النسخة أي مهارات.",
|
||||
removeTitle: "إزالة المهارات غير المحددة؟",
|
||||
removeMessage:
|
||||
"سيتم حذف {{skills}} من ~/.agents و~/.claude و~/.codex و~/.gemini/config. كما يُحذف كل ما أضفته داخل مجلدات المهارات تلك.",
|
||||
"سيتم حذف {{skills}} من ~/.agents و~/.claude و~/.codex. كما يُحذف كل ما أضفته داخل مجلدات المهارات تلك.",
|
||||
saveFailed: "تعذر حفظ اختيار المهارات.",
|
||||
statusFailed: "غير قادر على التحقق من حالة مهارات التنسيق.",
|
||||
updateFailed: "غير قادر على تحديث مهارات التنسيق.",
|
||||
|
||||
@@ -2333,9 +2333,6 @@ export const en = {
|
||||
resetsIn: "resets in {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} left at reset",
|
||||
limitReached: "Limit reached",
|
||||
mayHaveRunOut: "May have run out",
|
||||
runsOutNow: "runs out now",
|
||||
runsOutIn: "runs out in {{duration}}",
|
||||
justNow: "just now",
|
||||
@@ -2997,7 +2994,7 @@ export const en = {
|
||||
updateTitle: "Update Paseo skills?",
|
||||
uninstallTitle: "Uninstall Paseo skills?",
|
||||
uninstallMessage:
|
||||
"Removes all Paseo orchestration skills from ~/.agents, ~/.claude, ~/.codex, and ~/.gemini/config on this host.",
|
||||
"Removes all Paseo orchestration skills from ~/.agents, ~/.claude, ~/.codex on this host.",
|
||||
choose: "Choose skills",
|
||||
chooseAll: "All skills",
|
||||
chooseAllHint: "Keep every bundled skill installed, including ones added later.",
|
||||
@@ -3005,7 +3002,7 @@ export const en = {
|
||||
chooseEmpty: "This host bundles no skills.",
|
||||
removeTitle: "Remove deselected skills?",
|
||||
removeMessage:
|
||||
"{{skills}} will be deleted from ~/.agents, ~/.claude, ~/.codex, and ~/.gemini/config on this host. Anything you added inside those skill folders is deleted too.",
|
||||
"{{skills}} will be deleted from ~/.agents, ~/.claude, and ~/.codex on this host. Anything you added inside those skill folders is deleted too.",
|
||||
saveFailed: "Could not save your skill selection.",
|
||||
actions: {
|
||||
update: "Update",
|
||||
|
||||
@@ -2354,9 +2354,6 @@ export const es: TranslationResources = {
|
||||
resetsIn: "se restablece en {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} restante al restablecerse",
|
||||
limitReached: "Límite alcanzado",
|
||||
mayHaveRunOut: "Puede que ya se haya agotado",
|
||||
runsOutNow: "se agota ahora",
|
||||
runsOutIn: "se agota en {{duration}}",
|
||||
justNow: "ahora mismo",
|
||||
@@ -2919,7 +2916,7 @@ export const es: TranslationResources = {
|
||||
updateTitle: "¿Actualizar las habilidades dePaseo?",
|
||||
uninstallTitle: "¿Desinstalar las habilidadesPaseo?",
|
||||
uninstallMessage:
|
||||
"Elimina todas las habilidades de orquestación Paseo de ~/.agents, ~/.claude, ~/.codex y ~/.gemini/config.",
|
||||
"Elimina todas las habilidades de orquestaciónPaseode ~/.agents, ~/.claude, ~/.codex.",
|
||||
choose: "Elegir habilidades",
|
||||
chooseAll: "Todas las habilidades",
|
||||
chooseAllHint:
|
||||
@@ -2928,7 +2925,7 @@ export const es: TranslationResources = {
|
||||
chooseEmpty: "Esta versión no incluye habilidades.",
|
||||
removeTitle: "¿Eliminar las habilidades deseleccionadas?",
|
||||
removeMessage:
|
||||
"{{skills}} se eliminarán de ~/.agents, ~/.claude, ~/.codex y ~/.gemini/config. También se elimina todo lo que hayas añadido dentro de esas carpetas de habilidades.",
|
||||
"{{skills}} se eliminarán de ~/.agents, ~/.claude y ~/.codex. También se elimina todo lo que hayas añadido dentro de esas carpetas de habilidades.",
|
||||
saveFailed: "No se pudo guardar tu selección de habilidades.",
|
||||
statusFailed: "No se puede comprobar el estado de las habilidades de orquestación.",
|
||||
updateFailed: "No se pueden actualizar las habilidades de orquestación.",
|
||||
|
||||
@@ -2355,9 +2355,6 @@ export const fr: TranslationResources = {
|
||||
resetsIn: "se réinitialise dans {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} restant à la réinitialisation",
|
||||
limitReached: "Limite atteinte",
|
||||
mayHaveRunOut: "Le quota est peut-être épuisé",
|
||||
runsOutNow: "s’épuise maintenant",
|
||||
runsOutIn: "s’épuise dans {{duration}}",
|
||||
justNow: "à l’instant",
|
||||
@@ -2922,7 +2919,7 @@ export const fr: TranslationResources = {
|
||||
updateTitle: "Mettre à jour les skills Paseo ?",
|
||||
uninstallTitle: "Désinstaller les skills Paseo ?",
|
||||
uninstallMessage:
|
||||
"Supprime tous les skills d’orchestration Paseo de ~/.agents, ~/.claude, ~/.codex et ~/.gemini/config sur cet hôte.",
|
||||
"Supprime tous les skills d’orchestration Paseo de ~/.agents, ~/.claude et ~/.codex sur cet hôte.",
|
||||
choose: "Choisir les skills",
|
||||
chooseAll: "Tous les skills",
|
||||
chooseAllHint:
|
||||
@@ -2931,7 +2928,7 @@ export const fr: TranslationResources = {
|
||||
chooseEmpty: "Cet hôte ne fournit aucun skill.",
|
||||
removeTitle: "Supprimer les skills décochés ?",
|
||||
removeMessage:
|
||||
"{{skills}} seront supprimés de ~/.agents, ~/.claude, ~/.codex et ~/.gemini/config sur cet hôte. Tout ce que vous avez ajouté dans ces dossiers de skills sera également supprimé.",
|
||||
"{{skills}} seront supprimés de ~/.agents, ~/.claude et ~/.codex sur cet hôte. Tout ce que vous avez ajouté dans ces dossiers de skills sera également supprimé.",
|
||||
saveFailed: "Impossible d’enregistrer votre sélection de skills.",
|
||||
statusFailed: "Impossible de vérifier l’état des skills d’orchestration.",
|
||||
updateFailed: "Impossible de mettre à jour les skills d’orchestration.",
|
||||
|
||||
@@ -2328,9 +2328,6 @@ export const ja: TranslationResources = {
|
||||
resetsIn: "{{duration}}後にリセット",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み",
|
||||
limitReached: "上限に達しました",
|
||||
mayHaveRunOut: "上限に達した可能性があります",
|
||||
runsOutNow: "まもなく上限に到達",
|
||||
runsOutIn: "{{duration}}後に上限に到達",
|
||||
justNow: "たった今",
|
||||
@@ -2887,7 +2884,7 @@ export const ja: TranslationResources = {
|
||||
updateTitle: "Paseoスキルを更新しますか?",
|
||||
uninstallTitle: "Paseoスキルをアンインストールしますか?",
|
||||
uninstallMessage:
|
||||
"~/.agents、~/.claude、~/.codex、~/.gemini/configからすべてのPaseoオーケストレーションスキルを削除します。",
|
||||
"~/.agents、~/.claude、~/.codexからすべてのPaseoオーケストレーションスキルを削除します。",
|
||||
choose: "スキルを選択",
|
||||
chooseAll: "すべてのスキル",
|
||||
chooseAllHint:
|
||||
@@ -2896,7 +2893,7 @@ export const ja: TranslationResources = {
|
||||
chooseEmpty: "このビルドにはスキルが含まれていません。",
|
||||
removeTitle: "選択を外したスキルを削除しますか?",
|
||||
removeMessage:
|
||||
"{{skills}} を ~/.agents、~/.claude、~/.codex、~/.gemini/config から削除します。それらのスキルフォルダー内に追加したものもすべて削除されます。",
|
||||
"{{skills}} を ~/.agents、~/.claude、~/.codex から削除します。それらのスキルフォルダー内に追加したものもすべて削除されます。",
|
||||
saveFailed: "スキルの選択を保存できませんでした。",
|
||||
statusFailed: "オーケストレーションスキルのステータスを確認できません。",
|
||||
updateFailed: "オーケストレーションスキルを更新できません。",
|
||||
|
||||
@@ -2316,9 +2316,6 @@ export const ko: TranslationResources = {
|
||||
resetsIn: "{{duration}} 후 재설정",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정",
|
||||
limitReached: "한도에 도달함",
|
||||
mayHaveRunOut: "한도를 소진했을 수 있음",
|
||||
runsOutNow: "지금 한도에 도달",
|
||||
runsOutIn: "{{duration}} 후 한도에 도달",
|
||||
justNow: "방금",
|
||||
@@ -2874,7 +2871,7 @@ export const ko: TranslationResources = {
|
||||
updateTitle: "Paseo 스킬을 업데이트할까요?",
|
||||
uninstallTitle: "Paseo 스킬을 제거할까요?",
|
||||
uninstallMessage:
|
||||
"~/.agents, ~/.claude, ~/.codex, ~/.gemini/config에서 모든 Paseo 오케스트레이션 스킬을 제거합니다.",
|
||||
"~/.agents, ~/.claude, ~/.codex에서 모든 Paseo 오케스트레이션 스킬을 제거합니다.",
|
||||
choose: "스킬 선택",
|
||||
chooseAll: "모든 스킬",
|
||||
chooseAllHint: "나중에 추가되는 항목을 포함하여 모든 번들 스킬을 설치된 상태로 유지합니다.",
|
||||
@@ -2882,7 +2879,7 @@ export const ko: TranslationResources = {
|
||||
chooseEmpty: "이 빌드에는 번들 스킬이 없습니다.",
|
||||
removeTitle: "선택 해제한 스킬을 제거할까요?",
|
||||
removeMessage:
|
||||
"{{skills}}는 ~/.agents, ~/.claude, ~/.codex 및 ~/.gemini/config에서 삭제됩니다. 해당 스킬 폴더 안에 추가한 모든 항목도 삭제됩니다.",
|
||||
"{{skills}}는 ~/.agents, ~/.claude 및 ~/.codex에서 삭제됩니다. 해당 스킬 폴더 안에 추가한 모든 항목도 삭제됩니다.",
|
||||
saveFailed: "선택한 스킬을 저장하지 못했습니다.",
|
||||
statusFailed: "오케스트레이션 스킬 상태를 확인할 수 없습니다.",
|
||||
updateFailed: "오케스트레이션 스킬을 업데이트할 수 없습니다.",
|
||||
|
||||
@@ -2339,9 +2339,6 @@ export const ptBR: TranslationResources = {
|
||||
resetsIn: "redefine em {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "~{{percentage}} restará na renovação",
|
||||
limitReached: "Limite atingido",
|
||||
mayHaveRunOut: "A cota pode ter se esgotado",
|
||||
runsOutNow: "esgota agora",
|
||||
runsOutIn: "esgota em {{duration}}",
|
||||
justNow: "agora mesmo",
|
||||
@@ -2900,7 +2897,7 @@ export const ptBR: TranslationResources = {
|
||||
updateTitle: "Atualizar Paseo skills?",
|
||||
uninstallTitle: "Desinstalar Paseo skills?",
|
||||
uninstallMessage:
|
||||
"Remove todas as skills de orquestração do Paseo de ~/.agents, ~/.claude, ~/.codex e ~/.gemini/config.",
|
||||
"Remove todas as skills de orquestração do Paseo de ~/.agents, ~/.claude e ~/.codex.",
|
||||
choose: "Escolher skills",
|
||||
chooseAll: "Todas as skills",
|
||||
chooseAllHint:
|
||||
@@ -2909,7 +2906,7 @@ export const ptBR: TranslationResources = {
|
||||
chooseEmpty: "Esta versão não inclui skills.",
|
||||
removeTitle: "Remover as skills desmarcadas?",
|
||||
removeMessage:
|
||||
"{{skills}} serão excluídas de ~/.agents, ~/.claude, ~/.codex e ~/.gemini/config. Tudo o que você adicionou dentro dessas pastas de skills também é excluído.",
|
||||
"{{skills}} serão excluídas de ~/.agents, ~/.claude e ~/.codex. Tudo o que você adicionou dentro dessas pastas de skills também é excluído.",
|
||||
saveFailed: "Não foi possível salvar sua seleção de skills.",
|
||||
statusFailed: "Não foi possível verificar o status das skills de orquestração.",
|
||||
updateFailed: "Não foi possível atualizar as skills de orquestração.",
|
||||
|
||||
@@ -2341,9 +2341,6 @@ export const ru: TranslationResources = {
|
||||
resetsIn: "сброс через {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "К сбросу останется ~{{percentage}}",
|
||||
limitReached: "Лимит исчерпан",
|
||||
mayHaveRunOut: "Лимит мог уже исчерпаться",
|
||||
runsOutNow: "закончится сейчас",
|
||||
runsOutIn: "закончится через {{duration}}",
|
||||
justNow: "только что",
|
||||
@@ -2912,7 +2909,7 @@ export const ru: TranslationResources = {
|
||||
updateTitle: "Обновить навыки Paseo?",
|
||||
uninstallTitle: "Удалить навыки Paseo?",
|
||||
uninstallMessage:
|
||||
"Удаляет все навыки оркестрации Paseo из ~/.agents, ~/.claude, ~/.codex и ~/.gemini/config на этом хосте.",
|
||||
"Удаляет все навыки оркестрации Paseo из ~/.agents, ~/.claude и ~/.codex на этом хосте.",
|
||||
choose: "Выбрать навыки",
|
||||
chooseAll: "Все навыки",
|
||||
chooseAllHint: "Устанавливать все встроенные навыки, включая добавленные позже.",
|
||||
@@ -2920,7 +2917,7 @@ export const ru: TranslationResources = {
|
||||
chooseEmpty: "На этом хосте нет встроенных навыков.",
|
||||
removeTitle: "Удалить снятые навыки?",
|
||||
removeMessage:
|
||||
"{{skills}} будут удалены из ~/.agents, ~/.claude, ~/.codex и ~/.gemini/config на этом хосте. Всё, что вы добавили в эти папки навыков, тоже будет удалено.",
|
||||
"{{skills}} будут удалены из ~/.agents, ~/.claude и ~/.codex на этом хосте. Всё, что вы добавили в эти папки навыков, тоже будет удалено.",
|
||||
saveFailed: "Не удалось сохранить выбор навыков.",
|
||||
statusFailed: "Не удалось проверить состояние навыков оркестрации.",
|
||||
updateFailed: "Не удалось обновить навыки оркестрации.",
|
||||
|
||||
@@ -2282,9 +2282,6 @@ export const zhCN: TranslationResources = {
|
||||
resetsIn: "将在 {{duration}}后重置",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "重置时约剩余 {{percentage}}",
|
||||
limitReached: "已达到上限",
|
||||
mayHaveRunOut: "额度可能已用完",
|
||||
runsOutNow: "即将用尽",
|
||||
runsOutIn: "将在 {{duration}}后用尽",
|
||||
justNow: "刚刚",
|
||||
@@ -2829,8 +2826,7 @@ export const zhCN: TranslationResources = {
|
||||
updateAvailable: "有更新可用",
|
||||
updateTitle: "更新 Paseo skills?",
|
||||
uninstallTitle: "卸载 Paseo skills?",
|
||||
uninstallMessage:
|
||||
"会从 ~/.agents、~/.claude、~/.codex、~/.gemini/config 移除所有 Paseo 编排 skills。",
|
||||
uninstallMessage: "会从 ~/.agents、~/.claude、~/.codex 移除所有 Paseo 编排 skills。",
|
||||
choose: "选择 skills",
|
||||
chooseAll: "全部 skills",
|
||||
chooseAllHint: "保持安装所有内置 skills,包括以后新增的。",
|
||||
@@ -2838,7 +2834,7 @@ export const zhCN: TranslationResources = {
|
||||
chooseEmpty: "此版本未内置 skills。",
|
||||
removeTitle: "移除取消勾选的 skills?",
|
||||
removeMessage:
|
||||
"将从 ~/.agents、~/.claude、~/.codex、~/.gemini/config 中删除 {{skills}}。你在这些 skill 文件夹里添加的内容也会一并删除。",
|
||||
"将从 ~/.agents、~/.claude、~/.codex 中删除 {{skills}}。你在这些 skill 文件夹里添加的内容也会一并删除。",
|
||||
saveFailed: "无法保存你的 skills 选择。",
|
||||
statusFailed: "无法检查编排 skills 状态。",
|
||||
updateFailed: "无法更新编排 skills。",
|
||||
|
||||
@@ -22,7 +22,6 @@ import { shallow, useShallow } from "zustand/shallow";
|
||||
import { useStoreWithEqualityFn } from "zustand/traditional";
|
||||
import { useAgentStreamTail } from "@/agent-stream/use-agent-stream-tail";
|
||||
import { AgentStreamView, type AgentStreamViewHandle } from "@/agent-stream/view";
|
||||
import { CHAT_COLUMN_RAIL_DATASET, ChatColumnRailSurface } from "@/chat-rail";
|
||||
import { ArchivedAgentCallout } from "@/components/archived-agent-callout";
|
||||
import { ComposerDock } from "@/composer/dock";
|
||||
import { FileDropZone } from "@/components/file-drop/file-drop-zone";
|
||||
@@ -1268,11 +1267,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
);
|
||||
|
||||
const dock = (
|
||||
<ChatSurface
|
||||
serverId={serverId}
|
||||
disabled={isArchivingCurrentAgent}
|
||||
fullscreen={isComposerFullscreen}
|
||||
>
|
||||
<ChatSurface disabled={isArchivingCurrentAgent} fullscreen={isComposerFullscreen}>
|
||||
{dockContent}
|
||||
{composerSection}
|
||||
{dockOverlay}
|
||||
@@ -1342,12 +1337,10 @@ function wrapAgentCommandProvider({
|
||||
}
|
||||
|
||||
function ChatSurface({
|
||||
serverId,
|
||||
children,
|
||||
disabled,
|
||||
fullscreen,
|
||||
}: {
|
||||
serverId: string;
|
||||
children: [ReactNode, ReactNode, ReactNode];
|
||||
disabled: boolean;
|
||||
fullscreen: boolean;
|
||||
@@ -1356,11 +1349,9 @@ function ChatSurface({
|
||||
// closes everything the chat opened.
|
||||
return (
|
||||
<OverlayDismissalScope>
|
||||
<ChatColumnRailSurface serverId={serverId}>
|
||||
<FileDropZone style={styles.container} disabled={disabled}>
|
||||
<ComposerDock fullscreen={fullscreen}>{children}</ComposerDock>
|
||||
</FileDropZone>
|
||||
</ChatColumnRailSurface>
|
||||
<FileDropZone style={styles.container} disabled={disabled}>
|
||||
<ComposerDock fullscreen={fullscreen}>{children}</ComposerDock>
|
||||
</FileDropZone>
|
||||
</OverlayDismissalScope>
|
||||
);
|
||||
}
|
||||
@@ -1374,7 +1365,7 @@ function TimelineSyncErrorCallout({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.timelineSyncCalloutRail} dataSet={CHAT_COLUMN_RAIL_DATASET}>
|
||||
<View style={styles.timelineSyncCalloutRail}>
|
||||
<View style={styles.timelineSyncCalloutContent}>
|
||||
<View style={styles.timelineSyncCallout} testID="agent-timeline-sync-error">
|
||||
<Text style={styles.timelineSyncCalloutText}>
|
||||
|
||||
@@ -1,39 +1,24 @@
|
||||
import type { PluginSurfaceProps } from "@getpaseo/plugin/client";
|
||||
import type { NavigateToWorkspaceInput } from "@/stores/navigation-active-workspace-store";
|
||||
import { parseServerIdFromPathname } from "@/utils/host-routes";
|
||||
import { isHttpUrl } from "@/utils/http-url";
|
||||
|
||||
interface HostNavigationOwner {
|
||||
browserAvailable: boolean;
|
||||
isHostRegistered(serverId: string): boolean;
|
||||
openAgent(input: { serverId: string; agentId: string }): string;
|
||||
openWorkspace(input: NavigateToWorkspaceInput): string;
|
||||
openAgent(input: { serverId: string; agentId: string }): void;
|
||||
openWorkspace(input: NavigateToWorkspaceInput): void;
|
||||
resolveWorkspace(input: { serverId: string; workspaceId: string }): string | null;
|
||||
createBrowser(input: { initialUrl: string }): { browserId: string };
|
||||
focusHost(serverId: string): void;
|
||||
}
|
||||
|
||||
export function createPluginHostNavigation(
|
||||
serverId: string,
|
||||
owner: HostNavigationOwner,
|
||||
): NonNullable<PluginSurfaceProps["navigation"]> {
|
||||
const focusRouteHost = (route: string) => {
|
||||
const destinationServerId = parseServerIdFromPathname(route);
|
||||
if (destinationServerId && owner.isHostRegistered(destinationServerId)) {
|
||||
owner.focusHost(destinationServerId);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
supportsFocusHost: true,
|
||||
openAgent: ({ agentId, serverId: targetServerId, focusHost }) => {
|
||||
const route = owner.openAgent({ serverId: targetServerId ?? serverId, agentId });
|
||||
if (focusHost) focusRouteHost(route);
|
||||
},
|
||||
openWorkspace: ({ workspaceId, serverId: targetServerId, focusHost }) => {
|
||||
const route = owner.openWorkspace({ serverId: targetServerId ?? serverId, workspaceId });
|
||||
if (focusHost) focusRouteHost(route);
|
||||
},
|
||||
openAgent: ({ agentId, serverId: targetServerId }) =>
|
||||
owner.openAgent({ serverId: targetServerId ?? serverId, agentId }),
|
||||
openWorkspace: ({ workspaceId, serverId: targetServerId }) =>
|
||||
owner.openWorkspace({ serverId: targetServerId ?? serverId, workspaceId }),
|
||||
openBrowser: owner.browserAvailable
|
||||
? ({ url, workspaceId, serverId: targetServerId }) => {
|
||||
if (!isHttpUrl(url)) throw new Error("Only absolute HTTP(S) URLs are supported.");
|
||||
|
||||
@@ -1,58 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildHostAgentDetailRoute, buildHostWorkspaceRoute } from "@/utils/host-routes";
|
||||
import { createPluginHostNavigation } from "./host-navigation-model";
|
||||
import { useSidebarViewStore } from "../stores/sidebar-view-store";
|
||||
|
||||
describe("plugin host navigation", () => {
|
||||
function setup(electron = true) {
|
||||
const destinations: unknown[] = [];
|
||||
const browsers: string[] = [];
|
||||
const focusedHosts: string[] = [];
|
||||
const workspaces = new Set(["selected:one", "remote:two"]);
|
||||
const navigation = createPluginHostNavigation("selected", {
|
||||
browserAvailable: electron,
|
||||
isHostRegistered: (serverId: string) => serverId === "selected" || serverId === "remote",
|
||||
resolveWorkspace: ({ serverId, workspaceId }) =>
|
||||
workspaces.has(`${serverId}:${workspaceId}`) ? workspaceId : null,
|
||||
openAgent: (input) => {
|
||||
destinations.push(input);
|
||||
return buildHostAgentDetailRoute(input.serverId, input.agentId);
|
||||
},
|
||||
openWorkspace: (input) => {
|
||||
destinations.push(input);
|
||||
return buildHostWorkspaceRoute(input.serverId, input.workspaceId);
|
||||
},
|
||||
focusHost: (serverId) => {
|
||||
focusedHosts.push(serverId);
|
||||
useSidebarViewStore.getState().focusHost(serverId);
|
||||
},
|
||||
openAgent: (input) => destinations.push(input),
|
||||
openWorkspace: (input) => destinations.push(input),
|
||||
createBrowser: ({ initialUrl }) => {
|
||||
browsers.push(initialUrl);
|
||||
return { browserId: `browser-${browsers.length}` };
|
||||
},
|
||||
});
|
||||
return { navigation, destinations, browsers, workspaces, focusedHosts };
|
||||
return { navigation, destinations, browsers, workspaces };
|
||||
}
|
||||
|
||||
it("focuses the destination host and clears filters that could hide its workspace", () => {
|
||||
useSidebarViewStore.setState({
|
||||
groupMode: "status",
|
||||
hostFilters: ["selected", "other"],
|
||||
projectFilters: ["old-project"],
|
||||
labelFilter: { labels: ["urgent"] },
|
||||
});
|
||||
const { navigation, destinations, focusedHosts } = setup(false);
|
||||
navigation.openAgent({ serverId: "remote", agentId: "agent-2", focusHost: true });
|
||||
expect(focusedHosts).toEqual(["remote"]);
|
||||
expect(destinations).toEqual([{ serverId: "remote", agentId: "agent-2" }]);
|
||||
expect(useSidebarViewStore.getState()).toMatchObject({
|
||||
groupMode: "status",
|
||||
hostFilters: ["remote"],
|
||||
projectFilters: [],
|
||||
labelFilter: { labels: [] },
|
||||
});
|
||||
});
|
||||
|
||||
it("creates and focuses a local browser in the selected or explicit host workspace", () => {
|
||||
const { navigation, destinations, browsers } = setup();
|
||||
navigation.openBrowser!({ url: "https://example.com/one", workspaceId: "one" });
|
||||
@@ -76,110 +43,6 @@ describe("plugin host navigation", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("can return from a remote workspace to the installation host without toggling it off", () => {
|
||||
const { navigation, destinations, focusedHosts } = setup();
|
||||
navigation.openWorkspace({ serverId: "remote", workspaceId: "two", focusHost: true });
|
||||
navigation.openWorkspace({ workspaceId: "one", focusHost: true });
|
||||
navigation.openWorkspace({ workspaceId: "one", focusHost: true });
|
||||
expect(focusedHosts).toEqual(["remote", "selected", "selected"]);
|
||||
expect(destinations).toEqual([
|
||||
{ serverId: "remote", workspaceId: "two" },
|
||||
{ serverId: "selected", workspaceId: "one" },
|
||||
{ serverId: "selected", workspaceId: "one" },
|
||||
]);
|
||||
expect(useSidebarViewStore.getState().hostFilters).toEqual(["selected"]);
|
||||
});
|
||||
|
||||
it("focuses the host in the returned route for padded host IDs", () => {
|
||||
const { navigation, destinations, focusedHosts } = setup();
|
||||
navigation.openAgent({ serverId: " remote ", agentId: "agent-2", focusHost: true });
|
||||
navigation.openWorkspace({ serverId: " selected ", workspaceId: "one", focusHost: true });
|
||||
|
||||
expect(destinations).toEqual([
|
||||
{ serverId: " remote ", agentId: "agent-2" },
|
||||
{ serverId: " selected ", workspaceId: "one" },
|
||||
]);
|
||||
expect(focusedHosts).toEqual(["remote", "selected"]);
|
||||
expect(useSidebarViewStore.getState().hostFilters).toEqual(["selected"]);
|
||||
});
|
||||
|
||||
it("leaves existing sidebar filters alone unless explicitly requested", () => {
|
||||
useSidebarViewStore.setState({
|
||||
hostFilters: ["remote"],
|
||||
projectFilters: ["pinned-project"],
|
||||
labelFilter: { labels: ["urgent"] },
|
||||
});
|
||||
const { navigation, destinations, focusedHosts } = setup();
|
||||
navigation.openAgent({ agentId: "agent-1", serverId: " remote " });
|
||||
navigation.openWorkspace({ workspaceId: "one", serverId: " selected ", focusHost: false });
|
||||
expect(destinations).toEqual([
|
||||
{ serverId: " remote ", agentId: "agent-1" },
|
||||
{ serverId: " selected ", workspaceId: "one" },
|
||||
]);
|
||||
expect(focusedHosts).toEqual([]);
|
||||
expect(useSidebarViewStore.getState()).toMatchObject({
|
||||
hostFilters: ["remote"],
|
||||
projectFilters: ["pinned-project"],
|
||||
labelFilter: { labels: ["urgent"] },
|
||||
});
|
||||
expect(navigation.supportsFocusHost).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves sidebar filters when the navigation route has no destination", () => {
|
||||
const filters = {
|
||||
hostFilters: ["selected"],
|
||||
projectFilters: ["pinned-project"],
|
||||
labelFilter: { labels: ["urgent"] },
|
||||
};
|
||||
useSidebarViewStore.setState(filters);
|
||||
const { navigation } = setup();
|
||||
navigation.openAgent({ serverId: "remote", agentId: " ", focusHost: true });
|
||||
navigation.openWorkspace({ serverId: "remote", workspaceId: "", focusHost: true });
|
||||
|
||||
expect(useSidebarViewStore.getState()).toMatchObject(filters);
|
||||
});
|
||||
|
||||
it("preserves sidebar filters when the destination host has been removed", () => {
|
||||
const filters = {
|
||||
hostFilters: ["selected"],
|
||||
projectFilters: ["pinned-project"],
|
||||
labelFilter: { labels: ["urgent"] },
|
||||
};
|
||||
useSidebarViewStore.setState(filters);
|
||||
const { navigation, destinations } = setup();
|
||||
navigation.openAgent({ serverId: "removed", agentId: "agent-2", focusHost: true });
|
||||
navigation.openWorkspace({ serverId: "removed", workspaceId: "two", focusHost: true });
|
||||
|
||||
expect(useSidebarViewStore.getState()).toMatchObject(filters);
|
||||
expect(destinations).toEqual([
|
||||
{ serverId: "removed", agentId: "agent-2" },
|
||||
{ serverId: "removed", workspaceId: "two" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not change the filter when navigation rejects the target", () => {
|
||||
const focusedHosts: string[] = [];
|
||||
const unavailable = () => {
|
||||
throw new Error("Target unavailable");
|
||||
};
|
||||
const navigation = createPluginHostNavigation("selected", {
|
||||
browserAvailable: false,
|
||||
isHostRegistered: () => true,
|
||||
resolveWorkspace: () => null,
|
||||
openAgent: unavailable,
|
||||
openWorkspace: unavailable,
|
||||
createBrowser: unavailable,
|
||||
focusHost: (serverId) => focusedHosts.push(serverId),
|
||||
});
|
||||
expect(() => navigation.openAgent({ agentId: "missing", focusHost: true })).toThrow(
|
||||
"Target unavailable",
|
||||
);
|
||||
expect(() => navigation.openWorkspace({ workspaceId: "missing", focusHost: true })).toThrow(
|
||||
"Target unavailable",
|
||||
);
|
||||
expect(focusedHosts).toEqual([]);
|
||||
});
|
||||
|
||||
it("refuses unknown or removed workspaces before creating browser records", () => {
|
||||
const { navigation, destinations, browsers, workspaces } = setup();
|
||||
expect(() =>
|
||||
|
||||
@@ -4,12 +4,10 @@ import { resolveWorkspaceMapKeyByIdentity } from "@/utils/workspace-identity";
|
||||
import { useMemo } from "react";
|
||||
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
|
||||
import { navigateToAgent } from "@/utils/navigate-to-agent";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { createWorkspaceBrowser } from "@/desktop/browser/store";
|
||||
import { createPluginHostNavigation } from "./host-navigation-model";
|
||||
import { useSidebarViewStore } from "@/stores/sidebar-view-store";
|
||||
|
||||
export function usePluginHostNavigation(
|
||||
serverId: string,
|
||||
@@ -18,14 +16,9 @@ export function usePluginHostNavigation(
|
||||
() =>
|
||||
createPluginHostNavigation(serverId, {
|
||||
browserAvailable: getIsElectron(),
|
||||
isHostRegistered: (targetServerId) =>
|
||||
getHostRuntimeStore()
|
||||
.getHosts()
|
||||
.some((host) => host.serverId === targetServerId),
|
||||
openAgent: navigateToAgent,
|
||||
openWorkspace: navigateToWorkspace,
|
||||
createBrowser: createWorkspaceBrowser,
|
||||
focusHost: (targetServerId) => useSidebarViewStore.getState().focusHost(targetServerId),
|
||||
resolveWorkspace: ({ serverId: targetServerId, workspaceId }) =>
|
||||
resolveWorkspaceMapKeyByIdentity({
|
||||
workspaces: useSessionStore.getState().sessions[targetServerId]?.workspaces,
|
||||
|
||||
@@ -20,6 +20,8 @@ afterEach(async () => {
|
||||
await act(async () => root.render(null));
|
||||
usePanelStore.setState(initialPanel, true);
|
||||
});
|
||||
const noop = () => {};
|
||||
const explorerState = { expanded: false };
|
||||
const geometry: WindowLayout = {
|
||||
bounds: { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight },
|
||||
verticalBarEdge: "trailing",
|
||||
@@ -40,8 +42,9 @@ it("updates compact header actions on panel changes without rendering the worksp
|
||||
title="Workspace"
|
||||
subtitle="Project"
|
||||
isSubtitleDistinct
|
||||
explorerAction={null}
|
||||
inDesktopTitlebar={false}
|
||||
onToggleExplorer={noop}
|
||||
explorerToggleLabel="Explorer"
|
||||
explorerToggleAccessibilityState={explorerState}
|
||||
tabSwitcher={null}
|
||||
headerVariant="full"
|
||||
>
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { Fragment, useMemo, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { usePanelStore } from "@/stores/panel-store";
|
||||
import { CompactHeader } from "@/components/headers/compact-header";
|
||||
import {
|
||||
EXPLORER_TOGGLE_KEYS,
|
||||
WorkspaceExplorerToggle,
|
||||
} from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import { WorkspaceHeaderProjectRow } from "@/screens/workspace/workspace-header-project-row";
|
||||
import {
|
||||
useWindowLayout,
|
||||
@@ -18,9 +23,10 @@ interface CompactWorkspaceHeaderProps {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
isSubtitleDistinct: boolean;
|
||||
explorerAction: ReactNode;
|
||||
onToggleExplorer: () => void;
|
||||
explorerToggleLabel: string;
|
||||
explorerToggleAccessibilityState: { expanded: boolean };
|
||||
tabSwitcher: ReactNode;
|
||||
inDesktopTitlebar: boolean;
|
||||
/** Workspace overflow menu. */
|
||||
children: ReactNode;
|
||||
headerVariant: "compact" | "full";
|
||||
@@ -34,15 +40,17 @@ export function CompactWorkspaceHeader({
|
||||
title,
|
||||
subtitle,
|
||||
isSubtitleDistinct,
|
||||
explorerAction,
|
||||
onToggleExplorer,
|
||||
explorerToggleLabel,
|
||||
explorerToggleAccessibilityState,
|
||||
children,
|
||||
tabSwitcher,
|
||||
inDesktopTitlebar,
|
||||
serverId,
|
||||
headerVariant,
|
||||
isRouteFocused,
|
||||
isCompact,
|
||||
}: CompactWorkspaceHeaderProps) {
|
||||
const { t } = useTranslation();
|
||||
const actionsInBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
|
||||
const projectRow = useMemo(
|
||||
() => (
|
||||
@@ -57,7 +65,16 @@ export function CompactWorkspaceHeader({
|
||||
const symbols = {
|
||||
"tab-count": tabSwitcher,
|
||||
overflow: children,
|
||||
explorer: explorerAction,
|
||||
explorer: (
|
||||
<WorkspaceExplorerToggle
|
||||
onPress={onToggleExplorer}
|
||||
label={explorerToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
accessibilityState={explorerToggleAccessibilityState}
|
||||
mobile
|
||||
/>
|
||||
),
|
||||
};
|
||||
const actions = resolveWorkspaceBarActions(headerVariant).map((symbol) => (
|
||||
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
|
||||
@@ -68,7 +85,6 @@ export function CompactWorkspaceHeader({
|
||||
{headerVariant === "compact" ? (
|
||||
<CompactHeader
|
||||
navigation="menu"
|
||||
inDesktopTitlebar={inDesktopTitlebar}
|
||||
title={title}
|
||||
titleTestID="workspace-header-title"
|
||||
subtitle={projectRow}
|
||||
|
||||
@@ -1,37 +1,47 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PanelRight } from "lucide-react-native";
|
||||
import { View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
import { HeaderToggleButton, headerIconSlotStyle } from "@/components/headers/header-toggle-button";
|
||||
import { type StyleProp, type ViewStyle } from "react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
|
||||
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
|
||||
import {
|
||||
extraMutedIconColorMapping,
|
||||
iconButtonChromeGlyphSize,
|
||||
mutedIconColorMapping,
|
||||
} from "@/components/ui/icon-button-chrome";
|
||||
import { WORKSPACE_SECONDARY_HEADER_HEIGHT } from "@/constants/layout";
|
||||
import { useHasWindowChromeObstruction } from "@/utils/desktop-window";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
|
||||
const ThemedPanelRight = withUnistyles(PanelRight);
|
||||
|
||||
const EXPLORER_TOGGLE_KEYS: ShortcutKey[] = ["mod", "E"];
|
||||
export const EXPLORER_TOGGLE_KEYS: ShortcutKey[] = ["mod", "E"];
|
||||
|
||||
interface WorkspaceExplorerToggleProps {
|
||||
onPress: () => void;
|
||||
label: string;
|
||||
tooltipLabel: string;
|
||||
tooltipKeys: ShortcutKey[];
|
||||
accessibilityState: { expanded: boolean };
|
||||
mobile: boolean;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
}
|
||||
|
||||
function WorkspaceExplorerToggle({
|
||||
export type WorkspaceExplorerToggleOwner = "mobile" | "header" | "window";
|
||||
|
||||
export function resolveWorkspaceExplorerToggleOwner({
|
||||
isMobile,
|
||||
hasMacTrafficLights,
|
||||
}: {
|
||||
isMobile: boolean;
|
||||
hasMacTrafficLights: boolean;
|
||||
}): WorkspaceExplorerToggleOwner {
|
||||
if (isMobile) return "mobile";
|
||||
return hasMacTrafficLights ? "window" : "header";
|
||||
}
|
||||
|
||||
export function WorkspaceExplorerToggle({
|
||||
onPress,
|
||||
label,
|
||||
tooltipLabel,
|
||||
tooltipKeys,
|
||||
accessibilityState,
|
||||
mobile,
|
||||
style,
|
||||
@@ -41,7 +51,7 @@ function WorkspaceExplorerToggle({
|
||||
testID="workspace-explorer-toggle"
|
||||
onPress={onPress}
|
||||
tooltipLabel={tooltipLabel}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
tooltipKeys={tooltipKeys}
|
||||
tooltipSide="left"
|
||||
style={style}
|
||||
accessible
|
||||
@@ -58,97 +68,42 @@ function WorkspaceExplorerToggle({
|
||||
);
|
||||
}
|
||||
|
||||
export function useWorkspaceExplorerControls({
|
||||
hasWorkspace,
|
||||
compact,
|
||||
focusMode,
|
||||
expanded,
|
||||
onToggle,
|
||||
}: {
|
||||
hasWorkspace: boolean;
|
||||
compact: boolean;
|
||||
focusMode: boolean;
|
||||
expanded: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const hasLeadingWindowControls = useHasWindowChromeObstruction("top-left");
|
||||
const inDesktopTitlebar = hasLeadingWindowControls && hasWorkspace && !compact && !focusMode;
|
||||
|
||||
return useMemo(() => {
|
||||
const props = {
|
||||
label: expanded
|
||||
? t("workspace.tabs.explorerSidebar.close")
|
||||
: t("workspace.tabs.explorerSidebar.open"),
|
||||
tooltipLabel: t("workspace.tabs.explorerSidebar.toggle"),
|
||||
onPress: onToggle,
|
||||
accessibilityState: { expanded },
|
||||
};
|
||||
|
||||
if (inDesktopTitlebar) {
|
||||
// Keep the button in the header Tab order. The active rail carves its slot out of the drag region.
|
||||
const headerSlot = expanded ? null : (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
style={[headerIconSlotStyle.slot, styles.headerAction]}
|
||||
dataSet={WINDOW_NO_DRAG_DATASET}
|
||||
/>
|
||||
);
|
||||
return {
|
||||
inDesktopTitlebar,
|
||||
headerAction: headerSlot,
|
||||
compactAction: headerSlot,
|
||||
dockAction: (
|
||||
<View
|
||||
pointerEvents="none"
|
||||
style={[headerIconSlotStyle.slot, styles.dockAction]}
|
||||
dataSet={WINDOW_NO_DRAG_DATASET}
|
||||
/>
|
||||
),
|
||||
titlebarAction: (
|
||||
<View pointerEvents="box-none" style={styles.titlebarSlot}>
|
||||
<WorkspaceExplorerToggle {...props} mobile={false} />
|
||||
</View>
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
inDesktopTitlebar,
|
||||
headerAction: compact ? null : (
|
||||
<WorkspaceExplorerToggle {...props} mobile={false} style={styles.headerAction} />
|
||||
),
|
||||
compactAction: <WorkspaceExplorerToggle {...props} mobile />,
|
||||
dockAction: compact ? (
|
||||
<SidebarCloseButton
|
||||
label={props.label}
|
||||
onPress={onToggle}
|
||||
testID="workspace-explorer-toggle"
|
||||
accessibilityState={props.accessibilityState}
|
||||
/>
|
||||
) : null,
|
||||
titlebarAction: null,
|
||||
};
|
||||
}, [compact, expanded, inDesktopTitlebar, onToggle, t]);
|
||||
interface DesktopWorkspaceExplorerToggleProps extends Omit<WorkspaceExplorerToggleProps, "mobile"> {
|
||||
owner: WorkspaceExplorerToggleOwner;
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
headerAction: {
|
||||
marginRight: { xs: 0, md: -theme.spacing[2] },
|
||||
},
|
||||
dockAction: {
|
||||
// The dock divider is absolutely positioned. Match the other headers' content center.
|
||||
marginBottom: theme.borderWidth[1],
|
||||
},
|
||||
titlebarSlot: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: theme.spacing[1],
|
||||
height: WORKSPACE_SECONDARY_HEADER_HEIGHT,
|
||||
// Center with the bordered workspace header and Explorer tabs row.
|
||||
borderBottomWidth: theme.borderWidth[1],
|
||||
borderBottomColor: "transparent",
|
||||
justifyContent: "center",
|
||||
zIndex: 1,
|
||||
},
|
||||
}));
|
||||
export function WorkspaceHeaderExplorerToggle({
|
||||
owner,
|
||||
accessibilityState,
|
||||
style,
|
||||
...toggleProps
|
||||
}: DesktopWorkspaceExplorerToggleProps) {
|
||||
if (owner === "mobile" || (owner === "window" && accessibilityState.expanded)) return null;
|
||||
return (
|
||||
<WorkspaceExplorerToggle
|
||||
{...toggleProps}
|
||||
accessibilityState={accessibilityState}
|
||||
mobile={false}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function WorkspaceExplorerSidebarToggle({
|
||||
owner,
|
||||
...toggleProps
|
||||
}: DesktopWorkspaceExplorerToggleProps) {
|
||||
if (owner === "header") return null;
|
||||
if (owner === "mobile") {
|
||||
// The compact Explorer is an overlay like the compact agent list, so it closes with the same X.
|
||||
return (
|
||||
<SidebarCloseButton
|
||||
label={toggleProps.label}
|
||||
onPress={toggleProps.onPress}
|
||||
testID="workspace-explorer-toggle"
|
||||
accessibilityState={toggleProps.accessibilityState}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return <WorkspaceExplorerToggle {...toggleProps} mobile={false} />;
|
||||
}
|
||||
|
||||
@@ -157,8 +157,17 @@ import {
|
||||
} from "@/screens/workspace/workspace-desktop-tabs-row";
|
||||
import { useDesktopBrowserNewTabRequests } from "@/desktop/browser/new-tab-requests";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import { useWorkspaceExplorerControls } from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
|
||||
import {
|
||||
resolveWorkspaceExplorerToggleOwner,
|
||||
EXPLORER_TOGGLE_KEYS,
|
||||
WorkspaceExplorerSidebarToggle,
|
||||
WorkspaceHeaderExplorerToggle,
|
||||
} from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import {
|
||||
useHasWindowChromeObstruction,
|
||||
WindowChromeRegion,
|
||||
WindowChromeSafeArea,
|
||||
} from "@/utils/desktop-window";
|
||||
import {
|
||||
resolveWorkspaceHeaderRenderState,
|
||||
type WorkspaceHeaderCheckoutState,
|
||||
@@ -1049,8 +1058,12 @@ function WorkspaceScreenContent({
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const canRenderDesktopPaneSplits = supportsDesktopPaneSplits();
|
||||
const layoutMode = useWorkspaceLayoutStore((state) => state.layoutMode);
|
||||
const hasMacTrafficLights = useHasWindowChromeObstruction("top-left");
|
||||
const explorerToggleOwner = resolveWorkspaceExplorerToggleOwner({
|
||||
isMobile,
|
||||
hasMacTrafficLights,
|
||||
});
|
||||
const isFocusModeEnabled = usePanelStore((state) => state.desktop.focusModeEnabled);
|
||||
const desktopFocusModeEnabled = isFocusModeEnabled && !isMobile;
|
||||
const toggleFocusMode = usePanelStore((state) => state.toggleFocusMode);
|
||||
|
||||
const normalizedServerId = useMemo(() => trimNonEmpty(decodeSegment(serverId)) ?? "", [serverId]);
|
||||
@@ -1295,6 +1308,11 @@ function WorkspaceScreenContent({
|
||||
explorerOpen: isExplorerSidebarShowing,
|
||||
});
|
||||
|
||||
const explorerSidebarToggleAccessibilityState = useMemo(
|
||||
() => ({ expanded: isExplorerSidebarShowing }),
|
||||
[isExplorerSidebarShowing],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
// Back dismisses the compact overlay only. On a wide native layout the
|
||||
// explorer is a tab, `showMobileAgent` has no rendered consumer, and
|
||||
@@ -1802,6 +1820,9 @@ function WorkspaceScreenContent({
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
const explorerSidebarToggleLabel = isExplorerSidebarShowing
|
||||
? t("workspace.tabs.explorerSidebar.close")
|
||||
: t("workspace.tabs.explorerSidebar.open");
|
||||
|
||||
const activeTabKey = useMemo(() => activeTabId ?? "", [activeTabId]);
|
||||
const handleCreateDraftTab = useCallback(
|
||||
@@ -3207,13 +3228,6 @@ function WorkspaceScreenContent({
|
||||
workspaceKey: persistenceKey,
|
||||
});
|
||||
|
||||
const explorerControls = useWorkspaceExplorerControls({
|
||||
hasWorkspace: !!workspaceDirectory,
|
||||
compact: isMobile,
|
||||
focusMode: desktopFocusModeEnabled,
|
||||
expanded: isExplorerSidebarShowing,
|
||||
onToggle: handleToggleExplorerSidebar,
|
||||
});
|
||||
const headerRight = useMemo(
|
||||
() => (
|
||||
<View style={styles.headerRight}>
|
||||
@@ -3240,7 +3254,17 @@ function WorkspaceScreenContent({
|
||||
{workspaceDirectory ? (
|
||||
<>
|
||||
<WorkspaceActions serverId={normalizedServerId} cwd={workspaceDirectory} />
|
||||
{workspaceActionsInBar ? null : explorerControls.headerAction}
|
||||
{workspaceActionsInBar ? null : (
|
||||
<WorkspaceHeaderExplorerToggle
|
||||
owner={explorerToggleOwner}
|
||||
onPress={handleToggleExplorerSidebar}
|
||||
label={explorerSidebarToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
style={styles.compactHeaderActionButton}
|
||||
accessibilityState={explorerSidebarToggleAccessibilityState}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -3255,8 +3279,12 @@ function WorkspaceScreenContent({
|
||||
scriptActions,
|
||||
handleViewScriptTerminal,
|
||||
handleOpenUrlInBrowserTab,
|
||||
explorerControls.headerAction,
|
||||
handleToggleExplorerSidebar,
|
||||
explorerSidebarToggleLabel,
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerToggleOwner,
|
||||
workspaceActionsInBar,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3264,6 +3292,25 @@ function WorkspaceScreenContent({
|
||||
() => shouldShowWorkspaceScreenHeader({ isFocusModeEnabled, isMobile }),
|
||||
[isFocusModeEnabled, isMobile],
|
||||
);
|
||||
const renderExplorerSidebarHeaderAction = useCallback(
|
||||
() => (
|
||||
<WorkspaceExplorerSidebarToggle
|
||||
owner={explorerToggleOwner}
|
||||
onPress={handleToggleExplorerSidebar}
|
||||
label={explorerSidebarToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
accessibilityState={explorerSidebarToggleAccessibilityState}
|
||||
/>
|
||||
),
|
||||
[
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerSidebarToggleLabel,
|
||||
explorerToggleOwner,
|
||||
handleToggleExplorerSidebar,
|
||||
t,
|
||||
],
|
||||
);
|
||||
const createTerminalDisabled = useMemo(
|
||||
() => createTerminalMutation.isPending || pendingTerminalCreateInput !== null,
|
||||
[createTerminalMutation.isPending, pendingTerminalCreateInput],
|
||||
@@ -3286,6 +3333,10 @@ function WorkspaceScreenContent({
|
||||
],
|
||||
);
|
||||
const focusedPaneIdOrUndefined = useMemo(() => focusedPaneId ?? undefined, [focusedPaneId]);
|
||||
const desktopFocusModeEnabled = useMemo(
|
||||
() => isFocusModeEnabled && !isMobile,
|
||||
[isFocusModeEnabled, isMobile],
|
||||
);
|
||||
const workspaceFloatingPanelPortalHostName = useMemo(
|
||||
() =>
|
||||
`${WORKSPACE_FLOATING_PANEL_PORTAL_HOST_PREFIX}:${normalizedServerId}:${normalizedWorkspaceId}`,
|
||||
@@ -3409,13 +3460,14 @@ function WorkspaceScreenContent({
|
||||
isRouteFocused={isRouteFocused}
|
||||
isCompact={isMobile}
|
||||
tabSwitcher={tabSwitcher}
|
||||
inDesktopTitlebar={explorerControls.inDesktopTitlebar}
|
||||
explorerAction={explorerControls.compactAction}
|
||||
isLoading={isWorkspaceHeaderLoading}
|
||||
title={workspaceHeaderTitle}
|
||||
subtitle={workspaceHeaderSubtitle}
|
||||
isSubtitleDistinct={isWorkspaceHeaderSubtitleDistinct}
|
||||
serverId={normalizedServerId}
|
||||
onToggleExplorer={handleToggleExplorerSidebar}
|
||||
explorerToggleLabel={explorerSidebarToggleLabel}
|
||||
explorerToggleAccessibilityState={explorerSidebarToggleAccessibilityState}
|
||||
>
|
||||
<WorkspaceHeaderMenuMobile
|
||||
pane={paneTabs?.actions.pane}
|
||||
@@ -3441,19 +3493,20 @@ function WorkspaceScreenContent({
|
||||
},
|
||||
[
|
||||
renderWorkspaceTabSwitcher,
|
||||
explorerControls.inDesktopTitlebar,
|
||||
explorerControls.compactAction,
|
||||
isFocusModeEnabled,
|
||||
toggleFocusMode,
|
||||
canOpenImportSheet,
|
||||
compactHeaderScripts,
|
||||
createTerminalDisabled,
|
||||
currentBranchName,
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerSidebarToggleLabel,
|
||||
handleCopyBranchName,
|
||||
handleCopyWorkspacePath,
|
||||
handleCreateBrowserTab,
|
||||
handleCreateTerminalWithProfile,
|
||||
handleOpenSetupTab,
|
||||
handleToggleExplorerSidebar,
|
||||
isMobile,
|
||||
isRouteFocused,
|
||||
isWorkspaceHeaderLoading,
|
||||
@@ -3681,7 +3734,7 @@ function WorkspaceScreenContent({
|
||||
onExitFocusMode={toggleFocusMode}
|
||||
onReorderTabsInPane={handleReorderTabsInPane}
|
||||
buildPaneContentModel={buildDesktopPaneContentModel}
|
||||
headerAction={explorerControls.dockAction}
|
||||
headerAction={renderExplorerSidebarHeaderAction()}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
@@ -3722,7 +3775,7 @@ function WorkspaceScreenContent({
|
||||
toggleFocusMode,
|
||||
handleReorderTabsInPane,
|
||||
buildDesktopPaneContentModel,
|
||||
explorerControls.dockAction,
|
||||
renderExplorerSidebarHeaderAction,
|
||||
desktopFocusModeEnabled,
|
||||
]);
|
||||
|
||||
@@ -3796,7 +3849,6 @@ function WorkspaceScreenContent({
|
||||
onReorderTabsInPane={handleReorderTabsInPane}
|
||||
onSplitPane={handleSplitPane}
|
||||
>
|
||||
{explorerControls.titlebarAction}
|
||||
{workspaceCenterColumn}
|
||||
{sharedExplorer}
|
||||
</WorkspaceTabDragScope>
|
||||
@@ -3934,6 +3986,12 @@ const styles = StyleSheet.create((theme) => ({
|
||||
md: theme.spacing[2],
|
||||
},
|
||||
},
|
||||
compactHeaderActionButton: {
|
||||
marginRight: {
|
||||
xs: 0,
|
||||
md: -theme.spacing[2],
|
||||
},
|
||||
},
|
||||
compactHeaderMenuCluster: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { buildDesktopFrameStyle } from "@/components/ui/combobox-frame-style";
|
||||
import {
|
||||
WorkspaceHeaderExplorerToggle,
|
||||
WorkspaceExplorerSidebarToggle,
|
||||
} from "./workspace-explorer-toggle";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
|
||||
import { resolveWorkspaceTabChipBackdrop } from "@/screens/workspace/workspace-tab-chip-backdrop";
|
||||
import { darkPureBlackTheme, darkTheme, lightTheme } from "@/styles/theme";
|
||||
import {
|
||||
@@ -185,6 +190,37 @@ describe("retainWorkspaceTabMeasuredWidth", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("Explorer toggle ownership", () => {
|
||||
const toggleProps = {
|
||||
onPress: () => {},
|
||||
label: "Close Explorer sidebar",
|
||||
tooltipLabel: "Toggle Explorer sidebar",
|
||||
tooltipKeys: [],
|
||||
accessibilityState: { expanded: true },
|
||||
};
|
||||
|
||||
it("keeps only the header toggle when window controls do not obstruct it", () => {
|
||||
expect(WorkspaceHeaderExplorerToggle({ ...toggleProps, owner: "header" })).not.toBeNull();
|
||||
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "header" })).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps the dock toggle for window-owned and compact overlay chrome", () => {
|
||||
for (const owner of ["window", "mobile"] as const) {
|
||||
expect(WorkspaceHeaderExplorerToggle({ ...toggleProps, owner })).toBeNull();
|
||||
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner })).not.toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("closes the compact overlay with the same X as the compact agent list", () => {
|
||||
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "mobile" })?.type).toBe(
|
||||
SidebarCloseButton,
|
||||
);
|
||||
expect(WorkspaceExplorerSidebarToggle({ ...toggleProps, owner: "window" })?.type).not.toBe(
|
||||
SidebarCloseButton,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveWorkspaceTabChipBackdrop", () => {
|
||||
const themes = { light: lightTheme, dark: darkTheme, pureBlack: darkPureBlackTheme };
|
||||
const rails = {
|
||||
|
||||
@@ -69,7 +69,6 @@ interface SidebarViewStoreState {
|
||||
setWorkspaceSort: (sort: WorkspaceSort) => void;
|
||||
toggleHostFilter: (serverId: string) => void;
|
||||
clearHostFilters: () => void;
|
||||
focusHost: (serverId: string) => void;
|
||||
toggleProjectFilter: (viewKey: string) => void;
|
||||
clearProjectFilters: () => void;
|
||||
toggleLabelFilter: (name: string) => void;
|
||||
@@ -206,9 +205,6 @@ export const useSidebarViewStore = create<SidebarViewStoreState>()(
|
||||
toggleHostFilter: (serverId) =>
|
||||
set((state) => ({ hostFilters: toggleFilterEntry(state.hostFilters, serverId) })),
|
||||
clearHostFilters: () => set({ hostFilters: [] }),
|
||||
// An explicit navigation target must not be hidden by another host's facets.
|
||||
focusHost: (serverId) =>
|
||||
set({ hostFilters: [serverId], projectFilters: [], labelFilter: emptyLabelFilter() }),
|
||||
toggleProjectFilter: (viewKey) =>
|
||||
set((state) => ({ projectFilters: toggleFilterEntry(state.projectFilters, viewKey) })),
|
||||
clearProjectFilters: () => set({ projectFilters: [] }),
|
||||
|
||||
@@ -3,7 +3,6 @@ import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CornerUpLeft } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { CHAT_COLUMN_RAIL_DATASET } from "@/chat-rail";
|
||||
import { StatusIcon } from "@/components/status-icon";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { FOOTER_HEIGHT } from "@/constants/layout";
|
||||
@@ -38,7 +37,7 @@ export function ParentAgentCallout({
|
||||
const parent = useParentAgent(serverId, parentAgentId);
|
||||
|
||||
return (
|
||||
<View style={styles.rail} dataSet={CHAT_COLUMN_RAIL_DATASET}>
|
||||
<View style={styles.rail}>
|
||||
<View style={styles.callout} testID="parent-agent-callout">
|
||||
<StatusIcon statusBucket={parent.statusBucket} size={ICON_SIZE} backdrop="surface1">
|
||||
<ThemedParentIcon icon={parent.icon} size={ICON_SIZE} uniProps={foregroundColorMapping} />
|
||||
|
||||
@@ -1053,19 +1053,12 @@ export class TerminalEmulatorRuntime {
|
||||
if (!terminal) {
|
||||
return;
|
||||
}
|
||||
terminal.textarea?.removeAttribute("virtualkeyboardpolicy");
|
||||
if (input?.forceRefocus) {
|
||||
terminal.blur();
|
||||
}
|
||||
terminal.focus();
|
||||
}
|
||||
|
||||
suppressAutomaticKeyboard(): void {
|
||||
// Android Chrome can reopen the keyboard during a drag after Back leaves the input
|
||||
// focused. Manual policy prevents that without closing an already open keyboard.
|
||||
this.terminal?.textarea?.setAttribute("virtualkeyboardpolicy", "manual");
|
||||
}
|
||||
|
||||
blur(): void {
|
||||
this.terminal?.blur();
|
||||
}
|
||||
|
||||
@@ -32,7 +32,6 @@ it("translates mounted usage rows when the language changes", async () => {
|
||||
<>
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
forecastAt={null}
|
||||
displayAs="used"
|
||||
pinnable={false}
|
||||
pinned={false}
|
||||
@@ -52,44 +51,3 @@ it("translates mounted usage rows when the language changes", async () => {
|
||||
expect(container.textContent).toContain("セッション70% 使用済み");
|
||||
expect(container.textContent).toContain("クレジット");
|
||||
});
|
||||
|
||||
const narrowReadingMs = Date.now();
|
||||
const narrowForecastAt = new Date(narrowReadingMs).toISOString();
|
||||
const narrowWindow: UsageWindow = {
|
||||
id: "weekly",
|
||||
label: "Weekly",
|
||||
usedPct: 0.2,
|
||||
durationSeconds: 604_800,
|
||||
resetsAt: new Date(narrowReadingMs + 165.5 * 3_600_000).toISOString(),
|
||||
};
|
||||
|
||||
it("keeps the French reset countdown and forecast apart in a narrow card", async () => {
|
||||
await i18n.changeLanguage("fr");
|
||||
container.style.width = "272px";
|
||||
act(() =>
|
||||
root.render(
|
||||
<UsageWindowBar
|
||||
window={narrowWindow}
|
||||
forecastAt={narrowForecastAt}
|
||||
displayAs="used"
|
||||
pinnable={false}
|
||||
pinned={false}
|
||||
onTogglePin={ignorePin}
|
||||
pinLabel=""
|
||||
pinTestID=""
|
||||
/>,
|
||||
),
|
||||
);
|
||||
|
||||
function textBounds(prefix: string) {
|
||||
const element = Array.from(container.querySelectorAll("*")).find(
|
||||
(node) => node.childElementCount === 0 && node.textContent.startsWith(prefix),
|
||||
);
|
||||
expect(element).toBeDefined();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(element!);
|
||||
return range.getBoundingClientRect();
|
||||
}
|
||||
|
||||
expect(textBounds("se réinitialise").right).toBeLessThan(textBounds("~").left);
|
||||
});
|
||||
|
||||
@@ -70,7 +70,7 @@ export function UsageCard({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const { refresh, refreshState } = useReportRefresh(serverId, entry, agentId);
|
||||
const { refresh, refreshState } = useReportRefresh(serverId, entry.id, agentId);
|
||||
// Where there is no hover the freshness is printed on the card; elsewhere the Refresh tooltip.
|
||||
const showsFreshnessInline = isNative || isCompact || !refreshable;
|
||||
const usage = entry.report;
|
||||
@@ -176,7 +176,7 @@ function UsageCardBody({
|
||||
refreshState: UsageRefresh;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report;
|
||||
const { windows, balances, details, retained, successfulAt, messages } = report;
|
||||
const footer = entry.account.label ?? null;
|
||||
return (
|
||||
<>
|
||||
@@ -194,7 +194,6 @@ function UsageCardBody({
|
||||
entry={entry}
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
display={display}
|
||||
pinnable={pinnable}
|
||||
/>
|
||||
@@ -268,10 +267,8 @@ function CardWindowBar({
|
||||
display,
|
||||
pinnable,
|
||||
retained,
|
||||
forecastAt,
|
||||
}: {
|
||||
retained: boolean;
|
||||
forecastAt: string | null;
|
||||
entry: UsageReportEntry;
|
||||
window: UsageWindow;
|
||||
display: UsageDisplay;
|
||||
@@ -288,7 +285,6 @@ function CardWindowBar({
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
displayAs={display.displayAs}
|
||||
pinnable={pinnable}
|
||||
pinned={display.isPinned(pin)}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
resolveUsageReport,
|
||||
markUsageRefreshFailure,
|
||||
displayPercent,
|
||||
resolveAgentUsageView,
|
||||
replaceReport,
|
||||
@@ -83,7 +82,7 @@ describe("resolveUsageView", () => {
|
||||
expect(resolveUsageView({ ...base, query: undefined })).toEqual({ kind: "loading" });
|
||||
expect(
|
||||
resolveUsageView({ ...base, query: { data: [], error: null, isFetching: true } }),
|
||||
).toEqual({ kind: "ready", reports: [], isRefreshing: true, refreshFailed: false });
|
||||
).toEqual({ kind: "ready", reports: [], isRefreshing: true });
|
||||
expect(
|
||||
resolveUsageView({
|
||||
...base,
|
||||
@@ -91,19 +90,6 @@ describe("resolveUsageView", () => {
|
||||
}),
|
||||
).toEqual({ kind: "error", message: "boom" });
|
||||
});
|
||||
|
||||
it("shows a failed Refresh all alongside the reports still on screen", () => {
|
||||
const reports = [entry({})];
|
||||
expect(
|
||||
resolveUsageView({
|
||||
hostLabel: "Laptop",
|
||||
isConnected: true,
|
||||
supportsUsage: true,
|
||||
query: ready(reports),
|
||||
refreshState: "failed",
|
||||
}),
|
||||
).toEqual({ kind: "ready", reports, isRefreshing: false, refreshFailed: true });
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
@@ -217,12 +203,15 @@ describe("displayPercent", () => {
|
||||
|
||||
describe("resolveUsageRefresh", () => {
|
||||
it("is pending while a refresh runs, even after an earlier failure", () => {
|
||||
expect(resolveUsageRefresh({ isPending: true, isError: true })).toBe("pending");
|
||||
expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending");
|
||||
});
|
||||
|
||||
it("reports the request outcome independently of the reading", () => {
|
||||
expect(resolveUsageRefresh({ isPending: false, isError: true })).toBe("failed");
|
||||
expect(resolveUsageRefresh({ isPending: false, isError: false })).toBe("idle");
|
||||
it("is failed after a refresh errors", () => {
|
||||
expect(resolveUsageRefresh({ isPending: false, error: new Error("boom") })).toBe("failed");
|
||||
});
|
||||
|
||||
it("is idle before and after a successful refresh", () => {
|
||||
expect(resolveUsageRefresh({ isPending: false, error: null })).toBe("idle");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -363,7 +352,6 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: success.fetchedAt,
|
||||
forecastAt: null,
|
||||
retained: true,
|
||||
messages: ["Rate limited"],
|
||||
});
|
||||
@@ -373,7 +361,6 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: null,
|
||||
forecastAt: null,
|
||||
retained: false,
|
||||
messages: ["Rate limited"],
|
||||
});
|
||||
@@ -383,48 +370,11 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: success.fetchedAt,
|
||||
forecastAt: success.fetchedAt,
|
||||
retained: false,
|
||||
messages: [],
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the quota observation time for pace and keeps the reading after a failed request", () => {
|
||||
const success = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
|
||||
if (success.report.status !== "available") throw new Error("fixture must be available");
|
||||
const observedAt = success.fetchedAt;
|
||||
const successfulAt = "2026-01-01T00:15:00.000Z";
|
||||
const report = { ...success, successfulAt, report: { ...success.report, observedAt } };
|
||||
expect(resolveUsageReport(report, i18n.t)).toMatchObject({
|
||||
successfulAt,
|
||||
forecastAt: observedAt,
|
||||
});
|
||||
expect(resolveUsageReport({ ...report, forecastStale: true }, i18n.t)).toMatchObject({
|
||||
windows: success.report.windows,
|
||||
successfulAt,
|
||||
forecastAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps cached quota and hides its forecast when Refresh all fails before a new report arrives", () => {
|
||||
const before = entry({ windows: [{ id: "weekly", label: "Weekly", usedPct: 42 }] });
|
||||
const other = entry({ sourceId: "other" });
|
||||
const refreshedAt = "2026-01-01T00:06:00.000Z";
|
||||
const streamed = { ...other, fetchedAt: refreshedAt };
|
||||
const attempted = [before, other];
|
||||
const failed = markUsageRefreshFailure([before, streamed], attempted)!;
|
||||
|
||||
expect(resolveUsageReport(failed[0]!, i18n.t)).toMatchObject({
|
||||
forecastAt: null,
|
||||
windows: before.report.status === "available" ? before.report.windows : [],
|
||||
});
|
||||
expect(resolveUsageReport(failed[1]!, i18n.t).forecastAt).toBe(refreshedAt);
|
||||
expect(resolveUsageReport(upsertReport(failed, before)[0]!, i18n.t).forecastAt).toBeNull();
|
||||
|
||||
const retried = settleReports(failed, [{ ...before, fetchedAt: refreshedAt }, streamed]);
|
||||
expect(resolveUsageReport(retried[0]!, i18n.t).forecastAt).toBe(refreshedAt);
|
||||
});
|
||||
|
||||
it("orders failed polls by attempt time even when successful data is older", () => {
|
||||
const success = entry({});
|
||||
if (success.report.status !== "available") throw new Error("fixture must be available");
|
||||
|
||||
@@ -38,31 +38,18 @@ export function usageWindowRowLabel(input: {
|
||||
return `${input.pinLabel}, ${summary}`;
|
||||
}
|
||||
|
||||
/** The outcome of a user-requested usage refresh. */
|
||||
/** A user-requested refresh of one report. The previous report stays on screen throughout. */
|
||||
export type UsageRefresh = "idle" | "pending" | "failed";
|
||||
|
||||
export function resolveUsageRefresh(mutation: {
|
||||
isPending: boolean;
|
||||
isError: boolean;
|
||||
error: unknown;
|
||||
}): UsageRefresh {
|
||||
if (mutation.isPending) return "pending";
|
||||
if (mutation.isError) return "failed";
|
||||
if (mutation.error) return "failed";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
/** Keep quota readings after a failed refresh and attach the outcome to the readings it targeted. */
|
||||
export function markUsageRefreshFailure(
|
||||
current: UsageReportEntry[] | undefined,
|
||||
attempted: readonly UsageReportEntry[],
|
||||
): UsageReportEntry[] | undefined {
|
||||
const attemptedAt = new Map(attempted.map((entry) => [entry.id, entry.fetchedAt]));
|
||||
return current?.map((entry) =>
|
||||
attemptedAt.get(entry.id) === entry.fetchedAt && !entry.forecastStale
|
||||
? { ...entry, forecastStale: true }
|
||||
: entry,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A host's report list with one report swapped for its refreshed copy, in place.
|
||||
* `null` means the daemon no longer knows the ID, so the report leaves the list.
|
||||
@@ -73,9 +60,7 @@ export function replaceReport(
|
||||
refreshed: UsageReportEntry | null,
|
||||
): UsageReportEntry[] {
|
||||
if (!refreshed) return reports.filter((report) => report.id !== reportId);
|
||||
return reports.map((report) =>
|
||||
report.id === reportId ? laterFetched(report, refreshed) : report,
|
||||
);
|
||||
return reports.map((report) => (report.id === reportId ? refreshed : report));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -83,9 +68,7 @@ export function replaceReport(
|
||||
* started, so a Refresh that lands while it streams is newer than what the request still delivers.
|
||||
*/
|
||||
function laterFetched(shown: UsageReportEntry, arriving: UsageReportEntry): UsageReportEntry {
|
||||
const shownAt = Date.parse(shown.fetchedAt);
|
||||
const arrivingAt = Date.parse(arriving.fetchedAt);
|
||||
return shownAt > arrivingAt || (shownAt === arrivingAt && shown.forecastStale) ? shown : arriving;
|
||||
return Date.parse(shown.fetchedAt) > Date.parse(arriving.fetchedAt) ? shown : arriving;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -134,11 +117,10 @@ export function resolveUsageView(
|
||||
isConnected: boolean;
|
||||
supportsUsage: boolean;
|
||||
query: UsageQueryState | undefined;
|
||||
refreshState?: UsageRefresh;
|
||||
},
|
||||
t: TFunction = i18n.t,
|
||||
): UsageView {
|
||||
const { hostLabel, isConnected, supportsUsage, query, refreshState } = input;
|
||||
const { hostLabel, isConnected, supportsUsage, query } = input;
|
||||
if (!isConnected)
|
||||
return {
|
||||
kind: "unavailable",
|
||||
@@ -153,12 +135,7 @@ export function resolveUsageView(
|
||||
if (input.enabled === false)
|
||||
return { kind: "off", message: t("providerUsage.off", { host: hostLabel }) };
|
||||
if (query?.data) {
|
||||
return {
|
||||
kind: "ready",
|
||||
reports: query.data,
|
||||
isRefreshing: query.isFetching || refreshState === "pending",
|
||||
refreshFailed: refreshState === "failed",
|
||||
};
|
||||
return { kind: "ready", reports: query.data, isRefreshing: query.isFetching };
|
||||
}
|
||||
if (query?.error) {
|
||||
return {
|
||||
@@ -273,12 +250,7 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
|
||||
// COMPAT(usageLoginErrors): added in v0.11.0, remove after 2027-04-05 once daemon floor >= v0.11.0.
|
||||
else messages.push(usageProblemText(entry.report, t));
|
||||
}
|
||||
const forecastAt =
|
||||
snapshot && !snapshot.retained && !entry.forecastStale
|
||||
? (snapshot.report.observedAt ?? snapshot.successfulAt)
|
||||
: null;
|
||||
return {
|
||||
forecastAt,
|
||||
windows: snapshot?.report.windows ?? [],
|
||||
balances: snapshot?.report.balances ?? [],
|
||||
details: snapshot?.report.details ?? [],
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { usagePace } from "./pace";
|
||||
import type { UsageWindow } from "./types";
|
||||
|
||||
const day = "2026-11-20T";
|
||||
const reading = (time: string) => `${day}${time}:00.000Z`;
|
||||
const window: UsageWindow = {
|
||||
id: "five_hour",
|
||||
label: "Session",
|
||||
durationSeconds: 18_000,
|
||||
usedPct: 65,
|
||||
resetsAt: reading("15:00"),
|
||||
};
|
||||
|
||||
describe("usage pace", () => {
|
||||
it("projects the limit from the sample time and keeps it fixed between readings", () => {
|
||||
const sampledAt = reading("12:00");
|
||||
const estimate = { kind: "runsOut", at: `${day}13:04:36.923Z` };
|
||||
expect(usagePace(window, sampledAt, Date.parse(sampledAt))).toEqual(estimate);
|
||||
expect(usagePace(window, sampledAt, Date.parse(reading("12:30")))).toEqual(estimate);
|
||||
});
|
||||
|
||||
it("updates after a later reading and works with a remaining percentage", () => {
|
||||
const close = reading("13:30");
|
||||
const safe = reading("14:00");
|
||||
const forecast = usagePace(window, close, Date.parse(close));
|
||||
expect(forecast.kind).toBe("remaining");
|
||||
if (forecast.kind === "remaining") expect(forecast.remainingAtResetPct).toBeCloseTo(7.14);
|
||||
expect(
|
||||
usagePace({ ...window, usedPct: undefined, remainingPct: 35 }, safe, Date.parse(safe)),
|
||||
).toEqual({ kind: "remaining", remainingAtResetPct: 18.75 });
|
||||
});
|
||||
|
||||
it("only forecasts with timing and an active, usable reading", () => {
|
||||
const sampledAt = reading("12:00");
|
||||
const now = Date.parse(sampledAt);
|
||||
expect(usagePace({ ...window, durationSeconds: undefined }, sampledAt, now)).toEqual({
|
||||
kind: "unknown",
|
||||
});
|
||||
expect(usagePace(window, null, now)).toEqual({ kind: "unknown" });
|
||||
expect(usagePace(window, reading("10:01"), now)).toEqual({ kind: "unknown" });
|
||||
expect(usagePace(window, sampledAt, Date.parse(window.resetsAt!))).toEqual({ kind: "unknown" });
|
||||
expect(usagePace({ ...window, usedPct: 100 }, sampledAt, now)).toEqual({ kind: "reached" });
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { usedPercent } from "./model";
|
||||
import type { UsageWindow } from "./types";
|
||||
|
||||
type UsagePace =
|
||||
| { kind: "unknown" }
|
||||
| { kind: "reached" }
|
||||
| { kind: "runsOut"; at: string }
|
||||
| { kind: "remaining"; remainingAtResetPct: number };
|
||||
|
||||
/** Estimate from the window's average pace as of the reading. The clock only expires the estimate. */
|
||||
export function usagePace(window: UsageWindow, observedAt: string | null, now: number): UsagePace {
|
||||
if (observedAt === null) return { kind: "unknown" };
|
||||
const reset = Date.parse(window.resetsAt ?? "");
|
||||
if (reset <= now) return { kind: "unknown" };
|
||||
|
||||
const used = usedPercent(window);
|
||||
if (used != null && used >= 100) return { kind: "reached" };
|
||||
|
||||
const supplied = window.runsOutAt;
|
||||
const suppliedAt = Date.parse(supplied ?? "");
|
||||
if (supplied && Number.isFinite(suppliedAt) && (!Number.isFinite(reset) || suppliedAt < reset)) {
|
||||
return { kind: "runsOut", at: supplied };
|
||||
}
|
||||
|
||||
const duration = (window.durationSeconds ?? 0) * 1_000;
|
||||
const sampled = Date.parse(observedAt);
|
||||
const elapsed = sampled - (reset - duration);
|
||||
if (
|
||||
used == null ||
|
||||
!Number.isFinite(used) ||
|
||||
used < 0 ||
|
||||
!Number.isFinite(elapsed) ||
|
||||
sampled >= reset ||
|
||||
elapsed < Math.max(60_000, duration * 0.01)
|
||||
) {
|
||||
return { kind: "unknown" };
|
||||
}
|
||||
|
||||
const projectedAtReset = (used / elapsed) * duration;
|
||||
if (projectedAtReset > 100) {
|
||||
const runsOut = sampled + ((100 - used) / used) * elapsed;
|
||||
return { kind: "runsOut", at: new Date(runsOut).toISOString() };
|
||||
}
|
||||
return { kind: "remaining", remainingAtResetPct: 100 - projectedAtReset };
|
||||
}
|
||||
@@ -53,7 +53,7 @@ function preferences(
|
||||
}
|
||||
|
||||
describe("choosePinnedUsageLayout", () => {
|
||||
const widths = { labelsWidth: 200, compactWidth: 200, percentsWidth: 120, windowCount: 2 };
|
||||
const widths = { labelsWidth: 200, percentsWidth: 120, windowCount: 2 };
|
||||
|
||||
it("shows meters only when every window's meter fits beside the labels", () => {
|
||||
expect(choosePinnedUsageLayout({ ...widths, available: 240 })).toBe("meters");
|
||||
@@ -64,27 +64,11 @@ describe("choosePinnedUsageLayout", () => {
|
||||
expect(choosePinnedUsageLayout({ ...widths, available: 199 })).toBe("percents");
|
||||
});
|
||||
|
||||
it("uses compact period shorthands when full labels overflow but compact labels fit", () => {
|
||||
const scoped = { labelsWidth: 485, compactWidth: 388, percentsWidth: 268, windowCount: 6 };
|
||||
expect(choosePinnedUsageLayout({ ...scoped, available: 485 })).toBe("labels");
|
||||
expect(choosePinnedUsageLayout({ ...scoped, available: 399 })).toBe("compact");
|
||||
expect(choosePinnedUsageLayout({ ...scoped, available: 388 })).toBe("compact");
|
||||
expect(choosePinnedUsageLayout({ ...scoped, available: 387 })).toBe("percents");
|
||||
});
|
||||
|
||||
it("skips compact mode when no window has a compact label", () => {
|
||||
const noPeriod = { labelsWidth: 220, compactWidth: 120, percentsWidth: 120, windowCount: 2 };
|
||||
expect(choosePinnedUsageLayout({ ...noPeriod, available: 180 })).toBe("percents");
|
||||
});
|
||||
|
||||
it("shows labels until the widths are measured", () => {
|
||||
expect(choosePinnedUsageLayout({ ...widths, available: null })).toBe("labels");
|
||||
expect(choosePinnedUsageLayout({ ...widths, available: 999, labelsWidth: null })).toBe(
|
||||
"labels",
|
||||
);
|
||||
expect(choosePinnedUsageLayout({ ...widths, available: 999, compactWidth: null })).toBe(
|
||||
"labels",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -161,7 +145,6 @@ describe("resolvePinnedUsage", () => {
|
||||
key: "claude:default/five-hour",
|
||||
label: "Claude Session 31% used",
|
||||
shortLabel: "5h",
|
||||
compactLabel: "5h",
|
||||
percent: 31,
|
||||
percentText: "31%",
|
||||
tone: "default",
|
||||
@@ -170,7 +153,6 @@ describe("resolvePinnedUsage", () => {
|
||||
key: "claude:default/weekly",
|
||||
label: "Claude Weekly 80% used",
|
||||
shortLabel: "wk",
|
||||
compactLabel: "wk",
|
||||
percent: 80,
|
||||
percentText: "80%",
|
||||
tone: "warning",
|
||||
@@ -234,52 +216,6 @@ describe("resolvePinnedUsage", () => {
|
||||
const items = windows([opencode], preferences(null));
|
||||
|
||||
expect(items.map((item) => item.shortLabel)).toEqual([""]);
|
||||
expect(items.map((item) => item.compactLabel)).toEqual([""]);
|
||||
});
|
||||
|
||||
it("extracts bare period tokens as compact labels for scoped or verbose short labels", () => {
|
||||
const mixed = report({
|
||||
sourceId: "mixed",
|
||||
sourceLabel: "Mixed",
|
||||
windows: [
|
||||
{ id: "a", label: "Session", shortLabel: "5h", summary: true, usedPct: 10 },
|
||||
{ id: "b", label: "Weekly · Opus", shortLabel: "wk Opus", summary: true, usedPct: 20 },
|
||||
{
|
||||
id: "c",
|
||||
label: "Code review · Weekly",
|
||||
shortLabel: "Code review wk",
|
||||
summary: true,
|
||||
usedPct: 30,
|
||||
},
|
||||
{
|
||||
id: "d",
|
||||
label: "Gemini Models · Weekly",
|
||||
shortLabel: "Gemini Models weekly",
|
||||
summary: true,
|
||||
usedPct: 40,
|
||||
},
|
||||
{
|
||||
id: "e",
|
||||
label: "Gemini Models · 5h",
|
||||
shortLabel: "Gemini Models 5h",
|
||||
summary: true,
|
||||
usedPct: 50,
|
||||
},
|
||||
{ id: "f", label: "Monthly", shortLabel: "Monthly", summary: true, usedPct: 60 },
|
||||
{ id: "g", label: "Premium requests", summary: true, usedPct: 70 },
|
||||
],
|
||||
});
|
||||
const items = windows([mixed], preferences(null));
|
||||
|
||||
expect(items.map((item) => [item.shortLabel, item.compactLabel])).toEqual([
|
||||
["5h", "5h"],
|
||||
["wk Opus", "wk"],
|
||||
["Code review wk", "wk"],
|
||||
["Gemini Models weekly", "wk"],
|
||||
["Gemini Models 5h", "5h"],
|
||||
["Monthly", "mo"],
|
||||
["Premium requests", ""],
|
||||
]);
|
||||
});
|
||||
|
||||
it("formats the share left when the user reads usage as remaining", () => {
|
||||
|
||||
@@ -18,8 +18,6 @@ export interface PinnedUsageWindow {
|
||||
label: string;
|
||||
/** The window's short name ("5h"), empty for none, or its label when the source sends none. */
|
||||
shortLabel: string;
|
||||
/** Bare period token ("5h", "wk", "mo") used when full short labels overflow the sidebar row. */
|
||||
compactLabel: string;
|
||||
/** The share shown, under the user's used/remaining preference. */
|
||||
percent: number;
|
||||
percentText: string;
|
||||
@@ -36,66 +34,28 @@ export interface PinnedUsageSource {
|
||||
}
|
||||
|
||||
/** How much of each window the one-line summary has room for. */
|
||||
export type PinnedUsageLayout = "meters" | "labels" | "compact" | "percents";
|
||||
export type PinnedUsageLayout = "meters" | "labels" | "percents";
|
||||
|
||||
// A meter narrower than this is a sliver that reads as noise rather than a share.
|
||||
export const MIN_METER_WIDTH = 16;
|
||||
/** The space between a meter and its text. */
|
||||
export const METER_GAP = 4;
|
||||
|
||||
const DURATION_TOKEN_PATTERN = /^\d+[smhd]$/i;
|
||||
|
||||
function normalizePeriodToken(token: string): string | null {
|
||||
const lower = token.toLowerCase();
|
||||
if (lower === "wk" || lower === "weekly") return "wk";
|
||||
if (lower === "mo" || lower === "monthly") return "mo";
|
||||
if (DURATION_TOKEN_PATTERN.test(token)) return lower;
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a bare period token ("5h", "wk", "mo") from a window's short label so tight sidebar
|
||||
* rows can keep shorthands visible instead of dropping every label when one window is scoped.
|
||||
*/
|
||||
function compactShortLabel(shortLabel: string): string {
|
||||
const trimmed = shortLabel.trim();
|
||||
if (trimmed === "") return "";
|
||||
const exact = normalizePeriodToken(trimmed);
|
||||
if (exact !== null) return exact;
|
||||
const parts = trimmed.split(/\s+/);
|
||||
if (parts.length > 1) {
|
||||
const first = normalizePeriodToken(parts[0]!);
|
||||
if (first !== null) return first;
|
||||
const last = normalizePeriodToken(parts[parts.length - 1]!);
|
||||
if (last !== null) return last;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* The richest layout that fits on one line: every window's meter, else its short label, else its
|
||||
* bare period shorthand, else its percent alone. Meters are all or none; a line never mixes them.
|
||||
* Until the widths are known it shows labels, which never flashes meters that turn out not to fit.
|
||||
* percent alone. Meters are all or none; a line never mixes them. Until the widths are known it
|
||||
* shows labels, which never flashes meters that turn out not to fit.
|
||||
*/
|
||||
export function choosePinnedUsageLayout(input: {
|
||||
available: number | null;
|
||||
labelsWidth: number | null;
|
||||
compactWidth: number | null;
|
||||
percentsWidth: number | null;
|
||||
windowCount: number;
|
||||
}): PinnedUsageLayout {
|
||||
const { available, labelsWidth, compactWidth, percentsWidth, windowCount } = input;
|
||||
if (
|
||||
available === null ||
|
||||
labelsWidth === null ||
|
||||
compactWidth === null ||
|
||||
percentsWidth === null
|
||||
) {
|
||||
return "labels";
|
||||
}
|
||||
const { available, labelsWidth, percentsWidth, windowCount } = input;
|
||||
if (available === null || labelsWidth === null || percentsWidth === null) return "labels";
|
||||
if (labelsWidth + windowCount * (MIN_METER_WIDTH + METER_GAP) <= available) return "meters";
|
||||
if (labelsWidth <= available) return "labels";
|
||||
if (compactWidth <= available && compactWidth > percentsWidth) return "compact";
|
||||
return percentsWidth < labelsWidth ? "percents" : "labels";
|
||||
}
|
||||
|
||||
@@ -125,13 +85,10 @@ export function resolvePinnedUsage(
|
||||
.map((window) => {
|
||||
const percent = displayPercent(window, preferences.displayAs) ?? 0;
|
||||
const percentText = formatPct(percent);
|
||||
const shortLabel =
|
||||
window.shortLabel ?? formatProviderUsageLabel(window.id, window.label, t);
|
||||
return {
|
||||
key: `${entry.id}/${window.id}`,
|
||||
label: `${describe(entry, formatProviderUsageLabel(window.id, window.label, t))} ${formatDisplayPct(percent, preferences.displayAs, undefined, t)}`,
|
||||
shortLabel,
|
||||
compactLabel: compactShortLabel(shortLabel),
|
||||
shortLabel: window.shortLabel ?? formatProviderUsageLabel(window.id, window.label, t),
|
||||
percent,
|
||||
percentText,
|
||||
tone: windowTone(window),
|
||||
|
||||
@@ -20,7 +20,6 @@ import { useSessionStore, type SessionState } from "@/stores/session-store";
|
||||
import { useUsageSetting } from "./setting";
|
||||
import { usageCopy } from "./copy";
|
||||
import {
|
||||
markUsageRefreshFailure,
|
||||
replaceReport,
|
||||
resolveAgentUsageView,
|
||||
resolveUsageRefresh,
|
||||
@@ -98,32 +97,17 @@ async function streamReports(input: {
|
||||
return settleReports(queryClient.getQueryData<UsageReportEntry[]>(queryKey), reports);
|
||||
}
|
||||
|
||||
async function listReports(
|
||||
function listReports(
|
||||
queryClient: QueryClient,
|
||||
serverId: string,
|
||||
forceRefresh = false,
|
||||
): Promise<UsageReportEntry[]> {
|
||||
const queryKey = usageReportsQueryKey(serverId);
|
||||
const attempted = queryClient.getQueryData<UsageReportEntry[]>(queryKey) ?? [];
|
||||
try {
|
||||
return await streamReports({ queryClient, queryKey, serverId, forceRefresh });
|
||||
} catch (error) {
|
||||
recordUsageRefreshFailure(queryClient, queryKey, attempted);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function recordUsageRefreshFailure(
|
||||
queryClient: QueryClient,
|
||||
queryKey: QueryKey,
|
||||
attempted: readonly UsageReportEntry[],
|
||||
): void {
|
||||
const { dataUpdatedAt } = queryClient.getQueryState(queryKey) ?? {};
|
||||
queryClient.setQueryData<UsageReportEntry[]>(
|
||||
queryKey,
|
||||
(current) => markUsageRefreshFailure(current, attempted),
|
||||
{ updatedAt: dataUpdatedAt },
|
||||
);
|
||||
return streamReports({
|
||||
queryClient,
|
||||
queryKey: usageReportsQueryKey(serverId),
|
||||
serverId,
|
||||
forceRefresh,
|
||||
});
|
||||
}
|
||||
|
||||
async function getReport(
|
||||
@@ -174,12 +158,9 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
dataShape: "value",
|
||||
staleTimeMs: REPORTS_STALE_TIME_MS,
|
||||
});
|
||||
const mutation = useMutation({
|
||||
mutationKey: [...usageReportsQueryKey(serverId), "refresh"],
|
||||
mutationFn: (hostId: string) => refreshReports(queryClient, hostId),
|
||||
});
|
||||
const { mutate, variables } = mutation;
|
||||
const refresh = useCallback(() => mutate(serverId), [mutate, serverId]);
|
||||
const refresh = useCallback(() => {
|
||||
void refreshReports(queryClient, serverId).catch(() => undefined);
|
||||
}, [queryClient, serverId]);
|
||||
const { t } = useTranslation();
|
||||
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const view = resolveUsageView(
|
||||
@@ -189,7 +170,6 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
isConnected,
|
||||
supportsUsage: isSupported,
|
||||
query: toQueryState(query),
|
||||
refreshState: variables === serverId ? resolveUsageRefresh(mutation) : "idle",
|
||||
},
|
||||
t,
|
||||
);
|
||||
@@ -285,26 +265,23 @@ export function useUsageHosts(): UsageHost[] {
|
||||
*/
|
||||
export function useReportRefresh(
|
||||
serverId: string,
|
||||
entry: UsageReportEntry,
|
||||
reportId: string,
|
||||
agentId?: string,
|
||||
): { refresh: () => void; refreshState: UsageRefresh } {
|
||||
const queryClient = useQueryClient();
|
||||
const usageScopeKey = useAgentUsageScopeKey(serverId, agentId);
|
||||
const queryKey =
|
||||
agentId === undefined
|
||||
? usageReportsQueryKey(serverId)
|
||||
: agentUsageQueryKey(serverId, agentId, usageScopeKey);
|
||||
const mutation = useMutation({
|
||||
mutationKey: [...queryKey, "refresh", entry.id],
|
||||
mutationFn: (attempted: UsageReportEntry) => getReport(serverId, attempted.id, true, agentId),
|
||||
onSuccess: (report, attempted) => {
|
||||
queryClient.setQueryData<UsageReportEntry[]>(queryKey, (reports) =>
|
||||
reports ? replaceReport(reports, attempted.id, report) : reports,
|
||||
mutationFn: () => getReport(serverId, reportId, true, agentId),
|
||||
onSuccess: (report) => {
|
||||
queryClient.setQueryData<UsageReportEntry[]>(
|
||||
agentId === undefined
|
||||
? usageReportsQueryKey(serverId)
|
||||
: agentUsageQueryKey(serverId, agentId, usageScopeKey),
|
||||
(reports) => (reports ? replaceReport(reports, reportId, report) : reports),
|
||||
);
|
||||
},
|
||||
onError: (_error, attempted) => recordUsageRefreshFailure(queryClient, queryKey, [attempted]),
|
||||
});
|
||||
const { mutate } = mutation;
|
||||
const refresh = useCallback(() => mutate(entry), [mutate, entry]);
|
||||
const refresh = useCallback(() => mutate(), [mutate]);
|
||||
return { refresh, refreshState: resolveUsageRefresh(mutation) };
|
||||
}
|
||||
|
||||
@@ -3,21 +3,24 @@ import { StyleSheet } from "react-native-unistyles";
|
||||
|
||||
/**
|
||||
* The reset data of a window or balance: the countdown first, then the exact time. When the line
|
||||
* is too narrow the exact time truncates and the countdown wraps within its column.
|
||||
* is too narrow the exact time gives way (truncates) and the countdown stays whole.
|
||||
*/
|
||||
export function UsageResetLine({
|
||||
countdown,
|
||||
exactTime,
|
||||
atRisk = false,
|
||||
testID,
|
||||
}: {
|
||||
countdown: string | null;
|
||||
exactTime: string | null;
|
||||
/** The countdown is a runs-out warning rather than a reset. */
|
||||
atRisk?: boolean;
|
||||
testID?: string;
|
||||
}) {
|
||||
if (!countdown) return null;
|
||||
return (
|
||||
<View style={styles.line} testID={testID}>
|
||||
<Text style={[styles.text, styles.countdown]}>{countdown}</Text>
|
||||
<Text style={atRisk ? styles.atRisk : styles.text}>{countdown}</Text>
|
||||
{exactTime ? (
|
||||
<Text style={[styles.text, styles.exactTime]} numberOfLines={1} ellipsizeMode="tail">
|
||||
{`\u00a0·\u00a0${exactTime}`}
|
||||
@@ -28,13 +31,18 @@ export function UsageResetLine({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
line: { flexDirection: "row", alignItems: "baseline" },
|
||||
line: { flexDirection: "row", alignItems: "center" },
|
||||
text: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
countdown: { maxWidth: "100%" },
|
||||
exactTime: { flexShrink: 1, minWidth: 0 },
|
||||
atRisk: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.statusDanger,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
exactTime: { flexShrink: 1 },
|
||||
}));
|
||||
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
resolvePinnedUsage,
|
||||
type PinnedUsageLayout,
|
||||
type PinnedUsageSource,
|
||||
type PinnedUsageWindow,
|
||||
} from "./pinned";
|
||||
import { UsageModal } from "./usage-modal";
|
||||
|
||||
@@ -124,8 +123,8 @@ function layoutWidth(event: LayoutChangeEvent): number {
|
||||
|
||||
/**
|
||||
* One line: each account's icon, then per window a meter and "31% 5h". Off-screen copies measure
|
||||
* the line with full labels, bare period shorthands, and percents alone; the richest layout that
|
||||
* fits is shown, and what it leaves out takes no space at all.
|
||||
* the line with labels and with percents alone; the richest layout that fits is shown, and what
|
||||
* it leaves out takes no space at all.
|
||||
*/
|
||||
function PinnedUsageTrigger({
|
||||
label,
|
||||
@@ -140,7 +139,6 @@ function PinnedUsageTrigger({
|
||||
}) {
|
||||
const [available, setAvailable] = useState<number | null>(null);
|
||||
const [labelsWidth, setLabelsWidth] = useState<number | null>(null);
|
||||
const [compactWidth, setCompactWidth] = useState<number | null>(null);
|
||||
const [percentsWidth, setPercentsWidth] = useState<number | null>(null);
|
||||
const handleAvailableLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
setAvailable(layoutWidth(event));
|
||||
@@ -148,16 +146,12 @@ function PinnedUsageTrigger({
|
||||
const handleLabelsLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
setLabelsWidth(layoutWidth(event));
|
||||
}, []);
|
||||
const handleCompactLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
setCompactWidth(layoutWidth(event));
|
||||
}, []);
|
||||
const handlePercentsLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
setPercentsWidth(layoutWidth(event));
|
||||
}, []);
|
||||
const layout = choosePinnedUsageLayout({
|
||||
available,
|
||||
labelsWidth,
|
||||
compactWidth,
|
||||
percentsWidth,
|
||||
windowCount: sources.reduce((count, source) => count + source.windows.length, 0),
|
||||
});
|
||||
@@ -183,9 +177,6 @@ function PinnedUsageTrigger({
|
||||
<View style={styles.measured} onLayout={handleLabelsLayout}>
|
||||
<PinnedUsageLine sources={sources} layout="labels" measuring />
|
||||
</View>
|
||||
<View style={styles.measured} onLayout={handleCompactLayout}>
|
||||
<PinnedUsageLine sources={sources} layout="compact" measuring />
|
||||
</View>
|
||||
<View style={styles.measured} onLayout={handlePercentsLayout}>
|
||||
<PinnedUsageLine sources={sources} layout="percents" measuring />
|
||||
</View>
|
||||
@@ -194,12 +185,6 @@ function PinnedUsageTrigger({
|
||||
);
|
||||
}
|
||||
|
||||
function windowSuffix(window: PinnedUsageWindow, layout: PinnedUsageLayout): string {
|
||||
if (layout === "percents") return "";
|
||||
if (layout === "compact") return window.compactLabel;
|
||||
return window.shortLabel;
|
||||
}
|
||||
|
||||
/**
|
||||
* The line's items as direct children of one row, so every meter shares the leftover width
|
||||
* equally.
|
||||
@@ -230,7 +215,6 @@ function PinnedUsageLine({
|
||||
</View>
|
||||
{source.windows.map((window, windowIndex) => {
|
||||
const leadStyle = windowIndex === 0 ? styles.iconGap : styles.windowGap;
|
||||
const suffix = windowSuffix(window, layout);
|
||||
return (
|
||||
<Fragment key={window.key}>
|
||||
{layout === "meters" ? (
|
||||
@@ -244,7 +228,9 @@ function PinnedUsageLine({
|
||||
testID={measuring ? undefined : "sidebar-usage-pinned-window"}
|
||||
>
|
||||
{window.percentText}
|
||||
{suffix === "" ? null : <Text style={styles.windowLabel}>{` ${suffix}`}</Text>}
|
||||
{layout === "percents" || window.shortLabel === "" ? null : (
|
||||
<Text style={styles.windowLabel}>{` ${window.shortLabel}`}</Text>
|
||||
)}
|
||||
</Text>
|
||||
</Fragment>
|
||||
);
|
||||
|
||||