mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-20 23:35:27 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6d2ef62b42 | ||
|
|
27c126d352 | ||
|
|
7e3826ad6c | ||
|
|
c853f98b90 | ||
|
|
c3da87ee4c | ||
|
|
2298effb0b | ||
|
|
a7fed94e51 | ||
|
|
36dffc9503 | ||
|
|
d78cc90e4d | ||
|
|
0f57c2b4c7 | ||
|
|
ddd7aff9be | ||
|
|
7eec266f50 |
+7
-5
@@ -186,11 +186,13 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
|
||||
|
||||
Single file, validated with `PersistedConfigSchema`.
|
||||
|
||||
`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.
|
||||
`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.
|
||||
|
||||
`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
|
||||
|
||||
@@ -471,18 +471,6 @@ Workspace records decide ownership, including explicit non-ownership after recov
|
||||
ownership checks prefer the marker-verified worktree root over the legacy
|
||||
path shape: a plugin can place a worktree several directories below the default worktrees root.
|
||||
|
||||
A plugin can also take over worktree creation, removal, and restoration with
|
||||
`server.registerWorktreeManager({ create, remove?, restore? })`. It runs after
|
||||
`worktree.create.before` and before `worktree.create.after`, with a 120-second timeout matching Git
|
||||
worktree commands. Paseo snapshots existing worktree paths before calling `create` so a manager
|
||||
cannot adopt a pre-existing directory as Paseo-owned, verifies Git worktree postconditions, records
|
||||
`worktreeManagerPluginId` in `paseo/worktree.json` and on the workspace record,
|
||||
and skips first-agent branch auto-rename. Removal saves `refs/paseo/kept-commits/<sha>` before
|
||||
calling the owning plugin's `remove`, and `create`, `remove`, and `restore` carry `untrusted` for fork
|
||||
change requests; `remove` and `restore` fall back to built-in Git when the plugin declines or is disabled. See the
|
||||
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
|
||||
`plugin-examples/worktrunk`.
|
||||
|
||||
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
||||
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
||||
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
||||
|
||||
@@ -10,16 +10,19 @@ 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 leaves room for the outline at full width", async ({
|
||||
test("resizes mounted chat content and keeps timeline and composer on one rail beside the outline", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
@@ -37,26 +40,46 @@ test("resizes mounted chat content and leaves room for the outline at full width
|
||||
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();
|
||||
|
||||
@@ -503,6 +503,34 @@ 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);
|
||||
@@ -531,6 +559,26 @@ 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") {
|
||||
@@ -570,6 +618,20 @@ 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,13 +2,14 @@ import { tmpdir } from "node:os";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import type { UsageReport, 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 {
|
||||
@@ -45,6 +46,7 @@ import {
|
||||
refreshAllUsage,
|
||||
togglePin,
|
||||
usageItem,
|
||||
usageModal,
|
||||
} from "../support/helpers/usage-sidebar-item";
|
||||
|
||||
const emptyHome = path.join(tmpdir(), `paseo-usage-empty-${randomUUID()}`);
|
||||
@@ -233,8 +235,8 @@ test.describe("usage modal", () => {
|
||||
],
|
||||
});
|
||||
await gotoAppShell(page);
|
||||
// Three windows leave no room for labels in the summary, so it reads percents.
|
||||
await expectPinnedUsage(page, ["31%", "20%", "12%"]);
|
||||
// Three Weekly labels overflow the summary, so it falls back to compact shorthands.
|
||||
await expectPinnedUsage(page, ["31% wk", "20% wk", "12% wk"]);
|
||||
await openUsageFromItem(page);
|
||||
await expectUsageCardOrder(page, ["alpha:a", "beta:home", "beta:work"]);
|
||||
|
||||
@@ -865,6 +867,106 @@ 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,6 +40,7 @@ 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";
|
||||
@@ -577,3 +578,97 @@ 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%"]);
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ type AgentSkillsClient = Pick<
|
||||
"close" | "connect" | "getAgentSkillsStatus" | "saveAgentSkillsSelection"
|
||||
>;
|
||||
|
||||
export type SkillTargetName = "agents" | "claude";
|
||||
export type SkillTargetName = "agents" | "claude" | "antigravity";
|
||||
|
||||
export interface AgentSkillsSandbox {
|
||||
available: string[];
|
||||
@@ -64,6 +64,7 @@ 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,3 +51,18 @@ 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,13 +185,15 @@ 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(Date.now() - 2 * 60 * 60_000).toISOString(),
|
||||
expiresAt: new Date(fetchedAt - 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 or ~/.codex. `withBrokenProvider` adds a
|
||||
* installs never land in the real ~/.agents, ~/.claude, ~/.codex, or ~/.gemini/config. `withBrokenProvider` adds a
|
||||
* provider that cannot start.
|
||||
*/
|
||||
export async function startSetupHost(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { expect, test, type Page } from "@playwright/test";
|
||||
import { openChangesPanel } from "./branch-switcher";
|
||||
|
||||
export async function restoreArchivedWorkspace(page: Page): Promise<void> {
|
||||
@@ -32,7 +32,11 @@ export async function expectCommittedFile(page: Page, filename: string): Promise
|
||||
}
|
||||
|
||||
export async function expectCommittedFileAfterReload(page: Page, filename: string): Promise<void> {
|
||||
await expectCommittedFile(page, filename);
|
||||
await page.reload();
|
||||
await expectCommittedFile(page, filename);
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@
|
||||
[role="slider"],
|
||||
[role="menuitem"],
|
||||
[tabindex],
|
||||
[data-window-no-drag],
|
||||
[contenteditable="true"] {
|
||||
-webkit-app-region: no-drag !important;
|
||||
}
|
||||
|
||||
@@ -66,4 +66,23 @@ 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,6 +37,18 @@ 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;
|
||||
@@ -47,7 +59,7 @@ export async function fetchAgentCommands(input: {
|
||||
draftConfig: input.draftConfig,
|
||||
});
|
||||
if (response.error) throw new Error(response.error);
|
||||
return response.commands as AgentSlashCommand[];
|
||||
return dedupeSlashCommands(response.commands as AgentSlashCommand[]);
|
||||
}
|
||||
|
||||
interface UseAgentCommandsQueryOptions {
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
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,7 +11,3 @@ export interface ChatOutlineRailProps {
|
||||
export function ChatOutlineRail(_props: ChatOutlineRailProps): null {
|
||||
return null;
|
||||
}
|
||||
|
||||
export function useChatOutlineRailLayout(_enabled: boolean) {
|
||||
return { onLayout: undefined, inset: 0 };
|
||||
}
|
||||
|
||||
@@ -2,19 +2,17 @@ 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 = 36;
|
||||
const RAIL_LEFT = SPACING[2];
|
||||
const RAIL_WIDTH = CHAT_OUTLINE_RAIL_WIDTH;
|
||||
const RAIL_LEFT = CHAT_OUTLINE_RAIL_LEFT;
|
||||
const SLOT_HEIGHT = 8;
|
||||
const MIN_PANEL_WIDTH = 918;
|
||||
const RESTING_PILL_HEIGHT = 2;
|
||||
const MAGNIFIED_PILL_HEIGHT = 4;
|
||||
const RESTING_PILL_WIDTH = 10;
|
||||
@@ -24,11 +22,6 @@ 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,6 +40,7 @@ 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 {
|
||||
@@ -1228,21 +1229,20 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
]);
|
||||
|
||||
const contentContainerStyle = useMemo((): CSSProperties => {
|
||||
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;
|
||||
const gutter = isMobileBreakpoint ? 8 : CHAT_COLUMN_BASE_GUTTER;
|
||||
const { paddingLeft, paddingRight } = resolveChatColumnGutters({
|
||||
gutter,
|
||||
outlineInset,
|
||||
contentMaxWidth,
|
||||
});
|
||||
return {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
minHeight: "100%",
|
||||
paddingTop: CONTENT_PADDING_TOP_PX,
|
||||
paddingBottom: 16,
|
||||
paddingLeft: leftGutter,
|
||||
paddingRight: rightGutter,
|
||||
paddingLeft,
|
||||
paddingRight,
|
||||
boxSizing: "border-box",
|
||||
};
|
||||
}, [contentMaxWidth, isMobileBreakpoint, outlineInset]);
|
||||
|
||||
@@ -80,8 +80,9 @@ 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, useChatOutlineRailLayout } from "@/agent-stream/chat-outline/rail";
|
||||
import { ChatOutlineRail } 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 {
|
||||
@@ -322,7 +323,7 @@ function ScrollToBottomButton({
|
||||
);
|
||||
if (isNearBottom && !isTimelineDetached) return null;
|
||||
return (
|
||||
<View style={containerStyle} pointerEvents="box-none">
|
||||
<View style={containerStyle} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
|
||||
<Animated.View entering={scrollIndicatorFadeIn} exiting={scrollIndicatorFadeOut}>
|
||||
<Pressable
|
||||
style={stylesheet.scrollToBottomButton}
|
||||
@@ -365,7 +366,6 @@ 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,10 +404,6 @@ 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,
|
||||
);
|
||||
@@ -617,22 +613,21 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
mountedHistoryMessageIds.has(messageId) || liveHeadMessageIds.has(messageId),
|
||||
};
|
||||
}, [baseRenderModel.segments.liveHead, mountedHistoryMessageIds]);
|
||||
const outlineEnabled = supportsChatOutline && chatOutlineEnabled;
|
||||
const outlineRail = useChatOutlineRail();
|
||||
const outlineInset = outlineRail.inset;
|
||||
const chatOutline = useChatOutline({
|
||||
agentId,
|
||||
serverId: resolvedServerId,
|
||||
timelineEpoch,
|
||||
tail: effectiveStreamItems,
|
||||
head: effectiveStreamHead,
|
||||
enabled: outlineEnabled,
|
||||
enabled: outlineRail.enabled,
|
||||
viewportRef,
|
||||
onJumpError: handleTimelineHistoryLoadError,
|
||||
mountedHistoryMessageIds,
|
||||
revealLoadedMessage: revealLoadedHistory,
|
||||
});
|
||||
|
||||
const outlineLayout = useChatOutlineRailLayout(outlineEnabled);
|
||||
|
||||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
@@ -1176,10 +1171,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
visibleMessageIds={mountedMessageIds}
|
||||
>
|
||||
<ToolCallSheetProvider>
|
||||
<AssistantSelectionCopySurface
|
||||
style={stylesheet.container}
|
||||
onLayout={outlineLayout.onLayout}
|
||||
>
|
||||
<AssistantSelectionCopySurface style={stylesheet.container}>
|
||||
<MessageOuterSpacingProvider disableOuterSpacing>
|
||||
<ToolCallExpansionContext.Provider value={toolCallExpansion}>
|
||||
<UserMessageExpansionContext.Provider value={userMessageExpansion}>
|
||||
@@ -1208,12 +1200,12 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
baseListContentContainerStyle: stylesheet.listContentContainer,
|
||||
forwardListContentContainerStyle: stylesheet.forwardListContentContainer,
|
||||
contentMaxWidth,
|
||||
outlineInset: outlineLayout.inset,
|
||||
outlineInset,
|
||||
})}
|
||||
</UserMessageExpansionContext.Provider>
|
||||
</ToolCallExpansionContext.Provider>
|
||||
</MessageOuterSpacingProvider>
|
||||
{outlineLayout.inset > 0 && chatOutline.prompts.length >= 2 ? (
|
||||
{outlineInset > 0 && chatOutline.prompts.length >= 2 ? (
|
||||
<ChatOutlineRail
|
||||
prompts={chatOutline.prompts}
|
||||
activePrompt={chatOutline.activePrompt}
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { View, 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} onLayout={onLayout}>
|
||||
{children}
|
||||
</View>
|
||||
);
|
||||
return <View style={style}>{children}</View>;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { useCallback, type ClipboardEvent, type CSSProperties, type ReactNode } from "react";
|
||||
import { View, type LayoutChangeEvent, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { View, 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" };
|
||||
@@ -13,7 +12,6 @@ const DISPLAY_CONTENTS: CSSProperties = { display: "contents" };
|
||||
export function AssistantSelectionCopySurface({
|
||||
children,
|
||||
style,
|
||||
onLayout,
|
||||
}: AssistantSelectionCopySurfaceProps) {
|
||||
const handleCopy = useCallback((event: ClipboardEvent<HTMLDivElement>) => {
|
||||
const content = createAssistantSelectionClipboardContent(window.getSelection());
|
||||
@@ -28,9 +26,7 @@ export function AssistantSelectionCopySurface({
|
||||
|
||||
return (
|
||||
<div onCopy={handleCopy} style={DISPLAY_CONTENTS}>
|
||||
<View style={style} onLayout={onLayout}>
|
||||
{children}
|
||||
</View>
|
||||
<View style={style}>{children}</View>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
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 };
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export {
|
||||
CHAT_COLUMN_RAIL_DATASET,
|
||||
ChatColumnRailSurface,
|
||||
useChatOutlineRail,
|
||||
type ChatColumnRailSurfaceProps,
|
||||
type ChatOutlineRailState,
|
||||
} from "./index.native";
|
||||
@@ -0,0 +1,143 @@
|
||||
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,6 +2,7 @@ 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";
|
||||
@@ -35,7 +36,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
|
||||
|
||||
return (
|
||||
<KeyboardTranslateView style={styles.container}>
|
||||
<View style={styles.inputAreaContainer}>
|
||||
<View style={styles.inputAreaContainer} dataSet={CHAT_COLUMN_RAIL_DATASET}>
|
||||
<View style={styles.inputAreaContent}>
|
||||
<View style={styles.calloutStack}>
|
||||
<View style={styles.callout}>
|
||||
|
||||
@@ -24,6 +24,9 @@ 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,6 +27,7 @@ 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;
|
||||
@@ -49,6 +50,7 @@ interface CompactHeaderProps {
|
||||
*/
|
||||
export function CompactHeader({
|
||||
navigation,
|
||||
inDesktopTitlebar = false,
|
||||
onBack,
|
||||
title,
|
||||
titleTestID,
|
||||
@@ -58,22 +60,28 @@ export function CompactHeader({
|
||||
}: CompactHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const inTopBand = useTopBand() !== null;
|
||||
const usesTitlebarHeight = inTopBand || inDesktopTitlebar;
|
||||
const rootStyle = useMemo(
|
||||
() => [
|
||||
styles.root,
|
||||
{
|
||||
paddingTop: insets.top + (inTopBand ? 0 : HEADER_TOP_PADDING_MOBILE),
|
||||
paddingTop: insets.top + (usesTitlebarHeight ? 0 : HEADER_TOP_PADDING_MOBILE),
|
||||
marginLeft: insets.left,
|
||||
marginRight: insets.right,
|
||||
},
|
||||
],
|
||||
[inTopBand, insets.top, insets.left, insets.right],
|
||||
[usesTitlebarHeight, insets.top, insets.left, insets.right],
|
||||
);
|
||||
|
||||
return (
|
||||
<IconButtonChromeProvider value="header-island">
|
||||
<View style={rootStyle}>
|
||||
<View style={inTopBand ? styles.topBandRow : styles.row}>
|
||||
<View
|
||||
style={[
|
||||
usesTitlebarHeight ? styles.titlebarRow : styles.row,
|
||||
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
|
||||
]}
|
||||
>
|
||||
<View style={styles.island}>
|
||||
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
|
||||
</View>
|
||||
@@ -155,12 +163,16 @@ const styles = StyleSheet.create((theme) => ({
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
topBandRow: {
|
||||
titlebarRow: {
|
||||
height: HEADER_INNER_HEIGHT,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
desktopTitlebarDividerSpace: {
|
||||
borderBottomWidth: theme.borderWidth[1],
|
||||
borderBottomColor: "transparent",
|
||||
},
|
||||
titleGroup: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
useRef,
|
||||
type CSSProperties,
|
||||
type MouseEvent as ReactMouseEvent,
|
||||
type PointerEvent as ReactPointerEvent,
|
||||
type Ref,
|
||||
} from "react";
|
||||
import type { DOMProps } from "expo/dom";
|
||||
@@ -63,6 +64,12 @@ 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,
|
||||
@@ -553,10 +560,46 @@ export default function TerminalEmulator({
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleRootPointerDown = useCallback(() => {
|
||||
onFocus?.();
|
||||
runtimeRef.current?.focus();
|
||||
}, [onFocus]);
|
||||
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 handleRootContextMenu = useCallback(
|
||||
(event: ReactMouseEvent) => {
|
||||
@@ -588,6 +631,9 @@ 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} />
|
||||
|
||||
@@ -4,6 +4,7 @@ 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";
|
||||
@@ -536,14 +537,17 @@ export function WorkspaceDraftComposer({
|
||||
return (
|
||||
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
|
||||
{formErrorMessage ? (
|
||||
<View style={styles.formErrorRow}>
|
||||
<View
|
||||
style={styles.formErrorRow}
|
||||
dataSet={isComposerFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
|
||||
>
|
||||
<View style={styles.formError}>
|
||||
<Text style={styles.errorText}>{formErrorMessage}</Text>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
{importPillPress && !isComposerFullscreen ? (
|
||||
<View style={styles.importPillRow}>
|
||||
<View style={styles.importPillRow} dataSet={CHAT_COLUMN_RAIL_DATASET}>
|
||||
<View style={styles.importPillContent}>
|
||||
<ComposerImportPill onPress={importPillPress} />
|
||||
</View>
|
||||
|
||||
@@ -30,6 +30,7 @@ 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,
|
||||
@@ -2575,7 +2576,10 @@ function ComposerContentImpl({
|
||||
>
|
||||
<AttachmentLightbox source={lightboxSource} onClose={handleLightboxClose} />
|
||||
{/* Input area */}
|
||||
<View style={inputAreaContainerStyle}>
|
||||
<View
|
||||
style={inputAreaContainerStyle}
|
||||
dataSet={isFullscreen ? undefined : CHAT_COLUMN_RAIL_DATASET}
|
||||
>
|
||||
<View style={inputAreaContentStyle}>
|
||||
{isFullscreen ? null : queueList}
|
||||
{!isFullscreen && sendErrorNode}
|
||||
|
||||
@@ -21,6 +21,7 @@ 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";
|
||||
@@ -45,7 +46,7 @@ export function ComposerTrackBar({ children }: { children: ReactNode }): ReactEl
|
||||
const scrollGesture = usePanelAwareHorizontalScrollGesture();
|
||||
const scrollBoundary = useHorizontalScrollBoundary();
|
||||
return (
|
||||
<View style={styles.bar} pointerEvents="box-none">
|
||||
<View style={styles.bar} dataSet={CHAT_COLUMN_RAIL_DATASET} pointerEvents="box-none">
|
||||
<View style={styles.trackViewport} pointerEvents="box-none">
|
||||
<GestureDetector gesture={scrollGesture}>
|
||||
<Animated.ScrollView
|
||||
|
||||
@@ -2323,6 +2323,9 @@ export const ar: TranslationResources = {
|
||||
resetsIn: "تتم إعادة التعيين خلال {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}، {{time}}",
|
||||
projectedLeftAtReset: "نحو {{percentage}} متبقية عند إعادة التعيين",
|
||||
limitReached: "تم بلوغ الحد",
|
||||
mayHaveRunOut: "ربما نفدت الحصة",
|
||||
runsOutNow: "ينفد الآن",
|
||||
runsOutIn: "ينفد خلال {{duration}}",
|
||||
justNow: "الآن",
|
||||
@@ -2892,7 +2895,8 @@ export const ar: TranslationResources = {
|
||||
updateAvailable: "التحديث متاح",
|
||||
updateTitle: "تحديث مهارات Paseo ؟",
|
||||
uninstallTitle: "إلغاء تثبيت مهارات Paseo ؟",
|
||||
uninstallMessage: "يزيل جميع مهارات تنسيق Paseo من ~/.agents ، ~/.claude ، ~/.codex.",
|
||||
uninstallMessage:
|
||||
"يزيل جميع مهارات تنسيق Paseo من ~/.agents و~/.claude و~/.codex و~/.gemini/config.",
|
||||
choose: "اختيار المهارات",
|
||||
chooseAll: "كل المهارات",
|
||||
chooseAllHint: "أبقِ جميع المهارات المرفقة مثبتة، بما فيها ما يُضاف لاحقًا.",
|
||||
@@ -2900,7 +2904,7 @@ export const ar: TranslationResources = {
|
||||
chooseEmpty: "لا تتضمن هذه النسخة أي مهارات.",
|
||||
removeTitle: "إزالة المهارات غير المحددة؟",
|
||||
removeMessage:
|
||||
"سيتم حذف {{skills}} من ~/.agents و~/.claude و~/.codex. كما يُحذف كل ما أضفته داخل مجلدات المهارات تلك.",
|
||||
"سيتم حذف {{skills}} من ~/.agents و~/.claude و~/.codex و~/.gemini/config. كما يُحذف كل ما أضفته داخل مجلدات المهارات تلك.",
|
||||
saveFailed: "تعذر حفظ اختيار المهارات.",
|
||||
statusFailed: "غير قادر على التحقق من حالة مهارات التنسيق.",
|
||||
updateFailed: "غير قادر على تحديث مهارات التنسيق.",
|
||||
|
||||
@@ -2333,6 +2333,9 @@ 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",
|
||||
@@ -2994,7 +2997,7 @@ export const en = {
|
||||
updateTitle: "Update Paseo skills?",
|
||||
uninstallTitle: "Uninstall Paseo skills?",
|
||||
uninstallMessage:
|
||||
"Removes all Paseo orchestration skills from ~/.agents, ~/.claude, ~/.codex on this host.",
|
||||
"Removes all Paseo orchestration skills from ~/.agents, ~/.claude, ~/.codex, and ~/.gemini/config on this host.",
|
||||
choose: "Choose skills",
|
||||
chooseAll: "All skills",
|
||||
chooseAllHint: "Keep every bundled skill installed, including ones added later.",
|
||||
@@ -3002,7 +3005,7 @@ export const en = {
|
||||
chooseEmpty: "This host bundles no skills.",
|
||||
removeTitle: "Remove deselected skills?",
|
||||
removeMessage:
|
||||
"{{skills}} will be deleted from ~/.agents, ~/.claude, and ~/.codex on this host. Anything you added inside those skill folders is deleted too.",
|
||||
"{{skills}} will be deleted from ~/.agents, ~/.claude, ~/.codex, and ~/.gemini/config on this host. Anything you added inside those skill folders is deleted too.",
|
||||
saveFailed: "Could not save your skill selection.",
|
||||
actions: {
|
||||
update: "Update",
|
||||
|
||||
@@ -2354,6 +2354,9 @@ 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",
|
||||
@@ -2916,7 +2919,7 @@ export const es: TranslationResources = {
|
||||
updateTitle: "¿Actualizar las habilidades dePaseo?",
|
||||
uninstallTitle: "¿Desinstalar las habilidadesPaseo?",
|
||||
uninstallMessage:
|
||||
"Elimina todas las habilidades de orquestaciónPaseode ~/.agents, ~/.claude, ~/.codex.",
|
||||
"Elimina todas las habilidades de orquestación Paseo de ~/.agents, ~/.claude, ~/.codex y ~/.gemini/config.",
|
||||
choose: "Elegir habilidades",
|
||||
chooseAll: "Todas las habilidades",
|
||||
chooseAllHint:
|
||||
@@ -2925,7 +2928,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 y ~/.codex. También se elimina todo lo que hayas añadido dentro de esas carpetas de habilidades.",
|
||||
"{{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.",
|
||||
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,6 +2355,9 @@ 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",
|
||||
@@ -2919,7 +2922,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 et ~/.codex sur cet hôte.",
|
||||
"Supprime tous les skills d’orchestration Paseo de ~/.agents, ~/.claude, ~/.codex et ~/.gemini/config sur cet hôte.",
|
||||
choose: "Choisir les skills",
|
||||
chooseAll: "Tous les skills",
|
||||
chooseAllHint:
|
||||
@@ -2928,7 +2931,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 et ~/.codex 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, ~/.codex et ~/.gemini/config 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,6 +2328,9 @@ export const ja: TranslationResources = {
|
||||
resetsIn: "{{duration}}後にリセット",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "リセット時に約{{percentage}}残る見込み",
|
||||
limitReached: "上限に達しました",
|
||||
mayHaveRunOut: "上限に達した可能性があります",
|
||||
runsOutNow: "まもなく上限に到達",
|
||||
runsOutIn: "{{duration}}後に上限に到達",
|
||||
justNow: "たった今",
|
||||
@@ -2884,7 +2887,7 @@ export const ja: TranslationResources = {
|
||||
updateTitle: "Paseoスキルを更新しますか?",
|
||||
uninstallTitle: "Paseoスキルをアンインストールしますか?",
|
||||
uninstallMessage:
|
||||
"~/.agents、~/.claude、~/.codexからすべてのPaseoオーケストレーションスキルを削除します。",
|
||||
"~/.agents、~/.claude、~/.codex、~/.gemini/configからすべてのPaseoオーケストレーションスキルを削除します。",
|
||||
choose: "スキルを選択",
|
||||
chooseAll: "すべてのスキル",
|
||||
chooseAllHint:
|
||||
@@ -2893,7 +2896,7 @@ export const ja: TranslationResources = {
|
||||
chooseEmpty: "このビルドにはスキルが含まれていません。",
|
||||
removeTitle: "選択を外したスキルを削除しますか?",
|
||||
removeMessage:
|
||||
"{{skills}} を ~/.agents、~/.claude、~/.codex から削除します。それらのスキルフォルダー内に追加したものもすべて削除されます。",
|
||||
"{{skills}} を ~/.agents、~/.claude、~/.codex、~/.gemini/config から削除します。それらのスキルフォルダー内に追加したものもすべて削除されます。",
|
||||
saveFailed: "スキルの選択を保存できませんでした。",
|
||||
statusFailed: "オーケストレーションスキルのステータスを確認できません。",
|
||||
updateFailed: "オーケストレーションスキルを更新できません。",
|
||||
|
||||
@@ -2316,6 +2316,9 @@ export const ko: TranslationResources = {
|
||||
resetsIn: "{{duration}} 후 재설정",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "초기화 시 약 {{percentage}} 남을 예정",
|
||||
limitReached: "한도에 도달함",
|
||||
mayHaveRunOut: "한도를 소진했을 수 있음",
|
||||
runsOutNow: "지금 한도에 도달",
|
||||
runsOutIn: "{{duration}} 후 한도에 도달",
|
||||
justNow: "방금",
|
||||
@@ -2871,7 +2874,7 @@ export const ko: TranslationResources = {
|
||||
updateTitle: "Paseo 스킬을 업데이트할까요?",
|
||||
uninstallTitle: "Paseo 스킬을 제거할까요?",
|
||||
uninstallMessage:
|
||||
"~/.agents, ~/.claude, ~/.codex에서 모든 Paseo 오케스트레이션 스킬을 제거합니다.",
|
||||
"~/.agents, ~/.claude, ~/.codex, ~/.gemini/config에서 모든 Paseo 오케스트레이션 스킬을 제거합니다.",
|
||||
choose: "스킬 선택",
|
||||
chooseAll: "모든 스킬",
|
||||
chooseAllHint: "나중에 추가되는 항목을 포함하여 모든 번들 스킬을 설치된 상태로 유지합니다.",
|
||||
@@ -2879,7 +2882,7 @@ export const ko: TranslationResources = {
|
||||
chooseEmpty: "이 빌드에는 번들 스킬이 없습니다.",
|
||||
removeTitle: "선택 해제한 스킬을 제거할까요?",
|
||||
removeMessage:
|
||||
"{{skills}}는 ~/.agents, ~/.claude 및 ~/.codex에서 삭제됩니다. 해당 스킬 폴더 안에 추가한 모든 항목도 삭제됩니다.",
|
||||
"{{skills}}는 ~/.agents, ~/.claude, ~/.codex 및 ~/.gemini/config에서 삭제됩니다. 해당 스킬 폴더 안에 추가한 모든 항목도 삭제됩니다.",
|
||||
saveFailed: "선택한 스킬을 저장하지 못했습니다.",
|
||||
statusFailed: "오케스트레이션 스킬 상태를 확인할 수 없습니다.",
|
||||
updateFailed: "오케스트레이션 스킬을 업데이트할 수 없습니다.",
|
||||
|
||||
@@ -2339,6 +2339,9 @@ 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",
|
||||
@@ -2897,7 +2900,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 e ~/.codex.",
|
||||
"Remove todas as skills de orquestração do Paseo de ~/.agents, ~/.claude, ~/.codex e ~/.gemini/config.",
|
||||
choose: "Escolher skills",
|
||||
chooseAll: "Todas as skills",
|
||||
chooseAllHint:
|
||||
@@ -2906,7 +2909,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 e ~/.codex. Tudo o que você adicionou dentro dessas pastas de skills também é excluído.",
|
||||
"{{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.",
|
||||
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,6 +2341,9 @@ export const ru: TranslationResources = {
|
||||
resetsIn: "сброс через {{duration}}",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}}, {{time}}",
|
||||
projectedLeftAtReset: "К сбросу останется ~{{percentage}}",
|
||||
limitReached: "Лимит исчерпан",
|
||||
mayHaveRunOut: "Лимит мог уже исчерпаться",
|
||||
runsOutNow: "закончится сейчас",
|
||||
runsOutIn: "закончится через {{duration}}",
|
||||
justNow: "только что",
|
||||
@@ -2909,7 +2912,7 @@ export const ru: TranslationResources = {
|
||||
updateTitle: "Обновить навыки Paseo?",
|
||||
uninstallTitle: "Удалить навыки Paseo?",
|
||||
uninstallMessage:
|
||||
"Удаляет все навыки оркестрации Paseo из ~/.agents, ~/.claude и ~/.codex на этом хосте.",
|
||||
"Удаляет все навыки оркестрации Paseo из ~/.agents, ~/.claude, ~/.codex и ~/.gemini/config на этом хосте.",
|
||||
choose: "Выбрать навыки",
|
||||
chooseAll: "Все навыки",
|
||||
chooseAllHint: "Устанавливать все встроенные навыки, включая добавленные позже.",
|
||||
@@ -2917,7 +2920,7 @@ export const ru: TranslationResources = {
|
||||
chooseEmpty: "На этом хосте нет встроенных навыков.",
|
||||
removeTitle: "Удалить снятые навыки?",
|
||||
removeMessage:
|
||||
"{{skills}} будут удалены из ~/.agents, ~/.claude и ~/.codex на этом хосте. Всё, что вы добавили в эти папки навыков, тоже будет удалено.",
|
||||
"{{skills}} будут удалены из ~/.agents, ~/.claude, ~/.codex и ~/.gemini/config на этом хосте. Всё, что вы добавили в эти папки навыков, тоже будет удалено.",
|
||||
saveFailed: "Не удалось сохранить выбор навыков.",
|
||||
statusFailed: "Не удалось проверить состояние навыков оркестрации.",
|
||||
updateFailed: "Не удалось обновить навыки оркестрации.",
|
||||
|
||||
@@ -2282,6 +2282,9 @@ export const zhCN: TranslationResources = {
|
||||
resetsIn: "将在 {{duration}}后重置",
|
||||
resetsAtWeekday: "{{weekday}} {{time}}",
|
||||
resetsAtDate: "{{date}} {{time}}",
|
||||
projectedLeftAtReset: "重置时约剩余 {{percentage}}",
|
||||
limitReached: "已达到上限",
|
||||
mayHaveRunOut: "额度可能已用完",
|
||||
runsOutNow: "即将用尽",
|
||||
runsOutIn: "将在 {{duration}}后用尽",
|
||||
justNow: "刚刚",
|
||||
@@ -2826,7 +2829,8 @@ export const zhCN: TranslationResources = {
|
||||
updateAvailable: "有更新可用",
|
||||
updateTitle: "更新 Paseo skills?",
|
||||
uninstallTitle: "卸载 Paseo skills?",
|
||||
uninstallMessage: "会从 ~/.agents、~/.claude、~/.codex 移除所有 Paseo 编排 skills。",
|
||||
uninstallMessage:
|
||||
"会从 ~/.agents、~/.claude、~/.codex、~/.gemini/config 移除所有 Paseo 编排 skills。",
|
||||
choose: "选择 skills",
|
||||
chooseAll: "全部 skills",
|
||||
chooseAllHint: "保持安装所有内置 skills,包括以后新增的。",
|
||||
@@ -2834,7 +2838,7 @@ export const zhCN: TranslationResources = {
|
||||
chooseEmpty: "此版本未内置 skills。",
|
||||
removeTitle: "移除取消勾选的 skills?",
|
||||
removeMessage:
|
||||
"将从 ~/.agents、~/.claude、~/.codex 中删除 {{skills}}。你在这些 skill 文件夹里添加的内容也会一并删除。",
|
||||
"将从 ~/.agents、~/.claude、~/.codex、~/.gemini/config 中删除 {{skills}}。你在这些 skill 文件夹里添加的内容也会一并删除。",
|
||||
saveFailed: "无法保存你的 skills 选择。",
|
||||
statusFailed: "无法检查编排 skills 状态。",
|
||||
updateFailed: "无法更新编排 skills。",
|
||||
|
||||
@@ -22,6 +22,7 @@ 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";
|
||||
@@ -1267,7 +1268,11 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
);
|
||||
|
||||
const dock = (
|
||||
<ChatSurface disabled={isArchivingCurrentAgent} fullscreen={isComposerFullscreen}>
|
||||
<ChatSurface
|
||||
serverId={serverId}
|
||||
disabled={isArchivingCurrentAgent}
|
||||
fullscreen={isComposerFullscreen}
|
||||
>
|
||||
{dockContent}
|
||||
{composerSection}
|
||||
{dockOverlay}
|
||||
@@ -1337,10 +1342,12 @@ function wrapAgentCommandProvider({
|
||||
}
|
||||
|
||||
function ChatSurface({
|
||||
serverId,
|
||||
children,
|
||||
disabled,
|
||||
fullscreen,
|
||||
}: {
|
||||
serverId: string;
|
||||
children: [ReactNode, ReactNode, ReactNode];
|
||||
disabled: boolean;
|
||||
fullscreen: boolean;
|
||||
@@ -1349,9 +1356,11 @@ function ChatSurface({
|
||||
// closes everything the chat opened.
|
||||
return (
|
||||
<OverlayDismissalScope>
|
||||
<FileDropZone style={styles.container} disabled={disabled}>
|
||||
<ComposerDock fullscreen={fullscreen}>{children}</ComposerDock>
|
||||
</FileDropZone>
|
||||
<ChatColumnRailSurface serverId={serverId}>
|
||||
<FileDropZone style={styles.container} disabled={disabled}>
|
||||
<ComposerDock fullscreen={fullscreen}>{children}</ComposerDock>
|
||||
</FileDropZone>
|
||||
</ChatColumnRailSurface>
|
||||
</OverlayDismissalScope>
|
||||
);
|
||||
}
|
||||
@@ -1365,7 +1374,7 @@ function TimelineSyncErrorCallout({
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.timelineSyncCalloutRail}>
|
||||
<View style={styles.timelineSyncCalloutRail} dataSet={CHAT_COLUMN_RAIL_DATASET}>
|
||||
<View style={styles.timelineSyncCalloutContent}>
|
||||
<View style={styles.timelineSyncCallout} testID="agent-timeline-sync-error">
|
||||
<Text style={styles.timelineSyncCalloutText}>
|
||||
|
||||
@@ -1,24 +1,39 @@
|
||||
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;
|
||||
openAgent(input: { serverId: string; agentId: string }): void;
|
||||
openWorkspace(input: NavigateToWorkspaceInput): void;
|
||||
isHostRegistered(serverId: string): boolean;
|
||||
openAgent(input: { serverId: string; agentId: string }): string;
|
||||
openWorkspace(input: NavigateToWorkspaceInput): string;
|
||||
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 {
|
||||
openAgent: ({ agentId, serverId: targetServerId }) =>
|
||||
owner.openAgent({ serverId: targetServerId ?? serverId, agentId }),
|
||||
openWorkspace: ({ workspaceId, serverId: targetServerId }) =>
|
||||
owner.openWorkspace({ serverId: targetServerId ?? serverId, workspaceId }),
|
||||
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);
|
||||
},
|
||||
openBrowser: owner.browserAvailable
|
||||
? ({ url, workspaceId, serverId: targetServerId }) => {
|
||||
if (!isHttpUrl(url)) throw new Error("Only absolute HTTP(S) URLs are supported.");
|
||||
|
||||
@@ -1,25 +1,58 @@
|
||||
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),
|
||||
openWorkspace: (input) => destinations.push(input),
|
||||
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);
|
||||
},
|
||||
createBrowser: ({ initialUrl }) => {
|
||||
browsers.push(initialUrl);
|
||||
return { browserId: `browser-${browsers.length}` };
|
||||
},
|
||||
});
|
||||
return { navigation, destinations, browsers, workspaces };
|
||||
return { navigation, destinations, browsers, workspaces, focusedHosts };
|
||||
}
|
||||
|
||||
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" });
|
||||
@@ -43,6 +76,110 @@ 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,10 +4,12 @@ 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,
|
||||
@@ -16,9 +18,14 @@ 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,8 +20,6 @@ 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",
|
||||
@@ -42,9 +40,8 @@ it("updates compact header actions on panel changes without rendering the worksp
|
||||
title="Workspace"
|
||||
subtitle="Project"
|
||||
isSubtitleDistinct
|
||||
onToggleExplorer={noop}
|
||||
explorerToggleLabel="Explorer"
|
||||
explorerToggleAccessibilityState={explorerState}
|
||||
explorerAction={null}
|
||||
inDesktopTitlebar={false}
|
||||
tabSwitcher={null}
|
||||
headerVariant="full"
|
||||
>
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
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,
|
||||
@@ -23,10 +18,9 @@ interface CompactWorkspaceHeaderProps {
|
||||
title: string;
|
||||
subtitle: string;
|
||||
isSubtitleDistinct: boolean;
|
||||
onToggleExplorer: () => void;
|
||||
explorerToggleLabel: string;
|
||||
explorerToggleAccessibilityState: { expanded: boolean };
|
||||
explorerAction: ReactNode;
|
||||
tabSwitcher: ReactNode;
|
||||
inDesktopTitlebar: boolean;
|
||||
/** Workspace overflow menu. */
|
||||
children: ReactNode;
|
||||
headerVariant: "compact" | "full";
|
||||
@@ -40,17 +34,15 @@ export function CompactWorkspaceHeader({
|
||||
title,
|
||||
subtitle,
|
||||
isSubtitleDistinct,
|
||||
onToggleExplorer,
|
||||
explorerToggleLabel,
|
||||
explorerToggleAccessibilityState,
|
||||
explorerAction,
|
||||
children,
|
||||
tabSwitcher,
|
||||
inDesktopTitlebar,
|
||||
serverId,
|
||||
headerVariant,
|
||||
isRouteFocused,
|
||||
isCompact,
|
||||
}: CompactWorkspaceHeaderProps) {
|
||||
const { t } = useTranslation();
|
||||
const actionsInBar = resolveWorkspaceActionPlacement(useWindowLayout()) === "vertical-bar";
|
||||
const projectRow = useMemo(
|
||||
() => (
|
||||
@@ -65,16 +57,7 @@ export function CompactWorkspaceHeader({
|
||||
const symbols = {
|
||||
"tab-count": tabSwitcher,
|
||||
overflow: children,
|
||||
explorer: (
|
||||
<WorkspaceExplorerToggle
|
||||
onPress={onToggleExplorer}
|
||||
label={explorerToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
accessibilityState={explorerToggleAccessibilityState}
|
||||
mobile
|
||||
/>
|
||||
),
|
||||
explorer: explorerAction,
|
||||
};
|
||||
const actions = resolveWorkspaceBarActions(headerVariant).map((symbol) => (
|
||||
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
|
||||
@@ -85,6 +68,7 @@ export function CompactWorkspaceHeader({
|
||||
{headerVariant === "compact" ? (
|
||||
<CompactHeader
|
||||
navigation="menu"
|
||||
inDesktopTitlebar={inDesktopTitlebar}
|
||||
title={title}
|
||||
titleTestID="workspace-header-title"
|
||||
subtitle={projectRow}
|
||||
|
||||
@@ -1,47 +1,37 @@
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { PanelRight } from "lucide-react-native";
|
||||
import { type StyleProp, type ViewStyle } from "react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
|
||||
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 { 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);
|
||||
|
||||
export const EXPLORER_TOGGLE_KEYS: ShortcutKey[] = ["mod", "E"];
|
||||
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>;
|
||||
}
|
||||
|
||||
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({
|
||||
function WorkspaceExplorerToggle({
|
||||
onPress,
|
||||
label,
|
||||
tooltipLabel,
|
||||
tooltipKeys,
|
||||
accessibilityState,
|
||||
mobile,
|
||||
style,
|
||||
@@ -51,7 +41,7 @@ export function WorkspaceExplorerToggle({
|
||||
testID="workspace-explorer-toggle"
|
||||
onPress={onPress}
|
||||
tooltipLabel={tooltipLabel}
|
||||
tooltipKeys={tooltipKeys}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
tooltipSide="left"
|
||||
style={style}
|
||||
accessible
|
||||
@@ -68,42 +58,97 @@ export function WorkspaceExplorerToggle({
|
||||
);
|
||||
}
|
||||
|
||||
interface DesktopWorkspaceExplorerToggleProps extends Omit<WorkspaceExplorerToggleProps, "mobile"> {
|
||||
owner: WorkspaceExplorerToggleOwner;
|
||||
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]);
|
||||
}
|
||||
|
||||
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} />;
|
||||
}
|
||||
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,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -157,17 +157,8 @@ 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 {
|
||||
resolveWorkspaceExplorerToggleOwner,
|
||||
EXPLORER_TOGGLE_KEYS,
|
||||
WorkspaceExplorerSidebarToggle,
|
||||
WorkspaceHeaderExplorerToggle,
|
||||
} from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import {
|
||||
useHasWindowChromeObstruction,
|
||||
WindowChromeRegion,
|
||||
WindowChromeSafeArea,
|
||||
} from "@/utils/desktop-window";
|
||||
import { useWorkspaceExplorerControls } from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
|
||||
import {
|
||||
resolveWorkspaceHeaderRenderState,
|
||||
type WorkspaceHeaderCheckoutState,
|
||||
@@ -1058,12 +1049,8 @@ 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]);
|
||||
@@ -1308,11 +1295,6 @@ 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
|
||||
@@ -1820,9 +1802,6 @@ function WorkspaceScreenContent({
|
||||
}),
|
||||
[t],
|
||||
);
|
||||
const explorerSidebarToggleLabel = isExplorerSidebarShowing
|
||||
? t("workspace.tabs.explorerSidebar.close")
|
||||
: t("workspace.tabs.explorerSidebar.open");
|
||||
|
||||
const activeTabKey = useMemo(() => activeTabId ?? "", [activeTabId]);
|
||||
const handleCreateDraftTab = useCallback(
|
||||
@@ -3228,6 +3207,13 @@ function WorkspaceScreenContent({
|
||||
workspaceKey: persistenceKey,
|
||||
});
|
||||
|
||||
const explorerControls = useWorkspaceExplorerControls({
|
||||
hasWorkspace: !!workspaceDirectory,
|
||||
compact: isMobile,
|
||||
focusMode: desktopFocusModeEnabled,
|
||||
expanded: isExplorerSidebarShowing,
|
||||
onToggle: handleToggleExplorerSidebar,
|
||||
});
|
||||
const headerRight = useMemo(
|
||||
() => (
|
||||
<View style={styles.headerRight}>
|
||||
@@ -3254,17 +3240,7 @@ function WorkspaceScreenContent({
|
||||
{workspaceDirectory ? (
|
||||
<>
|
||||
<WorkspaceActions serverId={normalizedServerId} cwd={workspaceDirectory} />
|
||||
{workspaceActionsInBar ? null : (
|
||||
<WorkspaceHeaderExplorerToggle
|
||||
owner={explorerToggleOwner}
|
||||
onPress={handleToggleExplorerSidebar}
|
||||
label={explorerSidebarToggleLabel}
|
||||
tooltipLabel={t("workspace.tabs.explorerSidebar.toggle")}
|
||||
tooltipKeys={EXPLORER_TOGGLE_KEYS}
|
||||
style={styles.compactHeaderActionButton}
|
||||
accessibilityState={explorerSidebarToggleAccessibilityState}
|
||||
/>
|
||||
)}
|
||||
{workspaceActionsInBar ? null : explorerControls.headerAction}
|
||||
</>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -3279,12 +3255,8 @@ function WorkspaceScreenContent({
|
||||
scriptActions,
|
||||
handleViewScriptTerminal,
|
||||
handleOpenUrlInBrowserTab,
|
||||
handleToggleExplorerSidebar,
|
||||
explorerSidebarToggleLabel,
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerToggleOwner,
|
||||
explorerControls.headerAction,
|
||||
workspaceActionsInBar,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3292,25 +3264,6 @@ 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],
|
||||
@@ -3333,10 +3286,6 @@ 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}`,
|
||||
@@ -3460,14 +3409,13 @@ 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}
|
||||
@@ -3493,20 +3441,19 @@ function WorkspaceScreenContent({
|
||||
},
|
||||
[
|
||||
renderWorkspaceTabSwitcher,
|
||||
explorerControls.inDesktopTitlebar,
|
||||
explorerControls.compactAction,
|
||||
isFocusModeEnabled,
|
||||
toggleFocusMode,
|
||||
canOpenImportSheet,
|
||||
compactHeaderScripts,
|
||||
createTerminalDisabled,
|
||||
currentBranchName,
|
||||
explorerSidebarToggleAccessibilityState,
|
||||
explorerSidebarToggleLabel,
|
||||
handleCopyBranchName,
|
||||
handleCopyWorkspacePath,
|
||||
handleCreateBrowserTab,
|
||||
handleCreateTerminalWithProfile,
|
||||
handleOpenSetupTab,
|
||||
handleToggleExplorerSidebar,
|
||||
isMobile,
|
||||
isRouteFocused,
|
||||
isWorkspaceHeaderLoading,
|
||||
@@ -3734,7 +3681,7 @@ function WorkspaceScreenContent({
|
||||
onExitFocusMode={toggleFocusMode}
|
||||
onReorderTabsInPane={handleReorderTabsInPane}
|
||||
buildPaneContentModel={buildDesktopPaneContentModel}
|
||||
headerAction={renderExplorerSidebarHeaderAction()}
|
||||
headerAction={explorerControls.dockAction}
|
||||
/>
|
||||
);
|
||||
return (
|
||||
@@ -3775,7 +3722,7 @@ function WorkspaceScreenContent({
|
||||
toggleFocusMode,
|
||||
handleReorderTabsInPane,
|
||||
buildDesktopPaneContentModel,
|
||||
renderExplorerSidebarHeaderAction,
|
||||
explorerControls.dockAction,
|
||||
desktopFocusModeEnabled,
|
||||
]);
|
||||
|
||||
@@ -3849,6 +3796,7 @@ function WorkspaceScreenContent({
|
||||
onReorderTabsInPane={handleReorderTabsInPane}
|
||||
onSplitPane={handleSplitPane}
|
||||
>
|
||||
{explorerControls.titlebarAction}
|
||||
{workspaceCenterColumn}
|
||||
{sharedExplorer}
|
||||
</WorkspaceTabDragScope>
|
||||
@@ -3986,12 +3934,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
md: theme.spacing[2],
|
||||
},
|
||||
},
|
||||
compactHeaderActionButton: {
|
||||
marginRight: {
|
||||
xs: 0,
|
||||
md: -theme.spacing[2],
|
||||
},
|
||||
},
|
||||
compactHeaderMenuCluster: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,10 +1,5 @@
|
||||
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 {
|
||||
@@ -190,37 +185,6 @@ 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,6 +69,7 @@ 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;
|
||||
@@ -205,6 +206,9 @@ 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,6 +3,7 @@ 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";
|
||||
@@ -37,7 +38,7 @@ export function ParentAgentCallout({
|
||||
const parent = useParentAgent(serverId, parentAgentId);
|
||||
|
||||
return (
|
||||
<View style={styles.rail}>
|
||||
<View style={styles.rail} dataSet={CHAT_COLUMN_RAIL_DATASET}>
|
||||
<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,12 +1053,19 @@ 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,6 +32,7 @@ it("translates mounted usage rows when the language changes", async () => {
|
||||
<>
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
forecastAt={null}
|
||||
displayAs="used"
|
||||
pinnable={false}
|
||||
pinned={false}
|
||||
@@ -51,3 +52,44 @@ 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.id, agentId);
|
||||
const { refresh, refreshState } = useReportRefresh(serverId, entry, 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, messages } = report;
|
||||
const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report;
|
||||
const footer = entry.account.label ?? null;
|
||||
return (
|
||||
<>
|
||||
@@ -194,6 +194,7 @@ function UsageCardBody({
|
||||
entry={entry}
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
display={display}
|
||||
pinnable={pinnable}
|
||||
/>
|
||||
@@ -267,8 +268,10 @@ function CardWindowBar({
|
||||
display,
|
||||
pinnable,
|
||||
retained,
|
||||
forecastAt,
|
||||
}: {
|
||||
retained: boolean;
|
||||
forecastAt: string | null;
|
||||
entry: UsageReportEntry;
|
||||
window: UsageWindow;
|
||||
display: UsageDisplay;
|
||||
@@ -285,6 +288,7 @@ function CardWindowBar({
|
||||
<UsageWindowBar
|
||||
window={window}
|
||||
retained={retained}
|
||||
forecastAt={forecastAt}
|
||||
displayAs={display.displayAs}
|
||||
pinnable={pinnable}
|
||||
pinned={display.isPinned(pin)}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import {
|
||||
resolveUsageReport,
|
||||
markUsageRefreshFailure,
|
||||
displayPercent,
|
||||
resolveAgentUsageView,
|
||||
replaceReport,
|
||||
@@ -82,7 +83,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 });
|
||||
).toEqual({ kind: "ready", reports: [], isRefreshing: true, refreshFailed: false });
|
||||
expect(
|
||||
resolveUsageView({
|
||||
...base,
|
||||
@@ -90,6 +91,19 @@ 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 () => {
|
||||
@@ -203,15 +217,12 @@ describe("displayPercent", () => {
|
||||
|
||||
describe("resolveUsageRefresh", () => {
|
||||
it("is pending while a refresh runs, even after an earlier failure", () => {
|
||||
expect(resolveUsageRefresh({ isPending: true, error: new Error("boom") })).toBe("pending");
|
||||
expect(resolveUsageRefresh({ isPending: true, isError: true })).toBe("pending");
|
||||
});
|
||||
|
||||
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");
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -352,6 +363,7 @@ 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"],
|
||||
});
|
||||
@@ -361,6 +373,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
|
||||
details: [],
|
||||
planLabel: null,
|
||||
successfulAt: null,
|
||||
forecastAt: null,
|
||||
retained: false,
|
||||
messages: ["Rate limited"],
|
||||
});
|
||||
@@ -370,11 +383,48 @@ 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,18 +38,31 @@ export function usageWindowRowLabel(input: {
|
||||
return `${input.pinLabel}, ${summary}`;
|
||||
}
|
||||
|
||||
/** A user-requested refresh of one report. The previous report stays on screen throughout. */
|
||||
/** The outcome of a user-requested usage refresh. */
|
||||
export type UsageRefresh = "idle" | "pending" | "failed";
|
||||
|
||||
export function resolveUsageRefresh(mutation: {
|
||||
isPending: boolean;
|
||||
error: unknown;
|
||||
isError: boolean;
|
||||
}): UsageRefresh {
|
||||
if (mutation.isPending) return "pending";
|
||||
if (mutation.error) return "failed";
|
||||
if (mutation.isError) 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.
|
||||
@@ -60,7 +73,9 @@ export function replaceReport(
|
||||
refreshed: UsageReportEntry | null,
|
||||
): UsageReportEntry[] {
|
||||
if (!refreshed) return reports.filter((report) => report.id !== reportId);
|
||||
return reports.map((report) => (report.id === reportId ? refreshed : report));
|
||||
return reports.map((report) =>
|
||||
report.id === reportId ? laterFetched(report, refreshed) : report,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -68,7 +83,9 @@ 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 {
|
||||
return Date.parse(shown.fetchedAt) > Date.parse(arriving.fetchedAt) ? shown : arriving;
|
||||
const shownAt = Date.parse(shown.fetchedAt);
|
||||
const arrivingAt = Date.parse(arriving.fetchedAt);
|
||||
return shownAt > arrivingAt || (shownAt === arrivingAt && shown.forecastStale) ? shown : arriving;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -117,10 +134,11 @@ export function resolveUsageView(
|
||||
isConnected: boolean;
|
||||
supportsUsage: boolean;
|
||||
query: UsageQueryState | undefined;
|
||||
refreshState?: UsageRefresh;
|
||||
},
|
||||
t: TFunction = i18n.t,
|
||||
): UsageView {
|
||||
const { hostLabel, isConnected, supportsUsage, query } = input;
|
||||
const { hostLabel, isConnected, supportsUsage, query, refreshState } = input;
|
||||
if (!isConnected)
|
||||
return {
|
||||
kind: "unavailable",
|
||||
@@ -135,7 +153,12 @@ 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 };
|
||||
return {
|
||||
kind: "ready",
|
||||
reports: query.data,
|
||||
isRefreshing: query.isFetching || refreshState === "pending",
|
||||
refreshFailed: refreshState === "failed",
|
||||
};
|
||||
}
|
||||
if (query?.error) {
|
||||
return {
|
||||
@@ -250,7 +273,12 @@ 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 ?? [],
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
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" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
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, percentsWidth: 120, windowCount: 2 };
|
||||
const widths = { labelsWidth: 200, compactWidth: 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,11 +64,27 @@ 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",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -145,6 +161,7 @@ describe("resolvePinnedUsage", () => {
|
||||
key: "claude:default/five-hour",
|
||||
label: "Claude Session 31% used",
|
||||
shortLabel: "5h",
|
||||
compactLabel: "5h",
|
||||
percent: 31,
|
||||
percentText: "31%",
|
||||
tone: "default",
|
||||
@@ -153,6 +170,7 @@ describe("resolvePinnedUsage", () => {
|
||||
key: "claude:default/weekly",
|
||||
label: "Claude Weekly 80% used",
|
||||
shortLabel: "wk",
|
||||
compactLabel: "wk",
|
||||
percent: 80,
|
||||
percentText: "80%",
|
||||
tone: "warning",
|
||||
@@ -216,6 +234,52 @@ 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,6 +18,8 @@ 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;
|
||||
@@ -34,28 +36,66 @@ export interface PinnedUsageSource {
|
||||
}
|
||||
|
||||
/** How much of each window the one-line summary has room for. */
|
||||
export type PinnedUsageLayout = "meters" | "labels" | "percents";
|
||||
export type PinnedUsageLayout = "meters" | "labels" | "compact" | "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
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
export function choosePinnedUsageLayout(input: {
|
||||
available: number | null;
|
||||
labelsWidth: number | null;
|
||||
compactWidth: number | null;
|
||||
percentsWidth: number | null;
|
||||
windowCount: number;
|
||||
}): PinnedUsageLayout {
|
||||
const { available, labelsWidth, percentsWidth, windowCount } = input;
|
||||
if (available === null || labelsWidth === null || percentsWidth === null) return "labels";
|
||||
const { available, labelsWidth, compactWidth, percentsWidth, windowCount } = input;
|
||||
if (
|
||||
available === null ||
|
||||
labelsWidth === null ||
|
||||
compactWidth === 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";
|
||||
}
|
||||
|
||||
@@ -85,10 +125,13 @@ 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: window.shortLabel ?? formatProviderUsageLabel(window.id, window.label, t),
|
||||
shortLabel,
|
||||
compactLabel: compactShortLabel(shortLabel),
|
||||
percent,
|
||||
percentText,
|
||||
tone: windowTone(window),
|
||||
|
||||
@@ -20,6 +20,7 @@ import { useSessionStore, type SessionState } from "@/stores/session-store";
|
||||
import { useUsageSetting } from "./setting";
|
||||
import { usageCopy } from "./copy";
|
||||
import {
|
||||
markUsageRefreshFailure,
|
||||
replaceReport,
|
||||
resolveAgentUsageView,
|
||||
resolveUsageRefresh,
|
||||
@@ -97,17 +98,32 @@ async function streamReports(input: {
|
||||
return settleReports(queryClient.getQueryData<UsageReportEntry[]>(queryKey), reports);
|
||||
}
|
||||
|
||||
function listReports(
|
||||
async function listReports(
|
||||
queryClient: QueryClient,
|
||||
serverId: string,
|
||||
forceRefresh = false,
|
||||
): Promise<UsageReportEntry[]> {
|
||||
return streamReports({
|
||||
queryClient,
|
||||
queryKey: usageReportsQueryKey(serverId),
|
||||
serverId,
|
||||
forceRefresh,
|
||||
});
|
||||
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 },
|
||||
);
|
||||
}
|
||||
|
||||
async function getReport(
|
||||
@@ -158,9 +174,12 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
dataShape: "value",
|
||||
staleTimeMs: REPORTS_STALE_TIME_MS,
|
||||
});
|
||||
const refresh = useCallback(() => {
|
||||
void refreshReports(queryClient, serverId).catch(() => undefined);
|
||||
}, [queryClient, serverId]);
|
||||
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 { t } = useTranslation();
|
||||
const hostLabel = useHosts().find((host) => host.serverId === serverId)?.label ?? serverId;
|
||||
const view = resolveUsageView(
|
||||
@@ -170,6 +189,7 @@ export function useHostUsage(serverId: string): { view: UsageView; refresh: () =
|
||||
isConnected,
|
||||
supportsUsage: isSupported,
|
||||
query: toQueryState(query),
|
||||
refreshState: variables === serverId ? resolveUsageRefresh(mutation) : "idle",
|
||||
},
|
||||
t,
|
||||
);
|
||||
@@ -265,23 +285,26 @@ export function useUsageHosts(): UsageHost[] {
|
||||
*/
|
||||
export function useReportRefresh(
|
||||
serverId: string,
|
||||
reportId: string,
|
||||
entry: UsageReportEntry,
|
||||
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({
|
||||
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),
|
||||
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,
|
||||
);
|
||||
},
|
||||
onError: (_error, attempted) => recordUsageRefreshFailure(queryClient, queryKey, [attempted]),
|
||||
});
|
||||
const { mutate } = mutation;
|
||||
const refresh = useCallback(() => mutate(), [mutate]);
|
||||
const refresh = useCallback(() => mutate(entry), [mutate, entry]);
|
||||
return { refresh, refreshState: resolveUsageRefresh(mutation) };
|
||||
}
|
||||
|
||||
@@ -3,24 +3,21 @@ 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 gives way (truncates) and the countdown stays whole.
|
||||
* is too narrow the exact time truncates and the countdown wraps within its column.
|
||||
*/
|
||||
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={atRisk ? styles.atRisk : styles.text}>{countdown}</Text>
|
||||
<Text style={[styles.text, styles.countdown]}>{countdown}</Text>
|
||||
{exactTime ? (
|
||||
<Text style={[styles.text, styles.exactTime]} numberOfLines={1} ellipsizeMode="tail">
|
||||
{`\u00a0·\u00a0${exactTime}`}
|
||||
@@ -31,18 +28,13 @@ export function UsageResetLine({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
line: { flexDirection: "row", alignItems: "center" },
|
||||
line: { flexDirection: "row", alignItems: "baseline" },
|
||||
text: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
atRisk: {
|
||||
flexShrink: 0,
|
||||
color: theme.colors.statusDanger,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
},
|
||||
exactTime: { flexShrink: 1 },
|
||||
countdown: { maxWidth: "100%" },
|
||||
exactTime: { flexShrink: 1, minWidth: 0 },
|
||||
}));
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
resolvePinnedUsage,
|
||||
type PinnedUsageLayout,
|
||||
type PinnedUsageSource,
|
||||
type PinnedUsageWindow,
|
||||
} from "./pinned";
|
||||
import { UsageModal } from "./usage-modal";
|
||||
|
||||
@@ -123,8 +124,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 labels and with percents alone; the richest layout that fits is shown, and what
|
||||
* it leaves out takes no space at all.
|
||||
* 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.
|
||||
*/
|
||||
function PinnedUsageTrigger({
|
||||
label,
|
||||
@@ -139,6 +140,7 @@ 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));
|
||||
@@ -146,12 +148,16 @@ 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),
|
||||
});
|
||||
@@ -177,6 +183,9 @@ 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>
|
||||
@@ -185,6 +194,12 @@ 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.
|
||||
@@ -215,6 +230,7 @@ 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" ? (
|
||||
@@ -228,9 +244,7 @@ function PinnedUsageLine({
|
||||
testID={measuring ? undefined : "sidebar-usage-pinned-window"}
|
||||
>
|
||||
{window.percentText}
|
||||
{layout === "percents" || window.shortLabel === "" ? null : (
|
||||
<Text style={styles.windowLabel}>{` ${window.shortLabel}`}</Text>
|
||||
)}
|
||||
{suffix === "" ? null : <Text style={styles.windowLabel}>{` ${suffix}`}</Text>}
|
||||
</Text>
|
||||
</Fragment>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import type { ProviderUsageTone, UsageReportEntry } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
ProviderUsageTone,
|
||||
UsageReportEntry as WireUsageReportEntry,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
|
||||
export type { UsageReportEntry };
|
||||
export interface UsageReportEntry extends WireUsageReportEntry {
|
||||
/** A refresh failed while this reading was cached. */
|
||||
forecastStale?: true;
|
||||
}
|
||||
export type UsageReport = UsageReportEntry["report"];
|
||||
export type UsageTone = ProviderUsageTone;
|
||||
export type AvailableUsageReport = Extract<UsageReport, { status: "available" }>;
|
||||
@@ -14,4 +20,4 @@ export type UsageView =
|
||||
| { kind: "unavailable"; message: string }
|
||||
| { kind: "loading" }
|
||||
| { kind: "error"; message: string }
|
||||
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean };
|
||||
| { kind: "ready"; reports: UsageReportEntry[]; isRefreshing: boolean; refreshFailed: boolean };
|
||||
|
||||
@@ -84,11 +84,18 @@ export function UsageBody({
|
||||
);
|
||||
}
|
||||
|
||||
if (view.reports.length === 0) {
|
||||
return <UsageMessage text={t("providerUsage.empty")} />;
|
||||
}
|
||||
|
||||
return <UsageList serverId={serverId} reports={view.reports} display={display} />;
|
||||
return (
|
||||
<View style={styles.reports}>
|
||||
{view.refreshFailed ? (
|
||||
<Alert size="sm" variant="error" title={t("providerUsage.refreshFailed")} />
|
||||
) : null}
|
||||
{view.reports.length === 0 ? (
|
||||
<UsageMessage text={t("providerUsage.empty")} />
|
||||
) : (
|
||||
<UsageList serverId={serverId} reports={view.reports} display={display} />
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function UsageMessage({ text }: { text: string }) {
|
||||
@@ -100,6 +107,7 @@ export function UsageMessage({ text }: { text: string }) {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
reports: { gap: theme.spacing[3] },
|
||||
emptyCard: {
|
||||
padding: theme.spacing[4],
|
||||
alignItems: "center",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import { Pin } from "lucide-react-native";
|
||||
import { useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -6,6 +7,7 @@ import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import {
|
||||
formatDisplayPct,
|
||||
formatPct,
|
||||
formatProviderUsageLabel,
|
||||
formatResetLabel,
|
||||
formatResetTime,
|
||||
@@ -13,9 +15,9 @@ import {
|
||||
} from "./format";
|
||||
import { UsageMeter } from "./meter";
|
||||
import { displayPercent, usageWindowRowLabel } from "./model";
|
||||
import { usagePace } from "./pace";
|
||||
import { UsageResetLine } from "./reset-line";
|
||||
import type { UsageDisplayAs } from "./preferences";
|
||||
import { windowTone } from "./tone";
|
||||
import type { UsageTone, UsageWindow } from "./types";
|
||||
import { useRelativeTimeTick } from "./use-relative-time-tick";
|
||||
|
||||
@@ -28,8 +30,10 @@ export function UsageWindowBar({
|
||||
pinLabel,
|
||||
pinTestID,
|
||||
retained = false,
|
||||
forecastAt,
|
||||
}: {
|
||||
retained?: boolean;
|
||||
forecastAt: string | null;
|
||||
window: UsageWindow;
|
||||
displayAs: UsageDisplayAs;
|
||||
/** Whether the row pins the window to the sidebar. When false the row is a plain bar. */
|
||||
@@ -42,19 +46,11 @@ export function UsageWindowBar({
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const shownPct = displayPercent(window, displayAs);
|
||||
const tone = windowTone(window);
|
||||
|
||||
const now = useRelativeTimeTick({ enabled: window.runsOutAt != null || window.resetsAt != null });
|
||||
const isAtRisk =
|
||||
window.runsOutAt != null &&
|
||||
window.shortfallPct != null &&
|
||||
(!retained || Date.parse(window.runsOutAt) > now);
|
||||
const countdown = isAtRisk
|
||||
? formatRunsOutLabel(window.runsOutAt, now, t)
|
||||
: formatResetLabel(window.resetsAt, retained, now, t);
|
||||
// The exact time belongs to the reset; beside a runs-out warning it would read as the moment
|
||||
// the quota runs out.
|
||||
const exactTime = isAtRisk ? null : formatResetTime(window.resetsAt, now, t);
|
||||
const pace = usagePace(window, forecastAt, now);
|
||||
const forecast = formatPace(pace, now, t);
|
||||
const countdown = formatResetLabel(window.resetsAt, retained, now, t);
|
||||
const exactTime = formatResetTime(window.resetsAt, now, t);
|
||||
|
||||
const value =
|
||||
shownPct != null ? formatDisplayPct(shownPct, displayAs, i18n.resolvedLanguage, t) : "—";
|
||||
@@ -64,9 +60,8 @@ export function UsageWindowBar({
|
||||
value,
|
||||
countdown,
|
||||
exactTime,
|
||||
isAtRisk,
|
||||
forecast,
|
||||
percent: shownPct ?? 0,
|
||||
tone,
|
||||
pinned,
|
||||
};
|
||||
|
||||
@@ -86,7 +81,7 @@ export function UsageWindowBar({
|
||||
accessibilityLabel={usageWindowRowLabel({
|
||||
pinLabel,
|
||||
value,
|
||||
trailing: [countdown, exactTime].filter(Boolean).join(" · "),
|
||||
trailing: [countdown, exactTime, forecast?.label].filter(Boolean).join(" · "),
|
||||
})}
|
||||
accessibilityState={accessibilityState}
|
||||
aria-checked={pinned}
|
||||
@@ -103,9 +98,8 @@ function WindowRowContent({
|
||||
value,
|
||||
countdown,
|
||||
exactTime,
|
||||
isAtRisk,
|
||||
forecast,
|
||||
percent,
|
||||
tone,
|
||||
pinnable,
|
||||
pinned,
|
||||
}: {
|
||||
@@ -113,9 +107,8 @@ function WindowRowContent({
|
||||
value: string;
|
||||
countdown: string | null;
|
||||
exactTime: string | null;
|
||||
isAtRisk: boolean;
|
||||
forecast: PaceLabel | null;
|
||||
percent: number;
|
||||
tone: UsageTone;
|
||||
pinnable: boolean;
|
||||
pinned: boolean;
|
||||
}) {
|
||||
@@ -130,12 +123,51 @@ function WindowRowContent({
|
||||
</Text>
|
||||
{pinnable ? <UsagePinGlyph pinned={pinned} /> : null}
|
||||
</View>
|
||||
<UsageMeter percent={percent} tone={tone} />
|
||||
<UsageResetLine countdown={countdown} exactTime={exactTime} atRisk={isAtRisk} />
|
||||
<UsageMeter percent={percent} tone={forecast?.tone ?? "default"} />
|
||||
{countdown || forecast ? (
|
||||
<View style={styles.timingRow}>
|
||||
<View style={styles.resetTiming}>
|
||||
<UsageResetLine countdown={countdown} exactTime={exactTime} />
|
||||
</View>
|
||||
{forecast ? <Text style={styles.forecast(forecast.tone)}>{forecast.label}</Text> : null}
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
interface PaceLabel {
|
||||
label: string;
|
||||
tone: UsageTone;
|
||||
}
|
||||
|
||||
function formatPace(
|
||||
pace: ReturnType<typeof usagePace>,
|
||||
now: number,
|
||||
t: TFunction,
|
||||
): PaceLabel | null {
|
||||
switch (pace.kind) {
|
||||
case "reached":
|
||||
return { label: t("providerUsage.timing.limitReached"), tone: "danger" };
|
||||
case "runsOut": {
|
||||
const label =
|
||||
Date.parse(pace.at) <= now
|
||||
? t("providerUsage.timing.mayHaveRunOut")
|
||||
: formatRunsOutLabel(pace.at, now, t);
|
||||
return label ? { label, tone: "danger" } : null;
|
||||
}
|
||||
case "remaining":
|
||||
return {
|
||||
label: t("providerUsage.timing.projectedLeftAtReset", {
|
||||
percentage: formatPct(pace.remainingAtResetPct),
|
||||
}),
|
||||
tone: pace.remainingAtResetPct <= 10 ? "warning" : "default",
|
||||
};
|
||||
case "unknown":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const ThemedPin = withUnistyles(Pin);
|
||||
|
||||
function UsagePinGlyph({ pinned }: { pinned: boolean }) {
|
||||
@@ -167,6 +199,23 @@ function UsagePinGlyph({ pinned }: { pinned: boolean }) {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
timingRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "flex-start",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
resetTiming: { flex: 1, minWidth: 0 },
|
||||
forecast: (tone: UsageTone) => ({
|
||||
color: {
|
||||
danger: theme.colors.statusDanger,
|
||||
warning: theme.colors.statusWarning,
|
||||
default: theme.colors.foregroundMuted,
|
||||
ok: theme.colors.statusSuccess,
|
||||
}[tone],
|
||||
fontSize: theme.fontSize.sm,
|
||||
maxWidth: "50%",
|
||||
textAlign: "right",
|
||||
}),
|
||||
row: { gap: 3, paddingVertical: theme.spacing[1.5] },
|
||||
pin: { width: 12, alignItems: "center" },
|
||||
tooltipText: { color: theme.colors.popoverForeground, fontSize: theme.fontSize.sm },
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { runCreateCommandWithDeps } from "./create.js";
|
||||
import { buildCreateWorktreeRequest, type WorktreeCreateOptions } from "./create-input.js";
|
||||
|
||||
const REPO = "/tmp/repo";
|
||||
@@ -78,52 +77,3 @@ describe("buildCreateWorktreeRequest", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the explicit worktree creation RPC and returns the created worktree details", async () => {
|
||||
const result = await runCreateCommandWithDeps(
|
||||
{
|
||||
daemonTarget: { kind: "endpoint", host: "example.test:12345" },
|
||||
mode: "branch-off",
|
||||
newBranch: "topic",
|
||||
base: "main",
|
||||
cwd: REPO,
|
||||
},
|
||||
{
|
||||
connectToDaemon: async () => ({
|
||||
createPaseoWorktree: async (input) => {
|
||||
expect(input).toEqual({
|
||||
cwd: REPO,
|
||||
worktreeSlug: "topic",
|
||||
action: "branch-off",
|
||||
refName: "main",
|
||||
});
|
||||
return {
|
||||
workspace: {
|
||||
id: "wks_topic",
|
||||
projectId: "project",
|
||||
projectDisplayName: "Repo",
|
||||
projectRootPath: REPO,
|
||||
workspaceDirectory: `${REPO}/topic`,
|
||||
projectKind: "git",
|
||||
workspaceKind: "worktree",
|
||||
name: "topic",
|
||||
status: "idle",
|
||||
statusEnteredAt: null,
|
||||
activityAt: null,
|
||||
archivingAt: null,
|
||||
scripts: [],
|
||||
},
|
||||
error: null,
|
||||
requestId: "worktree-create",
|
||||
};
|
||||
},
|
||||
close: async () => {},
|
||||
}),
|
||||
},
|
||||
);
|
||||
expect(result.data).toEqual({
|
||||
name: "topic",
|
||||
branchName: "topic",
|
||||
worktreePath: `${REPO}/topic`,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,22 +26,11 @@ function cmdError(code: string, message: string, details?: string): CommandError
|
||||
export async function runCreateCommand(
|
||||
options: WorktreeCreateOptions,
|
||||
_command: Command,
|
||||
): Promise<SingleResult<WorktreeCreateResult>> {
|
||||
return runCreateCommandWithDeps(options, { connectToDaemon });
|
||||
}
|
||||
|
||||
export async function runCreateCommandWithDeps(
|
||||
options: WorktreeCreateOptions,
|
||||
deps: {
|
||||
connectToDaemon(
|
||||
options: Parameters<typeof connectToDaemon>[0],
|
||||
): Promise<Pick<Awaited<ReturnType<typeof connectToDaemon>>, "createPaseoWorktree" | "close">>;
|
||||
},
|
||||
): Promise<SingleResult<WorktreeCreateResult>> {
|
||||
const cwd = options.cwd ?? process.cwd();
|
||||
const request = buildCreateWorktreeRequest(options, cwd);
|
||||
|
||||
const client = await deps.connectToDaemon({ target: options.daemonTarget });
|
||||
const client = await connectToDaemon({ target: options.daemonTarget });
|
||||
|
||||
try {
|
||||
const response = await client.createPaseoWorktree(request);
|
||||
|
||||
@@ -1623,106 +1623,6 @@ test("defaults session RPC waiters to sixty seconds", async () => {
|
||||
await expect(responsePromise).rejects.toThrow("No response to fetch_agent_request after 60000ms");
|
||||
});
|
||||
|
||||
test.each([
|
||||
[
|
||||
"archive_workspace_request",
|
||||
(client: DaemonClient) => client.archiveWorkspace("workspace-1"),
|
||||
(requestId: string) => ({
|
||||
type: "archive_workspace_response" as const,
|
||||
payload: {
|
||||
requestId,
|
||||
workspaceId: "workspace-1",
|
||||
archivedAt: "2026-01-01T00:00:00.000Z",
|
||||
error: null,
|
||||
},
|
||||
}),
|
||||
],
|
||||
[
|
||||
"paseo_worktree_archive_request",
|
||||
(client: DaemonClient) => client.archivePaseoWorktree({ worktreePath: "/repo/worktree" }),
|
||||
(requestId: string) => ({
|
||||
type: "paseo_worktree_archive_response" as const,
|
||||
payload: { requestId, success: true, removedAgents: [], error: null },
|
||||
}),
|
||||
],
|
||||
[
|
||||
"workspace.recovery.restore.request",
|
||||
(client: DaemonClient) => client.restoreWorkspace("workspace-1"),
|
||||
(requestId: string) => ({
|
||||
type: "workspace.recovery.restore.response" as const,
|
||||
payload: { requestId, workspaceId: "workspace-1", accepted: true, error: null },
|
||||
}),
|
||||
],
|
||||
[
|
||||
"workspace.archive.undo.request",
|
||||
(client: DaemonClient) => client.undoWorkspaceArchive("workspace-1"),
|
||||
(requestId: string) => ({
|
||||
type: "workspace.archive.undo.response" as const,
|
||||
payload: { requestId, workspaceId: "workspace-1", accepted: true, error: null },
|
||||
}),
|
||||
],
|
||||
[
|
||||
"open_project_request",
|
||||
(client: DaemonClient) => client.openProject("/repo/worktree"),
|
||||
(requestId: string) => ({
|
||||
type: "open_project_response" as const,
|
||||
payload: { requestId, workspace: null, error: null },
|
||||
}),
|
||||
],
|
||||
[
|
||||
"create_paseo_worktree_request",
|
||||
(client: DaemonClient) => client.createPaseoWorktree({ cwd: "/repo", worktreeSlug: "topic" }),
|
||||
(requestId: string) => ({
|
||||
type: "create_paseo_worktree_response" as const,
|
||||
payload: { requestId, workspace: null, error: null, setupTerminalId: null },
|
||||
}),
|
||||
],
|
||||
] as const)(
|
||||
"waits on %s across queued and bounded daemon stages until response or disconnect",
|
||||
async (_type, run, buildResponse) => {
|
||||
useHeartbeatClock();
|
||||
const transport = createMockTransport();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "worktree-lifecycle-wait-test",
|
||||
logger: createMockLogger(),
|
||||
reconnect: { enabled: false },
|
||||
transportFactory: () => transport.transport,
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connecting = client.connect();
|
||||
transport.triggerOpen();
|
||||
await connecting;
|
||||
|
||||
const pending = run(client);
|
||||
const sentFrame = JSON.parse(assertStr(transport.sent.at(-1))) as {
|
||||
message: { requestId: string };
|
||||
};
|
||||
let settled = false;
|
||||
void pending.then(
|
||||
() => {
|
||||
settled = true;
|
||||
return undefined;
|
||||
},
|
||||
() => {
|
||||
settled = true;
|
||||
return undefined;
|
||||
},
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(200_000);
|
||||
await Promise.resolve();
|
||||
expect(settled).toBe(false);
|
||||
|
||||
transport.triggerMessage(wrapSessionMessage(buildResponse(sentFrame.message.requestId)));
|
||||
await expect(pending).resolves.not.toThrow();
|
||||
|
||||
const disconnected = run(client);
|
||||
transport.triggerClose({ code: 1006, reason: "gone" });
|
||||
await expect(disconnected).rejects.toMatchObject({ code: "DAEMON_CONNECTION_LOST" });
|
||||
},
|
||||
);
|
||||
|
||||
test("honors explicit fetchAgent timeout below the session RPC default", async () => {
|
||||
useHeartbeatClock();
|
||||
const logger = createMockLogger();
|
||||
|
||||
@@ -3188,9 +3188,6 @@ export class DaemonClient {
|
||||
cwd,
|
||||
},
|
||||
responseType: "open_project_response",
|
||||
// Opening a path whose checkout is currently archiving waits on the daemon checkout gate;
|
||||
// wait for the terminal response or transport disconnect instead of timing out while queued.
|
||||
timeout: 0,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3322,9 +3319,6 @@ export class DaemonClient {
|
||||
workspaceId,
|
||||
},
|
||||
responseType: "archive_workspace_response",
|
||||
// Archive may wait for a queued checkout operation and then run teardown/manager removal,
|
||||
// each bounded on the daemon; wait for the terminal response or transport disconnect.
|
||||
timeout: 0,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3847,9 +3841,7 @@ export class DaemonClient {
|
||||
type: "workspace.recovery.restore.request",
|
||||
workspaceId,
|
||||
},
|
||||
// Restore may wait behind an active archive/removal before running a bounded restore stage;
|
||||
// wait for the terminal response or transport disconnect instead of timing out mid-workflow.
|
||||
timeout: 0,
|
||||
timeout: 150_000,
|
||||
});
|
||||
if (!payload.accepted) {
|
||||
throw new Error(payload.error ?? "Workspace recovery was rejected by the host");
|
||||
@@ -3865,9 +3857,8 @@ export class DaemonClient {
|
||||
type: "workspace.archive.undo.request",
|
||||
workspaceId,
|
||||
},
|
||||
// Undo may wait for an in-flight archive to settle and then recreate the worktree;
|
||||
// wait for the terminal response or transport disconnect.
|
||||
timeout: 0,
|
||||
// Undoing a finished worktree archive recreates the worktree, like recovery does.
|
||||
timeout: 150_000,
|
||||
});
|
||||
if (!payload.accepted) {
|
||||
throw new Error(payload.error ?? "The host could not undo the workspace archive");
|
||||
@@ -5448,9 +5439,6 @@ export class DaemonClient {
|
||||
...(input.scope !== undefined ? { scope: input.scope } : {}),
|
||||
},
|
||||
responseType: "paseo_worktree_archive_response",
|
||||
// Archive may wait for a queued checkout operation and then run teardown/manager removal,
|
||||
// each bounded on the daemon; wait for the terminal response or transport disconnect.
|
||||
timeout: 0,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5474,10 +5462,6 @@ export class DaemonClient {
|
||||
...(input.githubPrNumber !== undefined ? { githubPrNumber: input.githubPrNumber } : {}),
|
||||
},
|
||||
responseType: "create_paseo_worktree_response",
|
||||
// Every daemon stage (before hooks, shared 120s manager budget, Git, after hooks) enforces
|
||||
// its own deadline, and transport heartbeats/close reject if the host drops, so wait for the
|
||||
// terminal worktree response instead of aborting prematurely mid-workflow.
|
||||
timeout: 0,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, test } from "../../app/e2e/support/fixtures";
|
||||
import { gotoWorkspace } from "../../app/e2e/support/helpers/launcher";
|
||||
|
||||
function explorerSidebar(page: Page) {
|
||||
return page.getByTestId("workspace-explorer-sidebar").filter({ visible: true });
|
||||
}
|
||||
|
||||
async function useDesktopWindowChrome(page: Page, mode: "native-mac" | "custom-windows") {
|
||||
await page.addInitScript((windowChromeMode) => {
|
||||
Object.assign(window, {
|
||||
paseoDesktop: {
|
||||
platform: windowChromeMode === "native-mac" ? "darwin" : "win32",
|
||||
windowChromeMode,
|
||||
invoke: async () => null,
|
||||
events: { on: async () => () => undefined },
|
||||
getPendingOpenProject: async () => null,
|
||||
window: {
|
||||
getCurrentWindow: () => ({
|
||||
isFullscreen: async () => false,
|
||||
onResized: async () => () => undefined,
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
}, mode);
|
||||
}
|
||||
|
||||
function explorerToggle(page: Page, expanded: boolean) {
|
||||
return page.getByRole("button", {
|
||||
name: expanded ? "Close Explorer sidebar" : "Open Explorer sidebar",
|
||||
exact: true,
|
||||
expanded,
|
||||
});
|
||||
}
|
||||
|
||||
async function recordExplorerToggle(button: Locator) {
|
||||
const recording = await button.evaluateHandle((target) => {
|
||||
const measure = () => {
|
||||
const glyph = target.querySelector("svg")?.getBoundingClientRect();
|
||||
return {
|
||||
connected: target.isConnected,
|
||||
x: glyph?.x,
|
||||
y: glyph?.y,
|
||||
width: glyph?.width,
|
||||
height: glyph?.height,
|
||||
};
|
||||
};
|
||||
const before = measure();
|
||||
const frames: ReturnType<typeof measure>[] = [];
|
||||
const done = new Promise<void>((resolve) => {
|
||||
target.addEventListener(
|
||||
"click",
|
||||
() => {
|
||||
const start = performance.now();
|
||||
const sample = () => {
|
||||
frames.push(measure());
|
||||
if (performance.now() - start < 300) requestAnimationFrame(sample);
|
||||
else resolve();
|
||||
};
|
||||
requestAnimationFrame(sample);
|
||||
},
|
||||
{ once: true },
|
||||
);
|
||||
});
|
||||
return { before, frames, done };
|
||||
});
|
||||
try {
|
||||
await button.click();
|
||||
return await recording.evaluate(async ({ before, frames, done }) => {
|
||||
await done;
|
||||
return { before, frames };
|
||||
});
|
||||
} finally {
|
||||
await recording.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
async function expectExplorerToggleHasNativeClickArea(toggle: Locator) {
|
||||
const regions = await toggle.evaluate((button) => {
|
||||
const rect = button.getBoundingClientRect();
|
||||
const x = rect.x + rect.width / 2;
|
||||
const y = rect.y + rect.height / 2;
|
||||
return [
|
||||
...document.querySelectorAll('[style*="app-region"], [data-window-no-drag], [role="button"]'),
|
||||
]
|
||||
.filter((element) => {
|
||||
const bounds = element.getBoundingClientRect();
|
||||
return bounds.left <= x && x < bounds.right && bounds.top <= y && y < bounds.bottom;
|
||||
})
|
||||
.map((element) => getComputedStyle(element).getPropertyValue("-webkit-app-region"))
|
||||
.filter((region) => region === "drag" || region === "no-drag");
|
||||
});
|
||||
expect(regions).toContain("drag");
|
||||
expect(regions.at(-1)).toBe("no-drag");
|
||||
}
|
||||
|
||||
async function expectExplorerToggleInHeaderTabOrder(page: Page, expanded: boolean) {
|
||||
const toggle = explorerToggle(page, expanded);
|
||||
await toggle.focus();
|
||||
await page.keyboard.press("Tab");
|
||||
await expect(page.getByRole("button", { name: "Workspace actions", exact: true })).toBeFocused();
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
await expect(toggle).toBeFocused();
|
||||
}
|
||||
|
||||
async function expectExplorerToggleToHoldPosition(page: Page, expanded: boolean) {
|
||||
const toggle = explorerToggle(page, expanded);
|
||||
await expect(toggle).toBeVisible();
|
||||
await expectExplorerToggleHasNativeClickArea(toggle);
|
||||
const { before, frames } = await recordExplorerToggle(toggle);
|
||||
await expect(explorerToggle(page, !expanded)).toBeVisible();
|
||||
expect(before.width).toBeGreaterThan(0);
|
||||
expect(frames.find((frame) => JSON.stringify(frame) !== JSON.stringify(before))).toBeUndefined();
|
||||
}
|
||||
|
||||
test("keeps the Mac Explorer toggle in place across open and close", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await useDesktopWindowChrome(page, "native-mac");
|
||||
|
||||
const { workspaceId } = await withWorkspace();
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
await expectExplorerToggleInHeaderTabOrder(page, false);
|
||||
await expectExplorerToggleToHoldPosition(page, false);
|
||||
await expectExplorerToggleInHeaderTabOrder(page, true);
|
||||
await expectExplorerToggleToHoldPosition(page, true);
|
||||
|
||||
await page.setViewportSize({ width: 930, height: 900 });
|
||||
await expectExplorerToggleToHoldPosition(page, false);
|
||||
await expectExplorerToggleToHoldPosition(page, true);
|
||||
});
|
||||
|
||||
async function expectClearOfWindowControls(page: Page, action: Locator) {
|
||||
const minimize = page.getByRole("button", { name: "Minimize window", exact: true });
|
||||
await expect(minimize).toBeVisible();
|
||||
await expect(action).toBeVisible();
|
||||
const controlBounds = await minimize.boundingBox();
|
||||
const actionBounds = await action.boundingBox();
|
||||
expect(actionBounds!.x + actionBounds!.width).toBeLessThanOrEqual(controlBounds!.x);
|
||||
}
|
||||
|
||||
test("keeps the Explorer actions clear of Windows controls", async ({ page, withWorkspace }) => {
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await useDesktopWindowChrome(page, "custom-windows");
|
||||
|
||||
const { workspaceId } = await withWorkspace();
|
||||
await gotoWorkspace(page, workspaceId);
|
||||
const open = explorerToggle(page, false);
|
||||
await expectClearOfWindowControls(page, open);
|
||||
await open.click();
|
||||
|
||||
const close = explorerToggle(page, true);
|
||||
const newExplorerTab = explorerSidebar(page).getByRole("button", {
|
||||
name: "New tab",
|
||||
exact: true,
|
||||
});
|
||||
await expectClearOfWindowControls(page, close);
|
||||
await expectClearOfWindowControls(page, newExplorerTab);
|
||||
await close.click();
|
||||
await expect(open).toBeVisible();
|
||||
});
|
||||
@@ -589,75 +589,3 @@ describe("sidebar data SDK boundary", () => {
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("worktree manager SDK boundary", () => {
|
||||
it("types create, remove, and restore handlers with discriminated results and cleanup", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import type {
|
||||
PluginServerContext,
|
||||
WorktreeManagerRegistration,
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeCreateResult,
|
||||
PluginWorktreeRemoveRequest,
|
||||
PluginWorktreeRemoveResult,
|
||||
PluginWorktreeRestoreRequest,
|
||||
PluginWorktreeRestoreResult,
|
||||
} from "@getpaseo/plugin/server";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
const manager: WorktreeManagerRegistration = {
|
||||
async create(request: PluginWorktreeCreateInput, { paseo, signal }) {
|
||||
const untrusted: boolean = request.untrusted;
|
||||
const headSha: string | undefined = request.headSha;
|
||||
void headSha;
|
||||
// @ts-expect-error untrusted is read-only
|
||||
request.untrusted = true;
|
||||
// @ts-expect-error headSha is read-only
|
||||
request.headSha = "deadbeef";
|
||||
if (request.kind === "branch-off") {
|
||||
const start: string = request.startPoint ?? request.baseRef;
|
||||
// @ts-expect-error startPoint is read-only
|
||||
request.startPoint = "other";
|
||||
if (!start || untrusted) return;
|
||||
}
|
||||
if (signal.aborted) return;
|
||||
void paseo;
|
||||
const result: PluginWorktreeCreateResult = { type: "created", path: request.path };
|
||||
return result;
|
||||
},
|
||||
async remove(request: PluginWorktreeRemoveRequest, { signal }) {
|
||||
const reason: "archive" | "rollback" = request.reason;
|
||||
const force: boolean = request.force;
|
||||
const untrusted: boolean = request.untrusted;
|
||||
// @ts-expect-error remove request fields are read-only
|
||||
request.path = "/other";
|
||||
if (!reason || !force || untrusted || signal.aborted) return;
|
||||
const result: PluginWorktreeRemoveResult = { type: "removed" };
|
||||
return result;
|
||||
},
|
||||
async restore(request: PluginWorktreeRestoreRequest) {
|
||||
const untrusted: boolean = request.untrusted;
|
||||
void untrusted;
|
||||
if (request.target.type === "commit") return;
|
||||
if (request.target.type === "from-base") {
|
||||
const base: string = request.target.baseRef;
|
||||
void base;
|
||||
}
|
||||
const result: PluginWorktreeRestoreResult = { type: "restored", path: request.path };
|
||||
return result;
|
||||
},
|
||||
};
|
||||
const dispose: () => void = server.registerWorktreeManager(manager);
|
||||
server.registerWorktreeManager({
|
||||
// @ts-expect-error create result requires discriminant
|
||||
async create() {
|
||||
return { path: "/tmp/wt" };
|
||||
},
|
||||
});
|
||||
return dispose;
|
||||
}
|
||||
`),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -49,16 +49,25 @@ export interface PluginHostProps {
|
||||
interface PluginNavigableHostProps extends PluginHostProps {
|
||||
/** Client-owned navigation. Undefined on older hosts; hide dependent affordances when absent. */
|
||||
readonly navigation?: {
|
||||
/** This client supports the focusHost option on agent/workspace navigation. */
|
||||
readonly supportsFocusHost?: boolean;
|
||||
/** Present only on Electron. The browser runs locally; serverId selects workspace ownership. */
|
||||
readonly openBrowser?: (input: {
|
||||
readonly url: string;
|
||||
readonly workspaceId: string;
|
||||
readonly serverId?: string;
|
||||
}) => void;
|
||||
readonly openAgent: (input: { readonly agentId: string; readonly serverId?: string }) => void;
|
||||
readonly openAgent: (input: {
|
||||
readonly agentId: string;
|
||||
readonly serverId?: string;
|
||||
/** Select only the destination host in the sidebar and clear project/label filters. */
|
||||
readonly focusHost?: boolean;
|
||||
}) => void;
|
||||
readonly openWorkspace: (input: {
|
||||
readonly workspaceId: string;
|
||||
readonly serverId?: string;
|
||||
/** Select only the destination host in the sidebar and clear project/label filters. */
|
||||
readonly focusHost?: boolean;
|
||||
}) => void;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ import type { PluginCleanup } from "../contracts.js";
|
||||
import type { ProviderRegistration } from "./provider.js";
|
||||
import type { UsageSourceRegistration } from "./usage.js";
|
||||
import type { PluginLifecycleRegistration } from "./lifecycle.js";
|
||||
import type { WorktreeManagerRegistration } from "./worktree.js";
|
||||
|
||||
export interface PluginHandlerContext {
|
||||
paseo: PaseoApi;
|
||||
@@ -65,7 +64,6 @@ export interface PluginServerContext extends PluginLifecycleRegistration {
|
||||
): void;
|
||||
registerProvider(provider: ProviderRegistration): void;
|
||||
registerUsageSource(source: UsageSourceRegistration): void;
|
||||
registerWorktreeManager(manager: WorktreeManagerRegistration): () => void;
|
||||
}
|
||||
|
||||
export type PluginServerContribution = (server: PluginServerContext) => PluginCleanup;
|
||||
|
||||
@@ -35,14 +35,3 @@ export { spawnProcess, execCommand, terminateProcess } from "./process.js";
|
||||
|
||||
export { defineAgentTool } from "./agent-tools.js";
|
||||
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
|
||||
export type {
|
||||
PluginWorktreeContext,
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeCreateResult,
|
||||
PluginWorktreeRemoveRequest,
|
||||
PluginWorktreeRemoveResult,
|
||||
PluginWorktreeRestoreTarget,
|
||||
PluginWorktreeRestoreRequest,
|
||||
PluginWorktreeRestoreResult,
|
||||
WorktreeManagerRegistration,
|
||||
} from "./worktree.js";
|
||||
|
||||
@@ -37,12 +37,7 @@ export type PluginWorktreeCreateRequest = {
|
||||
slug: string;
|
||||
path: string;
|
||||
} & (
|
||||
| {
|
||||
kind: "branch-off";
|
||||
baseRef: string;
|
||||
/** Where the new branch starts when that is not `baseRef`, such as a fork's head. */
|
||||
readonly startPoint?: string;
|
||||
}
|
||||
| { kind: "branch-off"; baseRef: string }
|
||||
| { kind: "checkout-branch" }
|
||||
| {
|
||||
kind: "checkout-change-request";
|
||||
|
||||
@@ -96,12 +96,12 @@ test.each([
|
||||
])(
|
||||
"duration %s owns the window's identity and both names",
|
||||
(durationSeconds, id, label, shortLabel) => {
|
||||
expect(
|
||||
windowFromReportedDuration({
|
||||
durationSeconds: durationSeconds as number | null,
|
||||
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
|
||||
utilizationPct: 11,
|
||||
}),
|
||||
).toMatchObject({ id, label, shortLabel, usedPct: 11 });
|
||||
const window = windowFromReportedDuration({
|
||||
durationSeconds: durationSeconds as number | null,
|
||||
unknown: { id: "primary", label: "Primary limit", shortLabel: "" },
|
||||
utilizationPct: 11,
|
||||
});
|
||||
expect(window).toMatchObject({ id, label, shortLabel, usedPct: 11 });
|
||||
expect(window.durationSeconds).toBe(durationSeconds ?? undefined);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -16,6 +16,8 @@ export interface UsageWindow {
|
||||
usedPct?: number | null;
|
||||
remainingPct?: number | null;
|
||||
resetsAt?: string | null;
|
||||
/** Full length of the quota window when known. */
|
||||
durationSeconds?: number;
|
||||
runsOutAt?: string | null;
|
||||
shortfallPct?: number | null;
|
||||
tone?: "default" | "ok" | "warning" | "danger";
|
||||
@@ -48,6 +50,8 @@ export type UsageReport =
|
||||
| {
|
||||
status: "available";
|
||||
planLabel?: string;
|
||||
/** When the provider measured the quota, if the report returns a previous reading. */
|
||||
observedAt?: string;
|
||||
windows: UsageWindow[];
|
||||
balances?: UsageBalance[];
|
||||
details?: UsageDetail[];
|
||||
@@ -96,6 +100,7 @@ export function windowFromUsedPct(input: {
|
||||
shortLabel?: string;
|
||||
summary?: boolean;
|
||||
utilizationPct: number | null | undefined;
|
||||
durationSeconds?: number;
|
||||
resetsAt?: string | null;
|
||||
tone?: UsageWindow["tone"];
|
||||
}): UsageWindow {
|
||||
@@ -107,6 +112,7 @@ export function windowFromUsedPct(input: {
|
||||
remainingPct: usedPct === null ? null : Math.max(0, 100 - usedPct),
|
||||
resetsAt: input.resetsAt ?? null,
|
||||
};
|
||||
if (input.durationSeconds !== undefined) window.durationSeconds = input.durationSeconds;
|
||||
if (input.shortLabel !== undefined) window.shortLabel = input.shortLabel;
|
||||
if (input.summary) window.summary = true;
|
||||
if (input.tone) window.tone = input.tone;
|
||||
@@ -129,11 +135,10 @@ export function windowFromReportedDuration(input: {
|
||||
summary?: boolean;
|
||||
tone?: UsageWindow["tone"];
|
||||
}): UsageWindow {
|
||||
const duration = input.durationSeconds;
|
||||
const name =
|
||||
duration !== null && Number.isFinite(duration) && duration > 0
|
||||
? durationWindowName(duration)
|
||||
: input.unknown;
|
||||
const reported = input.durationSeconds;
|
||||
const duration =
|
||||
reported !== null && Number.isFinite(reported) && reported > 0 ? reported : undefined;
|
||||
const name = duration === undefined ? input.unknown : durationWindowName(duration);
|
||||
const scope = input.scope;
|
||||
return windowFromUsedPct({
|
||||
id: scope ? `${scope.id}:${name.id}` : name.id,
|
||||
@@ -142,6 +147,7 @@ export function windowFromReportedDuration(input: {
|
||||
? `${scope.label}${name.shortLabel ? ` ${name.shortLabel}` : ""}`
|
||||
: name.shortLabel,
|
||||
utilizationPct: input.utilizationPct,
|
||||
durationSeconds: duration,
|
||||
resetsAt: input.resetsAt,
|
||||
summary: input.summary,
|
||||
tone: input.tone,
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
import type { PluginHookContext, PluginWorktreeCreateRequest } from "./lifecycle.js";
|
||||
|
||||
/** Context passed to worktree manager callbacks. */
|
||||
export type PluginWorktreeContext = PluginHookContext;
|
||||
|
||||
/** Resolved creation request handed to a worktree manager after `worktree.create.before`. */
|
||||
export type PluginWorktreeCreateInput = PluginWorktreeCreateRequest & {
|
||||
/** True when the worktree comes from an untrusted source such as a fork change request; skip repository-defined hooks. */
|
||||
readonly untrusted: boolean;
|
||||
/** Resolved remote head commit SHA for change-request checkouts when available. */
|
||||
readonly headSha?: string;
|
||||
};
|
||||
|
||||
/** Return `{ type: "created", path }` to claim creation, or `undefined` to decline. */
|
||||
export interface PluginWorktreeCreateResult {
|
||||
type: "created";
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface PluginWorktreeRemoveRequest {
|
||||
readonly repoRoot: string | null;
|
||||
readonly path: string;
|
||||
readonly branch: string | null;
|
||||
readonly reason: "archive" | "rollback";
|
||||
readonly force: boolean;
|
||||
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
|
||||
readonly untrusted: boolean;
|
||||
}
|
||||
|
||||
/** Return `{ type: "removed" }` after removing the worktree, or `undefined` to fall back to Git. */
|
||||
export interface PluginWorktreeRemoveResult {
|
||||
type: "removed";
|
||||
}
|
||||
|
||||
export type PluginWorktreeRestoreTarget =
|
||||
| { readonly type: "branch"; readonly branch: string }
|
||||
| { readonly type: "commit"; readonly commit: string }
|
||||
| { readonly type: "from-base"; readonly branch: string; readonly baseRef: string };
|
||||
|
||||
export interface PluginWorktreeRestoreRequest {
|
||||
readonly repoRoot: string;
|
||||
/** Recorded path the worktree must be restored to. */
|
||||
readonly path: string;
|
||||
readonly target: PluginWorktreeRestoreTarget;
|
||||
readonly baseRef: string | null;
|
||||
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
|
||||
readonly untrusted: boolean;
|
||||
}
|
||||
|
||||
/** Return `{ type: "restored", path }` after recreating the worktree, or `undefined` to fall back to Git. */
|
||||
export interface PluginWorktreeRestoreResult {
|
||||
type: "restored";
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface WorktreeManagerRegistration {
|
||||
create(
|
||||
request: PluginWorktreeCreateInput,
|
||||
context: PluginWorktreeContext,
|
||||
): Promise<PluginWorktreeCreateResult | void>;
|
||||
remove?(
|
||||
request: PluginWorktreeRemoveRequest,
|
||||
context: PluginWorktreeContext,
|
||||
): Promise<PluginWorktreeRemoveResult | void>;
|
||||
restore?(
|
||||
request: PluginWorktreeRestoreRequest,
|
||||
context: PluginWorktreeContext,
|
||||
): Promise<PluginWorktreeRestoreResult | void>;
|
||||
}
|
||||
@@ -6992,6 +6992,7 @@ export const ProviderUsageWindowSchema = z.object({
|
||||
usedPct: z.number().nullable().optional(),
|
||||
remainingPct: z.number().nullable().optional(),
|
||||
resetsAt: z.string().nullable().optional(),
|
||||
durationSeconds: z.number().optional(),
|
||||
runsOutAt: z.string().nullable().optional(),
|
||||
shortfallPct: z.number().nullable().optional(),
|
||||
tone: ProviderUsageToneSchema.optional(),
|
||||
@@ -7054,6 +7055,7 @@ export const UsageProblemSchema = z.discriminatedUnion("kind", [
|
||||
const AvailableUsageReportSchema = z.object({
|
||||
status: z.literal("available"),
|
||||
planLabel: z.string().optional(),
|
||||
observedAt: z.string().optional(),
|
||||
windows: z.array(ProviderUsageWindowSchema),
|
||||
balances: z.array(ProviderUsageBalanceSchema).optional(),
|
||||
details: z.array(ProviderUsageDetailSchema).optional(),
|
||||
|
||||
@@ -90,7 +90,7 @@
|
||||
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
|
||||
"test": "npm run test:unit && npm run test:integration",
|
||||
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
|
||||
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
|
||||
"test:integration": "vitest run --maxWorkers=1 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --maxWorkers=1 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
|
||||
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
|
||||
"test:integration:all": "npm run test:e2e",
|
||||
"test:integration:real": "vitest run real.e2e.test.ts",
|
||||
|
||||
@@ -10175,6 +10175,8 @@ test("a sender's start wait follows its prompt across a stale-session retry", as
|
||||
|
||||
test("a sender's start wait follows its prompt when the session is stale before the wait begins", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-manager-immediate-stale-start-"));
|
||||
const resumeEntered = deferred<void>();
|
||||
const releaseResume = deferred<void>();
|
||||
class StaleStartSession extends TestAgentSession {
|
||||
override async startTurn(): Promise<{ turnId: string }> {
|
||||
throw new StaleProviderSessionError("stale-bridge");
|
||||
@@ -10184,6 +10186,15 @@ test("a sender's start wait follows its prompt when the session is stale before
|
||||
override async createSession(config: AgentSessionConfig): Promise<AgentSession> {
|
||||
return new StaleStartSession(config);
|
||||
}
|
||||
|
||||
override async resumeSession(
|
||||
handle: AgentPersistenceHandle,
|
||||
config?: Partial<AgentSessionConfig>,
|
||||
): Promise<AgentSession> {
|
||||
resumeEntered.resolve();
|
||||
await releaseResume.promise;
|
||||
return await super.resumeSession(handle, config);
|
||||
}
|
||||
}
|
||||
const client = new StaleStartClient();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
@@ -10196,9 +10207,11 @@ test("a sender's start wait follows its prompt when the session is stale before
|
||||
runOptions: { clientMessageId: "immediate-stale-start" },
|
||||
});
|
||||
// The stale start has failed and been cleared before the sender begins waiting.
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await resumeEntered.promise;
|
||||
expect(manager.hasInFlightRun(agent.id)).toBe(false);
|
||||
await expect(dispatchStarted(dispatch)).resolves.toBeUndefined();
|
||||
const senderWait = dispatchStarted(dispatch);
|
||||
releaseResume.resolve();
|
||||
await expect(senderWait).resolves.toBeUndefined();
|
||||
await client.waitForRetryStart();
|
||||
expect(manager.getTimeline(agent.id).filter((item) => item.type === "user_message")).toEqual([
|
||||
expect.objectContaining({
|
||||
@@ -10207,6 +10220,7 @@ test("a sender's start wait follows its prompt when the session is stale before
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
releaseResume.resolve();
|
||||
manager.prepareForShutdown();
|
||||
await Promise.all(manager.listAgents().map((agent) => manager.closeAgent(agent.id)));
|
||||
await manager.flushForShutdown();
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { FORGE_IDS } from "@getpaseo/protocol/forge-manifest";
|
||||
import type { Logger } from "pino";
|
||||
import { z } from "zod";
|
||||
import type { ChangeRequestRouter } from "../../../services/change-request-router.js";
|
||||
import {
|
||||
changeRequestStatusSchema,
|
||||
type ChangeRequestSnapshot,
|
||||
type ChangeRequestSource,
|
||||
} from "../../../services/change-request-source.js";
|
||||
import type { AgentMessageDelivery } from "../agent-messages/index.js";
|
||||
import type {
|
||||
@@ -15,13 +16,17 @@ import type {
|
||||
import { writeJsonFileAtomic } from "../../atomic-file.js";
|
||||
|
||||
const DIGEST_WINDOW_MS = 30_000;
|
||||
const watchGroupSchema = z.object({
|
||||
const LEGACY_DEFAULT_FORGE = "github";
|
||||
const LEGACY_INFERENCE_FORGES = ["github", "gitlab"] as const;
|
||||
const persistedWatchGroupSchema = z.object({
|
||||
forge: z.string().min(1).optional(),
|
||||
url: z.url(),
|
||||
snapshot: changeRequestStatusSchema,
|
||||
seenActivity: z.array(z.string()),
|
||||
watchers: z.array(z.object({ agentId: z.string(), startedAt: z.string().optional() })),
|
||||
});
|
||||
type WatchGroup = z.infer<typeof watchGroupSchema>;
|
||||
type PersistedWatchGroup = z.infer<typeof persistedWatchGroupSchema>;
|
||||
type WatchGroup = Omit<PersistedWatchGroup, "forge"> & { forge: string };
|
||||
type Watcher = WatchGroup["watchers"][number];
|
||||
interface DigestWindow {
|
||||
dueAt: number;
|
||||
@@ -35,7 +40,7 @@ interface Observation {
|
||||
release(): void;
|
||||
}
|
||||
interface Dependencies {
|
||||
source: ChangeRequestSource;
|
||||
router: ChangeRequestRouter;
|
||||
paseoHome: string;
|
||||
logger: Logger;
|
||||
isActive(agentId: string): Promise<boolean>;
|
||||
@@ -73,7 +78,7 @@ function describeUpdate(group: WatchGroup, next: ChangeRequestSnapshot) {
|
||||
}
|
||||
for (const activity of next.activity) {
|
||||
if (seen.has(activity.id)) continue;
|
||||
changes.push(`New ${activity.kind}: ${activity.url}`);
|
||||
changes.push(activity.message ?? `New ${activity.kind}: ${activity.url}`);
|
||||
seen.add(activity.id);
|
||||
}
|
||||
if (next.state !== "open") changes.push(`Change request ${next.state}.`);
|
||||
@@ -85,6 +90,7 @@ export type ChangeRequestWatches = ReturnType<typeof createChangeRequestWatches>
|
||||
export function createChangeRequestWatches(deps: Dependencies) {
|
||||
const file = join(deps.paseoHome, "change-request-watches.json");
|
||||
const groups = new Map<string, WatchGroup>();
|
||||
const unrestored: WatchGroup[] = [];
|
||||
const observations = new Map<string, Observation>();
|
||||
const registrations = new Map<string, number>();
|
||||
let mutations = Promise.resolve();
|
||||
@@ -156,32 +162,47 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
}
|
||||
|
||||
function withdraw(agentId: string, url?: string): boolean {
|
||||
let removed = false;
|
||||
for (const [address, window] of windows) {
|
||||
if (url && address !== url) continue;
|
||||
removed = window.recipients.delete(agentId) || removed;
|
||||
function withdraw(agentId: string, matches: (url: string) => boolean): string | undefined {
|
||||
let withdrawn: string | undefined;
|
||||
for (const [url, window] of windows) {
|
||||
if (!window.recipients.has(agentId) || !matches(url)) continue;
|
||||
window.recipients.delete(agentId);
|
||||
withdrawn ??= url;
|
||||
if (!window.recipients.size) {
|
||||
clearTimeout(window.timer);
|
||||
windows.delete(address);
|
||||
windows.delete(url);
|
||||
}
|
||||
}
|
||||
const queued = deps
|
||||
.messages()
|
||||
.withdrawPending(
|
||||
agentId,
|
||||
(source) => source.kind === "change-request-update" && (!url || source.url === url),
|
||||
);
|
||||
return removed || queued > 0;
|
||||
deps.messages().withdrawPending(agentId, (source) => {
|
||||
if (source.kind !== "change-request-update" || !matches(source.url)) return false;
|
||||
withdrawn ??= source.url;
|
||||
return true;
|
||||
});
|
||||
return withdrawn;
|
||||
}
|
||||
|
||||
function withdrawByInput(agentId: string, input: string): string | undefined {
|
||||
const trimmed = input.trim();
|
||||
const candidates = new Set([trimmed]);
|
||||
for (const forge of FORGE_IDS) {
|
||||
const source = deps.router.source(forge);
|
||||
if (!source) continue;
|
||||
try {
|
||||
candidates.add(source.resolve(trimmed));
|
||||
} catch {
|
||||
// This source does not recognize the URL.
|
||||
}
|
||||
}
|
||||
return withdraw(agentId, (url) => candidates.has(url));
|
||||
}
|
||||
|
||||
async function commit(...updates: WatchGroup[]): Promise<void> {
|
||||
const next = new Map(groups);
|
||||
for (const group of updates) next.set(group.url, group);
|
||||
await writeJsonFileAtomic(
|
||||
file,
|
||||
[...next.values()].filter(({ watchers }) => watchers.length),
|
||||
);
|
||||
await writeJsonFileAtomic(file, [
|
||||
...[...next.values()].filter(({ watchers }) => watchers.length),
|
||||
...unrestored,
|
||||
]);
|
||||
for (const group of updates) {
|
||||
const previous = groups.get(group.url);
|
||||
// An in-flight subscription still needs the committed baseline and its observation.
|
||||
@@ -195,7 +216,20 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
}
|
||||
|
||||
function syncBackgroundWork({ url, watchers }: WatchGroup, previous: Watcher[] = []): void {
|
||||
function describeWatch(forge: string, url: string): string {
|
||||
const source = deps.router.source(forge);
|
||||
if (!source) return url;
|
||||
try {
|
||||
return source.describe(url);
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
function syncBackgroundWork(
|
||||
{ forge, url, watchers }: WatchGroup,
|
||||
previous: Watcher[] = [],
|
||||
): void {
|
||||
if (previous === watchers) return;
|
||||
const current = new Set(watchers);
|
||||
for (const watcher of previous) {
|
||||
@@ -209,7 +243,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
deps.backgroundWork.setDaemonBackgroundWork({
|
||||
...backgroundWorkKey(watcher.agentId, url),
|
||||
kind: "monitor",
|
||||
description: deps.source.describe(url),
|
||||
description: describeWatch(forge, url),
|
||||
startedAt: watcher.startedAt ?? new Date().toISOString(),
|
||||
stop: async () => {
|
||||
await unsubscribe(watcher.agentId, url, watcher);
|
||||
@@ -218,9 +252,13 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
}
|
||||
|
||||
function observe(url: string): Observation {
|
||||
function observe(forge: string, url: string): Observation {
|
||||
const existing = observations.get(url);
|
||||
if (existing) return existing;
|
||||
const source = deps.router.source(forge);
|
||||
if (!source) {
|
||||
throw new Error(`Change request watches are not supported for ${forge}.`);
|
||||
}
|
||||
let resolve!: (snapshot: ChangeRequestSnapshot) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const ready = new Promise<ChangeRequestSnapshot>((accept, fail) => {
|
||||
@@ -228,7 +266,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
reject = fail;
|
||||
});
|
||||
void ready.catch(() => undefined);
|
||||
const release = deps.source.observe(url, {
|
||||
const release = source.observe(url, {
|
||||
knownActivity: () => new Set(groups.get(url)?.seenActivity),
|
||||
snapshot: (snapshot) =>
|
||||
serialize(async () => {
|
||||
@@ -266,14 +304,14 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}),
|
||||
error(error) {
|
||||
if (!observation.stale) {
|
||||
deps.logger.warn({ err: error, url }, "Change request observation became stale");
|
||||
deps.logger.warn({ err: error, url, forge }, "Change request observation became stale");
|
||||
}
|
||||
observation.stale = true;
|
||||
if (!groups.has(url)) {
|
||||
reject(error);
|
||||
stopObserving(url);
|
||||
}
|
||||
deps.logger.debug({ err: error, url }, "Change request observation failed");
|
||||
deps.logger.debug({ err: error, url, forge }, "Change request observation failed");
|
||||
},
|
||||
});
|
||||
const observation: Observation = {
|
||||
@@ -288,16 +326,62 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
return observation;
|
||||
}
|
||||
|
||||
async function subscribe(agentId: string, input: string) {
|
||||
if (closed) throw new Error("Change request watches are closed");
|
||||
const url = deps.source.resolve(input);
|
||||
if (recoveryError)
|
||||
throw new Error("Change request watches could not recover.", { cause: recoveryError });
|
||||
function matchActiveGroup(input: string): { forge: string; url: string } | null {
|
||||
const trimmed = input.trim();
|
||||
const direct = groups.get(trimmed);
|
||||
if (direct) return { forge: direct.forge, url: direct.url };
|
||||
const sourcesTried = new Set<string>();
|
||||
for (const group of groups.values()) {
|
||||
if (sourcesTried.has(group.forge)) continue;
|
||||
sourcesTried.add(group.forge);
|
||||
const source = deps.router.source(group.forge);
|
||||
if (!source) continue;
|
||||
try {
|
||||
const canonical = source.resolve(trimmed);
|
||||
const matched = groups.get(canonical);
|
||||
if (matched && matched.forge === group.forge) {
|
||||
return { forge: matched.forge, url: matched.url };
|
||||
}
|
||||
} catch {
|
||||
// Input did not belong to this forge.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function subscribe(agentId: string, input: string) {
|
||||
if (closed) return Promise.reject(new Error("Change request watches are closed"));
|
||||
if (recoveryError) {
|
||||
return Promise.reject(
|
||||
new Error("Change request watches could not recover.", { cause: recoveryError }),
|
||||
);
|
||||
}
|
||||
const active = matchActiveGroup(input);
|
||||
if (active) {
|
||||
return subscribeResolved(agentId, active.forge, active.url);
|
||||
}
|
||||
return deps.router
|
||||
.resolve(input)
|
||||
.then(({ forge, url }) => subscribeResolved(agentId, forge, url));
|
||||
}
|
||||
|
||||
function subscribeResolved(agentId: string, forge: string, url: string) {
|
||||
registrations.set(url, (registrations.get(url) ?? 0) + 1);
|
||||
try {
|
||||
const existing = groups.get(url);
|
||||
const initial = existing ? { ...existing.snapshot, activity: [] } : await observe(url).ready;
|
||||
return await serialize(async () => {
|
||||
const existing = groups.get(url);
|
||||
const finish = () => {
|
||||
const remaining = registrations.get(url)! - 1;
|
||||
if (remaining) {
|
||||
registrations.set(url, remaining);
|
||||
} else {
|
||||
registrations.delete(url);
|
||||
if (!groups.get(url)?.watchers.length) {
|
||||
groups.delete(url);
|
||||
stopObserving(url);
|
||||
}
|
||||
}
|
||||
};
|
||||
const commitSubscription = (initial: ChangeRequestSnapshot) =>
|
||||
serialize(async () => {
|
||||
if (closed || !(await deps.isActive(agentId))) throw new Error("Agent is no longer active");
|
||||
const group = groups.get(url);
|
||||
const { activity, ...initialStatus } = initial;
|
||||
@@ -305,6 +389,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
const subscribed = snapshot.state === "open";
|
||||
if (subscribed && !group?.watchers.some((watcher) => watcher.agentId === agentId)) {
|
||||
await commit({
|
||||
forge: group?.forge ?? forge,
|
||||
url,
|
||||
snapshot,
|
||||
seenActivity: group?.seenActivity ?? activity.map(({ id }) => id),
|
||||
@@ -322,21 +407,13 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
checks: snapshot.checks,
|
||||
reviewDecision: snapshot.reviewDecision,
|
||||
subscribed,
|
||||
stale: observations.get(url)?.stale ?? false,
|
||||
stale: observations.get(url)?.stale ?? Boolean(existing),
|
||||
};
|
||||
});
|
||||
} finally {
|
||||
const remaining = registrations.get(url)! - 1;
|
||||
if (remaining) {
|
||||
registrations.set(url, remaining);
|
||||
} else {
|
||||
registrations.delete(url);
|
||||
if (!groups.get(url)?.watchers.length) {
|
||||
groups.delete(url);
|
||||
stopObserving(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
const pending = existing
|
||||
? commitSubscription({ ...existing.snapshot, activity: [] })
|
||||
: observe(forge, url).ready.then(commitSubscription);
|
||||
return pending.finally(finish);
|
||||
}
|
||||
|
||||
function removeWatcher(group: WatchGroup, agentId: string): Promise<void> {
|
||||
@@ -355,15 +432,15 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
throw new Error("Background work is no longer available to stop");
|
||||
}
|
||||
if (group && watcher) await removeWatcher(group, agentId);
|
||||
const withdrawn = withdraw(agentId, url);
|
||||
return { url, removed: Boolean(watcher) || withdrawn };
|
||||
const withdrawn = withdraw(agentId, (address) => address === url);
|
||||
return { url, removed: Boolean(watcher || withdrawn) };
|
||||
});
|
||||
}
|
||||
|
||||
function archive(agentId: string): Promise<void> {
|
||||
return serialize(async () => {
|
||||
if (closed) return;
|
||||
withdraw(agentId);
|
||||
withdraw(agentId, () => true);
|
||||
const updates: WatchGroup[] = [];
|
||||
for (const group of groups.values()) {
|
||||
const watchers = group.watchers.filter((watcher) => watcher.agentId !== agentId);
|
||||
@@ -373,6 +450,20 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
});
|
||||
}
|
||||
|
||||
function inferLegacyForge(url: string): string {
|
||||
for (const candidate of LEGACY_INFERENCE_FORGES) {
|
||||
const source = deps.router.source(candidate);
|
||||
if (!source) continue;
|
||||
try {
|
||||
source.resolve(url);
|
||||
return candidate;
|
||||
} catch {
|
||||
// URL does not match this forge's canonical path shape.
|
||||
}
|
||||
}
|
||||
return LEGACY_DEFAULT_FORGE;
|
||||
}
|
||||
|
||||
return {
|
||||
async start() {
|
||||
const active: WatchGroup[] = [];
|
||||
@@ -382,8 +473,12 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
if (error.code === "ENOENT") return "[]";
|
||||
throw error;
|
||||
});
|
||||
const restored = z.array(watchGroupSchema).parse(JSON.parse(stored));
|
||||
for (const group of restored) {
|
||||
const restored = z.array(persistedWatchGroupSchema).parse(JSON.parse(stored));
|
||||
for (const record of restored) {
|
||||
const group: WatchGroup = {
|
||||
...record,
|
||||
forge: record.forge ?? inferLegacyForge(record.url),
|
||||
};
|
||||
if (group.snapshot.state !== "open") {
|
||||
pruned = true;
|
||||
continue;
|
||||
@@ -393,7 +488,17 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
if (await deps.isActive(watcher.agentId)) watchers.push(watcher);
|
||||
}
|
||||
pruned ||= watchers.length !== group.watchers.length;
|
||||
if (watchers.length) active.push({ ...group, watchers });
|
||||
if (!watchers.length) continue;
|
||||
const nextGroup = { ...group, watchers };
|
||||
if (!deps.router.source(nextGroup.forge)) {
|
||||
deps.logger.warn(
|
||||
{ forge: nextGroup.forge, url: nextGroup.url },
|
||||
"Skipping persisted change request watch for unsupported forge",
|
||||
);
|
||||
unrestored.push(nextGroup);
|
||||
continue;
|
||||
}
|
||||
active.push(nextGroup);
|
||||
}
|
||||
} catch (error) {
|
||||
recoveryError = error;
|
||||
@@ -402,7 +507,7 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
}
|
||||
if (pruned) {
|
||||
try {
|
||||
await writeJsonFileAtomic(file, active);
|
||||
await writeJsonFileAtomic(file, [...active, ...unrestored]);
|
||||
} catch (error) {
|
||||
deps.logger.warn({ err: error, file }, "Could not prune archived change request watches");
|
||||
}
|
||||
@@ -410,12 +515,24 @@ export function createChangeRequestWatches(deps: Dependencies) {
|
||||
for (const group of active) {
|
||||
groups.set(group.url, group);
|
||||
syncBackgroundWork(group);
|
||||
observe(group.url);
|
||||
try {
|
||||
observe(group.forge, group.url);
|
||||
} catch (error) {
|
||||
deps.logger.warn(
|
||||
{ err: error, forge: group.forge, url: group.url },
|
||||
"Could not start observing restored change request watch",
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
subscribe,
|
||||
unsubscribe(agentId: string, input: string) {
|
||||
return unsubscribe(agentId, deps.source.resolve(input));
|
||||
async unsubscribe(agentId: string, input: string) {
|
||||
const active = matchActiveGroup(input);
|
||||
if (active) return unsubscribe(agentId, active.url);
|
||||
const withdrawn = await serialize(async () => withdrawByInput(agentId, input));
|
||||
if (withdrawn) return { url: withdrawn, removed: true };
|
||||
const { url } = await deps.router.resolve(input);
|
||||
return unsubscribe(agentId, url);
|
||||
},
|
||||
archive,
|
||||
async close() {
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { mkdir, mkdtemp, readFile, rename, rm } from "node:fs/promises";
|
||||
import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import pino from "pino";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import { createChangeRequestWatches } from "./index.js";
|
||||
import { AgentBackgroundWorkStore } from "../background-work/index.js";
|
||||
import { createAgentMessageDelivery, parseAgentMessages } from "../agent-messages/index.js";
|
||||
import type { ChangeRequestRouter } from "../../../services/change-request-router.js";
|
||||
import type {
|
||||
ChangeRequestSnapshot,
|
||||
ChangeRequestSource,
|
||||
} from "../../../services/change-request-source.js";
|
||||
|
||||
const url = "https://github.com/owner/repo/pull/42";
|
||||
const gitlabUrl = "https://gitlab.com/org/sub/app/-/merge_requests/9";
|
||||
const reviewUrl = url + "#pullrequestreview-1";
|
||||
const initial: ChangeRequestSnapshot = {
|
||||
state: "open",
|
||||
@@ -31,13 +33,19 @@ async function createTestHome() {
|
||||
|
||||
function createHarness(
|
||||
home: string,
|
||||
{ isActive = async (_id: string) => true, observationFails = false } = {},
|
||||
{
|
||||
isActive = async (_id: string) => true,
|
||||
observationFails = false,
|
||||
resolveFails = false,
|
||||
extraSources = {} as Record<string, ChangeRequestSource>,
|
||||
} = {},
|
||||
) {
|
||||
const observations = new Map<string, Parameters<ChangeRequestSource["observe"]>[1]>();
|
||||
const backgroundWork = new AgentBackgroundWorkStore();
|
||||
const busy = new Set<string>();
|
||||
const turns: { recipientId: string; prompt: string }[] = [];
|
||||
const listeners = new Set<(id: string) => void>();
|
||||
const resolveCalls: string[] = [];
|
||||
const messages = createAgentMessageDelivery({
|
||||
isRunning: (id) => busy.has(id),
|
||||
subscribe(listener) {
|
||||
@@ -52,10 +60,16 @@ function createHarness(
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const watches = createChangeRequestWatches({
|
||||
source: {
|
||||
resolve: (input) => input,
|
||||
describe: () => "owner/repo #42",
|
||||
function createFakeSource(
|
||||
describe: (address: string) => string,
|
||||
accepts: (input: string) => boolean,
|
||||
): ChangeRequestSource {
|
||||
return {
|
||||
resolve: (input) => {
|
||||
if (!accepts(input)) throw new Error("Unsupported URL for fake forge");
|
||||
return input.replace(/\/+$/, "");
|
||||
},
|
||||
describe,
|
||||
observe(address, callbacks) {
|
||||
observations.set(address, callbacks);
|
||||
queueMicrotask(() => {
|
||||
@@ -64,7 +78,34 @@ function createHarness(
|
||||
});
|
||||
return () => observations.delete(address);
|
||||
},
|
||||
};
|
||||
}
|
||||
const sources: Record<string, ChangeRequestSource> = {
|
||||
github: createFakeSource(
|
||||
() => "owner/repo #42",
|
||||
(input) => input.includes("/pull/"),
|
||||
),
|
||||
gitlab: createFakeSource(
|
||||
() => "org/sub/app !9",
|
||||
(input) => input.includes("/merge_requests/"),
|
||||
),
|
||||
...extraSources,
|
||||
};
|
||||
const router: ChangeRequestRouter = {
|
||||
async resolve(input) {
|
||||
resolveCalls.push(input);
|
||||
if (resolveFails) throw new Error("Host probe failed");
|
||||
const forge = input.includes("gitlab") ? "gitlab" : "github";
|
||||
const source = sources[forge];
|
||||
if (!source) throw new Error(`Unsupported forge: ${forge}`);
|
||||
return { forge, url: source.resolve(input) };
|
||||
},
|
||||
source(forge) {
|
||||
return sources[forge] ?? null;
|
||||
},
|
||||
};
|
||||
const watches = createChangeRequestWatches({
|
||||
router,
|
||||
paseoHome: home,
|
||||
logger: pino({ enabled: false }),
|
||||
isActive,
|
||||
@@ -78,6 +119,7 @@ function createHarness(
|
||||
messages,
|
||||
watches,
|
||||
backgroundWork,
|
||||
resolveCalls,
|
||||
idle(id: string) {
|
||||
busy.delete(id);
|
||||
for (const listener of listeners) listener(id);
|
||||
@@ -255,6 +297,47 @@ test("can withdraw a terminal digest after its observation has stopped", async (
|
||||
}
|
||||
});
|
||||
|
||||
test.each([0, 32_000])(
|
||||
"withdraws a terminal update without a host probe after %i ms",
|
||||
async (elapsed) => {
|
||||
vi.useFakeTimers();
|
||||
const home = await createTestHome();
|
||||
const enterpriseUrl = "https://github.example.com/owner/repo/pull/42";
|
||||
const { activity: _activity, ...snapshot } = initial;
|
||||
await writeFile(
|
||||
join(home, "change-request-watches.json"),
|
||||
JSON.stringify([
|
||||
{
|
||||
forge: "github",
|
||||
url: enterpriseUrl,
|
||||
snapshot,
|
||||
seenActivity: [],
|
||||
watchers: [{ agentId: "first" }],
|
||||
},
|
||||
]),
|
||||
);
|
||||
const h = createHarness(home, { resolveFails: true });
|
||||
try {
|
||||
h.busy.add("first");
|
||||
await h.watches.start();
|
||||
await h.observations.get(enterpriseUrl)!.snapshot({ ...initial, state: "merged" });
|
||||
expect(h.observations.has(enterpriseUrl)).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(elapsed);
|
||||
await expect(h.watches.unsubscribe("first", `${enterpriseUrl}/`)).resolves.toEqual({
|
||||
url: enterpriseUrl,
|
||||
removed: true,
|
||||
});
|
||||
expect(h.resolveCalls).toEqual([]);
|
||||
h.idle("first");
|
||||
await vi.advanceTimersByTimeAsync(32_000);
|
||||
expect(h.turns).toEqual([]);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("retains the current observation as the last subscriber leaves and a new one joins", async () => {
|
||||
const home = await createTestHome();
|
||||
const h = createHarness(home);
|
||||
@@ -343,3 +426,119 @@ test("recovers active watches even when pruning archived watchers cannot be writ
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("persists forge ids, restores legacy GitHub watches without probing, and preserves unknown forges", async () => {
|
||||
const home = await createTestHome();
|
||||
const file = join(home, "change-request-watches.json");
|
||||
const legacyRecord = {
|
||||
url,
|
||||
snapshot: {
|
||||
state: "open",
|
||||
headSha: "aaa",
|
||||
checksState: "pending",
|
||||
checks: [],
|
||||
reviewDecision: null,
|
||||
},
|
||||
seenActivity: [],
|
||||
watchers: [{ agentId: "legacy-agent", startedAt: "2026-01-01T00:00:00.000Z" }],
|
||||
};
|
||||
const unknownForgeRecord = {
|
||||
forge: "futureforge",
|
||||
url: "https://future.example.com/team/repo/cr/5",
|
||||
snapshot: legacyRecord.snapshot,
|
||||
seenActivity: [],
|
||||
watchers: [{ agentId: "future-agent", startedAt: "2026-01-01T00:00:00.000Z" }],
|
||||
};
|
||||
const strippedGitLabRecord = {
|
||||
url: gitlabUrl,
|
||||
snapshot: legacyRecord.snapshot,
|
||||
seenActivity: [],
|
||||
watchers: [{ agentId: "gitlab-agent", startedAt: "2026-01-01T00:00:00.000Z" }],
|
||||
};
|
||||
await writeFile(
|
||||
file,
|
||||
JSON.stringify([legacyRecord, strippedGitLabRecord, unknownForgeRecord]),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const h = createHarness(home, { resolveFails: true });
|
||||
try {
|
||||
await h.watches.start();
|
||||
expect(h.resolveCalls).toEqual([]);
|
||||
expect(h.backgroundWork.list("legacy-agent")).toEqual([
|
||||
expect.objectContaining({ description: "owner/repo #42", kind: "monitor" }),
|
||||
]);
|
||||
expect(h.backgroundWork.list("gitlab-agent")).toEqual([
|
||||
expect.objectContaining({ description: "org/sub/app !9", kind: "monitor" }),
|
||||
]);
|
||||
expect(h.observations.has(url)).toBe(true);
|
||||
expect(h.observations.has(gitlabUrl)).toBe(true);
|
||||
|
||||
// Unsubscribing an active watch succeeds even when host resolution is temporarily down.
|
||||
await expect(h.watches.unsubscribe("legacy-agent", `${url}/`)).resolves.toEqual({
|
||||
url,
|
||||
removed: true,
|
||||
});
|
||||
expect(h.backgroundWork.list("legacy-agent")).toEqual([]);
|
||||
const persisted = JSON.parse(await readFile(file, "utf8")) as Array<{
|
||||
forge?: string;
|
||||
url: string;
|
||||
}>;
|
||||
expect(persisted).toEqual([
|
||||
expect.objectContaining({ forge: "gitlab", url: gitlabUrl }),
|
||||
unknownForgeRecord,
|
||||
]);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("watches multiple forges concurrently with forge-native descriptions and custom approval messages", async () => {
|
||||
vi.useFakeTimers();
|
||||
const home = await createTestHome();
|
||||
const file = join(home, "change-request-watches.json");
|
||||
const h = createHarness(home);
|
||||
try {
|
||||
await h.watches.start();
|
||||
await h.watches.subscribe("agent-1", url);
|
||||
await h.watches.subscribe("agent-1", gitlabUrl);
|
||||
expect(h.backgroundWork.list("agent-1").map((item) => item.description)).toEqual([
|
||||
"owner/repo #42",
|
||||
"org/sub/app !9",
|
||||
]);
|
||||
|
||||
const persisted = JSON.parse(await readFile(file, "utf8")) as Array<{
|
||||
forge?: string;
|
||||
url: string;
|
||||
}>;
|
||||
expect(persisted.map(({ forge, url: entryUrl }) => ({ forge, url: entryUrl }))).toEqual([
|
||||
{ forge: "github", url },
|
||||
{ forge: "gitlab", url: gitlabUrl },
|
||||
]);
|
||||
|
||||
await h.observations.get(gitlabUrl)!.snapshot({
|
||||
...initial,
|
||||
activity: [
|
||||
{
|
||||
id: "approval-note:77",
|
||||
kind: "approval",
|
||||
url: `${gitlabUrl}#note_77`,
|
||||
message: `Merge request approved by @alice (1/1 approvals): ${gitlabUrl}#note_77`,
|
||||
},
|
||||
],
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(32_000);
|
||||
expect(h.turns).toEqual([
|
||||
{
|
||||
recipientId: "agent-1",
|
||||
prompt: expect.stringContaining(
|
||||
`Merge request approved by @alice (1/1 approvals): ${gitlabUrl}#note_77`,
|
||||
),
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
await h.close();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -4,11 +4,7 @@ import type pino from "pino";
|
||||
|
||||
import type { ForgeService } from "../../services/forge-service.js";
|
||||
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
|
||||
import {
|
||||
archiveByScope,
|
||||
type ActiveWorkspaceRef,
|
||||
type ArchiveDependencies,
|
||||
} from "../workspace-archive-service.js";
|
||||
import { archiveByScope, type ActiveWorkspaceRef } from "../workspace-archive-service.js";
|
||||
import type {
|
||||
CreatePaseoWorktreeWorkflowFn,
|
||||
CreatePaseoWorktreeWorkflowResult,
|
||||
@@ -21,15 +17,10 @@ import type {
|
||||
} from "../messages.js";
|
||||
import type { AgentManager, AgentSubscriber, SubscribeOptions } from "./agent-manager.js";
|
||||
import type { AgentStorage } from "./agent-storage.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
|
||||
|
||||
interface CreateAgentLifecycleDispatchDependencies {
|
||||
paseoHome: string;
|
||||
worktreesRoot?: string;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
|
||||
getWorkspace?: ArchiveDependencies["getWorkspace"];
|
||||
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
agentManager: AgentManager;
|
||||
agentStorage: AgentStorage;
|
||||
github: ForgeService;
|
||||
@@ -193,15 +184,11 @@ export class CreateAgentLifecycleDispatch {
|
||||
{
|
||||
paseoHome: this.dependencies.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.dependencies.worktreesRoot,
|
||||
worktreeManagers: this.dependencies.worktreeManagers,
|
||||
workspaceArchiveOperations: this.dependencies.workspaceArchiveOperations,
|
||||
github: this.dependencies.github,
|
||||
workspaceGitService: this.dependencies.workspaceGitService,
|
||||
agentManager: this.dependencies.agentManager,
|
||||
agentStorage: this.dependencies.agentStorage,
|
||||
findWorkspaceIdForCwd: this.dependencies.findWorkspaceIdForCwd,
|
||||
getWorkspace: this.dependencies.getWorkspace,
|
||||
isCheckoutUntrusted: this.dependencies.isCheckoutUntrusted,
|
||||
listActiveWorkspaces: this.dependencies.listActiveWorkspaces,
|
||||
archiveWorkspaceRecord: this.dependencies.archiveWorkspaceRecord,
|
||||
emitWorkspaceUpdatesForWorkspaceIds: this.dependencies.emitWorkspaceUpdatesForWorkspaceIds,
|
||||
|
||||
@@ -139,9 +139,6 @@ export interface PaseoToolHostDependencies {
|
||||
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
|
||||
>;
|
||||
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
|
||||
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
|
||||
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
|
||||
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
|
||||
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
|
||||
emitWorkspaceUpdatesForWorkspaceIds?: ArchiveDependencies["emitWorkspaceUpdatesForWorkspaceIds"];
|
||||
@@ -2731,13 +2728,19 @@ function createToolCatalog(
|
||||
|
||||
if (options.changeRequestWatches) {
|
||||
const watches = options.changeRequestWatches;
|
||||
const inputSchema = { url: z.string().trim().min(1).describe("URL of a GitHub pull request.") };
|
||||
const inputSchema = {
|
||||
url: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.describe("URL of a pull request or merge request on a supported forge."),
|
||||
};
|
||||
registerTool(
|
||||
"subscribe_change_request",
|
||||
{
|
||||
title: "Watch change request",
|
||||
description:
|
||||
"Watch a pull request for check failures, passing checks, new comments, reviews, and closure. Returns the current state and sends future updates after your current turn.",
|
||||
"Watch a pull request or merge request for check failures, passing checks, new comments, reviews, approvals, and closure. Returns the current state and sends future updates after your current turn.",
|
||||
inputSchema,
|
||||
outputSchema: {
|
||||
url: z.string(),
|
||||
@@ -3412,17 +3415,11 @@ function archiveWorktreeDependencies(
|
||||
return {
|
||||
paseoHome: options.paseoHome,
|
||||
paseoWorktreesBaseRoot: options.worktreesRoot,
|
||||
worktreeManagers: options.worktreeManagers,
|
||||
workspaceArchiveOperations: options.workspaceArchiveOperations,
|
||||
isCheckoutUntrusted: options.isCheckoutUntrusted,
|
||||
github: options.github,
|
||||
workspaceGitService: options.workspaceGitService,
|
||||
agentManager: context.agentManager,
|
||||
agentStorage: context.agentStorage,
|
||||
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
|
||||
...(options.workspaceRegistry
|
||||
? { getWorkspace: (workspaceId: string) => options.workspaceRegistry!.get(workspaceId) }
|
||||
: {}),
|
||||
listActiveWorkspaces: options.listActiveWorkspaces,
|
||||
archiveWorkspaceRecord: options.archiveWorkspaceRecord,
|
||||
emitWorkspaceUpdatesForWorkspaceIds: options.emitWorkspaceUpdatesForWorkspaceIds,
|
||||
|
||||
@@ -6,7 +6,6 @@ import type { DaemonConfigStore } from "../daemon-config-store.js";
|
||||
import {
|
||||
archiveByScope,
|
||||
type ActiveWorkspaceRef,
|
||||
type ArchiveDependencies,
|
||||
killTerminalsForWorkspace,
|
||||
} from "../workspace-archive-service.js";
|
||||
import type {
|
||||
@@ -17,15 +16,10 @@ import type { ForgeService } from "../../services/forge-service.js";
|
||||
import type { TerminalManager } from "../../terminal/terminal-manager.js";
|
||||
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
|
||||
import type { WorkspaceArchiveContext } from "../workspace-registry.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
|
||||
|
||||
export interface AutoArchiveArchiveOptions {
|
||||
paseoHome: string;
|
||||
paseoWorktreesBaseRoot?: string;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
workspaceArchiveOperations?: ArchiveDependencies["workspaceArchiveOperations"];
|
||||
getWorkspace?: ArchiveDependencies["getWorkspace"];
|
||||
isCheckoutUntrusted?: ArchiveDependencies["isCheckoutUntrusted"];
|
||||
daemonConfigStore: DaemonConfigStore;
|
||||
workspaceGitService: WorkspaceGitServiceImpl;
|
||||
github: ForgeService;
|
||||
@@ -105,15 +99,11 @@ export async function archiveIfSafe(input: {
|
||||
{
|
||||
paseoHome: options.paseoHome,
|
||||
paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot,
|
||||
worktreeManagers: options.worktreeManagers,
|
||||
workspaceArchiveOperations: options.workspaceArchiveOperations,
|
||||
github: options.github,
|
||||
workspaceGitService: options.workspaceGitService,
|
||||
agentManager: options.agentManager,
|
||||
agentStorage: options.agentStorage,
|
||||
findWorkspaceIdForCwd: options.findWorkspaceIdForCwd,
|
||||
getWorkspace: options.getWorkspace,
|
||||
isCheckoutUntrusted: options.isCheckoutUntrusted,
|
||||
listActiveWorkspaces: options.listActiveWorkspaces,
|
||||
archiveWorkspaceRecord: (workspaceIdToArchive, archivedAt) =>
|
||||
options.archiveWorkspaceRecord(
|
||||
|
||||
@@ -132,6 +132,9 @@ export async function fanOutReconciledWorkspaceUpdates(input: {
|
||||
import { VoiceAssistantWebSocketServer, isDaemonOriginAllowed } from "./websocket-server.js";
|
||||
import { WorkspaceSetupRuntime } from "./workspace-setup-runtime.js";
|
||||
import { createWorkspaceLabelService } from "./workspace-labels/index.js";
|
||||
import { createChangeRequestRouter } from "../services/change-request-router.js";
|
||||
import { createForgeService } from "../services/forge-registry.js";
|
||||
import { createForgeResolver } from "../services/forge-resolver.js";
|
||||
import { createGitHubService } from "../services/github-service.js";
|
||||
import { createPaseoWorktree as createRegisteredPaseoWorktree } from "./paseo-worktree-service.js";
|
||||
import { createWorkspaceProvisioningService } from "./session/workspace-provisioning/workspace-provisioning-service.js";
|
||||
@@ -181,7 +184,6 @@ import {
|
||||
killTerminalsForWorkspace,
|
||||
type ActiveWorkspaceRef,
|
||||
} from "./workspace-archive-service.js";
|
||||
import { WorkspaceArchiveOperations } from "./workspace-archive-operations.js";
|
||||
import { setupAutoArchiveOnMerge } from "./auto-archive-on-merge/index.js";
|
||||
import { wrapSessionMessage, type SessionOutboundMessage } from "./messages.js";
|
||||
import type { TerminalManager } from "../terminal/terminal-manager.js";
|
||||
@@ -212,10 +214,7 @@ import { ScriptHealthMonitor } from "./script-health-monitor.js";
|
||||
import { createScriptStatusEmitter } from "./script-status-projection.js";
|
||||
import { WorkspaceScriptRuntimeStore } from "./workspace-script-runtime-store.js";
|
||||
import { createWorkspaceScriptsService } from "./session/workspace-scripts/workspace-scripts-service.js";
|
||||
import {
|
||||
assertWorkspaceAutomationAllowedForWorkspace,
|
||||
isCheckoutUntrusted,
|
||||
} from "./workspace-automation-gate.js";
|
||||
import { assertWorkspaceAutomationAllowedForWorkspace } from "./workspace-automation-gate.js";
|
||||
import { spawnWorkspaceScript } from "./worktree-bootstrap.js";
|
||||
import {
|
||||
createManagedProcessRegistry,
|
||||
@@ -744,7 +743,6 @@ export async function createPaseoDaemon(
|
||||
});
|
||||
const scriptRuntimeStore = new WorkspaceScriptRuntimeStore();
|
||||
const workspaceSetupRuntime = new WorkspaceSetupRuntime();
|
||||
const workspaceArchiveOperations = new WorkspaceArchiveOperations();
|
||||
let configuredHostnames = config.hostnames ?? config.allowedHosts;
|
||||
let appBaseUrl = config.appBaseUrl ?? "https://app.paseo.sh";
|
||||
daemonConfigStore.onFieldChange("hostnames", (value) => {
|
||||
@@ -959,12 +957,15 @@ export async function createPaseoDaemon(
|
||||
workspaceRegistry,
|
||||
});
|
||||
const github = createGitHubService();
|
||||
const forgeResolver = createForgeResolver({
|
||||
createService: (forge) => (forge === "github" ? github : createForgeService(forge)),
|
||||
});
|
||||
const workspaceGitService = new WorkspaceGitServiceImpl({
|
||||
logger,
|
||||
paseoHome: config.paseoHome,
|
||||
worktreesRoot: config.worktreesRoot,
|
||||
deps: {
|
||||
forgeOverrides: { github },
|
||||
forgeResolver,
|
||||
},
|
||||
});
|
||||
const workspaceRuntimeStore = createWorkspaceRuntimeStore();
|
||||
@@ -1165,8 +1166,6 @@ export async function createPaseoDaemon(
|
||||
worktreeRoot: workspace.worktreeRoot,
|
||||
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
|
||||
mainRepoRoot: workspace.mainRepoRoot,
|
||||
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
|
||||
untrustedSource: workspace.untrustedSource,
|
||||
}));
|
||||
};
|
||||
const markWorkspaceArchivingExternal = (workspaceIds: Iterable<string>, archivingAt: string) => {
|
||||
@@ -1225,8 +1224,6 @@ export async function createPaseoDaemon(
|
||||
setupAutoArchiveOnMerge({
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
daemonConfigStore,
|
||||
workspaceGitService,
|
||||
github,
|
||||
@@ -1235,8 +1232,6 @@ export async function createPaseoDaemon(
|
||||
terminalManager,
|
||||
logger,
|
||||
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
|
||||
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
getAutoArchivedChangeRequestUrl: async (workspaceId) =>
|
||||
(await workspaceRegistry.get(workspaceId))?.autoArchivedChangeRequestUrl ?? null,
|
||||
@@ -1257,7 +1252,6 @@ export async function createPaseoDaemon(
|
||||
createPaseoWorktree: async (workflowInput, workflowOptions) => {
|
||||
return createRegisteredPaseoWorktree(workflowInput, {
|
||||
lifecycle: pluginRuntime,
|
||||
worktreeManagers: pluginRuntime,
|
||||
github,
|
||||
...(workflowOptions?.resolveDefaultBranch
|
||||
? {
|
||||
@@ -1318,8 +1312,6 @@ export async function createPaseoDaemon(
|
||||
{
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
github,
|
||||
workspaceGitService,
|
||||
agentManager,
|
||||
@@ -1337,7 +1329,6 @@ export async function createPaseoDaemon(
|
||||
stopWorkspaceSetup: (workspaceIdToStop) => workspaceSetupRuntime.stop(workspaceIdToStop),
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
sessionLogger: logger,
|
||||
},
|
||||
{ scope: { kind: "workspace", workspaceId }, requestId },
|
||||
@@ -1345,10 +1336,6 @@ export async function createPaseoDaemon(
|
||||
const hubAgentLifecycle = new CreateAgentLifecycleDispatch({
|
||||
paseoHome: config.paseoHome,
|
||||
worktreesRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
getWorkspace: (workspaceId) => workspaceRegistry.get(workspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
agentManager,
|
||||
agentStorage,
|
||||
github,
|
||||
@@ -1447,8 +1434,6 @@ export async function createPaseoDaemon(
|
||||
{
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
github,
|
||||
workspaceGitService,
|
||||
agentManager,
|
||||
@@ -1472,7 +1457,6 @@ export async function createPaseoDaemon(
|
||||
stopWorkspaceSetup: (workspaceIdToStop) => workspaceSetupRuntime.stop(workspaceIdToStop),
|
||||
assertWorkspaceAutomationAllowed: (guardedWorkspaceId) =>
|
||||
assertWorkspaceAutomationAllowedForWorkspace(workspaceRegistry, guardedWorkspaceId),
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
sessionLogger: logger,
|
||||
},
|
||||
{
|
||||
@@ -1494,7 +1478,7 @@ export async function createPaseoDaemon(
|
||||
await scheduleService.start();
|
||||
|
||||
const changeRequestWatches = createChangeRequestWatches({
|
||||
source: github.changeRequests,
|
||||
router: createChangeRequestRouter({ forgeResolver }),
|
||||
backgroundWork: agentManager,
|
||||
paseoHome: config.paseoHome,
|
||||
logger,
|
||||
@@ -1599,9 +1583,6 @@ export async function createPaseoDaemon(
|
||||
daemonConfigStore,
|
||||
github,
|
||||
workspaceGitService,
|
||||
worktreeManagers: pluginRuntime,
|
||||
workspaceArchiveOperations,
|
||||
isCheckoutUntrusted: (checkoutPath) => isCheckoutUntrusted(workspaceRegistry, checkoutPath),
|
||||
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
|
||||
@@ -1949,7 +1930,6 @@ export async function createPaseoDaemon(
|
||||
pluginRuntime,
|
||||
orchestrationSkills,
|
||||
workspaceLabelService,
|
||||
workspaceArchiveOperations,
|
||||
);
|
||||
pluginRuntime.bindPaseoSessionHost(wsServer);
|
||||
await pluginRuntime.start();
|
||||
@@ -2082,6 +2062,7 @@ export async function createPaseoDaemon(
|
||||
if (wsServer) {
|
||||
await wsServer.close();
|
||||
}
|
||||
forgeResolver.dispose();
|
||||
await serviceProxy.stopStandalone();
|
||||
// Force-drop remaining sockets so httpServer.close() resolves promptly.
|
||||
// We've already closed wsServer (which sent ws-layer close frames) and
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { test, expect } from "vitest";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createDaemonTestContext } from "../test-utils/index.js";
|
||||
|
||||
test("reports the provider's thinking level after an explicit live ACP mode change", async () => {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-acp-live-mode-"));
|
||||
const options = {
|
||||
paseoHomeRoot: root,
|
||||
staticDir: path.join(root, "static"),
|
||||
cleanup: false,
|
||||
mcpEnabled: false,
|
||||
pluginsEnabled: false,
|
||||
providerOverrides: {
|
||||
"thinking-fixture": {
|
||||
extends: "acp" as const,
|
||||
label: "Thinking fixture",
|
||||
env: { ACP_TEST_LOAD_MODEL: "second-model", ACP_TEST_SAVED_MODE: "plan" },
|
||||
command: [
|
||||
process.execPath,
|
||||
path.join(import.meta.dirname, "acp-thinking-resume-fixture.cjs"),
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
try {
|
||||
const first = await createDaemonTestContext(options);
|
||||
let agentId: string;
|
||||
try {
|
||||
const agent = await first.client.createAgent({
|
||||
provider: "thinking-fixture",
|
||||
cwd: root,
|
||||
model: "second-model",
|
||||
modeId: "agent",
|
||||
thinkingOptionId: "low",
|
||||
});
|
||||
agentId = agent.id;
|
||||
} finally {
|
||||
await first.cleanup();
|
||||
}
|
||||
const reopened = await createDaemonTestContext(options);
|
||||
try {
|
||||
await reopened.client.fetchAgentTimeline(agentId, { limit: 40 });
|
||||
const before = (await reopened.client.fetchAgent(agentId))?.agent.runtimeInfo;
|
||||
expect(before).toMatchObject({ modeId: "agent", thinkingOptionId: "low" });
|
||||
await reopened.client.setAgentMode(agentId, "plan");
|
||||
const after = (await reopened.client.fetchAgent(agentId))?.agent.runtimeInfo;
|
||||
expect(after).toMatchObject({ modeId: "plan", thinkingOptionId: "high" });
|
||||
} finally {
|
||||
await reopened.cleanup();
|
||||
}
|
||||
} finally {
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
@@ -0,0 +1,104 @@
|
||||
// ACP peer that accepts a thinking level on creation but rejects it after load.
|
||||
const readline = require("node:readline");
|
||||
|
||||
const sessionId = "thinking-resume-session";
|
||||
let model = "startup-model";
|
||||
let effort = "low";
|
||||
let mode = "agent";
|
||||
let loaded = false;
|
||||
|
||||
const send = (message) =>
|
||||
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...message }) + "\n");
|
||||
|
||||
function select(id, category, currentValue, values) {
|
||||
return {
|
||||
id,
|
||||
name: id,
|
||||
category,
|
||||
type: "select",
|
||||
currentValue,
|
||||
options: values.map((value) => ({ value, name: value })),
|
||||
};
|
||||
}
|
||||
|
||||
function configOptions() {
|
||||
return [
|
||||
select("mode", "mode", mode, ["agent", "plan"]),
|
||||
select("model", "model", model, ["startup-model", "second-model"]),
|
||||
select(
|
||||
"effort",
|
||||
"thought_level",
|
||||
effort,
|
||||
loaded && model === "second-model"
|
||||
? ["minimal", "low", "medium", "high", "xhigh"]
|
||||
: ["low", "high", "max"],
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
function assistantMessage(text) {
|
||||
send({
|
||||
method: "session/update",
|
||||
params: {
|
||||
sessionId,
|
||||
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text } },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
readline.createInterface({ input: process.stdin }).on("line", (line) => {
|
||||
const { id, method, params } = JSON.parse(line);
|
||||
if (id === undefined) return;
|
||||
let result;
|
||||
switch (method) {
|
||||
case "initialize":
|
||||
result = {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true, sessionCapabilities: { close: {} } },
|
||||
};
|
||||
break;
|
||||
case "session/new":
|
||||
result = { sessionId, configOptions: configOptions() };
|
||||
break;
|
||||
case "session/load":
|
||||
loaded = true;
|
||||
model = process.env.ACP_TEST_LOAD_MODEL;
|
||||
effort = model === "second-model" && !process.env.ACP_TEST_SAVED_MODE ? "high" : "low";
|
||||
assistantMessage("Response from the saved session");
|
||||
result = { configOptions: configOptions() };
|
||||
break;
|
||||
case "session/set_config_option":
|
||||
if (params.configId === "model") {
|
||||
model = params.value;
|
||||
if (loaded && model === "second-model") effort = "high";
|
||||
} else if (params.configId === "mode") {
|
||||
mode = params.value;
|
||||
if (loaded && mode === process.env.ACP_TEST_SAVED_MODE) effort = "high";
|
||||
} else if (loaded && params.value === "max") {
|
||||
send({
|
||||
id,
|
||||
error: {
|
||||
code: -32602,
|
||||
message: "Invalid params",
|
||||
data: "This model does not support that thinking level",
|
||||
},
|
||||
});
|
||||
return;
|
||||
} else {
|
||||
effort = params.value;
|
||||
}
|
||||
result = { configOptions: configOptions() };
|
||||
break;
|
||||
case "session/prompt":
|
||||
assistantMessage("Response from the saved session");
|
||||
result = { stopReason: "end_turn" };
|
||||
break;
|
||||
case "session/close":
|
||||
result = {};
|
||||
break;
|
||||
default:
|
||||
send({ id, error: { code: -32601, message: "Method not found" } });
|
||||
return;
|
||||
}
|
||||
send({ id, result });
|
||||
});
|
||||
@@ -22,9 +22,16 @@ import type { SkillSelectionStore } from "./selection-store";
|
||||
import { createSkillsController, type SkillsController } from "./controller";
|
||||
import { beginSkillsTransaction } from "./transaction";
|
||||
|
||||
interface TestSkillTargets extends SkillTargets {
|
||||
agentsDir: string;
|
||||
claudeDir: string;
|
||||
antigravityDir: string;
|
||||
installDirs: string[];
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
root: string;
|
||||
targets: SkillTargets;
|
||||
targets: TestSkillTargets;
|
||||
controller: SkillsController;
|
||||
selectionStore: SkillSelectionStore;
|
||||
}
|
||||
@@ -33,11 +40,17 @@ const BUNDLED_SKILLS = ["paseo", "paseo-advisor", "paseo-loop"];
|
||||
|
||||
async function makeHarness(selectionStore?: SkillSelectionStore): Promise<Harness> {
|
||||
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-skills-controller-"));
|
||||
const targets: SkillTargets = {
|
||||
const agentsDir = path.join(root, "home", ".agents", "skills");
|
||||
const claudeDir = path.join(root, "home", ".claude", "skills");
|
||||
const codexDir = path.join(root, "home", ".codex", "skills");
|
||||
const antigravityDir = path.join(root, "home", ".gemini", "config", "skills");
|
||||
const targets: TestSkillTargets = {
|
||||
sourceDir: path.join(root, "bundle"),
|
||||
agentsDir: path.join(root, "home", ".agents", "skills"),
|
||||
claudeDir: path.join(root, "home", ".claude", "skills"),
|
||||
codexDir: path.join(root, "home", ".codex", "skills"),
|
||||
installDirs: [agentsDir, claudeDir, antigravityDir],
|
||||
agentsDir,
|
||||
claudeDir,
|
||||
codexDir,
|
||||
antigravityDir,
|
||||
};
|
||||
for (const name of BUNDLED_SKILLS) {
|
||||
await mkdir(path.join(targets.sourceDir, name), { recursive: true });
|
||||
@@ -146,17 +159,26 @@ async function installedSkills(dir: string): Promise<string[]> {
|
||||
.sort();
|
||||
}
|
||||
|
||||
async function installedEverywhere(targets: SkillTargets): Promise<string[][]> {
|
||||
return Promise.all([targets.agentsDir, targets.claudeDir, targets.codexDir].map(installedSkills));
|
||||
async function installedEverywhere(targets: TestSkillTargets): Promise<string[][]> {
|
||||
return Promise.all(
|
||||
[targets.agentsDir, targets.claudeDir, targets.codexDir, targets.antigravityDir].map(
|
||||
installedSkills,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function writeUserFile(
|
||||
targets: SkillTargets,
|
||||
targets: TestSkillTargets,
|
||||
skill: string,
|
||||
relativePath: string,
|
||||
contents: string,
|
||||
): Promise<void> {
|
||||
for (const dir of [targets.agentsDir, targets.claudeDir, targets.codexDir]) {
|
||||
for (const dir of [
|
||||
targets.agentsDir,
|
||||
targets.claudeDir,
|
||||
targets.codexDir,
|
||||
targets.antigravityDir,
|
||||
]) {
|
||||
const file = path.join(dir, skill, relativePath);
|
||||
await mkdir(path.dirname(file), { recursive: true });
|
||||
await writeFile(file, contents);
|
||||
@@ -164,30 +186,33 @@ async function writeUserFile(
|
||||
}
|
||||
|
||||
async function readUserFile(
|
||||
targets: SkillTargets,
|
||||
targets: TestSkillTargets,
|
||||
skill: string,
|
||||
relativePath: string,
|
||||
): Promise<Array<string | null>> {
|
||||
return Promise.all(
|
||||
[targets.agentsDir, targets.claudeDir, targets.codexDir].map((dir) =>
|
||||
[targets.agentsDir, targets.claudeDir, targets.codexDir, targets.antigravityDir].map((dir) =>
|
||||
readFile(path.join(dir, skill, relativePath), "utf8").catch(() => null),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** Anything the transaction staged and failed to clean up sits beside the skills tree. */
|
||||
async function backupArtifacts(targets: SkillTargets): Promise<string[][]> {
|
||||
async function backupArtifacts(targets: TestSkillTargets): Promise<string[][]> {
|
||||
return Promise.all(
|
||||
[targets.agentsDir, targets.claudeDir, targets.codexDir].map(async (dir) => {
|
||||
const parentEntries = await readdir(path.dirname(dir)).catch(() => []);
|
||||
const rootEntries = await readdir(dir).catch(() => []);
|
||||
return [
|
||||
...parentEntries.filter(
|
||||
(entry) => entry !== path.basename(dir) && !entry.startsWith(".paseo-skills-recovered-"),
|
||||
),
|
||||
...rootEntries.filter((entry) => entry.startsWith(".paseo-skills-transaction-")),
|
||||
].sort();
|
||||
}),
|
||||
[targets.agentsDir, targets.claudeDir, targets.codexDir, targets.antigravityDir].map(
|
||||
async (dir) => {
|
||||
const parentEntries = await readdir(path.dirname(dir)).catch(() => []);
|
||||
const rootEntries = await readdir(dir).catch(() => []);
|
||||
return [
|
||||
...parentEntries.filter(
|
||||
(entry) =>
|
||||
entry !== path.basename(dir) && !entry.startsWith(".paseo-skills-recovered-"),
|
||||
),
|
||||
...rootEntries.filter((entry) => entry.startsWith(".paseo-skills-transaction-")),
|
||||
].sort();
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -203,14 +228,14 @@ async function waitForTransactionDirectory(parent: string): Promise<void> {
|
||||
}
|
||||
|
||||
/** Puts a regular file where the agents skills tree goes, so convergence fails with ENOTDIR. */
|
||||
async function blockAgentsDir(targets: SkillTargets): Promise<void> {
|
||||
async function blockAgentsDir(targets: TestSkillTargets): Promise<void> {
|
||||
await rm(targets.agentsDir, { recursive: true, force: true });
|
||||
await mkdir(path.dirname(targets.agentsDir), { recursive: true });
|
||||
await writeFile(targets.agentsDir, "not a directory");
|
||||
}
|
||||
|
||||
async function isInstalled(targets: SkillTargets, name: string): Promise<boolean> {
|
||||
const dirs = [targets.agentsDir, targets.claudeDir];
|
||||
async function isInstalled(targets: TestSkillTargets, name: string): Promise<boolean> {
|
||||
const dirs = [targets.agentsDir, targets.claudeDir, targets.antigravityDir];
|
||||
const present = await Promise.all(
|
||||
dirs.map((dir) =>
|
||||
access(path.join(dir, name))
|
||||
@@ -251,7 +276,7 @@ describe("skills controller", () => {
|
||||
selection: { mode: "custom", skills: ["paseo", "paseo-loop"] },
|
||||
},
|
||||
);
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([[], [], [], []]);
|
||||
});
|
||||
|
||||
let harness: Harness;
|
||||
@@ -299,6 +324,7 @@ describe("skills controller", () => {
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -455,13 +481,15 @@ describe("skills controller", () => {
|
||||
["paseo", "paseo-loop"],
|
||||
["paseo", "paseo-loop"],
|
||||
["paseo-loop"],
|
||||
["paseo", "paseo-loop"],
|
||||
]);
|
||||
expect(await readUserFile(readOnly.targets, "paseo-loop", "notes/mine.md")).toEqual([
|
||||
"hand written",
|
||||
"hand written",
|
||||
"hand written",
|
||||
"hand written",
|
||||
]);
|
||||
expect(await backupArtifacts(readOnly.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(readOnly.targets)).toEqual([[], [], [], []]);
|
||||
await rm(readOnly.root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
@@ -482,6 +510,7 @@ describe("skills controller", () => {
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
]);
|
||||
await rm(readOnly.root, { recursive: true, force: true });
|
||||
});
|
||||
@@ -506,6 +535,7 @@ describe("skills controller", () => {
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
]);
|
||||
await rm(readOnly.root, { recursive: true, force: true });
|
||||
});
|
||||
@@ -534,11 +564,13 @@ describe("skills controller", () => {
|
||||
"restore this",
|
||||
"restore this",
|
||||
"restore this",
|
||||
"restore this",
|
||||
]);
|
||||
expect(await readUserFile(readOnly.targets, "paseo-loop", "notes/concurrent.md")).toEqual([
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
]);
|
||||
await rm(readOnly.root, { recursive: true, force: true });
|
||||
});
|
||||
@@ -562,6 +594,7 @@ describe("skills controller", () => {
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
]);
|
||||
expect(await isInstalled(harness.targets, "paseo-loop")).toBe(true);
|
||||
});
|
||||
@@ -580,6 +613,7 @@ describe("skills controller", () => {
|
||||
harness.targets.agentsDir,
|
||||
harness.targets.claudeDir,
|
||||
harness.targets.codexDir,
|
||||
harness.targets.antigravityDir,
|
||||
].map((root) => path.join(root, "paseo-loop"));
|
||||
for (const live of livePaths) await chmod(live, 0o700);
|
||||
const before = await Promise.all(livePaths.map(lstat));
|
||||
@@ -591,7 +625,7 @@ describe("skills controller", () => {
|
||||
|
||||
const after = await Promise.all(livePaths.map(lstat));
|
||||
expect(after.map((entry) => entry.ino)).toEqual(before.map((entry) => entry.ino));
|
||||
expect(after.map((entry) => entry.mode & 0o777)).toEqual([0o700, 0o700, 0o700]);
|
||||
expect(after.map((entry) => entry.mode & 0o777)).toEqual([0o700, 0o700, 0o700, 0o700]);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -622,8 +656,9 @@ describe("skills controller", () => {
|
||||
"paseo-loop-v1",
|
||||
"paseo-loop-v1",
|
||||
null,
|
||||
"paseo-loop-v1",
|
||||
]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
await expect(harness.controller.status()).resolves.toMatchObject({ selection: previous });
|
||||
});
|
||||
|
||||
@@ -656,8 +691,9 @@ describe("skills controller", () => {
|
||||
"keep this",
|
||||
"keep this",
|
||||
null,
|
||||
"keep this",
|
||||
]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
await expect(harness.controller.status()).resolves.toMatchObject({ selection: previous });
|
||||
});
|
||||
|
||||
@@ -693,7 +729,7 @@ describe("skills controller", () => {
|
||||
expect(
|
||||
await readFile(path.join(harness.targets.codexDir, recovered!, "notes", "mine.md"), "utf8"),
|
||||
).toBe("staged notes");
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
await expect(harness.controller.status()).resolves.toMatchObject({ selection: previous });
|
||||
});
|
||||
|
||||
@@ -732,8 +768,9 @@ describe("skills controller", () => {
|
||||
null,
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
await expect(harness.controller.status()).resolves.toMatchObject({ selection: previous });
|
||||
});
|
||||
|
||||
@@ -775,7 +812,7 @@ describe("skills controller", () => {
|
||||
|
||||
expect(await readFile(entry!.livePath, "utf8")).toBe("external replacement");
|
||||
expect(await readFile(path.join(recovered, "notes", "mine.md"), "utf8")).toBe("captured notes");
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
});
|
||||
|
||||
it("preserves a directory that replaces a captured file before recovery", async () => {
|
||||
@@ -806,7 +843,7 @@ describe("skills controller", () => {
|
||||
expect(
|
||||
await readFile(path.join(path.dirname(harness.targets.agentsDir), recovered!), "utf8"),
|
||||
).toBe("captured file");
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
@@ -815,6 +852,7 @@ describe("skills controller", () => {
|
||||
const crossFilesystemRoot = await mkdtemp("/dev/shm/paseo-skills-controller-");
|
||||
try {
|
||||
harness.targets.claudeDir = path.join(crossFilesystemRoot, "skills");
|
||||
harness.targets.installDirs[1] = harness.targets.claudeDir;
|
||||
const previous: SkillSelection = {
|
||||
mode: "custom",
|
||||
skills: ["paseo", "paseo-loop"],
|
||||
@@ -926,6 +964,7 @@ describe("skills controller", () => {
|
||||
readOnly.targets.agentsDir,
|
||||
readOnly.targets.claudeDir,
|
||||
readOnly.targets.codexDir,
|
||||
readOnly.targets.antigravityDir,
|
||||
]) {
|
||||
const notes = path.join(root, "paseo-loop", "notes");
|
||||
await mkdir(notes, { recursive: true });
|
||||
@@ -946,6 +985,7 @@ describe("skills controller", () => {
|
||||
readOnly.targets.agentsDir,
|
||||
readOnly.targets.claudeDir,
|
||||
readOnly.targets.codexDir,
|
||||
readOnly.targets.antigravityDir,
|
||||
]) {
|
||||
const restored = path.join(root, "paseo-loop", "notes", "latest.md");
|
||||
expect((await lstat(restored)).isSymbolicLink()).toBe(true);
|
||||
@@ -970,6 +1010,7 @@ describe("skills controller", () => {
|
||||
readOnly.targets.agentsDir,
|
||||
readOnly.targets.claudeDir,
|
||||
readOnly.targets.codexDir,
|
||||
readOnly.targets.antigravityDir,
|
||||
]) {
|
||||
await chmod(path.join(root, "paseo-loop", "hooks", "run.sh"), 0o751);
|
||||
}
|
||||
@@ -987,6 +1028,7 @@ describe("skills controller", () => {
|
||||
readOnly.targets.agentsDir,
|
||||
readOnly.targets.claudeDir,
|
||||
readOnly.targets.codexDir,
|
||||
readOnly.targets.antigravityDir,
|
||||
]) {
|
||||
const restored = await lstat(path.join(root, "paseo-loop", "hooks", "run.sh"));
|
||||
expect(restored.mode & 0o777).toBe(0o751);
|
||||
@@ -998,7 +1040,7 @@ describe("skills controller", () => {
|
||||
it("leaves no backup artifacts behind after a successful save", async () => {
|
||||
await harness.controller.save({ mode: "custom", skills: ["paseo"] });
|
||||
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
@@ -1025,7 +1067,7 @@ describe("skills controller", () => {
|
||||
expect(outcome.ok).toBe(true);
|
||||
expect(await gated.store.get()).toEqual(next);
|
||||
await blocked.controller.status();
|
||||
expect(await backupArtifacts(blocked.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(blocked.targets)).toEqual([[], [], [], []]);
|
||||
await rm(blocked.root, { recursive: true, force: true });
|
||||
},
|
||||
);
|
||||
@@ -1061,6 +1103,7 @@ describe("skills controller", () => {
|
||||
harness.targets.agentsDir,
|
||||
harness.targets.claudeDir,
|
||||
harness.targets.codexDir,
|
||||
harness.targets.antigravityDir,
|
||||
]) {
|
||||
await rm(path.join(root, "paseo-loop"), { recursive: true, force: true });
|
||||
}
|
||||
@@ -1071,8 +1114,9 @@ describe("skills controller", () => {
|
||||
"hand written",
|
||||
"hand written",
|
||||
"hand written",
|
||||
"hand written",
|
||||
]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
});
|
||||
|
||||
it("does not roll back an interrupted transaction after the selection committed", async () => {
|
||||
@@ -1092,6 +1136,7 @@ describe("skills controller", () => {
|
||||
harness.targets.agentsDir,
|
||||
harness.targets.claudeDir,
|
||||
harness.targets.codexDir,
|
||||
harness.targets.antigravityDir,
|
||||
]) {
|
||||
await rm(path.join(root, "paseo-loop"), { recursive: true, force: true });
|
||||
}
|
||||
@@ -1101,7 +1146,7 @@ describe("skills controller", () => {
|
||||
|
||||
expect(snapshot.selection).toEqual(next);
|
||||
expect(await isInstalled(harness.targets, "paseo-loop")).toBe(false);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
});
|
||||
|
||||
it("asks for confirmation naming the directories a save would delete", async () => {
|
||||
@@ -1119,6 +1164,7 @@ describe("skills controller", () => {
|
||||
["paseo", "paseo-advisor", "paseo-loop"],
|
||||
["paseo", "paseo-advisor", "paseo-loop"],
|
||||
["paseo-advisor"],
|
||||
["paseo", "paseo-advisor", "paseo-loop"],
|
||||
]);
|
||||
expect(result.selection).toEqual({ mode: "custom", skills: ["paseo", "paseo-loop"] });
|
||||
});
|
||||
@@ -1134,7 +1180,12 @@ describe("skills controller", () => {
|
||||
|
||||
expect(result.confirmationRequired).toBeNull();
|
||||
expect(result.selection).toEqual({ mode: "custom", skills: ["paseo"] });
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([["paseo"], ["paseo"], []]);
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([
|
||||
["paseo"],
|
||||
["paseo"],
|
||||
[],
|
||||
["paseo"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("asks again when another directory appears before the retry", async () => {
|
||||
@@ -1154,6 +1205,7 @@ describe("skills controller", () => {
|
||||
["paseo", "paseo-advisor", "paseo-chat", "paseo-loop"],
|
||||
["paseo", "paseo-advisor", "paseo-chat", "paseo-loop"],
|
||||
["paseo-chat"],
|
||||
["paseo", "paseo-advisor", "paseo-chat", "paseo-loop"],
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1175,6 +1227,7 @@ describe("skills controller", () => {
|
||||
"hand written",
|
||||
"hand written",
|
||||
"hand written",
|
||||
"hand written",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1182,7 +1235,12 @@ describe("skills controller", () => {
|
||||
const result = await harness.controller.save({ mode: "custom", skills: ["paseo"] });
|
||||
|
||||
expect(result.confirmationRequired).toBeNull();
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([["paseo"], ["paseo"], []]);
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([
|
||||
["paseo"],
|
||||
["paseo"],
|
||||
[],
|
||||
["paseo"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves a regular file at a skill path when save convergence fails", async () => {
|
||||
@@ -1195,6 +1253,131 @@ describe("skills controller", () => {
|
||||
expect(await readFile(collision, "utf8")).toBe("keep this file");
|
||||
});
|
||||
|
||||
it("rolls back earlier targets when writing to Antigravity fails", async () => {
|
||||
await mkdir(harness.targets.antigravityDir, { recursive: true });
|
||||
const collision = path.join(harness.targets.antigravityDir, "paseo");
|
||||
await writeFile(collision, "keep this file");
|
||||
|
||||
await expect(harness.controller.save({ mode: "custom", skills: ["paseo"] })).rejects.toThrow();
|
||||
|
||||
expect(await readFile(collision, "utf8")).toBe("keep this file");
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([[], [], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
});
|
||||
|
||||
it("rolls back cleanly without locking later calls when an Antigravity parent is a file", async () => {
|
||||
const geminiConfig = path.dirname(harness.targets.antigravityDir);
|
||||
await mkdir(path.dirname(geminiConfig), { recursive: true });
|
||||
await writeFile(geminiConfig, "not a directory");
|
||||
|
||||
await expect(harness.controller.save({ mode: "custom", skills: ["paseo"] })).rejects.toThrow();
|
||||
|
||||
expect(await readFile(geminiConfig, "utf8")).toBe("not a directory");
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([[], [], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
await expect(harness.controller.status()).resolves.toMatchObject({
|
||||
state: "not-installed",
|
||||
selection: { mode: "all" },
|
||||
});
|
||||
await expect(harness.controller.uninstall()).resolves.toMatchObject({
|
||||
state: "not-installed",
|
||||
});
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
|
||||
"rolls back cleanly and still updates other targets when ~/.gemini is unwritable",
|
||||
async () => {
|
||||
const geminiHome = path.dirname(path.dirname(harness.targets.antigravityDir));
|
||||
await mkdir(geminiHome, { recursive: true });
|
||||
await chmod(geminiHome, 0o000);
|
||||
try {
|
||||
await expect(
|
||||
harness.controller.save({ mode: "custom", skills: ["paseo"] }),
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([[], [], [], []]);
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
await expect(harness.controller.status()).resolves.toMatchObject({
|
||||
state: "not-installed",
|
||||
selection: { mode: "all" },
|
||||
});
|
||||
} finally {
|
||||
await chmod(geminiHome, 0o755);
|
||||
}
|
||||
|
||||
// Install v1 everywhere, remove ~/.gemini/config so ~/.gemini (0555) blocks
|
||||
// Antigravity writes with EACCES, then upgrade bundle to v2 and autoUpdate.
|
||||
await harness.controller.install();
|
||||
await rm(path.dirname(harness.targets.antigravityDir), { recursive: true, force: true });
|
||||
for (const name of BUNDLED_SKILLS) {
|
||||
await writeFile(path.join(harness.targets.sourceDir, name, "SKILL.md"), `${name}-v2`);
|
||||
}
|
||||
await chmod(geminiHome, 0o555);
|
||||
try {
|
||||
await expect(harness.controller.autoUpdate()).rejects.toThrow();
|
||||
for (const root of [harness.targets.agentsDir, harness.targets.claudeDir]) {
|
||||
for (const name of BUNDLED_SKILLS) {
|
||||
expect(await readFile(path.join(root, name, "SKILL.md"), "utf8")).toBe(`${name}-v2`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await chmod(geminiHome, 0o755);
|
||||
}
|
||||
|
||||
// With ~/.gemini unreadable (0000), uninstall still removes every skill from healthy targets.
|
||||
await chmod(geminiHome, 0o000);
|
||||
try {
|
||||
await expect(harness.controller.uninstall()).rejects.toThrow();
|
||||
expect(await installedSkills(harness.targets.agentsDir)).toEqual([]);
|
||||
expect(await installedSkills(harness.targets.claudeDir)).toEqual([]);
|
||||
} finally {
|
||||
await chmod(geminiHome, 0o755);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("recovers a pre-upgrade transaction manifest that recorded codex at root index 2", async () => {
|
||||
const previous: SkillSelection = { mode: "custom", skills: ["paseo"] };
|
||||
const next: SkillSelection = { mode: "all" };
|
||||
await harness.controller.save(previous);
|
||||
|
||||
const transactionDir = path.join(
|
||||
path.dirname(harness.targets.agentsDir),
|
||||
".paseo-skills-transaction-legacy-codex-index",
|
||||
);
|
||||
const codexBackup = path.join(transactionDir, "backup", "2", "paseo");
|
||||
await mkdir(path.join(codexBackup, "notes"), { recursive: true });
|
||||
await writeFile(path.join(codexBackup, "notes", "codex.md"), "restored codex note");
|
||||
await writeFile(
|
||||
path.join(transactionDir, "transaction.json"),
|
||||
`${JSON.stringify(
|
||||
{
|
||||
owner: "paseo-skills-transaction",
|
||||
version: 1,
|
||||
phase: "converging",
|
||||
previousSelection: previous,
|
||||
nextSelection: next,
|
||||
entries: [
|
||||
{
|
||||
livePath: path.join(harness.targets.codexDir, "paseo"),
|
||||
kind: "update",
|
||||
backupPath: path.join("backup", "2", "paseo"),
|
||||
},
|
||||
],
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
);
|
||||
|
||||
await harness.controller.status();
|
||||
|
||||
expect(
|
||||
await readFile(path.join(harness.targets.codexDir, "paseo", "notes", "codex.md"), "utf8"),
|
||||
).toBe("restored codex note");
|
||||
expect(await backupArtifacts(harness.targets)).toEqual([[], [], [], []]);
|
||||
});
|
||||
|
||||
it("serializes startup convergence with an interactive save", async () => {
|
||||
await harness.controller.install();
|
||||
// Startup finds drift it wants to repair while the user narrows the
|
||||
@@ -1214,7 +1397,12 @@ describe("skills controller", () => {
|
||||
]);
|
||||
|
||||
expect(saved.selection).toEqual({ mode: "custom", skills: ["paseo"] });
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([["paseo"], ["paseo"], []]);
|
||||
expect(await installedEverywhere(harness.targets)).toEqual([
|
||||
["paseo"],
|
||||
["paseo"],
|
||||
[],
|
||||
["paseo"],
|
||||
]);
|
||||
expect(await harness.controller.status()).toEqual({
|
||||
state: "up-to-date",
|
||||
ops: [],
|
||||
@@ -1247,6 +1435,7 @@ describe("skills controller", () => {
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
"keep this",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -21,18 +21,31 @@ function only(...skills: string[]): SkillSelection {
|
||||
return { mode: "custom", skills };
|
||||
}
|
||||
|
||||
interface TestSkillTargets extends SkillTargets {
|
||||
agentsDir: string;
|
||||
claudeDir: string;
|
||||
antigravityDir: string;
|
||||
installDirs: string[];
|
||||
}
|
||||
|
||||
interface Sandbox {
|
||||
root: string;
|
||||
targets: SkillTargets;
|
||||
targets: TestSkillTargets;
|
||||
}
|
||||
|
||||
async function makeSandbox(): Promise<Sandbox> {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-skills-"));
|
||||
const targets: SkillTargets = {
|
||||
const agentsDir = path.join(root, "home", ".agents", "skills");
|
||||
const claudeDir = path.join(root, "home", ".claude", "skills");
|
||||
const codexDir = path.join(root, "home", ".codex", "skills");
|
||||
const antigravityDir = path.join(root, "home", ".gemini", "config", "skills");
|
||||
const targets: TestSkillTargets = {
|
||||
sourceDir: path.join(root, "bundle"),
|
||||
agentsDir: path.join(root, "home", ".agents", "skills"),
|
||||
claudeDir: path.join(root, "home", ".claude", "skills"),
|
||||
codexDir: path.join(root, "home", ".codex", "skills"),
|
||||
installDirs: [agentsDir, claudeDir, antigravityDir],
|
||||
agentsDir,
|
||||
claudeDir,
|
||||
codexDir,
|
||||
antigravityDir,
|
||||
};
|
||||
await fs.mkdir(targets.sourceDir, { recursive: true });
|
||||
return { root, targets };
|
||||
@@ -63,7 +76,7 @@ async function writeOnDiskSkill(
|
||||
}
|
||||
|
||||
async function writeOnDiskSkillToAllTargets(
|
||||
targets: SkillTargets,
|
||||
targets: TestSkillTargets,
|
||||
name: string,
|
||||
files: Record<string, string>,
|
||||
): Promise<void> {
|
||||
@@ -71,6 +84,7 @@ async function writeOnDiskSkillToAllTargets(
|
||||
writeOnDiskSkill(targets.agentsDir, name, files),
|
||||
writeOnDiskSkill(targets.claudeDir, name, files),
|
||||
writeOnDiskSkill(targets.codexDir, name, files),
|
||||
writeOnDiskSkill(targets.antigravityDir, name, files),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -86,9 +100,9 @@ async function pathExists(p: string): Promise<boolean> {
|
||||
.catch(() => false);
|
||||
}
|
||||
|
||||
async function installedIn(targets: SkillTargets, name: string): Promise<boolean[]> {
|
||||
async function installedIn(targets: TestSkillTargets, name: string): Promise<boolean[]> {
|
||||
return Promise.all(
|
||||
[targets.agentsDir, targets.claudeDir, targets.codexDir].map((dir) =>
|
||||
[targets.agentsDir, targets.claudeDir, targets.codexDir, targets.antigravityDir].map((dir) =>
|
||||
pathExists(path.join(dir, name)),
|
||||
),
|
||||
);
|
||||
@@ -196,6 +210,10 @@ describe("getSkillsStatus", () => {
|
||||
"SKILL.md": "paseo-v1",
|
||||
"hooks/guard.sh": "user guard",
|
||||
});
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", {
|
||||
"SKILL.md": "paseo-v1",
|
||||
"notes/local.md": "user notes",
|
||||
});
|
||||
|
||||
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
|
||||
|
||||
@@ -212,6 +230,7 @@ describe("getSkillsStatus", () => {
|
||||
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo", { "SKILL.md": "stale" });
|
||||
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.codexDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkillToAllTargets(sandbox.targets, "paseo-loop", { "SKILL.md": "loop-v1" });
|
||||
|
||||
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
|
||||
@@ -228,6 +247,8 @@ describe("getSkillsStatus", () => {
|
||||
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo-loop", { "SKILL.md": "loop-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.codexDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.codexDir, "paseo-loop", { "SKILL.md": "loop-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo-loop", { "SKILL.md": "loop-v1" });
|
||||
|
||||
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
|
||||
|
||||
@@ -235,6 +256,35 @@ describe("getSkillsStatus", () => {
|
||||
expect(status.ops).toEqual([{ kind: "update", name: "paseo" }]);
|
||||
});
|
||||
|
||||
it("returns drift when Antigravity is missing or stale", async () => {
|
||||
await writeCurrentBundle(sandbox.targets.sourceDir);
|
||||
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo-loop", { "SKILL.md": "loop-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo-loop", { "SKILL.md": "loop-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", { "SKILL.md": "stale" });
|
||||
|
||||
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
|
||||
|
||||
expect(status.state).toBe("drift");
|
||||
expect(status.ops).toEqual([
|
||||
{ kind: "update", name: "paseo" },
|
||||
{ kind: "add", name: "paseo-loop" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns not-installed when only user-personal skills exist in Antigravity", async () => {
|
||||
await writeCurrentBundle(sandbox.targets.sourceDir);
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "my-agy-skill", {
|
||||
"SKILL.md": "user-agy",
|
||||
});
|
||||
|
||||
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
|
||||
|
||||
expect(status.state).toBe("not-installed");
|
||||
expect(status.installed).toEqual([]);
|
||||
});
|
||||
|
||||
it("returns drift with add ops for the bundled skills missing from disk", async () => {
|
||||
await writeCurrentBundle(sandbox.targets.sourceDir);
|
||||
await writeOnDiskSkillToAllTargets(sandbox.targets, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
@@ -262,6 +312,7 @@ describe("getSkillsStatus", () => {
|
||||
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo", { "SKILL.md": "stale" });
|
||||
await writeOnDiskSkill(sandbox.targets.claudeDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.codexDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "paseo", { "SKILL.md": "paseo-v1" });
|
||||
await writeOnDiskSkill(sandbox.targets.agentsDir, "paseo-chat", { "SKILL.md": "chat-old" });
|
||||
|
||||
const status = await getSkillsStatus(sandbox.targets, ALL_SKILLS);
|
||||
@@ -299,9 +350,14 @@ describe("custom skill selection", () => {
|
||||
available: ["paseo", "paseo-advisor", "paseo-loop"],
|
||||
installed: ["paseo", "paseo-loop"],
|
||||
});
|
||||
expect(await installedIn(sandbox.targets, "paseo")).toEqual([true, true, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([true, true, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-advisor")).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo")).toEqual([true, true, false, true]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([true, true, false, true]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-advisor")).toEqual([
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports up-to-date while an unselected bundled skill is absent", async () => {
|
||||
@@ -323,9 +379,14 @@ describe("custom skill selection", () => {
|
||||
const status = await installSkills(sandbox.targets, only("paseo"));
|
||||
|
||||
expect(status.state).toBe("up-to-date");
|
||||
expect(await installedIn(sandbox.targets, "paseo")).toEqual([true, true, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-advisor")).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo")).toEqual([true, true, false, true]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([false, false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-advisor")).toEqual([
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports a delete op for a deselected skill before it is applied", async () => {
|
||||
@@ -339,12 +400,21 @@ describe("custom skill selection", () => {
|
||||
|
||||
it("leaves unrelated user skills untouched", async () => {
|
||||
await writeOnDiskSkill(sandbox.targets.agentsDir, "unslop", { "SKILL.md": "user-unslop" });
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "custom-agy", {
|
||||
"SKILL.md": "user-agy",
|
||||
});
|
||||
|
||||
await installSkills(sandbox.targets, only("paseo"));
|
||||
|
||||
expect(
|
||||
await fs.readFile(path.join(sandbox.targets.agentsDir, "unslop", "SKILL.md"), "utf-8"),
|
||||
).toBe("user-unslop");
|
||||
expect(
|
||||
await fs.readFile(
|
||||
path.join(sandbox.targets.antigravityDir, "custom-agy", "SKILL.md"),
|
||||
"utf-8",
|
||||
),
|
||||
).toBe("user-agy");
|
||||
});
|
||||
|
||||
it("treats an empty custom selection as no managed skills installed", async () => {
|
||||
@@ -358,8 +428,8 @@ describe("custom skill selection", () => {
|
||||
available: ["paseo", "paseo-advisor", "paseo-loop"],
|
||||
installed: [],
|
||||
});
|
||||
expect(await installedIn(sandbox.targets, "paseo")).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo")).toEqual([false, false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-loop")).toEqual([false, false, false, false]);
|
||||
});
|
||||
|
||||
it("ignores selected names that the bundle does not ship", async () => {
|
||||
@@ -371,7 +441,7 @@ describe("custom skill selection", () => {
|
||||
available: ["paseo", "paseo-advisor", "paseo-loop"],
|
||||
installed: ["paseo"],
|
||||
});
|
||||
expect(await installedIn(sandbox.targets, "not-a-skill")).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "not-a-skill")).toEqual([false, false, false, false]);
|
||||
});
|
||||
|
||||
it("still deletes legacy skill names that are not selectable", async () => {
|
||||
@@ -381,7 +451,12 @@ describe("custom skill selection", () => {
|
||||
|
||||
await installSkills(sandbox.targets, only("paseo"));
|
||||
|
||||
expect(await installedIn(sandbox.targets, "paseo-orchestrator")).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-orchestrator")).toEqual([
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -396,9 +471,12 @@ describe("installSkills / updateSkills", () => {
|
||||
await fs.rm(sandbox.root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("installs into shared and Claude roots without duplicating Codex discovery", async () => {
|
||||
it("installs into shared, Claude, and Antigravity roots without duplicating Codex discovery", async () => {
|
||||
await writeCurrentBundle(sandbox.targets.sourceDir);
|
||||
await writeOnDiskSkill(sandbox.targets.agentsDir, "unslop", { "SKILL.md": "user-unslop" });
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "custom-agy", {
|
||||
"SKILL.md": "user-agy",
|
||||
});
|
||||
|
||||
const status = await installSkills(sandbox.targets, ALL_SKILLS);
|
||||
|
||||
@@ -409,15 +487,25 @@ describe("installSkills / updateSkills", () => {
|
||||
installed: ["paseo", "paseo-loop"],
|
||||
});
|
||||
for (const name of ["paseo", "paseo-loop"]) {
|
||||
const expected = name === "paseo" ? "paseo-v1" : "loop-v1";
|
||||
expect(
|
||||
await fs.readFile(path.join(sandbox.targets.agentsDir, name, "SKILL.md"), "utf-8"),
|
||||
).toBe(name === "paseo" ? "paseo-v1" : "loop-v1");
|
||||
).toBe(expected);
|
||||
expect(await pathExists(path.join(sandbox.targets.codexDir, name, "SKILL.md"))).toBe(false);
|
||||
expect(await pathExists(path.join(sandbox.targets.claudeDir, name))).toBe(true);
|
||||
expect(
|
||||
await fs.readFile(path.join(sandbox.targets.antigravityDir, name, "SKILL.md"), "utf-8"),
|
||||
).toBe(expected);
|
||||
}
|
||||
expect(
|
||||
await fs.readFile(path.join(sandbox.targets.agentsDir, "unslop", "SKILL.md"), "utf-8"),
|
||||
).toBe("user-unslop");
|
||||
expect(
|
||||
await fs.readFile(
|
||||
path.join(sandbox.targets.antigravityDir, "custom-agy", "SKILL.md"),
|
||||
"utf-8",
|
||||
),
|
||||
).toBe("user-agy");
|
||||
});
|
||||
|
||||
it("retires unchanged managed Codex copies while preserving personal files", async () => {
|
||||
@@ -469,14 +557,23 @@ describe("installSkills / updateSkills", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ alias: "codex", target: "agents" },
|
||||
{ alias: "codex", target: "claude" },
|
||||
{ alias: "claude", target: "codex" },
|
||||
{ alias: "codex", target: "agents", expected: [true, true, true, true] },
|
||||
{ alias: "codex", target: "claude", expected: [true, true, true, true] },
|
||||
{ alias: "claude", target: "codex", expected: [true, true, true, true] },
|
||||
{ alias: "codex", target: "antigravity", expected: [true, true, true, true] },
|
||||
{ alias: "antigravity", target: "codex", expected: [true, true, true, true] },
|
||||
{ alias: "antigravity", target: "agents", expected: [true, true, false, true] },
|
||||
{ alias: "antigravity", target: "claude", expected: [true, true, false, true] },
|
||||
] as const)(
|
||||
"keeps installed skills when the $alias root links to the $target root",
|
||||
async ({ alias, target }) => {
|
||||
async ({ alias, target, expected }) => {
|
||||
await writeCurrentBundle(sandbox.targets.sourceDir);
|
||||
const rootOf = { agents: "agentsDir", claude: "claudeDir", codex: "codexDir" } as const;
|
||||
const rootOf = {
|
||||
agents: "agentsDir",
|
||||
claude: "claudeDir",
|
||||
codex: "codexDir",
|
||||
antigravity: "antigravityDir",
|
||||
} as const;
|
||||
const aliasRoot = sandbox.targets[rootOf[alias]];
|
||||
const targetRoot = sandbox.targets[rootOf[target]];
|
||||
await fs.mkdir(targetRoot, { recursive: true });
|
||||
@@ -488,12 +585,36 @@ describe("installSkills / updateSkills", () => {
|
||||
|
||||
expect(installed.state).toBe("up-to-date");
|
||||
expect(updated.state).toBe("up-to-date");
|
||||
expect((await fs.lstat(aliasRoot)).isSymbolicLink()).toBe(true);
|
||||
for (const name of ["paseo", "paseo-loop"]) {
|
||||
expect(await installedIn(sandbox.targets, name)).toEqual([true, true, true]);
|
||||
expect(await installedIn(sandbox.targets, name)).toEqual([...expected]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps an installed skill when its Antigravity directory links to the shared copy", async () => {
|
||||
await writeCurrentBundle(sandbox.targets.sourceDir);
|
||||
await fs.mkdir(path.join(sandbox.targets.agentsDir, "paseo"), { recursive: true });
|
||||
await fs.mkdir(sandbox.targets.antigravityDir, { recursive: true });
|
||||
await fs.symlink(
|
||||
path.join(sandbox.targets.agentsDir, "paseo"),
|
||||
path.join(sandbox.targets.antigravityDir, "paseo"),
|
||||
"dir",
|
||||
);
|
||||
|
||||
const installed = await installSkills(sandbox.targets, ALL_SKILLS);
|
||||
const updated = await autoUpdateInstalledSkills(sandbox.targets, ALL_SKILLS);
|
||||
|
||||
expect(installed.state).toBe("up-to-date");
|
||||
expect(updated.state).toBe("up-to-date");
|
||||
expect(
|
||||
(await fs.lstat(path.join(sandbox.targets.antigravityDir, "paseo"))).isSymbolicLink(),
|
||||
).toBe(true);
|
||||
expect(
|
||||
await fs.readFile(path.join(sandbox.targets.antigravityDir, "paseo", "SKILL.md"), "utf8"),
|
||||
).toBe("paseo-v1");
|
||||
});
|
||||
|
||||
it("keeps an installed skill when its Codex directory links to the shared copy", async () => {
|
||||
await writeCurrentBundle(sandbox.targets.sourceDir);
|
||||
await fs.mkdir(path.join(sandbox.targets.agentsDir, "paseo"), { recursive: true });
|
||||
@@ -604,6 +725,15 @@ describe("installSkills / updateSkills", () => {
|
||||
expect(
|
||||
await fs.readFile(path.join(sandbox.targets.claudeDir, "paseo-loop", "SKILL.md"), "utf-8"),
|
||||
).toBe("loop-v1");
|
||||
expect(
|
||||
await fs.readFile(path.join(sandbox.targets.antigravityDir, "paseo", "SKILL.md"), "utf-8"),
|
||||
).toBe("paseo-v1");
|
||||
expect(
|
||||
await fs.readFile(
|
||||
path.join(sandbox.targets.antigravityDir, "paseo-loop", "SKILL.md"),
|
||||
"utf-8",
|
||||
),
|
||||
).toBe("loop-v1");
|
||||
});
|
||||
|
||||
it("auto-updates drifted installed skills", async () => {
|
||||
@@ -626,6 +756,9 @@ describe("installSkills / updateSkills", () => {
|
||||
"utf-8",
|
||||
),
|
||||
).toBe("user guard");
|
||||
expect(
|
||||
await fs.readFile(path.join(sandbox.targets.antigravityDir, "paseo", "SKILL.md"), "utf-8"),
|
||||
).toBe("paseo-v1");
|
||||
});
|
||||
|
||||
it("does not auto-install skills on a clean machine", async () => {
|
||||
@@ -642,7 +775,7 @@ describe("installSkills / updateSkills", () => {
|
||||
available: ["paseo", "paseo-loop"],
|
||||
installed: [],
|
||||
});
|
||||
expect(await installedIn(sandbox.targets, "paseo")).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo")).toEqual([false, false, false, false]);
|
||||
});
|
||||
|
||||
it("is idempotent — running install twice keeps state at up-to-date", async () => {
|
||||
@@ -667,24 +800,51 @@ describe("uninstallSkills", () => {
|
||||
await fs.rm(sandbox.root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("removes every Paseo skill from all three targets and preserves user dirs", async () => {
|
||||
it("removes every Paseo skill from all targets and preserves user dirs and symlinks", async () => {
|
||||
await writeCurrentBundle(sandbox.targets.sourceDir);
|
||||
await installSkills(sandbox.targets, ALL_SKILLS);
|
||||
for (const name of ["unslop", "tdd", "devbox"]) {
|
||||
await writeOnDiskSkill(sandbox.targets.agentsDir, name, { "SKILL.md": `user-${name}` });
|
||||
}
|
||||
await writeOnDiskSkill(sandbox.targets.antigravityDir, "user-agy-skill", {
|
||||
"SKILL.md": "user-agy",
|
||||
});
|
||||
const linkedSource = path.join(sandbox.root, "external-user-skill");
|
||||
await writeFiles(linkedSource, { "SKILL.md": "linked-user-skill" });
|
||||
await fs.symlink(
|
||||
linkedSource,
|
||||
path.join(sandbox.targets.antigravityDir, "linked-user-skill"),
|
||||
"dir",
|
||||
);
|
||||
|
||||
const status = await uninstallSkills(sandbox.targets, ALL_SKILLS);
|
||||
|
||||
expect(status.state).toBe("not-installed");
|
||||
for (const name of ["paseo", "paseo-loop", ...LEGACY_SKILL_NAMES]) {
|
||||
expect(await installedIn(sandbox.targets, name)).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, name)).toEqual([false, false, false, false]);
|
||||
}
|
||||
for (const name of ["unslop", "tdd", "devbox"]) {
|
||||
expect(
|
||||
await fs.readFile(path.join(sandbox.targets.agentsDir, name, "SKILL.md"), "utf-8"),
|
||||
).toBe(`user-${name}`);
|
||||
}
|
||||
expect(
|
||||
await fs.readFile(
|
||||
path.join(sandbox.targets.antigravityDir, "user-agy-skill", "SKILL.md"),
|
||||
"utf-8",
|
||||
),
|
||||
).toBe("user-agy");
|
||||
expect(
|
||||
(
|
||||
await fs.lstat(path.join(sandbox.targets.antigravityDir, "linked-user-skill"))
|
||||
).isSymbolicLink(),
|
||||
).toBe(true);
|
||||
expect(
|
||||
await fs.readFile(
|
||||
path.join(sandbox.targets.antigravityDir, "linked-user-skill", "SKILL.md"),
|
||||
"utf-8",
|
||||
),
|
||||
).toBe("linked-user-skill");
|
||||
});
|
||||
|
||||
it("is a no-op when nothing is installed", async () => {
|
||||
@@ -695,12 +855,13 @@ describe("uninstallSkills", () => {
|
||||
expect(status.state).toBe("not-installed");
|
||||
});
|
||||
|
||||
it("cleans up legacy skill names that linger in agents, claude, and codex", async () => {
|
||||
it("cleans up legacy skill names that linger in agents, claude, codex, and antigravity", async () => {
|
||||
await writeCurrentBundle(sandbox.targets.sourceDir);
|
||||
for (const dir of [
|
||||
sandbox.targets.agentsDir,
|
||||
sandbox.targets.claudeDir,
|
||||
sandbox.targets.codexDir,
|
||||
sandbox.targets.antigravityDir,
|
||||
]) {
|
||||
await writeOnDiskSkill(dir, "paseo-chat", { "SKILL.md": "chat-old" });
|
||||
}
|
||||
@@ -708,6 +869,6 @@ describe("uninstallSkills", () => {
|
||||
const status = await uninstallSkills(sandbox.targets, ALL_SKILLS);
|
||||
|
||||
expect(status.state).toBe("not-installed");
|
||||
expect(await installedIn(sandbox.targets, "paseo-chat")).toEqual([false, false, false]);
|
||||
expect(await installedIn(sandbox.targets, "paseo-chat")).toEqual([false, false, false, false]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,8 +35,12 @@ export interface SkillsStatus {
|
||||
|
||||
export interface SkillTargets {
|
||||
sourceDir: string;
|
||||
agentsDir: string;
|
||||
claudeDir: string;
|
||||
/**
|
||||
* Ordered active install roots. Append new roots to the end so transaction
|
||||
* backup indices remain stable across daemon upgrades.
|
||||
*/
|
||||
installDirs: readonly string[];
|
||||
/** Legacy dedicated Codex root, retired on sync unless it aliases an install root. */
|
||||
codexDir: string;
|
||||
}
|
||||
|
||||
@@ -163,13 +167,11 @@ export async function getSkillsStatus(
|
||||
): Promise<SkillsStatus> {
|
||||
const available = await listBundledSkills(targets.sourceDir);
|
||||
const names = managedSkillNames(available);
|
||||
const [bundle, agentsDisk, claudeDisk, codexDisk] = await Promise.all([
|
||||
const [bundle, codexDisk, ...disks] = await Promise.all([
|
||||
hashSkills(targets.sourceDir, available),
|
||||
hashSkills(targets.agentsDir, names),
|
||||
hashSkills(targets.claudeDir, names),
|
||||
hashSkills(targets.codexDir, names),
|
||||
...targets.installDirs.map((root) => hashSkills(root, names)),
|
||||
]);
|
||||
const disks = [agentsDisk, claudeDisk];
|
||||
const desired = resolveDesiredSkills(selection, available);
|
||||
const ops = diff(bundle, disks, names, desired);
|
||||
for (const name of codexDisk.keys()) {
|
||||
@@ -203,8 +205,7 @@ async function applySkills(
|
||||
if (writes.length > 0) {
|
||||
await syncSkills({
|
||||
sourceDir: targets.sourceDir,
|
||||
agentsDir: targets.agentsDir,
|
||||
claudeDir: targets.claudeDir,
|
||||
installDirs: targets.installDirs,
|
||||
codexDir: targets.codexDir,
|
||||
skillNames: writes,
|
||||
});
|
||||
@@ -213,8 +214,7 @@ async function applySkills(
|
||||
for (const op of status.ops) {
|
||||
if (op.kind !== "delete") continue;
|
||||
await removeSkill(op.name, {
|
||||
agentsDir: targets.agentsDir,
|
||||
claudeDir: targets.claudeDir,
|
||||
installDirs: targets.installDirs,
|
||||
codexDir: targets.codexDir,
|
||||
});
|
||||
}
|
||||
@@ -259,12 +259,21 @@ export async function uninstallSkills(
|
||||
selection: SkillSelection,
|
||||
): Promise<SkillsStatus> {
|
||||
const available = await listBundledSkills(targets.sourceDir);
|
||||
let hasError = false;
|
||||
let firstError: unknown = null;
|
||||
for (const name of managedSkillNames(available)) {
|
||||
await removeSkill(name, {
|
||||
agentsDir: targets.agentsDir,
|
||||
claudeDir: targets.claudeDir,
|
||||
codexDir: targets.codexDir,
|
||||
});
|
||||
try {
|
||||
await removeSkill(name, {
|
||||
installDirs: targets.installDirs,
|
||||
codexDir: targets.codexDir,
|
||||
});
|
||||
} catch (error) {
|
||||
if (!hasError) {
|
||||
hasError = true;
|
||||
firstError = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasError) throw firstError;
|
||||
return getSkillsStatus(targets, selection);
|
||||
}
|
||||
|
||||
@@ -45,8 +45,11 @@ describe("orchestration skill paths", () => {
|
||||
const home = os.homedir();
|
||||
|
||||
expect(resolveSkillTargets()).toMatchObject({
|
||||
agentsDir: path.join(home, ".agents", "skills"),
|
||||
claudeDir: path.join(home, ".claude", "skills"),
|
||||
installDirs: [
|
||||
path.join(home, ".agents", "skills"),
|
||||
path.join(home, ".claude", "skills"),
|
||||
path.join(home, ".gemini", "config", "skills"),
|
||||
],
|
||||
codexDir: path.join(home, ".codex", "skills"),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,8 +17,13 @@ export function resolveBundledSkillsDir(moduleUrl: string | URL = import.meta.ur
|
||||
export function resolveSkillTargets(home: string = os.homedir()): SkillTargets {
|
||||
return {
|
||||
sourceDir: resolveBundledSkillsDir(),
|
||||
agentsDir: path.join(home, ".agents", "skills"),
|
||||
claudeDir: path.join(home, ".claude", "skills"),
|
||||
// Append new install roots to the end — transaction backups reference roots
|
||||
// by index, so existing positions must remain stable across upgrades.
|
||||
installDirs: [
|
||||
path.join(home, ".agents", "skills"),
|
||||
path.join(home, ".claude", "skills"),
|
||||
path.join(home, ".gemini", "config", "skills"),
|
||||
],
|
||||
codexDir: path.join(home, ".codex", "skills"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ interface Sandbox {
|
||||
agentsDir: string;
|
||||
claudeDir: string;
|
||||
codexDir: string;
|
||||
antigravityDir: string;
|
||||
installDirs: string[];
|
||||
}
|
||||
|
||||
async function makeSandbox(): Promise<Sandbox> {
|
||||
@@ -18,8 +20,10 @@ async function makeSandbox(): Promise<Sandbox> {
|
||||
const agentsDir = path.join(root, "home", ".agents", "skills");
|
||||
const claudeDir = path.join(root, "home", ".claude", "skills");
|
||||
const codexDir = path.join(root, "home", ".codex", "skills");
|
||||
const antigravityDir = path.join(root, "home", ".gemini", "config", "skills");
|
||||
const installDirs = [agentsDir, claudeDir, antigravityDir];
|
||||
await fs.mkdir(sourceDir, { recursive: true });
|
||||
return { root, sourceDir, agentsDir, claudeDir, codexDir };
|
||||
return { root, sourceDir, agentsDir, claudeDir, codexDir, antigravityDir, installDirs };
|
||||
}
|
||||
|
||||
async function writeBundleSkill(
|
||||
@@ -57,8 +61,7 @@ describe("syncSkills", () => {
|
||||
|
||||
const result = await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
});
|
||||
@@ -75,6 +78,11 @@ describe("syncSkills", () => {
|
||||
"utf-8",
|
||||
);
|
||||
expect(claudeContent).toBe("new paseo content");
|
||||
const antigravityContent = await fs.readFile(
|
||||
path.join(sandbox.antigravityDir, "paseo", "SKILL.md"),
|
||||
"utf-8",
|
||||
);
|
||||
expect(antigravityContent).toBe("new paseo content");
|
||||
await expect(fs.stat(path.join(sandbox.codexDir, "paseo", "SKILL.md"))).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
@@ -88,8 +96,7 @@ describe("syncSkills", () => {
|
||||
|
||||
await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo-committee"],
|
||||
});
|
||||
@@ -115,6 +122,15 @@ describe("syncSkills", () => {
|
||||
expect(await fs.readFile(path.join(claudeSkillDir, "references", "roles.md"), "utf-8")).toBe(
|
||||
"roles content",
|
||||
);
|
||||
|
||||
const antigravitySkillDir = path.join(sandbox.antigravityDir, "paseo-committee");
|
||||
expect((await fs.lstat(antigravitySkillDir)).isDirectory()).toBe(true);
|
||||
expect(await fs.readFile(path.join(antigravitySkillDir, "SKILL.md"), "utf-8")).toBe(
|
||||
"committee content",
|
||||
);
|
||||
expect(
|
||||
await fs.readFile(path.join(antigravitySkillDir, "references", "roles.md"), "utf-8"),
|
||||
).toBe("roles content");
|
||||
});
|
||||
|
||||
it("leaves on-disk skills not in the bundle untouched", async () => {
|
||||
@@ -122,16 +138,21 @@ describe("syncSkills", () => {
|
||||
const customSkill = path.join(sandbox.agentsDir, "user-custom-skill");
|
||||
await fs.mkdir(customSkill, { recursive: true });
|
||||
await fs.writeFile(path.join(customSkill, "SKILL.md"), "user content");
|
||||
const antigravityCustomSkill = path.join(sandbox.antigravityDir, "user-antigravity-skill");
|
||||
await fs.mkdir(antigravityCustomSkill, { recursive: true });
|
||||
await fs.writeFile(path.join(antigravityCustomSkill, "SKILL.md"), "antigravity user content");
|
||||
|
||||
await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
});
|
||||
|
||||
expect(await fs.readFile(path.join(customSkill, "SKILL.md"), "utf-8")).toBe("user content");
|
||||
expect(await fs.readFile(path.join(antigravityCustomSkill, "SKILL.md"), "utf-8")).toBe(
|
||||
"antigravity user content",
|
||||
);
|
||||
});
|
||||
|
||||
it("removes stale files previously written to managed skill dirs", async () => {
|
||||
@@ -143,8 +164,7 @@ describe("syncSkills", () => {
|
||||
|
||||
await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
});
|
||||
@@ -154,8 +174,7 @@ describe("syncSkills", () => {
|
||||
|
||||
await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
});
|
||||
@@ -163,6 +182,12 @@ describe("syncSkills", () => {
|
||||
expect(await fs.readFile(path.join(onDiskSkill, "SKILL.md"), "utf-8")).toBe("new");
|
||||
await expect(fs.access(path.join(onDiskSkill, "references", "stale.md"))).rejects.toThrow();
|
||||
await expect(fs.access(path.join(onDiskSkill, "references"))).rejects.toThrow();
|
||||
const antigravitySkill = path.join(sandbox.antigravityDir, "paseo");
|
||||
expect(await fs.readFile(path.join(antigravitySkill, "SKILL.md"), "utf-8")).toBe("new");
|
||||
await expect(
|
||||
fs.access(path.join(antigravitySkill, "references", "stale.md")),
|
||||
).rejects.toThrow();
|
||||
await expect(fs.access(path.join(antigravitySkill, "references"))).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("preserves user-added files in managed skill dirs", async () => {
|
||||
@@ -172,11 +197,14 @@ describe("syncSkills", () => {
|
||||
await fs.writeFile(path.join(onDiskSkill, "SKILL.md"), "old");
|
||||
await fs.writeFile(path.join(onDiskSkill, "my-context.md"), "user context");
|
||||
await fs.writeFile(path.join(onDiskSkill, "references", "notes.md"), "user notes");
|
||||
const antigravitySkill = path.join(sandbox.antigravityDir, "paseo");
|
||||
await fs.mkdir(path.join(antigravitySkill, "references"), { recursive: true });
|
||||
await fs.writeFile(path.join(antigravitySkill, "SKILL.md"), "old");
|
||||
await fs.writeFile(path.join(antigravitySkill, "my-context.md"), "antigravity user context");
|
||||
|
||||
await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
});
|
||||
@@ -188,6 +216,10 @@ describe("syncSkills", () => {
|
||||
expect(await fs.readFile(path.join(onDiskSkill, "references", "notes.md"), "utf-8")).toBe(
|
||||
"user notes",
|
||||
);
|
||||
expect(await fs.readFile(path.join(antigravitySkill, "SKILL.md"), "utf-8")).toBe("new");
|
||||
expect(await fs.readFile(path.join(antigravitySkill, "my-context.md"), "utf-8")).toBe(
|
||||
"antigravity user context",
|
||||
);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
@@ -208,8 +240,39 @@ describe("syncSkills", () => {
|
||||
await expect(
|
||||
syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
}),
|
||||
).rejects.toThrow("Cannot sync through symbolic link");
|
||||
|
||||
expect(await fs.readFile(path.join(onDiskSkill, "SKILL.md"), "utf-8")).toBe("old skill");
|
||||
expect(await fs.readFile(path.join(externalReferences, "guide.md"), "utf-8")).toBe(
|
||||
"external guide",
|
||||
);
|
||||
expect((await fs.lstat(path.join(onDiskSkill, "references"))).isSymbolicLink()).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects managed paths that would write through a symlink in Antigravity",
|
||||
async () => {
|
||||
await writeBundleSkill(sandbox.sourceDir, "paseo", {
|
||||
"SKILL.md": "new skill",
|
||||
"references/guide.md": "new guide",
|
||||
});
|
||||
const onDiskSkill = path.join(sandbox.antigravityDir, "paseo");
|
||||
const externalReferences = path.join(sandbox.root, "external-antigravity-references");
|
||||
await fs.mkdir(onDiskSkill, { recursive: true });
|
||||
await fs.mkdir(externalReferences, { recursive: true });
|
||||
await fs.writeFile(path.join(onDiskSkill, "SKILL.md"), "old skill");
|
||||
await fs.writeFile(path.join(externalReferences, "guide.md"), "external guide");
|
||||
await fs.symlink(externalReferences, path.join(onDiskSkill, "references"), "dir");
|
||||
|
||||
await expect(
|
||||
syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
}),
|
||||
@@ -231,8 +294,7 @@ describe("syncSkills", () => {
|
||||
|
||||
const first = await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
});
|
||||
@@ -240,8 +302,7 @@ describe("syncSkills", () => {
|
||||
|
||||
const second = await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
});
|
||||
@@ -255,8 +316,7 @@ describe("syncSkills", () => {
|
||||
const errors: Array<{ name: string; error: unknown }> = [];
|
||||
const result = await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo", "paseo-removed"],
|
||||
onSkillError: (name, error) => errors.push({ name, error }),
|
||||
@@ -278,8 +338,7 @@ describe("syncSkills", () => {
|
||||
|
||||
await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo", "paseo-deprecated"],
|
||||
});
|
||||
@@ -293,8 +352,7 @@ describe("syncSkills", () => {
|
||||
const errors: string[] = [];
|
||||
const result = await syncSkills({
|
||||
sourceDir: missingSourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
onSkillError: (skillName) => errors.push(skillName),
|
||||
@@ -313,8 +371,7 @@ describe("syncSkills", () => {
|
||||
const errors: string[] = [];
|
||||
const result = await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
onSkillError: (skillName) => errors.push(skillName),
|
||||
@@ -336,32 +393,30 @@ describe("removeSkill", () => {
|
||||
await fs.rm(sandbox.root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("removes the skill from all three targets when present", async () => {
|
||||
it("removes the skill from all targets when present", async () => {
|
||||
await writeBundleSkill(sandbox.sourceDir, "paseo", { "SKILL.md": "content" });
|
||||
await syncSkills({
|
||||
sourceDir: sandbox.sourceDir,
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
skillNames: ["paseo"],
|
||||
});
|
||||
|
||||
await removeSkill("paseo", {
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
});
|
||||
|
||||
await expect(fs.access(path.join(sandbox.agentsDir, "paseo"))).rejects.toThrow();
|
||||
await expect(fs.access(path.join(sandbox.claudeDir, "paseo"))).rejects.toThrow();
|
||||
await expect(fs.access(path.join(sandbox.codexDir, "paseo"))).rejects.toThrow();
|
||||
await expect(fs.access(path.join(sandbox.antigravityDir, "paseo"))).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("does not throw when targets are missing", async () => {
|
||||
await expect(
|
||||
removeSkill("does-not-exist", {
|
||||
agentsDir: sandbox.agentsDir,
|
||||
claudeDir: sandbox.claudeDir,
|
||||
installDirs: sandbox.installDirs,
|
||||
codexDir: sandbox.codexDir,
|
||||
}),
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
@@ -4,8 +4,7 @@ import path from "node:path";
|
||||
|
||||
export interface SkillSyncOptions {
|
||||
sourceDir: string;
|
||||
agentsDir: string;
|
||||
claudeDir: string;
|
||||
installDirs: readonly string[];
|
||||
codexDir: string;
|
||||
skillNames: readonly string[];
|
||||
onSkillError?: (skillName: string, error: unknown) => void;
|
||||
@@ -171,20 +170,29 @@ async function syncDirectoryFiles(srcDir: string, dstDir: string): Promise<numbe
|
||||
}
|
||||
|
||||
export interface RemoveSkillTargets {
|
||||
agentsDir: string;
|
||||
claudeDir: string;
|
||||
installDirs: readonly string[];
|
||||
codexDir: string;
|
||||
}
|
||||
|
||||
export async function removeSkill(skillName: string, targets: RemoveSkillTargets): Promise<void> {
|
||||
const paths = [
|
||||
path.join(targets.agentsDir, skillName),
|
||||
path.join(targets.claudeDir, skillName),
|
||||
path.join(targets.codexDir, skillName),
|
||||
];
|
||||
const paths = [...targets.installDirs, targets.codexDir].map((root) =>
|
||||
path.join(root, skillName),
|
||||
);
|
||||
let hasError = false;
|
||||
let firstError: unknown = null;
|
||||
for (const p of paths) {
|
||||
await fs.rm(p, { recursive: true, force: true });
|
||||
try {
|
||||
await fs.rm(p, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
// If an ancestor is a regular file, no skill directory can exist below it.
|
||||
if ((error as NodeJS.ErrnoException).code === "ENOTDIR") continue;
|
||||
if (!hasError) {
|
||||
hasError = true;
|
||||
firstError = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasError) throw firstError;
|
||||
}
|
||||
|
||||
async function isSameDirectory(a: string, b: string): Promise<boolean> {
|
||||
@@ -194,7 +202,7 @@ async function isSameDirectory(a: string, b: string): Promise<boolean> {
|
||||
|
||||
/**
|
||||
* Codex also discovers .agents/skills, so its dedicated copy is a leftover. When
|
||||
* the Codex skill directory resolves to the shared or Claude copy, it is that
|
||||
* the Codex skill directory resolves to an active install target, it is that
|
||||
* copy, and retiring it would delete the install.
|
||||
*/
|
||||
export async function isLegacyCodexCopy(
|
||||
@@ -202,7 +210,7 @@ export async function isLegacyCodexCopy(
|
||||
targets: RemoveSkillTargets,
|
||||
): Promise<boolean> {
|
||||
const codexSkillDir = path.join(targets.codexDir, skillName);
|
||||
for (const root of [targets.agentsDir, targets.claudeDir]) {
|
||||
for (const root of targets.installDirs) {
|
||||
if (await isSameDirectory(codexSkillDir, path.join(root, skillName))) return false;
|
||||
}
|
||||
return true;
|
||||
@@ -234,6 +242,8 @@ async function retireManagedSkill(dstDir: string): Promise<number> {
|
||||
export async function syncSkills(options: SkillSyncOptions): Promise<SkillSyncResult> {
|
||||
let changedFiles = 0;
|
||||
let processedSkills = 0;
|
||||
let hasError = false;
|
||||
let firstError: unknown = null;
|
||||
|
||||
for (const skillName of options.skillNames) {
|
||||
const bundleSkillDir = path.join(options.sourceDir, skillName);
|
||||
@@ -241,28 +251,47 @@ export async function syncSkills(options: SkillSyncOptions): Promise<SkillSyncRe
|
||||
const bundleStat = await fs.stat(bundleSkillDir).catch(() => null);
|
||||
if (!bundleStat?.isDirectory()) continue;
|
||||
|
||||
try {
|
||||
changedFiles += await syncDirectoryFiles(
|
||||
bundleSkillDir,
|
||||
path.join(options.agentsDir, skillName),
|
||||
);
|
||||
let skillFailed = false;
|
||||
let skillError: unknown = null;
|
||||
|
||||
changedFiles += await syncDirectoryFiles(
|
||||
bundleSkillDir,
|
||||
path.join(options.claudeDir, skillName),
|
||||
);
|
||||
|
||||
// Retain user edits to the old dedicated Codex copy.
|
||||
if (await isLegacyCodexCopy(skillName, options)) {
|
||||
changedFiles += await retireManagedSkill(path.join(options.codexDir, skillName));
|
||||
// Attempt every install root for every skill before throwing so one
|
||||
// unwritable target does not stop updates from reaching healthy targets.
|
||||
for (const installDir of options.installDirs) {
|
||||
try {
|
||||
changedFiles += await syncDirectoryFiles(bundleSkillDir, path.join(installDir, skillName));
|
||||
} catch (error) {
|
||||
if (!skillFailed) {
|
||||
skillFailed = true;
|
||||
skillError = error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!skillFailed) {
|
||||
try {
|
||||
// Retain user edits to the old dedicated Codex copy.
|
||||
if (await isLegacyCodexCopy(skillName, options)) {
|
||||
changedFiles += await retireManagedSkill(path.join(options.codexDir, skillName));
|
||||
}
|
||||
} catch (error) {
|
||||
skillFailed = true;
|
||||
skillError = error;
|
||||
}
|
||||
}
|
||||
|
||||
if (skillFailed) {
|
||||
if (options.onSkillError) {
|
||||
options.onSkillError(skillName, skillError);
|
||||
} else if (!hasError) {
|
||||
hasError = true;
|
||||
firstError = skillError;
|
||||
}
|
||||
} else {
|
||||
processedSkills++;
|
||||
} catch (error) {
|
||||
if (!options.onSkillError) throw error;
|
||||
options.onSkillError(skillName, error);
|
||||
}
|
||||
}
|
||||
|
||||
if (hasError) throw firstError;
|
||||
|
||||
return { changedFiles, processedSkills };
|
||||
}
|
||||
|
||||
@@ -128,13 +128,28 @@ function selectionsEqual(left: SkillSelection, right: SkillSelection): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ordered roots for transaction capture and recovery. Pre-0.17 manifests
|
||||
* recorded `[agents, claude, codex]` at indices 0–2, so `codexDir` stays at
|
||||
* index 2 and newer install roots follow at index 3+.
|
||||
*/
|
||||
function skillRoots(targets: SkillTargets): string[] {
|
||||
const [agentsDir, claudeDir, ...additionalInstallDirs] = targets.installDirs;
|
||||
return [
|
||||
...(agentsDir ? [agentsDir] : []),
|
||||
...(claudeDir ? [claudeDir] : []),
|
||||
targets.codexDir,
|
||||
...additionalInstallDirs,
|
||||
];
|
||||
}
|
||||
|
||||
async function validateEntries(
|
||||
targets: SkillTargets,
|
||||
transactionDir: string,
|
||||
entries: CapturedDirectory[],
|
||||
): Promise<boolean> {
|
||||
const names = new Set(await listManagedSkillNames(targets.sourceDir));
|
||||
const roots = [targets.agentsDir, targets.claudeDir, targets.codexDir];
|
||||
const roots = skillRoots(targets);
|
||||
return entries.every((entry) => {
|
||||
const rootIndex = roots.findIndex((root) => path.dirname(entry.livePath) === root);
|
||||
if (rootIndex === -1) return false;
|
||||
@@ -409,6 +424,10 @@ async function restore(
|
||||
continue;
|
||||
}
|
||||
const liveInfo = await lstat(entry.livePath).catch(() => null);
|
||||
// An add entry with no backup and no readable live path wrote nothing here
|
||||
// (absent, under a file, or under an unreadable parent). Skipping avoids
|
||||
// failing rollback with ENOTDIR/EACCES and leaving a stuck transaction.
|
||||
if (liveInfo === null && backup === null) continue;
|
||||
if (liveInfo !== null && !(await isDirectory(entry.livePath))) {
|
||||
// Add/update rollback has the same conflict state as delete rollback. A
|
||||
// recreated file or file symlink belongs to the external writer; preserve
|
||||
@@ -441,11 +460,7 @@ async function restore(
|
||||
}
|
||||
|
||||
function transactionParents(targets: SkillTargets): string[] {
|
||||
return [
|
||||
...new Set(
|
||||
[targets.agentsDir, targets.claudeDir, targets.codexDir].map((root) => path.dirname(root)),
|
||||
),
|
||||
];
|
||||
return [...new Set(skillRoots(targets).map((root) => path.dirname(root)))];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -493,7 +508,7 @@ export async function beginSkillsTransaction(
|
||||
nextSelection: SkillSelection,
|
||||
ops: readonly SkillOp[],
|
||||
): Promise<SkillsTransaction> {
|
||||
const roots = [targets.agentsDir, targets.claudeDir, targets.codexDir];
|
||||
const roots = skillRoots(targets);
|
||||
const seenRoots = new Set<string>();
|
||||
const uniqueRoots: Array<{ root: string; rootIndex: number }> = [];
|
||||
for (const [rootIndex, root] of roots.entries()) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user