Compare commits

...
Author SHA1 Message Date
Mohamed Boudra bd8c515ea3 docs(hub): address PR review findings and split dense paragraphs
Fixes all five accuracy findings across English and Simplified Chinese docs: Audience: Everyone default (from_users: ["*"]), queued dispatch retries for offline daemons, launch-time run.github.connection lookup, ${{ paseo.prompt }} in the manual-task API example, and the execution-mode requirement for paseo hub init. Splits all paragraphs and list items longer than three sentences across Hub docs and the Hub sections of CLI and security docs.
2026-11-20 15:36:35 +01:00
Mohamed Boudra 4341d86238 docs(hub): rewrite Hub docs for triggers, Linear, webhooks, schedules, and scoped tools
Removes legacy multi-step workflow and hub.yml documentation and aligns all English and Simplified Chinese Hub guides with current Hub behavior: self-contained .paseo/triggers/*.yml documents, generic daemon providers, Integrations terminology, Linear app and triggers, scheduled triggers, inbound webhooks, scoped Slack and Discord MCP tools, and Open in Paseo reply links. Adds legacy doc redirects and per-source trigger doc links in the /hub showcase.
2026-11-20 15:18:50 +01:00
Mohamed Boudra fa5d915364 fix(website): align Hub examples and docs with service behavior 2026-11-20 14:53:45 +01:00
Mohamed Boudra a15c8af302 website: prevent font-swap wrap jank and remove left bar on /hub source pills 2026-11-20 14:53:45 +01:00
Mohamed Boudra 37a513ea3d website: interactive source showcase on /hub automations section 2026-11-20 14:53:45 +01:00
Mohamed Boudra 35bc541bda style(website): tighten display-scale Paseo Hub lockup gap 2026-11-20 14:53:45 +01:00
Mohamed Boudra f34aa469c5 feat(website): replace Hub Discord demo with animated Slack mockup 2026-11-20 14:53:45 +01:00
Mohamed Boudra ef00b7fc41 feat(website): derive landing page plugin count from published registry 2026-11-20 14:53:45 +01:00
Mohamed Boudra 750be237e3 style(website): remove hairline rails from header and hero bands 2026-11-20 14:53:44 +01:00
Mohamed Boudra c7e000bb1a feat(website): use Plus Jakarta Sans for display titles 2026-11-20 14:53:44 +01:00
Mohamed Boudra 576048ebb8 chore(website): remove forced eyebrow numbering and redundant section eyebrows 2026-11-20 14:53:44 +01:00
Mohamed Boudra fd579a249a feat(website): unify page frame, rails, section rhythm, and hairline grids across home and /hub 2026-11-20 14:53:44 +01:00
Mohamed Boudra 2c69f5a5d2 chore(website): simplify homepage Hub flow layout and remove highlight cards 2026-11-20 14:53:44 +01:00
Mohamed Boudra 78a7508e3d chore(website): align Hub automation source copy and team visibility wording 2026-11-20 14:53:44 +01:00
Mohamed Boudra 0d436b1ae6 feat(website): refresh Paseo Hub page and add homepage Hub entry points 2026-11-20 14:53:44 +01:00
paseo-bot[bot] c853f98b90 fix(server): wait for restored checkout status on concurrent reads (#10304)
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-20 12:45:08 +00:00
Mohamed Boudra c3da87ee4c Support Gitea, Forgejo, and Codeberg change request watches (#10280)
* feat(server): add Gitea, Forgejo, and Codeberg support for change request watches

Implement the Gitea-family ChangeRequestSource using cwd-free tea login list and tea api --login -i requests, inspecting HTTP status codes directly on stdout/stderr rather than treating exit code 0 alone as success.

Reuse the shared per-host bounded poller for concurrency limits, 429 Retry-After pauses, and exponential backoff. Combine commit statuses and Actions tasks (including approval-held runs via need_approval and cross-repo waiting shadows) with mid-pagination headSha validation, and paginate comments, reviews, and inline review comments with bounded fan-out and quiet-poll caching.

* fix(server): address review findings on Gitea watch pagination, check sharing, and runs fetch

- Read /pulls/:index/reviews/:id/comments in a single request instead of a page loop because Gitea ignores page/limit on that endpoint and omits X-Total-Count/Link headers.
- Paginate /commits/:sha/status using the X-Total-Count response header instead of body total_count (which Gitea sets to the page length).
- Extract shared pure Gitea check schemas, shadow detection, rerun selection, and tea login matching into gitea-checks.ts imported by both gitea-service.ts and gitea-change-requests.ts.
- Remove the redundant /actions/runs fetch from the watch adapter because watch checks carry no action_required trait and approval-held tasks/pending shadows already map to pending.

* fix(server): preserve Gitea watch identity, checks, and backoff

* fix(server): route Gitea watches by base URL and retain complete updates

* fix(server): reconcile Gitea checks by job and refresh watch logins

* fix(server): validate Gitea and Forgejo Actions job responses

* fix(server): classify canceled native Actions statuses as neutral

* fix(server): drain failed Gitea polls before releasing host slots

* fix(server): let admitted Gitea polls finish with low quota

* fix(server): normalize Gitea watch URLs and refresh inline replies

* test(server): cover late Gitea rate limits across recovery windows
2026-11-20 18:41:41 +07:00
Mohamed Boudra 2298effb0b Support multi-forge change request watches and GitLab merge request watches (#10279)
* feat(server): add multi-forge routing and GitLab support for change request watches

Route change request watch URLs host-first through ForgeResolver (cloud host match plus cached async CLI auth probe) before delegating path canonicalization and polling to the matched forge adapter, while sharing adapter instances with workspace reads.

Persist the resolved forge id on saved watch records (defaulting legacy records to github) so daemon restarts recover active watches directly by forge without probing hosts during outages, and keep unknown-forge records intact rather than aborting boot.

Add the GitLab ChangeRequestSource using cwd-free glab api --hostname calls, bounded per-host polling and rate-limit/error backoff, head-pipeline job/bridge checks with mid-pagination headSha verification, discussions/comments, and observable GitLab approval transition updates without manufacturing a GitHub reviewDecision.

* fix(server): address review findings on GitLab watch rate limits, approvals, and legacy recovery

- Decide rate limits from HTTP status codes only on parsed glab responses so MR titles, comments, or IIDs mentioning 429 or rate limit never trip false host pauses.
- Remove the duplicate in-memory approval baseline and counter in favor of immutable GitLab approval system notes enriched with /approvals counts only on new notes, keeping seenActivity as the single persisted owner.
- Infer forge from URL shape when a persisted record omits forge so GitLab watches survive an older-daemon downgrade/upgrade cycle without probing.

* fix(server): handle GitLab locked merge state and custom-port glab host keys

- Pass the bare hostname to glab auth status and glab api --hostname (matching ForgeResolver.resolveHost and glab's api_host config) while preserving host:port in the canonical URL and description.
- Map GitLab's transient locked merge-in-progress state to open so watches keep polling until merged or closed.

* fix(server): preserve accurate GitLab watch updates and offline unsubscribe

* fix(server): validate GitLab watch project addresses and retain approval updates

* fix(server): honor GitLab watch profiles written by glab login

* fix(server): refresh authenticated GitLab watch profiles

* fix(server): keep GitLab poll access checks on merge requests

* fix(server): use GitLab MR access and enforce host pauses on every request

* fix(server): let admitted polls finish and retry denied GitLab reads

* fix(server): give quota-limited change request watches a turn

* fix(server): recover from shared forge quotas one poll at a time

* fix(server): rotate watches after failed quota recovery attempts
2026-11-20 18:05:10 +07:00
Mohamed Boudra a7fed94e51 Keep the Mac Explorer toggle in place (#10297)
Keep one titlebar toggle mounted while Explorer opens and closes. Reserve its footprint in the active rail so native pointer clicks and the header tab sequence work, and verify clearance from the Windows window controls.
2026-11-20 17:42:38 +07:00
36dffc9503 feat(plugin): let plugin navigation focus the destination host in the sidebar (#5574)
* feat(plugin): let plugin navigation focus the destination host in the sidebar

Plugins that link across hosts open agents and workspaces with
navigation.openAgent and navigation.openWorkspace, but the sidebar keeps its
host, project and label filters, so the destination can be hidden. Plugins
can't change those client-side filters.

Add an opt-in focusHost flag. With focusHost: true the client selects only the
destination host in the sidebar and clears project and label filters that
could hide it, keeping the grouping mode. Calls without the flag are
unchanged, and navigation.supportsFocusHost lets plugins detect support.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Normalize plugin navigation host IDs

* Preserve sidebar filters for removed hosts

* Focus the host returned by plugin navigation

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-11-20 17:28:19 +07:00
Mohamed Boudra d78cc90e4d Install bundled orchestration skills for Antigravity (#10273)
* feat(skills): install bundled orchestration skills for Antigravity

Antigravity CLI (`agy`), App, and IDE do not scan `~/.agents/skills` or
`~/.claude/skills` globally; they discover global skills one level deep
from `~/.gemini/config/skills/<skill>/SKILL.md`. Gemini CLI already
discovers `~/.agents/skills`, so targeting `~/.gemini/config/skills`
only (instead of `~/.gemini/skills`) avoids duplicate skill entries in
both Gemini CLI and `agy`.

Appends `antigravityDir` at root index 3 in skill transactions so any
in-flight pre-upgrade transaction manifest retains its existing backup
indices, and includes `antigravityDir` in legacy Codex alias checks so
symlinked roots are not retired.

* fix(skills): unify install roots and keep rollback/updates resilient to unwritable targets

- Replace separate per-target fields on SkillTargets with an ordered
  `installDirs` list plus `codexDir`, deriving status, sync, removal,
  legacy Codex alias checks, and transaction root indexing from one
  source while preserving pre-upgrade backup indices 0–2 (`codexDir` at
  index 2, additional install roots at index 3+).
- Skip unreadable `add` entries with no backup during transaction
  rollback so an ENOTDIR/EACCES parent under `~/.gemini` does not fail
  rollback and leave a stuck transaction blocking later skills calls.
- Ignore `ENOTDIR` in `removeSkill` (a skill cannot exist below a
  regular file).
- Continue syncing remaining skills and install roots in `syncSkills`
  before throwing the first error so an unwritable `~/.gemini` does not
  block startup auto-updates from reaching `~/.agents` and `~/.claude`.

* fix(skills): finish removing reachable skills during uninstall when one root is unreadable

Continue across every target root in `removeSkill` and every managed
skill in `uninstallSkills` before throwing the first error (matching
`syncSkills`), while still reporting `EACCES` rather than ignoring it.

* test(agent): synchronize stale-session retry before checking cleared run

Replace the racy `setTimeout(0)` in `agent-manager.test.ts` with a
deferred gate on `resumeSession`. Under CI load, `setTimeout(0)` could
fire after the immediate retry had already resumed and started its new
in-flight run, causing `hasInFlightRun(agent.id)` to read `true`.
2026-11-20 15:32:14 +07:00
Mohamed Boudra 0f57c2b4c7 Prevent duplicate slash-command entries from breaking composer autocomplete (#10275)
* fix(commands): deduplicate provider slash commands by name

Antigravity ACP emits both its built-in slash commands and discovered skills in one available_commands_update without deduplicating colliding names (such as a local plan skill alongside built-in /plan). Both entries flowed through plugin ACP, plugin-provider, and mergeSlashCommandSources into Autocomplete's FlatList, triggering React's duplicate key error on .$plan.

Enforce unique command names (first-wins) at the plugin ACP, plugin provider, core ACP, and Codex boundaries so every daemon consumer gets a valid catalog, and claim provider command names in mergeSlashCommandSources and inline skill filtering so the app stays safe against older daemons.

* refactor(commands): enforce unique command names at daemon and app boundaries

Move slash-command deduplication from six per-provider and per-consumer copies to the two single boundaries: handleListCommandsRequest in packages/server/src/server/session.ts (covering live agents and drafts for every provider) and fetchAgentCommands in packages/app/src/agent-commands/use-query.ts (covering all app consumers, including against older daemons).

* chore(app): tag app-side command deduplication as a COMPAT shim
2026-11-20 15:12:21 +07:00
Mohamed Boudra ddd7aff9be Keep the composer and chat column aligned with the chat outline rail (#10277)
* fix(app): keep composer and chat column on the outline rail

Previously only WebStreamViewport reserved the 44px chat outline gutter and clamped right gutter on wide web panes (>= 918px), leaving the composer, floating track bar, and callouts at symmetric 16px padding. On Full width, on Wide (1200px) below 1320px pane width, and on Default (820px) between 918px and 939px, the composer extended off the timeline's vertical rail.

Move outline gutter ownership to a platform-split chat-rail module mounted at the chat pane surface. On web it measures the pane width once against the 918px threshold and publishes the shared left and clamped right gutters via CSS custom properties so composer, tracks, and callouts stay aligned with zero resize re-renders or dynamic Unistyles rules, while native stays a zero-hook pass-through. Removing direct outline measurement from AgentStreamView also stops ProviderSubagentPanel from reserving space for an outline it never renders.

* fix(app): keep outline prompt index across 918px crossings and exclude draft error from fullscreen rail
2026-11-20 14:37:32 +07:00
Mohamed Boudra 7eec266f50 fix(usage): keep window shorthands visible in sidebar usage row (#10274)
* fix(usage): keep window shorthands visible in sidebar usage row

Antigravity usage windows emitted full group names and raw period strings (for example "Gemini Models weekly") in shortLabel, which pushed the measured labels row past the maximum sidebar width. On the app side, choosePinnedUsageLayout dropped every window on the row straight to bare percentages whenever any scoped short label overflowed the row.

Normalize Antigravity shortLabel periods (weekly -> wk, monthly -> mo) and shorten group prefixes, and add a compact period-shorthand tier between full labels and bare percentages in PinnedUsageTrigger so tight sidebar rows keep shorthands like 5h and wk visible instead of collapsing to percentages alone.

* test(usage): expect compact shorthands in usage modal sidebar summary

With the compact period-shorthand tier between full labels and bare percentages, three Weekly windows now render as "31% wk", "20% wk", "12% wk" in the 320px sidebar instead of dropping to bare percentages.
2026-11-20 13:58:45 +07:00
182 changed files with 15630 additions and 4772 deletions
+7 -5
View File
@@ -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
+10
View File
@@ -6651,6 +6651,15 @@
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@fontsource-variable/plus-jakarta-sans": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/plus-jakarta-sans/-/plus-jakarta-sans-5.3.0.tgz",
"integrity": "sha512-/l/4r0yyWK9JzAlmA0LiYgGgmJe/Gswt4jTJEzr5QhJfwMbvJZDmYWyW0M4X7yCK69BajMVlV/Lx8g7WDc1+sw==",
"license": "OFL-1.1",
"funding": {
"url": "https://github.com/sponsors/ayuhito"
}
},
"node_modules/@getpaseo/app": {
"resolved": "packages/app",
"link": true
@@ -41479,6 +41488,7 @@
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
"@fontsource-variable/geist": "^5.3.0",
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
"@getpaseo/protocol": "*",
"@tanstack/react-router": "^1.170.16",
"@tanstack/react-start": "^1.168.26",
+24 -1
View File
@@ -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();
+2 -2
View File
@@ -233,8 +233,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"]);
@@ -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);
}
@@ -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);
});
}
+1
View File
@@ -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: "" },
]);
});
});
+13 -1
View File
@@ -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]);
+9 -17
View File
@@ -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);
});
});
+30
View File
@@ -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;
}
+7
View File
@@ -0,0 +1,7 @@
export {
CHAT_COLUMN_RAIL_DATASET,
ChatColumnRailSurface,
useChatOutlineRail,
type ChatColumnRailSurfaceProps,
type ChatOutlineRailState,
} from "./index.native";
+143
View File
@@ -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,
@@ -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>
+5 -1
View File
@@ -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}
+2 -1
View File
@@ -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
+3 -2
View File
@@ -2892,7 +2892,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 +2901,7 @@ export const ar: TranslationResources = {
chooseEmpty: "لا تتضمن هذه النسخة أي مهارات.",
removeTitle: "إزالة المهارات غير المحددة؟",
removeMessage:
"سيتم حذف {{skills}} من ~/.agents و~/.claude و~/.codex. كما يُحذف كل ما أضفته داخل مجلدات المهارات تلك.",
"سيتم حذف {{skills}} من ~/.agents و~/.claude و~/.codex و~/.gemini/config. كما يُحذف كل ما أضفته داخل مجلدات المهارات تلك.",
saveFailed: "تعذر حفظ اختيار المهارات.",
statusFailed: "غير قادر على التحقق من حالة مهارات التنسيق.",
updateFailed: "غير قادر على تحديث مهارات التنسيق.",
+2 -2
View File
@@ -2994,7 +2994,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 +3002,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",
+2 -2
View File
@@ -2916,7 +2916,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 +2925,7 @@ export const es: TranslationResources = {
chooseEmpty: "Esta versión no incluye habilidades.",
removeTitle: "¿Eliminar las habilidades deseleccionadas?",
removeMessage:
"{{skills}} se eliminarán de ~/.agents, ~/.claude 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.",
+2 -2
View File
@@ -2919,7 +2919,7 @@ export const fr: TranslationResources = {
updateTitle: "Mettre à jour les skills Paseo ?",
uninstallTitle: "Désinstaller les skills Paseo ?",
uninstallMessage:
"Supprime tous les skills d’orchestration Paseo de ~/.agents, ~/.claude 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 +2928,7 @@ export const fr: TranslationResources = {
chooseEmpty: "Cet hôte ne fournit aucun skill.",
removeTitle: "Supprimer les skills décochés ?",
removeMessage:
"{{skills}} seront supprimés de ~/.agents, ~/.claude 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.",
+2 -2
View File
@@ -2884,7 +2884,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 +2893,7 @@ export const ja: TranslationResources = {
chooseEmpty: "このビルドにはスキルが含まれていません。",
removeTitle: "選択を外したスキルを削除しますか?",
removeMessage:
"{{skills}} を ~/.agents、~/.claude、~/.codex から削除します。それらのスキルフォルダー内に追加したものもすべて削除されます。",
"{{skills}} を ~/.agents、~/.claude、~/.codex、~/.gemini/config から削除します。それらのスキルフォルダー内に追加したものもすべて削除されます。",
saveFailed: "スキルの選択を保存できませんでした。",
statusFailed: "オーケストレーションスキルのステータスを確認できません。",
updateFailed: "オーケストレーションスキルを更新できません。",
+2 -2
View File
@@ -2871,7 +2871,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 +2879,7 @@ export const ko: TranslationResources = {
chooseEmpty: "이 빌드에는 번들 스킬이 없습니다.",
removeTitle: "선택 해제한 스킬을 제거할까요?",
removeMessage:
"{{skills}}는 ~/.agents, ~/.claude 및 ~/.codex에서 삭제됩니다. 해당 스킬 폴더 안에 추가한 모든 항목도 삭제됩니다.",
"{{skills}}는 ~/.agents, ~/.claude, ~/.codex 및 ~/.gemini/config에서 삭제됩니다. 해당 스킬 폴더 안에 추가한 모든 항목도 삭제됩니다.",
saveFailed: "선택한 스킬을 저장하지 못했습니다.",
statusFailed: "오케스트레이션 스킬 상태를 확인할 수 없습니다.",
updateFailed: "오케스트레이션 스킬을 업데이트할 수 없습니다.",
+2 -2
View File
@@ -2897,7 +2897,7 @@ export const ptBR: TranslationResources = {
updateTitle: "Atualizar Paseo skills?",
uninstallTitle: "Desinstalar Paseo skills?",
uninstallMessage:
"Remove todas as skills de orquestração do Paseo de ~/.agents, ~/.claude 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 +2906,7 @@ export const ptBR: TranslationResources = {
chooseEmpty: "Esta versão não inclui skills.",
removeTitle: "Remover as skills desmarcadas?",
removeMessage:
"{{skills}} serão excluídas de ~/.agents, ~/.claude 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.",
+2 -2
View File
@@ -2909,7 +2909,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 +2917,7 @@ export const ru: TranslationResources = {
chooseEmpty: "На этом хосте нет встроенных навыков.",
removeTitle: "Удалить снятые навыки?",
removeMessage:
"{{skills}} будут удалены из ~/.agents, ~/.claude и ~/.codex на этом хосте. Всё, что вы добавили в эти папки навыков, тоже будет удалено.",
"{{skills}} будут удалены из ~/.agents, ~/.claude, ~/.codex и ~/.gemini/config на этом хосте. Всё, что вы добавили в эти папки навыков, тоже будет удалено.",
saveFailed: "Не удалось сохранить выбор навыков.",
statusFailed: "Не удалось проверить состояние навыков оркестрации.",
updateFailed: "Не удалось обновить навыки оркестрации.",
+3 -2
View File
@@ -2826,7 +2826,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 +2835,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。",
+14 -5
View File
@@ -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} />
+65 -1
View File
@@ -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", () => {
+49 -6
View File
@@ -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),
+19 -5
View File
@@ -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>
);
@@ -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();
});
+10 -1
View File
@@ -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;
};
}
@@ -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 });
}
});
@@ -2728,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(),
+9 -2
View File
@@ -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";
@@ -954,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();
@@ -1472,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,
@@ -2056,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
@@ -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()) {
@@ -6661,3 +6661,77 @@ test("does not publish internal agents' background work to subscribed clients",
await new Promise<void>((resolve) => setImmediate(resolve));
expect(messages.some((message) => message.type === "agent.background_work.update")).toBe(false);
});
test("deduplicates repeated command names in list_commands_response for live agents and drafts", async () => {
const duplicateCommands = [
{
name: "goal",
description: "Run until goal is finished",
argumentHint: "",
kind: "command" as const,
},
{
name: "plan",
description: "Plan carefully before executing a task.",
argumentHint: "",
kind: "command" as const,
},
{
name: "plan",
description: "Local plan skill description",
argumentHint: "",
kind: "skill" as const,
},
];
const expected = [duplicateCommands[0], duplicateCommands[1]];
const liveMessages: SessionOutboundMessage[] = [];
const liveSession = createSessionForTest({
messages: liveMessages,
agentManager: {
waitForAgentClose: async () => undefined,
getAgent: () =>
({
id: "agent-1",
session: { listCommands: async () => duplicateCommands },
}) as never,
},
});
await liveSession.handleMessage({
type: "list_commands_request",
agentId: "agent-1",
requestId: "req-live",
});
expect(findByType(liveMessages, "list_commands_response")).toMatchObject({
payload: {
agentId: "agent-1",
requestId: "req-live",
error: null,
commands: expected,
},
});
const draftMessages: SessionOutboundMessage[] = [];
const draftSession = createSessionForTest({
messages: draftMessages,
agentManager: {
getAgent: () => undefined,
listDraftCommands: async () => duplicateCommands,
},
agentStorage: { get: async () => null },
});
await draftSession.handleMessage({
type: "list_commands_request",
agentId: "draft-1",
requestId: "req-draft",
draftConfig: { provider: "antigravity", cwd: "/tmp/repo" },
});
expect(findByType(draftMessages, "list_commands_response")).toMatchObject({
payload: {
agentId: "draft-1",
requestId: "req-draft",
error: null,
commands: expected,
},
});
});
+15 -2
View File
@@ -5603,7 +5603,7 @@ export class Session {
: null;
if (agent?.session?.listCommands) {
const commands = await agent.session.listCommands();
const commands = dedupeSlashCommands(await agent.session.listCommands());
this.emit({
type: "list_commands_response",
payload: {
@@ -5627,7 +5627,9 @@ export class Session {
: {}),
};
const commands = await this.agentManager.listDraftCommands(sessionConfig);
const commands = dedupeSlashCommands(
await this.agentManager.listDraftCommands(sessionConfig),
);
this.emit({
type: "list_commands_response",
payload: {
@@ -9614,3 +9616,14 @@ function createHostSession(options: SessionOptions, session: Session): Connected
function hostSource(options: SessionOptions): string {
return options.sourceId ?? "owner";
}
function dedupeSlashCommands<T extends { name: string }>(commands: readonly T[]): T[] {
const seen = new Set<string>();
const unique: T[] = [];
for (const command of commands) {
if (seen.has(command.name)) continue;
seen.add(command.name);
unique.push(command);
}
return unique;
}
@@ -2404,6 +2404,46 @@ describe("WorkspaceGitServiceImpl with workspace folders that no longer exist",
await service.dispose();
});
test("a snapshot read during restoration waits for fresh checkout facts", async () => {
const workspace = await createTemporaryFolder();
const git = createFolderBackedGit();
const started = createDeferred<void>();
const release = createDeferred<void>();
let holdRestoredRead = false;
const service = createService({
...git.deps,
getCheckoutSnapshotFacts: async (cwd: string) => {
if (holdRestoredRead) {
started.resolve();
await release.promise;
}
return git.deps.getCheckoutSnapshotFacts(cwd);
},
});
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
await waitForObservationToSettle(service, 1);
await rm(workspace, { recursive: true, force: true });
service.onWorkspaceStateMayHaveChanged(workspace);
await vi.advanceTimersByTimeAsync(1_000);
await waitForRefreshesToSettle(service);
expect((await service.getSnapshot(workspace)).git.isGit).toBe(false);
await advanceThroughDegradedPolls(service);
await waitForObservationToSettle(service, 0);
await mkdir(workspace);
holdRestoredRead = true;
const restoringRead = service.getSnapshot(workspace);
await started.promise;
const concurrentRead = service.getSnapshot(workspace);
release.resolve();
expect((await restoringRead).git.isGit).toBe(true);
expect((await concurrentRead).git.isGit).toBe(true);
subscription.unsubscribe();
await service.dispose();
});
test("a resumed workspace rebuilds observation from fresh facts, not the non-git facts cached while its folder was gone", async () => {
const workspace = await createTemporaryFolder();
const git = createFolderBackedGit();
@@ -422,6 +422,8 @@ interface WorkspaceGitServiceDependencies {
* fakes. Any forge not listed here is built (and cached once) by the registry.
*/
forgeOverrides?: Record<string, ForgeService>;
/** Shared forge resolver when callers share adapter instances with other services. */
forgeResolver?: ForgeResolver;
/** Resolves an SSH config alias to its HostName; defaults to `ssh -G`. */
resolveSshHostname?: SshHostnameResolver;
resolveAbsoluteGitDir: (cwd: string) => Promise<string | null>;
@@ -723,10 +725,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
this.fileObserver.subscribe.bind(this.fileObserver),
options.deps,
);
this.forgeResolver = createForgeResolver({
createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge),
resolveSshHostname: this.deps.resolveSshHostname,
});
this.forgeResolver =
this.deps.forgeResolver ??
createForgeResolver({
createService: (forge) => this.deps.forgeOverrides?.[forge] ?? createForgeService(forge),
resolveSshHostname: this.deps.resolveSshHostname,
});
}
resolveForge(cwd: string): Promise<ForgeResolution | null> {
@@ -834,9 +838,10 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
cwd = resolve(cwd);
const request = this.normalizeRefreshRequest(options, "getSnapshot");
const target = this.ensureWorkspaceTarget(cwd);
// The snapshot cached while the folder was gone can say "not git". Resume
// first, so a restored folder is read again instead of served from it.
if (target.folderMissing) {
// Restoration clears folderMissing before the fresh snapshot is ready.
if (target.folderRestorePromise) {
await target.folderRestorePromise;
} else if (target.folderMissing) {
await this.resumeWorkspaceIfFolderRestored(target);
}
if (!request.force && target.latestSnapshot) {
@@ -0,0 +1,230 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ChangeRequestSnapshot } from "./change-request-source.js";
import {
ChangeRequestRateLimitError,
createPerHostChangeRequestPoller,
parseCliHttpResponse,
parseRetryAfterMs,
} from "./change-request-poller.js";
const sampleSnapshot: ChangeRequestSnapshot = {
state: "open",
headSha: "abc123",
checksState: "passed",
checks: [],
reviewDecision: null,
activity: [],
};
afterEach(() => {
vi.useRealTimers();
});
describe("parseCliHttpResponse", () => {
it("parses status line, mixed line endings, redirect blocks, and JSON body", () => {
const raw = [
"HTTP/1.1 100 Continue\r\n\r\n",
"HTTP/2.0 200 OK\n",
"Content-Type: application/json\r\n",
"X-Next-Page: 2\r\n",
"Ratelimit-Remaining: 95\r\n",
"Ratelimit-Reset: 1700000120\r\n",
"\r\n",
'{"ok":true}',
].join("");
const parsed = parseCliHttpResponse(raw);
expect(parsed.status).toBe(200);
expect(parsed.headers.get("x-next-page")).toBe("2");
expect(parsed.headers.get("ratelimit-remaining")).toBe("95");
expect(parsed.body).toBe('{"ok":true}');
});
it("returns null status and raw body when headers are absent", () => {
const parsed = parseCliHttpResponse('{"ok":true}');
expect(parsed.status).toBeNull();
expect(parsed.headers.size).toBe(0);
expect(parsed.body).toBe('{"ok":true}');
});
});
describe("parseRetryAfterMs", () => {
it("parses Retry-After seconds and exhausted Ratelimit-Reset headers", () => {
const now = 1_700_000_000_000;
expect(parseRetryAfterMs(new Map([["retry-after", "45"]]), now)).toBe(now + 45_000);
expect(
parseRetryAfterMs(
new Map([
["ratelimit-remaining", "0"],
["ratelimit-reset", "1700000060"],
]),
now,
),
).toBe(1_700_000_060_000);
expect(
parseRetryAfterMs(
new Map([
["ratelimit-remaining", "50"],
["ratelimit-reset", "1700000060"],
]),
now,
),
).toBeNull();
});
});
describe("createPerHostChangeRequestPoller", () => {
it("bounds concurrent reads per host and drains waiting watches as slots free", async () => {
vi.useFakeTimers();
let active = 0;
let maxActive = 0;
const resolvers = new Map<string, () => void>();
const poller = createPerHostChangeRequestPoller({
hostOf: (url) => new URL(url).hostname,
maxConcurrencyPerHost: 2,
pollIntervalMs: 20_000,
async read({ url }) {
active += 1;
maxActive = Math.max(maxActive, active);
await new Promise<void>((resolve) => {
resolvers.set(url, resolve);
});
active -= 1;
return sampleSnapshot;
},
});
const received: string[] = [];
try {
for (const n of [1, 2, 3]) {
const url = `https://gitlab.com/org/repo/-/merge_requests/${n}`;
poller.observe(url, {
async snapshot() {
received.push(url);
},
error(error) {
throw error;
},
});
}
await vi.advanceTimersByTimeAsync(25);
expect(maxActive).toBe(2);
expect(resolvers.size).toBe(2);
resolvers.get("https://gitlab.com/org/repo/-/merge_requests/1")?.();
await vi.advanceTimersByTimeAsync(0);
expect(maxActive).toBe(2);
expect(resolvers.has("https://gitlab.com/org/repo/-/merge_requests/3")).toBe(true);
resolvers.get("https://gitlab.com/org/repo/-/merge_requests/2")?.();
resolvers.get("https://gitlab.com/org/repo/-/merge_requests/3")?.();
await vi.advanceTimersByTimeAsync(0);
expect(received).toHaveLength(3);
} finally {
poller.dispose();
}
});
it("backs off exponentially on transient errors and resets after a successful poll", async () => {
vi.useFakeTimers();
let calls = 0;
let shouldFail = true;
const poller = createPerHostChangeRequestPoller({
hostOf: (url) => new URL(url).hostname,
pollIntervalMs: 10_000,
maxErrorBackoffMs: 40_000,
async read() {
calls += 1;
if (shouldFail) throw new Error(`fail ${calls}`);
return sampleSnapshot;
},
});
const errors: unknown[] = [];
const snapshots: ChangeRequestSnapshot[] = [];
try {
poller.observe("https://gitlab.com/org/repo/-/merge_requests/1", {
async snapshot(s) {
snapshots.push(s);
},
error(err) {
errors.push(err);
},
});
await vi.advanceTimersByTimeAsync(25);
expect(calls).toBe(1);
expect(errors).toHaveLength(1);
// 1st failure -> 10s backoff
await vi.advanceTimersByTimeAsync(9_999);
expect(calls).toBe(1);
await vi.advanceTimersByTimeAsync(1);
expect(calls).toBe(2);
// 2nd failure -> 20s backoff
await vi.advanceTimersByTimeAsync(19_999);
expect(calls).toBe(2);
shouldFail = false;
await vi.advanceTimersByTimeAsync(1);
expect(calls).toBe(3);
expect(snapshots).toHaveLength(1);
// Reset to 10s base interval after success
await vi.advanceTimersByTimeAsync(10_000);
expect(calls).toBe(4);
} finally {
poller.dispose();
}
});
it("pauses all watches on a rate-limited host until resetAt and fast-fails new observers", async () => {
vi.useFakeTimers();
vi.setSystemTime(1_700_000_000_000);
let calls = 0;
const poller = createPerHostChangeRequestPoller({
hostOf: (url) => new URL(url).hostname,
pollIntervalMs: 10_000,
async read() {
calls += 1;
if (calls === 1) {
throw new ChangeRequestRateLimitError({
host: "gitlab.com",
resetAtMs: Date.now() + 60_000,
});
}
return sampleSnapshot;
},
});
const errors1: unknown[] = [];
const errors2: unknown[] = [];
const snapshots2: ChangeRequestSnapshot[] = [];
try {
poller.observe("https://gitlab.com/org/repo/-/merge_requests/1", {
async snapshot() {},
error(err) {
errors1.push(err);
},
});
await vi.advanceTimersByTimeAsync(25);
expect(calls).toBe(1);
expect(errors1[0]).toBeInstanceOf(ChangeRequestRateLimitError);
poller.observe("https://gitlab.com/org/repo/-/merge_requests/2", {
async snapshot(s) {
snapshots2.push(s);
},
error(err) {
errors2.push(err);
},
});
await vi.advanceTimersByTimeAsync(0);
expect(errors2[0]).toBeInstanceOf(ChangeRequestRateLimitError);
await vi.advanceTimersByTimeAsync(59_999);
expect(calls).toBe(1);
await vi.advanceTimersByTimeAsync(1);
expect(calls).toBe(3);
expect(snapshots2).toHaveLength(1);
} finally {
poller.dispose();
}
});
});
@@ -0,0 +1,362 @@
import type { ChangeRequestSnapshot, ChangeRequestSource } from "./change-request-source.js";
const DEFAULT_INITIAL_DELAY_MS = 25;
const DEFAULT_POLL_INTERVAL_MS = 20_000;
const DEFAULT_MAX_ERROR_BACKOFF_MS = 300_000;
const DEFAULT_MAX_CONCURRENCY_PER_HOST = 2;
const MIN_RATE_LIMIT_PAUSE_MS = 1_000;
const MAX_RATE_LIMIT_PAUSE_MS = 15 * 60_000;
export interface ParsedCliHttpResponse {
status: number | null;
headers: Map<string, string>;
body: string;
}
const HTTP_STATUS_PREFIX = /^HTTP\/\d(?:\.\d)?\s+(\d{3})[^\r\n]*\r?\n/;
const HEADER_BODY_SEPARATOR = /\r?\n\r?\n/;
/**
* Parse output from CLI API commands invoked with `-i` / `--include`.
* Consumes multiple leading HTTP response blocks (e.g. `100 Continue` or
* redirect headers) and returns the final status code, lowercased headers,
* and response body. Returns `status: null` when no HTTP header block is
* present.
*/
export function parseCliHttpResponse(raw: string): ParsedCliHttpResponse {
let remaining = raw.trimStart();
let status: number | null = null;
let headers = new Map<string, string>();
while (true) {
const statusMatch = HTTP_STATUS_PREFIX.exec(remaining);
if (!statusMatch) {
break;
}
const separatorMatch = HEADER_BODY_SEPARATOR.exec(remaining);
if (!separatorMatch) {
status = Number(statusMatch[1]);
headers = parseHeaderLines(remaining.slice(statusMatch[0].length));
remaining = "";
break;
}
status = Number(statusMatch[1]);
const headerBlock = remaining.slice(statusMatch[0].length, separatorMatch.index);
headers = parseHeaderLines(headerBlock);
remaining = remaining.slice(separatorMatch.index + separatorMatch[0].length);
}
return { status, headers, body: remaining.trim() };
}
function parseHeaderLines(block: string): Map<string, string> {
const headers = new Map<string, string>();
for (const line of block.split(/\r?\n/)) {
const colon = line.indexOf(":");
if (colon <= 0) continue;
const name = line.slice(0, colon).trim().toLowerCase();
const value = line.slice(colon + 1).trim();
if (!name) continue;
const existing = headers.get(name);
headers.set(name, existing ? `${existing}, ${value}` : value);
}
return headers;
}
function clampPauseUntil(targetMs: number, nowMs: number): number {
return Math.min(
Math.max(targetMs, nowMs + MIN_RATE_LIMIT_PAUSE_MS),
nowMs + MAX_RATE_LIMIT_PAUSE_MS,
);
}
/**
* Extract the timestamp (epoch ms) until which a host should pause polling
* based on `Retry-After` or exhausted `Ratelimit-Remaining` / `Ratelimit-Reset`
* headers. Returns null when no pause is signaled.
*/
export function parseRetryAfterMs(
headers: ReadonlyMap<string, string>,
nowMs: number,
options: { forceOnMissing?: boolean; defaultPauseMs?: number } = {},
): number | null {
const retryAfter = headers.get("retry-after");
if (retryAfter) {
const seconds = Number(retryAfter);
if (Number.isFinite(seconds) && seconds >= 0) {
return clampPauseUntil(nowMs + Math.ceil(seconds * 1_000), nowMs);
}
const parsedDate = Date.parse(retryAfter);
if (Number.isFinite(parsedDate)) {
return clampPauseUntil(parsedDate, nowMs);
}
}
const remainingRaw = headers.get("ratelimit-remaining") ?? headers.get("x-ratelimit-remaining");
const resetRaw = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
const remaining = remainingRaw !== undefined ? Number(remainingRaw) : Number.NaN;
const resetSec = resetRaw !== undefined ? Number(resetRaw) : Number.NaN;
if (
(options.forceOnMissing || (Number.isFinite(remaining) && remaining <= 1)) &&
Number.isFinite(resetSec) &&
resetSec > 0
) {
return clampPauseUntil(resetSec * 1_000, nowMs);
}
if (options.forceOnMissing) {
return clampPauseUntil(nowMs + (options.defaultPauseMs ?? 60_000), nowMs);
}
return null;
}
export class ChangeRequestRateLimitError extends Error {
readonly host: string;
readonly resetAtMs: number;
constructor(params: { host: string; resetAtMs: number; message?: string }) {
super(
params.message ??
`Change request polling for ${params.host} is rate-limited until ${new Date(params.resetAtMs).toISOString()}`,
);
this.name = "ChangeRequestRateLimitError";
this.host = params.host;
this.resetAtMs = params.resetAtMs;
}
}
export interface PerHostReadContext {
url: string;
host: string;
knownActivity(): ReadonlySet<string> | undefined;
isObserved(): boolean;
assertHostAvailable(): void;
deferPollsUntil(untilMs: number): void;
pauseHost(untilMs: number): void;
}
export interface PerHostChangeRequestPollerOptions {
hostOf(url: string): string;
read(context: PerHostReadContext): Promise<ChangeRequestSnapshot>;
now?: () => number;
initialDelayMs?: number;
pollIntervalMs?: number;
maxErrorBackoffMs?: number;
maxConcurrencyPerHost?: number;
onError?(error: unknown, host: string): void;
}
interface WatchedEntry {
url: string;
host: string;
callbacks: Parameters<ChangeRequestSource["observe"]>[1];
nextDueAt: number;
consecutiveErrors: number;
inFlight: boolean;
}
export interface PerHostChangeRequestPoller {
observe: ChangeRequestSource["observe"];
dispose(): void;
}
/**
* Bounded per-host polling loop shared by REST-backed forge watch adapters.
* Limits concurrent reads per host, applies exponential backoff on transient
* failures, and pauses all watches for a host when rate-limited.
*/
export function createPerHostChangeRequestPoller(
options: PerHostChangeRequestPollerOptions,
): PerHostChangeRequestPoller {
const now = options.now ?? Date.now;
const initialDelayMs = options.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
const maxErrorBackoffMs = options.maxErrorBackoffMs ?? DEFAULT_MAX_ERROR_BACKOFF_MS;
const maxConcurrencyPerHost = options.maxConcurrencyPerHost ?? DEFAULT_MAX_CONCURRENCY_PER_HOST;
const watches = new Map<string, WatchedEntry>();
const inFlightByHost = new Map<string, number>();
const pausesByHost = new Map<string, { pollsUntil: number; requestsUntil: number }>();
let timer: NodeJS.Timeout | null = null;
let disposed = false;
function clearTimer(): void {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
function deferHost(host: string, untilMs: number, blockRequests: boolean): void {
const current = pausesByHost.get(host) ?? { pollsUntil: 0, requestsUntil: 0 };
pausesByHost.set(host, {
pollsUntil: Math.max(current.pollsUntil, untilMs),
requestsUntil: blockRequests
? Math.max(current.requestsUntil, untilMs)
: current.requestsUntil,
});
}
function hostPauseUntil(host: string, nowMs: number): number {
const pause = pausesByHost.get(host);
if (!pause) return 0;
if (pause.pollsUntil > nowMs) return pause.pollsUntil;
if (!pause.requestsUntil) pausesByHost.delete(host);
return 0;
}
function pollLimit(host: string): number {
// After a 429, admit one poll until it has delivered a full snapshot.
// This lets it use the reset quota without competing with another poll.
return pausesByHost.get(host)?.requestsUntil ? 1 : maxConcurrencyPerHost;
}
function armTimer(): void {
clearTimer();
if (disposed || watches.size === 0) return;
const nowMs = now();
let earliestDue = Number.POSITIVE_INFINITY;
for (const watch of watches.values()) {
if (watch.inFlight) continue;
if ((inFlightByHost.get(watch.host) ?? 0) >= pollLimit(watch.host)) continue;
const dueAt = Math.max(watch.nextDueAt, hostPauseUntil(watch.host, nowMs));
if (dueAt < earliestDue) {
earliestDue = dueAt;
}
}
if (!Number.isFinite(earliestDue)) return;
const delay = Math.max(0, earliestDue - nowMs);
timer = setTimeout(() => {
timer = null;
drainDueWatches();
}, delay);
timer.unref();
}
function drainDueWatches(): void {
if (disposed) return;
const nowMs = now();
for (const watch of watches.values()) {
if (watch.inFlight) continue;
const inFlightCount = inFlightByHost.get(watch.host) ?? 0;
if (inFlightCount >= pollLimit(watch.host)) continue;
const dueAt = Math.max(watch.nextDueAt, hostPauseUntil(watch.host, nowMs));
if (dueAt > nowMs) continue;
startPoll(watch);
}
armTimer();
}
function startPoll(watch: WatchedEntry): void {
watch.inFlight = true;
inFlightByHost.set(watch.host, (inFlightByHost.get(watch.host) ?? 0) + 1);
const isObserved = () => !disposed && watches.get(watch.url) === watch;
const recovering = Boolean(pausesByHost.get(watch.host)?.requestsUntil);
let completed = false;
void (async () => {
try {
const snapshot = await options.read({
url: watch.url,
host: watch.host,
knownActivity: () => watch.callbacks.knownActivity?.(),
isObserved,
assertHostAvailable() {
const nowMs = now();
const resetAtMs = pausesByHost.get(watch.host)?.requestsUntil ?? 0;
if (resetAtMs > nowMs) {
throw new ChangeRequestRateLimitError({ host: watch.host, resetAtMs });
}
},
deferPollsUntil: (untilMs) => deferHost(watch.host, untilMs, false),
pauseHost: (untilMs) => deferHost(watch.host, untilMs, true),
});
if (!isObserved()) return;
watch.consecutiveErrors = 0;
await watch.callbacks.snapshot(snapshot);
if (!isObserved()) return;
const nowMs = now();
const pause = pausesByHost.get(watch.host);
if (pause && pause.requestsUntil <= nowMs) pause.requestsUntil = 0;
watch.nextDueAt = Math.max(nowMs + pollIntervalMs, hostPauseUntil(watch.host, nowMs));
completed = true;
} catch (error) {
if (!isObserved()) return;
options.onError?.(error, watch.host);
const nowMs = now();
if (error instanceof ChangeRequestRateLimitError) {
deferHost(watch.host, error.resetAtMs, true);
watch.nextDueAt = Math.max(nowMs + pollIntervalMs, error.resetAtMs);
} else {
watch.consecutiveErrors += 1;
const backoff = Math.min(
pollIntervalMs * 2 ** (watch.consecutiveErrors - 1),
maxErrorBackoffMs,
);
watch.nextDueAt = nowMs + backoff;
}
watch.callbacks.error(error);
} finally {
// Rotate after a snapshot or a recovery attempt so a watch that
// keeps failing cannot take every turn after a quota reset.
if ((completed || recovering) && isObserved()) {
watches.delete(watch.url);
watches.set(watch.url, watch);
}
watch.inFlight = false;
const remaining = (inFlightByHost.get(watch.host) ?? 1) - 1;
if (remaining > 0) inFlightByHost.set(watch.host, remaining);
else inFlightByHost.delete(watch.host);
if (!disposed) {
// Immediately admit any queued due watch on this host, then re-arm timer.
drainDueWatches();
}
}
})();
}
return {
observe(url, callbacks) {
if (disposed) {
queueMicrotask(() => callbacks.error(new Error("Change request poller is disposed")));
return () => {};
}
const host = options.hostOf(url);
const nowMs = now();
const watch: WatchedEntry = {
url,
host,
callbacks,
nextDueAt: nowMs + initialDelayMs,
consecutiveErrors: 0,
inFlight: false,
};
watches.set(url, watch);
const pauseUntil = hostPauseUntil(host, nowMs);
if (pauseUntil > nowMs) {
queueMicrotask(() => {
if (!disposed && watches.get(url) === watch) {
callbacks.error(new ChangeRequestRateLimitError({ host, resetAtMs: pauseUntil }));
}
});
}
armTimer();
return () => {
if (watches.get(url) === watch) {
watches.delete(url);
armTimer();
}
};
},
dispose() {
disposed = true;
clearTimer();
watches.clear();
inFlightByHost.clear();
pausesByHost.clear();
},
};
}
@@ -0,0 +1,120 @@
import { describe, expect, it, vi } from "vitest";
import { createChangeRequestRouter } from "./change-request-router.js";
import type { ChangeRequestSource } from "./change-request-source.js";
import { createForgeResolver } from "./forge-resolver.js";
import type { ForgeService } from "./forge-service.js";
function createFakeSource(
forge: string,
canonicalize: (url: string) => string,
): ChangeRequestSource {
return {
resolve: canonicalize,
describe: (url) => `${forge}:${url}`,
observe: () => () => {},
};
}
function createFakeForgeService(changeRequests?: ChangeRequestSource): ForgeService {
return {
...(changeRequests ? { changeRequests } : {}),
invalidate() {},
} as unknown as ForgeService;
}
describe("createChangeRequestRouter", () => {
it("routes cloud hosts without probing and delegates canonicalization to the matched forge", async () => {
const probeForge = vi.fn(async () => {
throw new Error("cloud host must not trigger a probe");
});
const githubSource = createFakeSource(
"github",
(url) => `https://github.com/canonical/${new URL(url).pathname.split("/").at(-1)}`,
);
const gitlabSource = createFakeSource(
"gitlab",
(url) => `https://gitlab.com/canonical/${new URL(url).pathname.split("/").at(-1)}`,
);
const resolver = createForgeResolver({
probeForge,
createService: (forge) => {
if (forge === "github") return createFakeForgeService(githubSource);
if (forge === "gitlab") return createFakeForgeService(gitlabSource);
return null;
},
});
const router = createChangeRequestRouter({ forgeResolver: resolver });
await expect(router.resolve("https://GitHub.com/Org/Repo/pull/7")).resolves.toEqual({
forge: "github",
url: "https://github.com/canonical/7",
});
await expect(
router.resolve("https://gitlab.com/org/sub/repo/-/merge_requests/12"),
).resolves.toEqual({
forge: "gitlab",
url: "https://gitlab.com/canonical/12",
});
expect(probeForge).not.toHaveBeenCalled();
expect(router.source("github")).toBe(githubSource);
expect(router.source("gitlab")).toBe(gitlabSource);
});
it("probes self-hosted hosts before parsing the URL path", async () => {
const probeForge = vi.fn(async (host: string) =>
host === "git.corp.internal" ? "gitlab" : null,
);
const gitlabResolve = vi.fn(() => "https://git.corp.internal/team/app/-/merge_requests/9");
const githubResolve = vi.fn(() => {
throw new Error("github must not parse a gitlab host");
});
const resolver = createForgeResolver({
probeForge,
createService: (forge) => {
if (forge === "github")
return createFakeForgeService(createFakeSource("github", githubResolve));
if (forge === "gitlab")
return createFakeForgeService(createFakeSource("gitlab", gitlabResolve));
return null;
},
});
const router = createChangeRequestRouter({ forgeResolver: resolver });
await expect(
router.resolve("https://git.corp.internal/team/app/-/merge_requests/9"),
).resolves.toEqual({
forge: "gitlab",
url: "https://git.corp.internal/team/app/-/merge_requests/9",
});
expect(probeForge).toHaveBeenCalledWith("git.corp.internal");
expect(gitlabResolve).toHaveBeenCalledTimes(1);
expect(githubResolve).not.toHaveBeenCalled();
});
it("rejects unrecognized hosts, credentials, non-http schemes, and forges without watch support", async () => {
const resolver = createForgeResolver({
probeForge: async () => null,
createService: (forge) => {
if (forge === "gitea") return createFakeForgeService();
return null;
},
});
const router = createChangeRequestRouter({ forgeResolver: resolver });
await expect(router.resolve("not a url")).rejects.toThrow(/change request URL/i);
await expect(router.resolve("ftp://github.com/org/repo/pull/1")).rejects.toThrow(
/change request URL/i,
);
await expect(router.resolve("https://user:pass@github.com/org/repo/pull/1")).rejects.toThrow(
/change request URL/i,
);
await expect(router.resolve("https://unknown.example.com/org/repo/pull/1")).rejects.toThrow(
/unknown\.example\.com/,
);
await expect(router.resolve("https://gitea.com/org/repo/pulls/1")).rejects.toThrow(
/not supported.*gitea/i,
);
expect(router.source("gitea")).toBeNull();
expect(router.source("unknown")).toBeNull();
});
});
@@ -0,0 +1,80 @@
import { normalizeHost } from "@getpaseo/protocol/git-remote";
import type { ChangeRequestSource } from "./change-request-source.js";
import type { ForgeResolver } from "./forge-resolver.js";
export interface ResolvedChangeRequest {
forge: string;
url: string;
}
export interface ChangeRequestRouter {
/** Route a user-supplied URL host-first through registered forges and canonicalize it. */
resolve(url: string): Promise<ResolvedChangeRequest>;
/** Return the watch source for a known forge id without probing the network. */
source(forge: string): ChangeRequestSource | null;
}
export interface CreateChangeRequestRouterOptions {
forgeResolver: Pick<ForgeResolver, "resolveHost" | "getService">;
}
function extractUrlHost(input: string): { trimmed: string; host: string; authority: string } {
const trimmed = input.trim();
if (!trimmed || /\s/.test(trimmed)) {
throw new Error("Enter a supported change request URL.");
}
let parsed: URL;
try {
parsed = new URL(trimmed);
} catch {
throw new Error("Enter a supported change request URL.");
}
if (
(parsed.protocol !== "https:" && parsed.protocol !== "http:") ||
parsed.username ||
parsed.password
) {
throw new Error("Enter a supported change request URL.");
}
const host = normalizeHost(parsed.hostname);
if (!host) {
throw new Error("Enter a supported change request URL.");
}
return { trimmed, host, authority: parsed.port ? `${host}:${parsed.port}` : host };
}
/**
* Host-first router for change request watches. Resolves the target forge from
* the URL host via ForgeResolver (cloud match first, then cached CLI auth
* probe) before delegating path parsing and canonicalization to that forge's
* ChangeRequestSource.
*/
export function createChangeRequestRouter({
forgeResolver,
}: CreateChangeRequestRouterOptions): ChangeRequestRouter {
return {
async resolve(input: string): Promise<ResolvedChangeRequest> {
const { trimmed, host, authority } = extractUrlHost(input);
const resolution =
(await forgeResolver.resolveHost(authority)) ??
(authority === host ? null : await forgeResolver.resolveHost(host));
if (!resolution) {
throw new Error(
`Could not recognize a supported forge for host ${host}. Authenticate the forge CLI for this host first.`,
);
}
const source = resolution.service.changeRequests;
if (!source) {
throw new Error(`Change request watches are not supported for ${resolution.forge} yet.`);
}
return {
forge: resolution.forge,
url: source.resolve(trimmed),
};
},
source(forge: string): ChangeRequestSource | null {
return forgeResolver.getService(forge)?.changeRequests ?? null;
},
};
}
@@ -17,8 +17,9 @@ const changeRequestSnapshotSchema = changeRequestStatusSchema.extend({
activity: z.array(
z.object({
id: z.string(),
kind: z.enum(["comment", "inline comment", "review"]),
kind: z.enum(["comment", "inline comment", "review", "approval"]),
url: z.string(),
message: z.string().optional(),
}),
),
});
@@ -373,4 +373,40 @@ describe("createForgeResolver", () => {
expect(b).toMatchObject({ forge: "gitlab", host: "git.acme.internal" });
expect(probeForge).toHaveBeenCalledTimes(1);
});
it("resolves cloud and probed hosts directly via resolveHost and shares service instances", async () => {
const probeForge = vi.fn(async (host: string) =>
host === "git.acme.internal" ? "gitlab" : null,
);
const created: string[] = [];
const disposed: string[] = [];
const resolver = createForgeResolver({
probeForge,
createService: (forge) => {
created.push(forge);
const base = createForgeService(forge);
if (!base) return null;
return {
...base,
dispose: () => {
disposed.push(forge);
},
};
},
});
const cloud = await resolver.resolveHost("GitLab.com.");
expect(cloud).toMatchObject({ forge: "gitlab", host: "gitlab.com" });
expect(probeForge).not.toHaveBeenCalled();
const selfHosted = await resolver.resolveHost("GIT.ACME.INTERNAL");
expect(selfHosted).toMatchObject({ forge: "gitlab", host: "git.acme.internal" });
expect(selfHosted?.service).toBe(cloud?.service);
expect(probeForge).toHaveBeenCalledTimes(1);
expect(resolver.getService("gitlab")).toBe(cloud?.service);
expect(created).toEqual(["gitlab"]);
resolver.dispose();
expect(disposed).toEqual(["gitlab"]);
});
});
+60 -11
View File
@@ -1,5 +1,9 @@
import { LRUCache } from "lru-cache";
import { parseGitRemoteLocation, type GitRemoteLocation } from "@getpaseo/protocol/git-remote";
import {
normalizeHost,
parseGitRemoteLocation,
type GitRemoteLocation,
} from "@getpaseo/protocol/git-remote";
import { resolveSshHostname, type SshHostnameResolver } from "../utils/ssh-hostname.js";
import { defaultResolveRemoteUrl } from "./forge-cli-command.js";
import type { ForgeService } from "./forge-service.js";
@@ -24,6 +28,7 @@ export type ForgeHostProbe = (host: string) => Promise<string | null>;
export interface CreateForgeResolverOptions {
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
createService?: (forge: string) => ForgeService | null;
matchHost?: (host: string) => string | null;
probeForge?: ForgeHostProbe;
resolveSshHostname?: SshHostnameResolver;
now?: () => number;
@@ -36,12 +41,18 @@ export interface ForgeResolver {
resolveFromRemoteUrl(remoteUrl: string | null): ForgeResolution | null;
/** Resolve from a known origin remote URL, running the per-host probe when needed. */
resolveFromRemoteUrlAsync(remoteUrl: string | null): Promise<ForgeResolution | null>;
/** Resolve a forge directly by hostname (cloud match first, then cached async probe). */
resolveHost(host: string): Promise<ForgeResolution | null>;
/** Return the shared adapter instance for a known forge id without probing the network. */
getService(forge: string): ForgeService | null;
/**
* Invalidate every cached adapter's state for a cwd. Routed through the
* resolver so invalidation hits the same adapter instance the poller reads,
* regardless of which forge backs the workspace.
*/
invalidate(cwd: string): void;
/** Dispose all instantiated forge adapters owned by this resolver. */
dispose(): void;
}
// A positive probe (host IS a known forge) is cached permanently; a negative one
@@ -64,6 +75,7 @@ export function forgeForHost(host: string): string | null {
export function createForgeResolver(options: CreateForgeResolverOptions = {}): ForgeResolver {
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
const create = options.createService ?? createForgeService;
const matchHost = options.matchHost ?? forgeForHost;
const probeForge = options.probeForge ?? probeRegisteredForgeHost;
const resolveSsh = options.resolveSshHostname ?? resolveSshHostname;
const now = options.now ?? Date.now;
@@ -110,22 +122,34 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
if (!entry) {
return undefined;
}
if (entry.expiresAt !== null && Date.now() >= entry.expiresAt) {
if (entry.expiresAt !== null && now() >= entry.expiresAt) {
probedForgeByHost.delete(host);
return undefined;
}
return entry.forge;
}
function buildResolution(forge: string, host: string): ForgeResolution | null {
let service = services.get(forge);
function getService(forge: string): ForgeService | null {
const normalized = forge.trim().toLowerCase();
if (!normalized) {
return null;
}
let service = services.get(normalized);
if (!service) {
const created = create(forge);
const created = create(normalized);
if (!created) {
return null;
}
service = created;
services.set(forge, service);
services.set(normalized, service);
}
return service;
}
function buildResolution(forge: string, host: string): ForgeResolution | null {
const service = getService(forge);
if (!service) {
return null;
}
return { forge, host, service };
}
@@ -151,7 +175,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
}
probedForgeByHost.set(host, {
forge: probed,
expiresAt: probed === null ? Date.now() + NEGATIVE_PROBE_TTL_MS : null,
expiresAt: probed === null ? now() + NEGATIVE_PROBE_TTL_MS : null,
});
return probed;
} finally {
@@ -170,13 +194,29 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
if (!host) {
return null;
}
const forge = forgeForHost(host) ?? readFreshProbe(host) ?? null;
const forge = matchHost(host) ?? readFreshProbe(host) ?? null;
if (!forge) {
return null;
}
return buildResolution(forge, host);
}
async function resolveHost(host: string): Promise<ForgeResolution | null> {
const normalized = normalizeHost(host);
if (!normalized) {
return null;
}
const directForge = matchHost(normalized);
if (directForge) {
return buildResolution(directForge, normalized);
}
const probed = await probeHostForge(normalized);
if (!probed) {
return null;
}
return buildResolution(probed, normalized);
}
async function resolveFromRemoteUrlAsync(
remoteUrl: string | null,
): Promise<ForgeResolution | null> {
@@ -187,7 +227,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
if (!location) {
return null;
}
const directForge = forgeForHost(location.host);
const directForge = matchHost(location.host);
if (directForge) {
return buildResolution(directForge, location.host);
}
@@ -215,7 +255,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
}
probedForgeByHost.set(aliasHost, {
forge,
expiresAt: forge === null ? Date.now() + NEGATIVE_PROBE_TTL_MS : null,
expiresAt: forge === null ? now() + NEGATIVE_PROBE_TTL_MS : null,
});
}
@@ -231,7 +271,7 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
return { host: location.host };
}
const resolvedForge = forgeForHost(resolvedHost);
const resolvedForge = matchHost(resolvedHost);
if (resolvedForge) {
return { host: resolvedHost, forge: resolvedForge };
}
@@ -246,10 +286,19 @@ export function createForgeResolver(options: CreateForgeResolverOptions = {}): F
}
}
function dispose(): void {
for (const service of services.values()) {
service.dispose?.();
}
}
return {
resolveFromRemoteUrl,
resolveFromRemoteUrlAsync,
resolveHost,
getService,
invalidate,
dispose,
async resolve(cwd: string): Promise<ForgeResolution | null> {
return resolveFromRemoteUrlAsync(await resolveRemoteUrlCached(cwd));
},
@@ -1,4 +1,5 @@
import type { ForgeSearchKind } from "@getpaseo/protocol/messages";
import type { ChangeRequestSource } from "./change-request-source.js";
export type ForgeSearchRequestKind = ForgeSearchKind | "github-issue" | "github-pr" | "pr";
@@ -533,6 +534,8 @@ export interface ForgeService {
onError?: (error: unknown) => void;
},
): { unsubscribe: () => void };
/** Exact-URL change request observation adapter for watches, when supported by the forge. */
changeRequests?: ChangeRequestSource;
invalidate(options: { cwd: string }): void;
dispose?(): void;
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,936 @@
import pLimit from "p-limit";
import { z } from "zod";
import { normalizeHost } from "@getpaseo/protocol/git-remote";
import {
ChangeRequestRateLimitError,
createPerHostChangeRequestPoller,
type PerHostReadContext,
parseCliHttpResponse,
parseRetryAfterMs,
} from "./change-request-poller.js";
import type { ChangeRequestSnapshot, ChangeRequestSource } from "./change-request-source.js";
import {
findTeaLoginNameForBaseUrl,
getGiteaActionTaskName,
GITEA_ACTION_MAX_PAGES,
GITEA_ACTION_PAGE_LIMIT,
GiteaActionsListResponseSchema,
GiteaCombinedCommitStatusSchema,
latestGiteaActionTasksByWorkflow,
parseGiteaActionTasks,
type GiteaActionTask,
type GiteaCommitStatus,
} from "./gitea-checks.js";
const GITEA_CLOUD_HOSTS = new Set(["gitea.com", "codeberg.org"]);
const GITEA_PR_TABS = new Set(["commits", "files", "checks"]);
const GITEA_PAGE_SIZE = GITEA_ACTION_PAGE_LIMIT;
const GITEA_REVIEW_COMMENT_CONCURRENCY = 3;
const GITEA_REVIEW_COMMENTS_TTL_MS = 5 * 60_000;
const GITEA_ACTION_RUN_LOOKUP_LIMIT = 5;
const checkUrlSchema = z.url({ protocol: /^https?$/ });
const giteaWatchPrSchema = z
.object({
number: z.number(),
state: z.string(),
merged: z.boolean().optional(),
merged_at: z.string().nullable().optional(),
html_url: z.string().optional(),
head: z
.object({
sha: z.string(),
})
.passthrough(),
})
.passthrough();
const giteaIssueCommentSchema = z
.object({
id: z.number(),
html_url: z.string().optional(),
type: z.string().optional(),
})
.passthrough();
const giteaReviewSchema = z
.object({
id: z.number(),
state: z.string(),
comments_count: z.number().optional().default(0),
submitted_at: z.string().nullable().optional(),
updated_at: z.string().nullable().optional(),
html_url: z.string().optional(),
})
.passthrough();
const giteaReviewCommentSchema = z
.object({
id: z.number(),
html_url: z.string().optional(),
})
.passthrough();
const giteaActionJobSchema = z.object({
id: z.number(),
name: z.string(),
status: z.string(),
conclusion: z.string().nullable().optional(),
html_url: z.string().nullable().optional(),
});
const giteaActionJobsPageSchema = z.union([
z.object({
jobs: z
.array(giteaActionJobSchema)
.nullable()
.transform((jobs) => jobs ?? []),
total_count: z.number(),
}),
// Forgejo returns the complete job list as an array.
z.array(giteaActionJobSchema),
]);
type GiteaActionJob = z.infer<typeof giteaActionJobSchema>;
type GiteaWatchPr = z.infer<typeof giteaWatchPrSchema>;
type GiteaReview = z.infer<typeof giteaReviewSchema>;
interface GiteaPullRequestIdentity {
baseUrl: string;
displayBase: string | null;
owner: string;
repo: string;
number: number;
}
function invalidGiteaUrl(): never {
throw new Error("Enter a Gitea, Forgejo, or Codeberg pull request URL.");
}
function parseGiteaUrlOrigin(input: string): {
protocol: "http:" | "https:";
host: string;
port: string;
hostWithPort: string;
pathname: string;
} {
const trimmed = input.trim();
if (!trimmed || /\s/.test(trimmed)) invalidGiteaUrl();
let parsed: URL;
try {
parsed = new URL(trimmed);
} catch {
invalidGiteaUrl();
}
const protocol = parsed.protocol.toLowerCase();
if ((protocol !== "https:" && protocol !== "http:") || parsed.username || parsed.password) {
invalidGiteaUrl();
}
const host = normalizeHost(parsed.hostname);
if (!host || (GITEA_CLOUD_HOSTS.has(host) && protocol !== "https:")) {
invalidGiteaUrl();
}
return {
protocol: protocol as "http:" | "https:",
host,
port: parsed.port,
hostWithPort: parsed.port ? `${host}:${parsed.port}` : host,
pathname: parsed.pathname,
};
}
function decodeRepoSegment(raw: string): string {
let decoded: string;
try {
decoded = decodeURIComponent(raw);
} catch {
invalidGiteaUrl();
}
if (
!decoded ||
decoded === "." ||
decoded === ".." ||
decoded.includes("/") ||
decoded.includes("\\")
) {
invalidGiteaUrl();
}
return decoded;
}
function parseGiteaPullRequestUrl(input: string): GiteaPullRequestIdentity {
const origin = parseGiteaUrlOrigin(input);
const segments = origin.pathname.split("/").filter(Boolean);
if (
segments.length >= 5 &&
GITEA_PR_TABS.has(segments.at(-1)!.toLowerCase()) &&
/^\d+$/.test(segments.at(-2)!)
) {
segments.pop();
}
const rawNumber = segments.pop();
const number = Number(rawNumber);
const resource = segments.pop();
const repo = segments.pop();
const owner = segments.pop();
if (
resource?.toLowerCase() !== "pulls" ||
!owner ||
!repo ||
!rawNumber ||
!/^\d+$/.test(rawNumber) ||
!Number.isInteger(number) ||
number < 1 ||
number > 2_147_483_647
) {
invalidGiteaUrl();
}
const path = segments.length ? `/${segments.join("/")}` : "";
const displayBase =
!path && !origin.port && GITEA_CLOUD_HOSTS.has(origin.host)
? null
: `${origin.hostWithPort}${path}`;
return {
baseUrl: `${origin.protocol}//${origin.hostWithPort}${path}`,
displayBase,
owner: decodeRepoSegment(owner),
repo: decodeRepoSegment(repo),
number,
};
}
export function resolveGiteaChangeRequest(input: string): string {
const { baseUrl, owner, repo, number } = parseGiteaPullRequestUrl(input);
return `${baseUrl}/${owner.toLowerCase()}/${repo.toLowerCase()}/pulls/${number}`;
}
export function describeGiteaChangeRequest(url: string): string {
const { displayBase, owner, repo, number } = parseGiteaPullRequestUrl(url);
const project = displayBase ? `${displayBase}/${owner}/${repo}` : `${owner}/${repo}`;
return `${project} #${number}`;
}
function mapGiteaPrState(pr: GiteaWatchPr): ChangeRequestSnapshot["state"] {
if (pr.merged === true || pr.merged_at != null) return "merged";
const normalized = pr.state.toLowerCase();
if (normalized === "open") return "open";
if (normalized === "merged") return "merged";
return "closed";
}
function mapCommitStatusToWatchState(
status: string,
): ChangeRequestSnapshot["checks"][number]["state"] {
switch (status.toLowerCase()) {
case "success":
return "passed";
case "failure":
case "error":
case "warning":
return "failed";
case "pending":
case "running":
return "pending";
default:
return "neutral";
}
}
function isCanceledActionStatus(status: GiteaCommitStatus): boolean {
// Actions writes a generic failure state on cancellation, with a distinct
// description in the native job's commit status.
const description = status.description ?? "";
return description === "Has been cancelled" || description.startsWith("Canceled after ");
}
function mapActionTaskToWatchState(
status: string,
): ChangeRequestSnapshot["checks"][number]["state"] {
switch (status.toLowerCase()) {
case "success":
return "passed";
case "failure":
case "failed":
case "error":
return "failed";
case "cancelled":
case "canceled":
case "skipped":
return "neutral";
default:
return "pending";
}
}
function computeAggregateChecksState(
checks: ChangeRequestSnapshot["checks"],
): ChangeRequestSnapshot["checksState"] {
if (checks.length === 0) return "neutral";
if (checks.some((check) => check.state === "failed")) return "failed";
if (checks.some((check) => check.state === "pending")) return "pending";
if (checks.some((check) => check.state === "passed")) return "passed";
return "neutral";
}
function nativeActionUrl(value: string | null | undefined, origin: string) {
if (!value) return null;
try {
const url = new URL(value, origin);
if (url.origin !== origin) return null;
const match = /^(.*\/actions\/runs\/(\d+))(\/jobs\/\d+)?\/?$/.exec(url.pathname);
if (!match) return null;
const [, run, runId, job] = match;
return { run: run!, runId: runId!, jobUrl: job ? `${origin}${run}${job}` : null };
} catch {
return null;
}
}
function combineWatchChecks(
commitStatuses: GiteaCommitStatus[],
actionTasks: GiteaActionTask[],
jobsByRun: ReadonlyMap<string, GiteaActionJob[]>,
origin: string,
): ChangeRequestSnapshot["checks"] {
const checks: ChangeRequestSnapshot["checks"] = [];
const actionJobs = [...jobsByRun.values()].flat();
const coveredJobUrls = new Set(
actionJobs.map((job) => nativeActionUrl(job.html_url, origin)?.jobUrl),
);
for (const status of commitStatuses) {
const jobUrl = nativeActionUrl(status.target_url, origin)?.jobUrl;
if (jobUrl && coveredJobUrls.has(jobUrl)) continue;
const url = checkUrlSchema.safeParse(status.target_url).data;
checks.push({
id: `status:${status.id}`,
name: status.context || `status-${status.id}`,
state:
jobUrl && isCanceledActionStatus(status)
? "neutral"
: mapCommitStatusToWatchState(status.status),
...(url ? { url } : {}),
});
}
for (const job of actionJobs) {
const url = checkUrlSchema.safeParse(job.html_url).data;
checks.push({
id: `action-job:${job.id}`,
name: job.name,
state: mapActionTaskToWatchState(job.conclusion || job.status),
...(url ? { url } : {}),
});
}
const seenTaskIds = new Set<number>();
for (const task of actionTasks) {
if (seenTaskIds.has(task.id)) continue;
const address = nativeActionUrl(task.url, origin);
if (address && jobsByRun.has(address.run)) continue;
seenTaskIds.add(task.id);
const url = checkUrlSchema.safeParse(task.url).data;
checks.push({
id: `action:${task.id}`,
name: getGiteaActionTaskName(task),
state: mapActionTaskToWatchState(task.status),
...(url ? { url } : {}),
});
}
return checks;
}
function hasNextLinkHeader(headers: ReadonlyMap<string, string>): boolean {
const link = headers.get("link");
return link ? /rel=["']?next["']?/i.test(link) : false;
}
function parseTotalCountHeader(headers: ReadonlyMap<string, string>): number | null {
const raw = headers.get("x-total-count");
if (!raw) return null;
const parsed = Number(raw);
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
}
function isSubmittedGiteaReview(review: GiteaReview): boolean {
const state = review.state.trim().toUpperCase();
return state !== "PENDING" && state !== "REQUEST_REVIEW";
}
function parseTeaHttpStreams(
stdout: string,
stderr: string,
): {
status: number | null;
headers: Map<string, string>;
body: string;
} {
const fromStdout = parseCliHttpResponse(stdout);
if (fromStdout.status !== null) {
return fromStdout;
}
const fromStderr = parseCliHttpResponse(stderr);
if (fromStderr.status !== null) {
return { status: fromStderr.status, headers: fromStderr.headers, body: stdout.trim() };
}
return { status: null, headers: new Map(), body: stdout.trim() };
}
class TeaHttpStatusError extends Error {
readonly status: number;
constructor(status: number, message: string) {
super(message);
this.name = "TeaHttpStatusError";
this.status = status;
}
}
function isOptionalEndpointStatus(error: unknown): boolean {
return (
error instanceof TeaHttpStatusError &&
(error.status === 403 || error.status === 404 || error.status === 501)
);
}
type TeaApiGet = <T>(
endpoint: string,
schema: z.ZodType<T>,
) => Promise<{ data: T; headers: ReadonlyMap<string, string> }>;
interface TeaPollApi {
get: TeaApiGet;
all<T extends readonly unknown[]>(
reads: T,
): Promise<{ -readonly [Key in keyof T]: Awaited<T[Key]> }>;
}
interface CachedReviewComments {
count: number;
fetchedAt: number;
items: ChangeRequestSnapshot["activity"];
}
export interface CreateGiteaChangeRequestSourceOptions {
runCommand(
args: string[],
options: { cwd: string; envOverlay?: Record<string, string> },
): Promise<{ stdout: string; stderr: string }>;
createAuthError(stderr: string): Error;
createCommandError(params: {
args: string[];
cwd: string;
exitCode: number | null;
stderr: string;
stdout?: string;
}): Error;
now?: () => number;
pollIntervalMs?: number;
initialDelayMs?: number;
}
export function createGiteaChangeRequestSource(
options: CreateGiteaChangeRequestSourceOptions,
): ChangeRequestSource & { dispose(): void } {
const now = options.now ?? Date.now;
const cachedReviewCommentsByUrl = new Map<string, Map<number, CachedReviewComments>>();
const reviewCommentLimit = pLimit(GITEA_REVIEW_COMMENT_CONCURRENCY);
async function resolveLogin(baseUrl: string): Promise<string> {
const result = await options.runCommand(["login", "list", "-o", "json"], {
cwd: process.cwd(),
});
const loginName = findTeaLoginNameForBaseUrl(result.stdout, baseUrl);
if (!loginName) {
throw options.createAuthError(`No tea login configured for ${baseUrl}`);
}
return loginName;
}
function parseJsonBody<T>(params: {
args: string[];
cwd: string;
body: string;
schema: z.ZodType<T>;
}): T {
let data: unknown;
try {
data = JSON.parse(params.body);
} catch {
throw options.createCommandError({
args: params.args,
cwd: params.cwd,
exitCode: null,
stderr: `tea did not return valid JSON (${params.body.length} bytes)`,
});
}
const parsed = params.schema.safeParse(data);
if (!parsed.success) {
throw options.createCommandError({
args: params.args,
cwd: params.cwd,
exitCode: null,
stderr: `tea JSON did not match the expected schema: ${parsed.error.message}`,
});
}
return parsed.data;
}
function bindTeaApi(context: PerHostReadContext, loginName: string): TeaPollApi {
let active = true;
const get: TeaApiGet = async (endpoint, schema) => {
if (!active || !context.isObserved()) throw new Error("Change request observation ended");
context.assertHostAvailable();
const args = ["api", "--login", loginName, "-i", endpoint];
const cwd = process.cwd();
const result = await options.runCommand(args, { cwd });
const parsed = parseTeaHttpStreams(result.stdout, result.stderr);
const nowMs = now();
// tea api can exit 0 on an HTTP failure, so always check the status line.
if (parsed.status === null) {
throw options.createCommandError({
args,
cwd,
exitCode: 0,
stderr: "tea api -i did not return an HTTP status line",
stdout: result.stdout,
});
}
if (parsed.status === 429) {
const resetAtMs = parseRetryAfterMs(parsed.headers, nowMs, {
forceOnMissing: true,
defaultPauseMs: 60_000,
})!;
context.pauseHost(resetAtMs);
throw new ChangeRequestRateLimitError({ host: context.host, resetAtMs });
}
if (parsed.status === 401) {
throw options.createAuthError(parsed.body || "401 Unauthorized");
}
if (parsed.status < 200 || parsed.status >= 300) {
throw new TeaHttpStatusError(
parsed.status,
`Gitea API returned HTTP ${parsed.status} for ${endpoint}: ${parsed.body}`.trim(),
);
}
const proactivePause = parseRetryAfterMs(parsed.headers, nowMs);
if (proactivePause !== null) context.deferPollsUntil(proactivePause);
const data = parseJsonBody({ args, cwd, body: parsed.body, schema });
return { data, headers: parsed.headers };
};
return {
get,
all(reads) {
return Promise.all(reads).catch(async (error: unknown) => {
// Stop admitting reads from this poll and hold its host slot until
// requests already sent (including late rate limits) settle.
active = false;
await Promise.allSettled(reads);
throw error;
});
},
};
}
async function teaApiGetAllPages<T>(params: {
get: TeaApiGet;
endpoint: string;
itemSchema: z.ZodType<T>;
}): Promise<T[]> {
const items: T[] = [];
const schema = z.array(params.itemSchema);
let minPageSize = 1;
for (let page = 1; ; page += 1) {
const sep = params.endpoint.includes("?") ? "&" : "?";
const { data, headers } = await params.get(
`${params.endpoint}${sep}page=${page}&limit=${GITEA_PAGE_SIZE}`,
schema,
);
items.push(...data);
if (headers.has("link")) {
if (hasNextLinkHeader(headers)) continue;
break;
}
const totalCount = parseTotalCountHeader(headers);
if (totalCount !== null) {
// Gitea can cap limit below the requested value and filter pending
// reviews after pagination. The largest page is a lower bound on
// the number of records advanced on every page.
minPageSize = Math.max(minPageSize, data.length);
if (page * minPageSize < totalCount) continue;
break;
}
if (data.length < GITEA_PAGE_SIZE) break;
}
return items;
}
async function readCommitStatuses(params: {
get: TeaApiGet;
repoPrefix: string;
headSha: string;
isObserved(): boolean;
}): Promise<{ statuses: GiteaCommitStatus[]; pagesRead: number }> {
const statuses: GiteaCommitStatus[] = [];
const seenIds = new Set<number>();
let page = 1;
let pagesRead = 0;
while (true) {
if (!params.isObserved()) return { statuses, pagesRead };
const response = await params.get(
`${params.repoPrefix}/commits/${encodeURIComponent(params.headSha)}/status?limit=${GITEA_PAGE_SIZE}&page=${page}`,
GiteaCombinedCommitStatusSchema,
);
pagesRead += 1;
const pageStatuses = response.data.statuses;
if (pageStatuses.length === 0) break;
for (const status of pageStatuses) {
if (seenIds.has(status.id)) {
throw new Error("Gitea commit status pages overlap. Retry the poll.");
}
seenIds.add(status.id);
statuses.push(status);
}
// Gitea sets body `total_count` to the current page length; the full total
// lives only in the `X-Total-Count` response header.
const headerTotal = parseTotalCountHeader(response.headers);
if (headerTotal !== null) {
if (statuses.length >= headerTotal) break;
page += 1;
continue;
}
if (hasNextLinkHeader(response.headers) || pageStatuses.length >= GITEA_PAGE_SIZE) {
page += 1;
continue;
}
break;
}
return { statuses, pagesRead };
}
async function readBoundedActionTasks(params: {
get: TeaApiGet;
repoPrefix: string;
isObserved(): boolean;
}): Promise<{ items: unknown[]; pagesRead: number }> {
const items: unknown[] = [];
let fetched = 0;
let pagesRead = 0;
for (let page = 1; page <= GITEA_ACTION_MAX_PAGES; page += 1) {
if (!params.isObserved()) return { items, pagesRead };
let response: { data: z.infer<typeof GiteaActionsListResponseSchema> };
try {
response = await params.get(
`${params.repoPrefix}/actions/tasks?limit=${GITEA_PAGE_SIZE}&page=${page}`,
GiteaActionsListResponseSchema,
);
} catch (error) {
if (page === 1 && isOptionalEndpointStatus(error)) {
return { items: [], pagesRead: 0 };
}
throw error;
}
pagesRead += 1;
const runs = response.data.workflow_runs;
if (runs.length === 0) break;
fetched += runs.length;
items.push(...runs);
if (response.data.total_count !== undefined && fetched >= response.data.total_count) break;
}
return { items, pagesRead };
}
async function readActionJobs(params: {
get: TeaApiGet;
origin: string;
repoPrefix: string;
tasks: GiteaActionTask[];
statuses: GiteaCommitStatus[];
}): Promise<Map<string, GiteaActionJob[]>> {
// Commit statuses identify a job URL. Tasks identify a run, so only a job
// list can establish coverage when both sources report the same run.
const statusRuns = new Set<string>();
for (const status of params.statuses) {
const address = nativeActionUrl(status.target_url, params.origin);
if (address?.jobUrl) statusRuns.add(address.run);
}
const runs = new Map<string, string>();
for (const task of params.tasks) {
const address = nativeActionUrl(task.url, params.origin);
if (address && statusRuns.has(address.run)) runs.set(address.run, address.runId);
}
const jobsByRun = new Map<string, GiteaActionJob[]>();
for (const [run, runId] of [...runs].slice(0, GITEA_ACTION_RUN_LOOKUP_LIMIT)) {
const endpoint = `${params.repoPrefix}/actions/runs/${runId}/jobs`;
const jobs = new Map<number, GiteaActionJob>();
for (let page = 1; page <= GITEA_ACTION_MAX_PAGES; page += 1) {
try {
const { data } = await params.get(
`${endpoint}?limit=${GITEA_PAGE_SIZE}&page=${page}`,
giteaActionJobsPageSchema,
);
const items = Array.isArray(data) ? data : data.jobs;
const totalCount = Array.isArray(data) ? data.length : data.total_count;
if (!items.length) break;
// The browser run number and API ID differ on some versions. Keep
// the original sources if any job belongs to another run.
if (items.some((job) => nativeActionUrl(job.html_url, params.origin)?.run !== run)) {
break;
}
for (const job of items) jobs.set(job.id, job);
if (jobs.size >= totalCount) {
jobsByRun.set(run, [...jobs.values()]);
break;
}
} catch (error) {
if (page === 1 && isOptionalEndpointStatus(error)) break;
throw error;
}
}
}
return jobsByRun;
}
async function readChecks(params: {
api: TeaPollApi;
origin: string;
repoPrefix: string;
prEndpoint: string;
headSha: string;
isObserved(): boolean;
}): Promise<ChangeRequestSnapshot["checks"]> {
const { get, all } = params.api;
const [statusResult, tasksResult] = await all([
readCommitStatuses({ ...params, get }),
readBoundedActionTasks({ ...params, get }),
]);
if (!params.isObserved()) {
throw new Error("Change request observation ended");
}
const matchingTasks = parseGiteaActionTasks(tasksResult.items).filter(
(task) => task.head_sha === params.headSha,
);
const latestTasks = latestGiteaActionTasksByWorkflow(matchingTasks);
const jobsByRun = await readActionJobs({
...params,
get,
tasks: latestTasks,
statuses: statusResult.statuses,
});
if (statusResult.pagesRead > 1 || tasksResult.pagesRead > 1 || jobsByRun.size > 0) {
const { data: recheck } = await get(params.prEndpoint, giteaWatchPrSchema);
if (recheck.head.sha !== params.headSha) {
throw new Error("The pull request head changed during pagination.");
}
}
return combineWatchChecks(statusResult.statuses, latestTasks, jobsByRun, params.origin);
}
async function readActivity(params: {
url: string;
api: TeaPollApi;
repoPrefix: string;
number: number;
prWebUrl: string;
terminal: boolean;
knownActivity(): ReadonlySet<string> | undefined;
isObserved(): boolean;
}): Promise<ChangeRequestSnapshot["activity"]> {
const { get, all } = params.api;
const [comments, reviews] = await all([
teaApiGetAllPages({
get,
endpoint: `${params.repoPrefix}/issues/${params.number}/comments`,
itemSchema: giteaIssueCommentSchema,
}),
teaApiGetAllPages({
get,
endpoint: `${params.repoPrefix}/pulls/${params.number}/reviews`,
itemSchema: giteaReviewSchema,
}),
]);
if (!params.isObserved()) {
throw new Error("Change request observation ended");
}
const activity: ChangeRequestSnapshot["activity"] = [];
for (const comment of comments) {
if (comment.type !== undefined && comment.type !== "comment") continue;
activity.push({
id: `comment:${comment.id}`,
kind: "comment",
url: comment.html_url || `${params.prWebUrl}#issuecomment-${comment.id}`,
});
}
const submittedReviews = reviews.filter(isSubmittedGiteaReview);
for (const review of submittedReviews) {
activity.push({
id: `review:${review.id}`,
kind: "review",
url: review.html_url || `${params.prWebUrl}#pullrequestreview-${review.id}`,
});
}
const known = params.knownActivity();
let reviewCache = cachedReviewCommentsByUrl.get(params.url);
if (!reviewCache) {
reviewCache = new Map<number, CachedReviewComments>();
cachedReviewCommentsByUrl.set(params.url, reviewCache);
}
const staleBefore = now() - GITEA_REVIEW_COMMENTS_TTL_MS;
const reviewsNeedingFetch = submittedReviews.filter((review) => {
if (review.comments_count <= 0) return false;
const cached = reviewCache.get(review.id);
if (
!params.terminal &&
cached &&
cached.fetchedAt > staleBefore &&
cached.count === review.comments_count &&
cached.items.every((item) => known?.has(item.id))
) {
return false;
}
return true;
});
// Gitea's review-comments endpoint returns all comments for a review in one
// response and ignores page/limit, so fetch it once without a pagination loop.
const fetchedGroups = await all(
reviewsNeedingFetch.map((review) =>
reviewCommentLimit(async () => {
if (!params.isObserved()) {
return { reviewId: review.id, count: review.comments_count, items: [] };
}
const { data: inlineComments } = await get(
`${params.repoPrefix}/pulls/${params.number}/reviews/${review.id}/comments`,
z.array(giteaReviewCommentSchema),
);
const items: ChangeRequestSnapshot["activity"] = inlineComments.map((comment) => ({
id: `inline:${comment.id}`,
kind: "inline comment",
url: comment.html_url || `${params.prWebUrl}#issuecomment-${comment.id}`,
}));
return { reviewId: review.id, count: review.comments_count, items };
}),
),
);
if (!params.isObserved()) {
throw new Error("Change request observation ended");
}
const fetchedAt = now();
for (const group of fetchedGroups) {
reviewCache.set(group.reviewId, { count: group.count, fetchedAt, items: group.items });
}
for (const review of submittedReviews) {
if (review.comments_count <= 0) continue;
const cached = reviewCache.get(review.id);
if (cached) {
activity.push(...cached.items);
}
}
return activity;
}
async function readPullRequest(context: PerHostReadContext): Promise<ChangeRequestSnapshot> {
const identity = parseGiteaPullRequestUrl(context.url);
const { baseUrl, owner, repo, number } = identity;
const loginName = await resolveLogin(baseUrl);
const api = bindTeaApi(context, loginName);
const repoPrefix = `repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}`;
const prEndpoint = `${repoPrefix}/pulls/${number}`;
const { data: pr } = await api.get(prEndpoint, giteaWatchPrSchema);
if (!pr.head.sha) {
throw new Error(`Gitea pull request #${number} did not include a head commit SHA.`);
}
const prWebUrl = pr.html_url || context.url;
const address = parseGiteaPullRequestUrl(prWebUrl);
if (
address.baseUrl !== baseUrl ||
address.owner.toLowerCase() !== owner.toLowerCase() ||
address.repo.toLowerCase() !== repo.toLowerCase() ||
address.number !== number ||
pr.number !== number
) {
throw new Error("Tea returned a pull request that does not match the watch URL.");
}
const checks = await readChecks({
api,
origin: context.host,
repoPrefix,
prEndpoint,
headSha: pr.head.sha,
isObserved: context.isObserved,
});
const state = mapGiteaPrState(pr);
const activity = await readActivity({
url: context.url,
api,
repoPrefix,
number,
prWebUrl,
terminal: state !== "open",
knownActivity: context.knownActivity,
isObserved: context.isObserved,
});
return {
state,
headSha: pr.head.sha,
checksState: computeAggregateChecksState(checks),
checks,
reviewDecision: null,
activity,
};
}
const poller = createPerHostChangeRequestPoller({
hostOf: (url) => new URL(url).origin,
read: readPullRequest,
now,
pollIntervalMs: options.pollIntervalMs,
initialDelayMs: options.initialDelayMs,
});
return {
resolve: resolveGiteaChangeRequest,
describe: describeGiteaChangeRequest,
observe(url, callbacks) {
const release = poller.observe(url, callbacks);
return () => {
cachedReviewCommentsByUrl.delete(url);
release();
};
},
dispose() {
cachedReviewCommentsByUrl.clear();
poller.dispose();
},
};
}
@@ -0,0 +1,253 @@
import { z } from "zod";
import { normalizeHost } from "@getpaseo/protocol/git-remote";
// 50 is the page-size cap Gitea enforces on list endpoints; five pages bounds
// the sweep to the 250 most recent Actions tasks.
export const GITEA_ACTION_PAGE_LIMIT = 50;
export const GITEA_ACTION_MAX_PAGES = 5;
const GITEA_RELATIVE_URL_ORIGIN = "https://gitea.invalid";
export const GiteaLoginSchema = z
.object({
name: z.string().optional(),
url: z.string().optional(),
ssh_host: z.string().optional(),
})
.passthrough();
export const GiteaCommitStatusSchema = z
.object({
id: z.number(),
status: z.string(),
target_url: z.string().nullable().optional(),
description: z.string().nullable().optional(),
url: z.string().nullable().optional(),
context: z.string().optional().default(""),
creator: z.unknown().nullable().optional(),
})
.passthrough();
export const GiteaCombinedCommitStatusSchema = z
.object({
state: z.string().optional().default(""),
sha: z.string().optional(),
total_count: z.number().optional(),
statuses: z
.array(GiteaCommitStatusSchema)
.nullable()
.optional()
.transform((value) => value ?? []),
})
.passthrough();
export const GiteaActionTaskSchema = z
.object({
id: z.number(),
name: z.string().nullable().optional(),
head_branch: z.string().nullable().optional(),
head_sha: z.string(),
run_number: z.number().optional(),
event: z.string().nullable().optional(),
display_title: z.string().nullable().optional(),
status: z.string(),
need_approval: z.boolean().optional().default(false),
workflow_id: z.string().nullable().optional(),
url: z.string().nullable().optional(),
created_at: z.string().nullable().optional(),
run_started_at: z.string().nullable().optional(),
})
.passthrough();
// The item shape is validated per-task rather than as `z.array(GiteaActionTaskSchema)`
// so one malformed task (missing id/status/head_sha) drops only itself instead of
// throwing out the whole page and zeroing every Actions check for the PR.
export const GiteaActionsListResponseSchema = z
.object({
workflow_runs: z
.array(z.unknown())
.nullable()
.optional()
.transform((value) => value ?? []),
total_count: z.number().optional(),
})
.passthrough();
export type GiteaCommitStatus = z.infer<typeof GiteaCommitStatusSchema>;
export type GiteaCombinedCommitStatus = z.infer<typeof GiteaCombinedCommitStatusSchema>;
export type GiteaActionTask = z.infer<typeof GiteaActionTaskSchema>;
export function getGiteaActionTaskName(task: GiteaActionTask): string {
return task.name || task.display_title || task.workflow_id || `actions-${task.id}`;
}
export function getUrlOrigin(value: string | null | undefined): string | null {
if (!value) return null;
try {
return new URL(value).origin;
} catch {
return null;
}
}
export function getGiteaActionRunIdFromUrl(value: string | null | undefined): number | null {
if (!value) return null;
try {
const url = new URL(value, GITEA_RELATIVE_URL_ORIGIN);
const match = url.pathname.match(/\/actions\/runs\/(\d+)(?:\/jobs\/\d+)?\/?$/);
return match?.[1] ? Number.parseInt(match[1], 10) : null;
} catch {
return null;
}
}
function isNativeActionJobUrl(
targetUrl: string | null | undefined,
nativeOrigins: ReadonlySet<string>,
nativeRunIds: ReadonlySet<number>,
): boolean {
if (!targetUrl) return false;
try {
const url = new URL(targetUrl, GITEA_RELATIVE_URL_ORIGIN);
if (!/\/actions\/runs\/\d+\/jobs\/\d+\/?$/.test(url.pathname)) return false;
if (url.origin !== GITEA_RELATIVE_URL_ORIGIN && !nativeOrigins.has(url.origin)) return false;
const runId = getGiteaActionRunIdFromUrl(targetUrl);
return runId !== null && nativeRunIds.has(runId);
} catch {
return false;
}
}
// A "shadow" is the commit status Gitea synthesizes to mirror one of its own
// Actions jobs; keeping both would double-report every job. Detection is purely
// structural: Gitea always creates these statuses with a target_url of the form
// "<run link>/jobs/<job id>" (services/actions/commit_status.go upstream), so a
// status is a shadow exactly when its URL points at a job of a run we actually
// fetched from the Actions API. Anything else - external CI, URL-less statuses,
// contexts that merely look like "<workflow> / <job> (<event>)" - is kept.
export function isGiteaActionShadowStatus(
status: GiteaCommitStatus,
nativeOrigins: ReadonlySet<string>,
nativeRunIds: ReadonlySet<number>,
): boolean {
return isNativeActionJobUrl(status.target_url, nativeOrigins, nativeRunIds);
}
function getGiteaActionWorkflowIdentity(task: GiteaActionTask): string {
if (task.workflow_id) {
return `workflow\u0000${task.workflow_id}`;
}
// Instances that omit workflow_id (older Gitea/Forgejo payloads) still need
// reruns of the same job collapsed to the latest execution, so fall back to
// the job name before treating the task as its own group.
const name = task.name || task.display_title;
if (name) {
return `name\u0000${name}`;
}
return `task\u0000${getGiteaActionExecutionIdentity(task)}`;
}
function getGiteaActionExecutionIdentity(task: GiteaActionTask): string {
if (task.run_number !== undefined) return `run-number\u0000${task.run_number}`;
const runId = getGiteaActionRunIdFromUrl(task.url);
if (runId !== null) return `run-id\u0000${runId}`;
if (task.url) return `url\u0000${task.url}`;
return `task\u0000${task.id}`;
}
function parseGiteaActionTaskTime(task: GiteaActionTask): number {
const timestamp = task.created_at ?? task.run_started_at ?? null;
if (!timestamp) {
return 0;
}
const time = Date.parse(timestamp);
return Number.isNaN(time) ? 0 : time;
}
function compareGiteaActionTaskRecency(left: GiteaActionTask, right: GiteaActionTask): number {
const leftRunNumber = left.run_number ?? 0;
const rightRunNumber = right.run_number ?? 0;
if (leftRunNumber !== rightRunNumber) {
return leftRunNumber - rightRunNumber;
}
const leftTime = parseGiteaActionTaskTime(left);
const rightTime = parseGiteaActionTaskTime(right);
if (leftTime !== rightTime) {
return leftTime - rightTime;
}
return left.id - right.id;
}
export function parseGiteaActionTasks(rawTasks: unknown[]): GiteaActionTask[] {
const tasks: GiteaActionTask[] = [];
for (const raw of rawTasks) {
const parsed = GiteaActionTaskSchema.safeParse(raw);
if (parsed.success) {
tasks.push(parsed.data);
}
}
return tasks;
}
/**
* Keep all sibling tasks from the latest execution of each workflow.
* Per docs/forge-providers.md, ambiguous same-run tasks are preserved because
* display names are not stable job identities and `/actions/tasks` omits rerun
* attempt numbers.
*/
export function latestGiteaActionTasksByWorkflow(tasks: GiteaActionTask[]): GiteaActionTask[] {
const latestExecutions = new Map<string, GiteaActionTask>();
for (const task of tasks) {
const identity = getGiteaActionWorkflowIdentity(task);
const current = latestExecutions.get(identity);
if (!current || compareGiteaActionTaskRecency(current, task) < 0) {
latestExecutions.set(identity, task);
}
}
return tasks.filter((task) => {
const latest = latestExecutions.get(getGiteaActionWorkflowIdentity(task));
return (
latest !== undefined &&
getGiteaActionExecutionIdentity(task) === getGiteaActionExecutionIdentity(latest)
);
});
}
function parseTeaLogins(stdout: string): z.infer<typeof GiteaLoginSchema>[] {
try {
return z.array(GiteaLoginSchema).safeParse(JSON.parse(stdout)).data ?? [];
} catch {
return [];
}
}
export function findTeaLoginNameForBaseUrl(stdout: string, baseUrl: string): string | null {
const match = parseTeaLogins(stdout).find((login) => {
if (!login.name || !login.url) return false;
try {
const url = new URL(login.url);
return `${url.origin}${url.pathname.replace(/\/+$/, "")}` === baseUrl;
} catch {
return false;
}
});
return match?.name ?? null;
}
export function findTeaLoginNameForHost(stdout: string, host: string): string | null {
const targetHost = normalizeHost(host);
const match = parseTeaLogins(stdout).find((login) => {
const candidates = [login.ssh_host, login.name];
if (login.url) {
try {
candidates.push(new URL(login.url).hostname);
} catch {
// ignore malformed login url
}
}
return candidates.some((candidate) => candidate && normalizeHost(candidate) === targetHost);
});
return match?.name ?? null;
}
+44 -227
View File
@@ -61,6 +61,23 @@ import type {
SearchIssuesAndPrsOptions,
SearchResult,
} from "./forge-service.js";
import {
findTeaLoginNameForHost,
getGiteaActionRunIdFromUrl,
getGiteaActionTaskName,
getUrlOrigin,
GITEA_ACTION_MAX_PAGES,
GITEA_ACTION_PAGE_LIMIT,
GiteaActionsListResponseSchema,
GiteaCombinedCommitStatusSchema,
isGiteaActionShadowStatus,
latestGiteaActionTasksByWorkflow,
parseGiteaActionTasks,
type GiteaActionTask,
type GiteaCombinedCommitStatus,
type GiteaCommitStatus,
} from "./gitea-checks.js";
import { createGiteaChangeRequestSource } from "./gitea-change-requests.js";
import { isGiteaStatusFacts, type GiteaStatusFacts } from "./gitea-facts.js";
const TEA_ENV = {
@@ -77,10 +94,6 @@ const reviewCommentsLimit = pLimit(REVIEW_COMMENTS_FAN_OUT_CONCURRENCY);
// short cache, each poll re-derives the PR head SHA from scratch (branch name +
// PR lookup + PR view). The TTL keeps a new push visible within one poll cycle.
const CURRENT_PR_HEAD_SHA_CACHE_TTL_MS = 30_000;
// 50 is the page-size cap Gitea enforces on list endpoints; five pages bounds
// the sweep to the 250 most recent Actions tasks.
const GITEA_ACTION_PAGE_LIMIT = 50;
const GITEA_ACTION_MAX_PAGES = 5;
// PullRequestFlowAGit in forgejo models/issues/pull.go
const GITEA_PULL_REQUEST_FLOW_AGIT = 1;
@@ -142,6 +155,8 @@ export interface CreateGiteaServiceOptions {
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
resolveCurrentBranch?: (cwd: string) => Promise<string | null>;
now?: () => number;
watchPollMs?: number;
watchInitialDelayMs?: number;
}
/**
@@ -180,14 +195,6 @@ const GiteaIssueListItemSchema = z
})
.passthrough();
const GiteaLoginSchema = z
.object({
name: z.string().optional(),
url: z.string().optional(),
ssh_host: z.string().optional(),
})
.passthrough();
const GiteaUserSchema = z
.object({
login: z.string().optional(),
@@ -288,55 +295,6 @@ const GiteaCurrentPullRequestApiSchema = z
})
.passthrough();
const GiteaCommitStatusSchema = z
.object({
id: z.number(),
status: z.string(),
target_url: z.string().nullable().optional(),
description: z.string().nullable().optional(),
url: z.string().nullable().optional(),
context: z.string().optional().default(""),
creator: z.unknown().nullable().optional(),
})
.passthrough();
const GiteaCombinedCommitStatusSchema = z
.object({
state: z.string().optional().default(""),
sha: z.string().optional(),
total_count: z.number().optional(),
statuses: z.array(GiteaCommitStatusSchema).optional().default([]),
})
.passthrough();
const GiteaActionTaskSchema = z
.object({
id: z.number(),
name: z.string().nullable().optional(),
head_branch: z.string().nullable().optional(),
head_sha: z.string(),
run_number: z.number().optional(),
event: z.string().nullable().optional(),
display_title: z.string().nullable().optional(),
status: z.string(),
need_approval: z.boolean().optional().default(false),
workflow_id: z.string().nullable().optional(),
url: z.string().nullable().optional(),
created_at: z.string().nullable().optional(),
run_started_at: z.string().nullable().optional(),
})
.passthrough();
// The item shape is validated per-task rather than as `z.array(GiteaActionTaskSchema)`
// so one malformed task (missing id/status/head_sha) drops only itself instead of
// throwing out the whole page and zeroing every Actions check for the PR.
const GiteaActionsListResponseSchema = z
.object({
workflow_runs: z.array(z.unknown()).optional().default([]),
total_count: z.number().optional(),
})
.passthrough();
const GiteaActionRunPullRequestRefSchema = z
.object({
repo: z.object({ id: z.number().optional() }).passthrough().nullable().optional(),
@@ -410,9 +368,6 @@ type GiteaPrListItem = z.infer<typeof GiteaPrListItemSchema>;
type GiteaIssueListItem = z.infer<typeof GiteaIssueListItemSchema>;
type GiteaPullRequestView = z.infer<typeof GiteaPullRequestViewSchema>;
type GiteaCurrentPullRequestApi = z.infer<typeof GiteaCurrentPullRequestApiSchema>;
type GiteaCommitStatus = z.infer<typeof GiteaCommitStatusSchema>;
type GiteaCombinedCommitStatus = z.infer<typeof GiteaCombinedCommitStatusSchema>;
type GiteaActionTask = z.infer<typeof GiteaActionTaskSchema>;
type GiteaIssueComment = z.infer<typeof GiteaIssueCommentSchema>;
type GiteaReview = z.infer<typeof GiteaReviewSchema>;
type GiteaReviewComment = z.infer<typeof GiteaReviewCommentSchema>;
@@ -797,10 +752,6 @@ function deriveGiteaActionRequiredRunIds(runs: unknown[], sha: string): Set<numb
return runIds;
}
function getGiteaActionTaskName(task: GiteaActionTask): string {
return task.name || task.display_title || task.workflow_id || `actions-${task.id}`;
}
function toGiteaActionTaskCheck(task: GiteaActionTask): PullRequestCheck {
const rawStatus = task.status.toLowerCase();
return {
@@ -814,136 +765,6 @@ function toGiteaActionTaskCheck(task: GiteaActionTask): PullRequestCheck {
};
}
function getGiteaActionWorkflowIdentity(task: GiteaActionTask): string {
if (task.workflow_id) {
return `workflow\u0000${task.workflow_id}`;
}
// Instances that omit workflow_id (older Gitea/Forgejo payloads) still need
// reruns of the same job collapsed to the latest execution, so fall back to
// the job name before treating the task as its own group.
const name = task.name || task.display_title;
if (name) {
return `name\u0000${name}`;
}
return `task\u0000${getGiteaActionExecutionIdentity(task)}`;
}
function getGiteaActionExecutionIdentity(task: GiteaActionTask): string {
if (task.run_number !== undefined) return `run-number\u0000${task.run_number}`;
const runId = getGiteaActionRunIdFromUrl(task.url);
if (runId !== null) return `run-id\u0000${runId}`;
if (task.url) return `url\u0000${task.url}`;
return `task\u0000${task.id}`;
}
function parseGiteaActionTaskTime(task: GiteaActionTask): number {
const timestamp = task.created_at ?? task.run_started_at ?? null;
if (!timestamp) {
return 0;
}
const time = Date.parse(timestamp);
return Number.isNaN(time) ? 0 : time;
}
function compareGiteaActionTaskRecency(left: GiteaActionTask, right: GiteaActionTask): number {
const leftRunNumber = left.run_number ?? 0;
const rightRunNumber = right.run_number ?? 0;
if (leftRunNumber !== rightRunNumber) {
return leftRunNumber - rightRunNumber;
}
const leftTime = parseGiteaActionTaskTime(left);
const rightTime = parseGiteaActionTaskTime(right);
if (leftTime !== rightTime) {
return leftTime - rightTime;
}
return left.id - right.id;
}
function parseGiteaActionTasks(rawTasks: unknown[]): GiteaActionTask[] {
const tasks: GiteaActionTask[] = [];
for (const raw of rawTasks) {
const parsed = GiteaActionTaskSchema.safeParse(raw);
if (parsed.success) {
tasks.push(parsed.data);
}
}
return tasks;
}
function latestGiteaActionTasksByWorkflow(tasks: GiteaActionTask[]): GiteaActionTask[] {
const latestExecutions = new Map<string, GiteaActionTask>();
for (const task of tasks) {
const identity = getGiteaActionWorkflowIdentity(task);
const current = latestExecutions.get(identity);
if (!current || compareGiteaActionTaskRecency(current, task) < 0) {
latestExecutions.set(identity, task);
}
}
return tasks.filter((task) => {
const latest = latestExecutions.get(getGiteaActionWorkflowIdentity(task));
return (
latest !== undefined &&
getGiteaActionExecutionIdentity(task) === getGiteaActionExecutionIdentity(latest)
);
});
}
function getUrlOrigin(value: string | null | undefined): string | null {
if (!value) return null;
try {
return new URL(value).origin;
} catch {
return null;
}
}
const GITEA_RELATIVE_URL_ORIGIN = "https://gitea.invalid";
function getGiteaActionRunIdFromUrl(value: string | null | undefined): number | null {
if (!value) return null;
try {
const url = new URL(value, GITEA_RELATIVE_URL_ORIGIN);
const match = url.pathname.match(/\/actions\/runs\/(\d+)(?:\/jobs\/\d+)?\/?$/);
return match?.[1] ? Number.parseInt(match[1], 10) : null;
} catch {
return null;
}
}
function isNativeActionJobUrl(
targetUrl: string | null | undefined,
nativeOrigins: ReadonlySet<string>,
nativeRunIds: ReadonlySet<number>,
): boolean {
if (!targetUrl) return false;
try {
const url = new URL(targetUrl, GITEA_RELATIVE_URL_ORIGIN);
if (!/\/actions\/runs\/\d+\/jobs\/\d+\/?$/.test(url.pathname)) return false;
if (url.origin !== GITEA_RELATIVE_URL_ORIGIN && !nativeOrigins.has(url.origin)) return false;
const runId = getGiteaActionRunIdFromUrl(targetUrl);
return runId !== null && nativeRunIds.has(runId);
} catch {
return false;
}
}
// A "shadow" is the commit status Gitea synthesizes to mirror one of its own
// Actions jobs; keeping both would double-report every job. Detection is purely
// structural: Gitea always creates these statuses with a target_url of the form
// "<run link>/jobs/<job id>" (services/actions/commit_status.go upstream), so a
// status is a shadow exactly when its URL points at a job of a run we actually
// fetched from the Actions API. Anything else - external CI, URL-less statuses,
// contexts that merely look like "<workflow> / <job> (<event>)" - is kept.
function isGiteaActionShadowStatus(
status: GiteaCommitStatus,
nativeOrigins: ReadonlySet<string>,
nativeRunIds: ReadonlySet<number>,
): boolean {
return isNativeActionJobUrl(status.target_url, nativeOrigins, nativeRunIds);
}
function combineGiteaChecks(
commitStatuses: GiteaCommitStatus[],
actionTasks: GiteaActionTask[],
@@ -1219,32 +1040,6 @@ export async function probeGiteaHost(host: string): Promise<boolean> {
}
}
function findTeaLoginNameForHost(stdout: string, host: string): string | null {
let data: unknown;
try {
data = JSON.parse(stdout);
} catch {
return null;
}
const parsed = z.array(GiteaLoginSchema).safeParse(data);
if (!parsed.success) {
return null;
}
const target = host.toLowerCase();
const match = parsed.data.find((login) => {
const candidates = [login.ssh_host, login.name];
if (login.url) {
try {
candidates.push(new URL(login.url).hostname);
} catch {
// ignore malformed login url
}
}
return candidates.some((candidate) => candidate?.toLowerCase() === target);
});
return match?.name ?? null;
}
function hostHasLogin(stdout: string, host: string): boolean {
return findTeaLoginNameForHost(stdout, host) !== null;
}
@@ -1409,19 +1204,35 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
const now = options.now ?? Date.now;
const currentPrHeadShaCache = new Map<string, { sha: string; expiresAt: number }>();
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
async function runRaw(
args: string[],
runOptions: TeaCommandRunnerOptions,
): Promise<TeaCommandResult> {
const teaPath = await resolveTea();
if (!teaPath) {
throw new TeaCliMissingError();
}
try {
const result = await runner(args, runOptions);
return result.stdout.trim();
return await runner(args, runOptions);
} catch (error) {
throw teaCliRunner.normalizeError(error, { args: redactTeaArgs(args), cwd: runOptions.cwd });
}
}
async function run(args: string[], runOptions: TeaCommandRunnerOptions): Promise<string> {
const result = await runRaw(args, runOptions);
return result.stdout.trim();
}
const changeRequests = createGiteaChangeRequestSource({
runCommand: runRaw,
createAuthError: (stderr) => new TeaAuthenticationError({ stderr }),
createCommandError: (params) => new TeaCommandError(params),
now,
pollIntervalMs: options.watchPollMs,
initialDelayMs: options.watchInitialDelayMs,
});
function runJsonParse<T>(
args: string[],
runOptions: TeaCommandRunnerOptions,
@@ -2359,6 +2170,8 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
return notSupported("disablePullRequestAutoMerge");
},
changeRequests,
invalidate(input: { cwd: string }): void {
const prefix = `${input.cwd}:`;
for (const key of currentPrHeadShaCache.keys()) {
@@ -2367,5 +2180,9 @@ export function createGiteaService(options: CreateGiteaServiceOptions = {}): For
}
}
},
dispose(): void {
changeRequests.dispose();
},
};
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,917 @@
import { z } from "zod";
import { normalizeHost } from "@getpaseo/protocol/git-remote";
import { GITLAB_ACTIVE_PIPELINE_STATUS_SET } from "@getpaseo/protocol/gitlab-pipeline";
import {
ChangeRequestRateLimitError,
createPerHostChangeRequestPoller,
parseCliHttpResponse,
parseRetryAfterMs,
type PerHostReadContext,
} from "./change-request-poller.js";
import type { ChangeRequestSnapshot, ChangeRequestSource } from "./change-request-source.js";
const GITLAB_CLOUD_HOST = "gitlab.com";
const GITLAB_PAGE_SIZE = 100;
const GITLAB_MR_TABS = new Set(["diffs", "commits", "pipelines", "builds", "reports"]);
const checkUrlSchema = z.url({ protocol: /^https?$/ });
const gitLabWatchPipelineSchema = z
.object({
id: z.number(),
project_id: z.number().nullable().optional(),
sha: z.string().nullable().optional(),
status: z.string(),
web_url: z.string().nullable().optional(),
})
.passthrough();
const gitLabWatchMrSchema = z
.object({
iid: z.number(),
state: z.string(),
sha: z.string().nullable().optional(),
diff_refs: z
.object({
head_sha: z.string().nullable().optional(),
})
.passthrough()
.nullable()
.optional(),
web_url: checkUrlSchema,
target_project_id: z.number().nullable().optional(),
merged_at: z.string().nullable().optional(),
head_pipeline: gitLabWatchPipelineSchema.nullable().optional(),
})
.passthrough();
const gitLabWatchJobSchema = z
.object({
id: z.number(),
name: z.string(),
status: z.string(),
allow_failure: z.boolean().optional(),
web_url: z.string().nullable().optional(),
})
.passthrough();
const gitLabWatchNoteAuthorSchema = z
.object({
username: z.string().optional(),
name: z.string().optional(),
})
.passthrough();
const gitLabWatchNoteSchema = z
.object({
id: z.number(),
body: z.string().nullable().optional(),
system: z.boolean().optional(),
type: z.string().nullable().optional(),
position: z.unknown().nullable().optional(),
author: gitLabWatchNoteAuthorSchema.nullable().optional(),
})
.passthrough();
const gitLabWatchDiscussionSchema = z
.object({
id: z.string(),
notes: z.array(gitLabWatchNoteSchema).optional().default([]),
})
.passthrough();
const gitLabWatchApprovalsSchema = z
.object({
approvals_required: z.number().nullable().optional(),
approvals_left: z.number().nullable().optional(),
})
.passthrough();
type GitLabWatchMr = z.infer<typeof gitLabWatchMrSchema>;
type GitLabWatchJob = z.infer<typeof gitLabWatchJobSchema>;
type GitLabWatchNote = z.infer<typeof gitLabWatchNoteSchema>;
type GitLabWatchDiscussion = z.infer<typeof gitLabWatchDiscussionSchema>;
type GitLabWatchApprovals = z.infer<typeof gitLabWatchApprovalsSchema>;
interface GitLabMergeRequestIdentity {
protocol: "http:" | "https:";
host: string;
port: string;
hostWithPort: string;
projectPath: string;
iid: number;
}
function invalidGitLabUrl(): never {
throw new Error("Enter a GitLab merge request URL.");
}
function parseGitLabUrlOrigin(input: string): {
protocol: "http:" | "https:";
host: string;
port: string;
hostWithPort: string;
pathname: string;
} {
const trimmed = input.trim();
if (!trimmed || /\s/.test(trimmed)) invalidGitLabUrl();
let parsed: URL;
try {
parsed = new URL(trimmed);
} catch {
invalidGitLabUrl();
}
const protocol = parsed.protocol.toLowerCase();
if ((protocol !== "https:" && protocol !== "http:") || parsed.username || parsed.password) {
invalidGitLabUrl();
}
const host = normalizeHost(parsed.hostname);
if (!host || (host === GITLAB_CLOUD_HOST && protocol !== "https:")) {
invalidGitLabUrl();
}
return {
protocol: protocol as "http:" | "https:",
host,
port: parsed.port,
hostWithPort: parsed.port ? `${host}:${parsed.port}` : host,
pathname: parsed.pathname,
};
}
function decodeGitLabProjectPath(rawSegments: string[]): string {
if (rawSegments.length < 2) invalidGitLabUrl();
const decodedSegments: string[] = [];
for (const segment of rawSegments) {
let decoded: string;
try {
decoded = decodeURIComponent(segment);
} catch {
invalidGitLabUrl();
}
const invalidSegment =
!decoded ||
decoded === "." ||
decoded === ".." ||
decoded === "-" ||
decoded.includes("/") ||
decoded.includes("\\");
if (invalidSegment) invalidGitLabUrl();
decodedSegments.push(decoded);
}
return decodedSegments.join("/");
}
function parseGitLabMergeRequestUrl(input: string): GitLabMergeRequestIdentity {
const origin = parseGitLabUrlOrigin(input);
const rawSegments = origin.pathname.split("/").filter((segment) => segment.length > 0);
if (rawSegments.length < 4) invalidGitLabUrl();
// Strip an optional browser tab suffix (e.g. /diffs, /commits, /pipelines).
if (
rawSegments.length >= 5 &&
GITLAB_MR_TABS.has(rawSegments[rawSegments.length - 1]!.toLowerCase()) &&
/^\d+$/.test(rawSegments[rawSegments.length - 2]!)
) {
rawSegments.pop();
}
const iidRaw = rawSegments.pop();
const resource = rawSegments.pop();
if (!iidRaw || !/^\d+$/.test(iidRaw) || resource?.toLowerCase() !== "merge_requests") {
invalidGitLabUrl();
}
const iid = Number(iidRaw);
if (!Number.isInteger(iid) || iid < 1 || iid > 2_147_483_647) {
invalidGitLabUrl();
}
// Modern GitLab URLs place `-` before `merge_requests`; legacy URLs omit it.
if (rawSegments[rawSegments.length - 1] === "-") {
rawSegments.pop();
}
return {
protocol: origin.protocol,
host: origin.host,
port: origin.port,
hostWithPort: origin.hostWithPort,
projectPath: decodeGitLabProjectPath(rawSegments),
iid,
};
}
export function resolveGitLabChangeRequest(input: string): string {
const { protocol, hostWithPort, projectPath, iid } = parseGitLabMergeRequestUrl(input);
return `${protocol}//${hostWithPort}/${projectPath}/-/merge_requests/${iid}`;
}
export function gitlabChangeRequestHost(url: string): string {
return parseGitLabMergeRequestUrl(url).hostWithPort;
}
export function describeGitLabChangeRequest(url: string): string {
const { host, port, hostWithPort, projectPath, iid } = parseGitLabMergeRequestUrl(url);
const project =
host === GITLAB_CLOUD_HOST && !port ? projectPath : `${hostWithPort}/${projectPath}`;
return `${project} !${iid}`;
}
function mapGitLabMrState(mr: GitLabWatchMr): ChangeRequestSnapshot["state"] {
const state = mr.state.toLowerCase();
// GitLab reports "locked" while a merge is actively in progress; treat it as
// open so polling continues until GitLab transitions to "merged" (or "closed").
if (state === "opened" || state === "locked") return "open";
if (state === "merged" || mr.merged_at != null) return "merged";
return "closed";
}
function mapGitLabPipelineState(
status: string | null | undefined,
): ChangeRequestSnapshot["checksState"] {
if (!status) return "neutral";
const normalized = status.toLowerCase();
if (normalized === "success" || normalized === "passed") return "passed";
if (normalized === "failed") return "failed";
if (normalized === "manual" || GITLAB_ACTIVE_PIPELINE_STATUS_SET.has(normalized)) {
return "pending";
}
return "neutral";
}
function mapGitLabJobState(job: GitLabWatchJob): ChangeRequestSnapshot["checks"][number]["state"] {
const raw = job.status.toLowerCase();
const allowFailure = job.allow_failure ?? false;
if (raw === "failed") return allowFailure ? "neutral" : "failed";
if (raw === "success" || raw === "passed") return "passed";
if (raw === "manual") return allowFailure ? "neutral" : "pending";
if (GITLAB_ACTIVE_PIPELINE_STATUS_SET.has(raw)) return "pending";
return "neutral";
}
function toWatchCheck(
job: GitLabWatchJob,
prefix: "job" | "bridge",
): ChangeRequestSnapshot["checks"][number] {
const url = checkUrlSchema.safeParse(job.web_url).data;
return {
id: `${prefix}:${job.id}`,
name: job.name,
state: mapGitLabJobState(job),
...(url ? { url } : {}),
};
}
type ApprovalNoteAction = "approved" | "unapproved" | "reset";
interface ParsedApprovalNote {
id: string;
action: ApprovalNoteAction;
actor: string | null;
url: string;
}
function parseGitLabApprovalNote(
note: GitLabWatchNote,
mrWebUrl: string,
): ParsedApprovalNote | null {
if (note.system !== true) return null;
const body = note.body?.trim().toLowerCase() ?? "";
if (!body) return null;
let action: ApprovalNoteAction | null = null;
if (body === "approved this merge request" || body.startsWith("approved this merge request")) {
action = "approved";
} else if (
body === "unapproved this merge request" ||
body.startsWith("unapproved this merge request") ||
body.startsWith("removed approval") ||
body.startsWith("revoked approval")
) {
action = "unapproved";
} else if (body.startsWith("reset approvals")) {
action = "reset";
}
if (!action) return null;
const actor = note.author?.username?.trim() || note.author?.name?.trim() || null;
return {
id: `approval-note:${note.id}`,
action,
actor,
url: `${mrWebUrl}#note_${note.id}`,
};
}
interface ApprovalCount {
given: number;
required: number;
}
function summarizeApprovalCount(approvals: GitLabWatchApprovals): ApprovalCount | null {
const { approvals_required: required, approvals_left: remaining } = approvals;
if (required == null || remaining == null) return null;
return { given: Math.max(0, required - remaining), required };
}
function formatApprovalCount(summary: ApprovalCount | null): string {
if (!summary || summary.required <= 0) return "";
return ` (${summary.given}/${summary.required} approvals)`;
}
function formatApprovalActor(actor: string | null): string {
if (!actor) return "";
return actor.startsWith("@") ? actor : `@${actor}`;
}
function formatApprovalNoteMessage(
note: ParsedApprovalNote,
summary: ApprovalCount | null,
): string {
const actor = formatApprovalActor(note.actor);
const count = formatApprovalCount(summary);
if (note.action === "approved") {
return `Merge request approved${actor ? ` by ${actor}` : ""}${count}: ${note.url}`;
}
if (note.action === "unapproved") {
return `Merge request approval removed${actor ? ` by ${actor}` : ""}${count}: ${note.url}`;
}
return `Merge request approvals reset${actor ? ` by ${actor}` : ""}${count}: ${note.url}`;
}
interface ParsedDiscussionItems {
humanActivity: ChangeRequestSnapshot["activity"];
approvalNotes: ParsedApprovalNote[];
}
function parseDiscussionItems(
discussions: GitLabWatchDiscussion[],
mrWebUrl: string,
): ParsedDiscussionItems {
const humanActivity: ChangeRequestSnapshot["activity"] = [];
const approvalNotes: ParsedApprovalNote[] = [];
for (const discussion of discussions) {
for (const note of discussion.notes) {
if (note.system === true) {
const approvalNote = parseGitLabApprovalNote(note, mrWebUrl);
if (approvalNote) approvalNotes.push(approvalNote);
continue;
}
const isInline = note.position != null || note.type === "DiffNote";
humanActivity.push({
id: isInline ? `inline:${note.id}` : `comment:${note.id}`,
kind: isInline ? "inline comment" : "comment",
url: `${mrWebUrl}#note_${note.id}`,
});
}
}
return { humanActivity, approvalNotes };
}
function resolvePipelineProjectId(
pipeline: z.infer<typeof gitLabWatchPipelineSchema>,
mr: GitLabWatchMr,
encodedProject: string,
): string {
if (pipeline.project_id != null) return String(pipeline.project_id);
if (mr.target_project_id != null) return String(mr.target_project_id);
return encodedProject;
}
function pipelineFailureCheck(
pipeline: z.infer<typeof gitLabWatchPipelineSchema>,
): ChangeRequestSnapshot["checks"][number] {
const url = checkUrlSchema.safeParse(pipeline.web_url).data;
return {
id: `pipeline:${pipeline.id}`,
name: `Pipeline #${pipeline.id}`,
state: "failed",
...(url ? { url } : {}),
};
}
function createRateLimitError(
host: string,
nowMs: number,
headers: ReadonlyMap<string, string>,
): ChangeRequestRateLimitError {
const resetAtMs = parseRetryAfterMs(headers, nowMs, {
forceOnMissing: true,
defaultPauseMs: 60_000,
})!;
return new ChangeRequestRateLimitError({ host, resetAtMs });
}
function extractRateLimitFromFailedCommand(
host: string,
nowMs: number,
status: number | null,
headers: ReadonlyMap<string, string>,
text: string,
): ChangeRequestRateLimitError | null {
if (status !== null) {
return status === 429 ? createRateLimitError(host, nowMs, headers) : null;
}
if (!/\b(429|too many requests|rate limit)\b/i.test(text)) return null;
return createRateLimitError(host, nowMs, headers);
}
export interface CreateGitLabChangeRequestSourceOptions {
runCommand(
args: string[],
options: { cwd: string; envOverlay?: Record<string, string> },
): Promise<{ stdout: string; stderr: string }>;
isAuthError(error: unknown): boolean;
isCommandError(error: unknown): error is Error & { stderr: string; stdout?: string };
createAuthError(stderr: string): Error;
createCommandError(params: {
args: string[];
cwd: string;
exitCode: number | null;
stderr: string;
stdout?: string;
}): Error;
now?: () => number;
pollIntervalMs?: number;
initialDelayMs?: number;
}
export function createGitLabChangeRequestSource(
options: CreateGitLabChangeRequestSourceOptions,
): ChangeRequestSource & { dispose(): void } {
const now = options.now ?? Date.now;
async function readConfig(
host: string,
key: string,
envOverlay: Record<string, string> = {},
): Promise<string> {
const config = await options.runCommand(["config", "get", key, "--host", host], {
cwd: process.cwd(),
envOverlay: { GITLAB_HOST: host, ...envOverlay },
});
return config.stdout.trim();
}
async function preferredProfileHost(identity: GitLabMergeRequestIdentity): Promise<string> {
const { host, hostWithPort } = identity;
if (hostWithPort === host) return host;
// An API host override applies to either profile. Use the configured value
// to decide which profile to try first, then check access through the MR.
const exactProfile = await readConfig(hostWithPort, "api_host", { GITLAB_API_HOST: "" });
return exactProfile ? hostWithPort : host;
}
async function readApiPrefix(profileHost: string): Promise<string> {
if (profileHost === GITLAB_CLOUD_HOST) return "";
const trimSlashes = /^\/+|\/+$/g;
let prefix = (await readConfig(profileHost, "subfolder")).replace(trimSlashes, "");
if (!prefix) {
const apiHost = await readConfig(profileHost, "api_host");
if (apiHost) {
const apiUrl = new URL(apiHost.includes("://") ? apiHost : `https://${apiHost}`);
prefix = apiUrl.pathname.replace(trimSlashes, "");
}
}
return decodeURI(prefix);
}
function parseJsonResponseBody<T>(params: {
args: string[];
cwd: string;
body: string;
schema: z.ZodType<T>;
}): T {
let json: unknown;
try {
json = JSON.parse(params.body);
} catch {
throw options.createCommandError({
args: params.args,
cwd: params.cwd,
exitCode: null,
stderr: `glab did not return valid JSON (${params.body.length} bytes)`,
});
}
const validated = params.schema.safeParse(json);
if (!validated.success) {
throw options.createCommandError({
args: params.args,
cwd: params.cwd,
exitCode: null,
stderr: `glab JSON did not match the expected schema: ${validated.error.message}`,
});
}
return validated.data;
}
function checkHttpStatus(params: {
host: string;
args: string[];
cwd: string;
status: number | null;
headers: ReadonlyMap<string, string>;
body: string;
rawStdout: string;
rawStderr: string;
pauseHost(untilMs: number): void;
}): void {
// Only decide rate limits from the HTTP status code on parsed responses so
// ordinary MR titles, comments, or IIDs mentioning "429" or "rate limit"
// never trip a false rate-limit pause.
if (params.status === null) return;
if (params.status === 429) {
const error = createRateLimitError(params.host, now(), params.headers);
params.pauseHost(error.resetAtMs);
throw error;
}
if (params.status === 401) {
throw options.createAuthError(params.body || params.rawStderr || "401 Unauthorized");
}
if (params.status < 200 || params.status >= 300) {
throw options.createCommandError({
args: params.args,
cwd: params.cwd,
exitCode: null,
stderr: `HTTP ${params.status}: ${params.body || params.rawStderr}`.trim(),
stdout: params.rawStdout,
});
}
}
async function apiGet<T>(params: {
host: string;
endpoint: string;
schema: z.ZodType<T>;
poll: PerHostReadContext;
}): Promise<{ data: T; headers: ReadonlyMap<string, string> }> {
if (!params.poll.isObserved()) throw new Error("Change request observation ended");
params.poll.assertHostAvailable();
// glab api rejects a port in --hostname. GITLAB_HOST selects that profile.
const args = params.host.includes(":")
? ["api", "-i", params.endpoint]
: ["api", "--hostname", params.host, "-i", params.endpoint];
const cwd = process.cwd();
let result: { stdout: string; stderr: string };
try {
result = await options.runCommand(args, {
cwd,
envOverlay: { GITLAB_HOST: params.host },
});
} catch (error) {
if (options.isCommandError(error)) {
const parsedError = error.stdout ? parseCliHttpResponse(error.stdout) : null;
const rateLimit = extractRateLimitFromFailedCommand(
params.host,
now(),
parsedError?.status ?? null,
parsedError?.headers ?? new Map(),
`${error.stderr}\n${error.stdout ?? ""}`,
);
if (rateLimit) {
params.poll.pauseHost(rateLimit.resetAtMs);
throw rateLimit;
}
}
throw error;
}
const parsed = parseCliHttpResponse(result.stdout);
checkHttpStatus({
host: params.host,
args,
cwd,
status: parsed.status,
headers: parsed.headers,
body: parsed.body,
rawStdout: result.stdout,
rawStderr: result.stderr,
pauseHost: params.poll.pauseHost,
});
const proactivePause = parseRetryAfterMs(parsed.headers, now());
if (proactivePause !== null) {
params.poll.deferPollsUntil(proactivePause);
}
const data = parseJsonResponseBody({ args, cwd, body: parsed.body, schema: params.schema });
return { data, headers: parsed.headers };
}
async function apiGetAllPages<T>(params: {
host: string;
endpoint: string;
itemSchema: z.ZodType<T>;
poll: PerHostReadContext;
}): Promise<{ items: T[]; pagesRead: number }> {
const items: T[] = [];
const schema = z.array(params.itemSchema);
const seenPages = new Set<number>([1]);
let page = 1;
let pagesRead = 0;
while (true) {
if (!params.poll.isObserved()) {
return { items, pagesRead };
}
const sep = params.endpoint.includes("?") ? "&" : "?";
const response = await apiGet({
host: params.host,
endpoint: `${params.endpoint}${sep}per_page=${GITLAB_PAGE_SIZE}&page=${page}`,
schema,
poll: params.poll,
});
pagesRead += 1;
items.push(...response.data);
const nextPageHeader = response.headers.get("x-next-page");
if (nextPageHeader !== undefined) {
const trimmed = nextPageHeader.trim();
if (!trimmed) break;
const nextPage = Number(trimmed);
if (!Number.isInteger(nextPage) || nextPage <= 0 || seenPages.has(nextPage)) {
throw new Error("GitLab returned an invalid pagination header.");
}
seenPages.add(nextPage);
page = nextPage;
} else {
if (response.data.length < GITLAB_PAGE_SIZE) break;
page += 1;
seenPages.add(page);
}
}
return { items, pagesRead };
}
function commandErrorStatus(error: unknown): number | null {
return options.isCommandError(error) && error.stdout
? parseCliHttpResponse(error.stdout).status
: null;
}
async function readMergeRequestMetadata(params: {
host: string;
identity: GitLabMergeRequestIdentity;
endpoint: string;
poll: PerHostReadContext;
}): Promise<GitLabWatchMr> {
const { data: mr } = await apiGet({
host: params.host,
endpoint: params.endpoint,
schema: gitLabWatchMrSchema,
poll: params.poll,
});
const address = parseGitLabMergeRequestUrl(mr.web_url);
const expected = params.identity;
if (address.protocol !== expected.protocol || address.hostWithPort !== expected.hostWithPort) {
throw new Error(
`GitLab returned a merge request from a different web origin: ${address.protocol}//${address.hostWithPort}`,
);
}
if (address.projectPath.toLowerCase() !== expected.projectPath.toLowerCase()) {
throw new Error("GitLab returned a merge request from a different project.");
}
if (address.iid !== expected.iid || mr.iid !== expected.iid) {
throw new Error("GitLab returned a different merge request number.");
}
return mr;
}
function pipelineDetailsUnavailable(error: unknown): boolean {
const status = commandErrorStatus(error);
return status === 403 || status === 404;
}
async function readPipelineChecks(params: {
host: string;
identity: GitLabMergeRequestIdentity;
mrEndpoint: string;
encodedProject: string;
mr: GitLabWatchMr;
headSha: string;
poll: PerHostReadContext;
}): Promise<ChangeRequestSnapshot["checks"]> {
const pipeline = params.mr.head_pipeline;
if (!pipeline) return [];
const pipelineProject = resolvePipelineProjectId(pipeline, params.mr, params.encodedProject);
let jobsResult: { items: GitLabWatchJob[]; pagesRead: number };
try {
jobsResult = await apiGetAllPages({
host: params.host,
endpoint: `projects/${pipelineProject}/pipelines/${pipeline.id}/jobs`,
itemSchema: gitLabWatchJobSchema,
poll: params.poll,
});
} catch (error) {
if (!pipelineDetailsUnavailable(error)) throw error;
// The MR can expose pipeline status even when its jobs are restricted.
return mapGitLabPipelineState(pipeline.status) === "failed"
? [pipelineFailureCheck(pipeline)]
: [];
}
if (!params.poll.isObserved()) {
throw new Error("Change request observation ended");
}
const checks = jobsResult.items.map((job) => toWatchCheck(job, "job"));
let fetchedBridges = false;
if (
mapGitLabPipelineState(pipeline.status) === "failed" &&
!checks.some((check) => check.state === "failed")
) {
fetchedBridges = true;
await appendFailedBridgeOrPipelineChecks({
host: params.host,
pipelineProject,
pipeline,
checks,
poll: params.poll,
});
}
// Guard against headSha or head_pipeline shifting while paginating check pages.
if (jobsResult.pagesRead > 1 || fetchedBridges) {
const recheck = await readMergeRequestMetadata({
host: params.host,
identity: params.identity,
endpoint: params.mrEndpoint,
poll: params.poll,
});
const recheckSha = recheck.sha || recheck.diff_refs?.head_sha || "";
if (
recheckSha !== params.headSha ||
recheck.head_pipeline?.id !== pipeline.id ||
recheck.head_pipeline?.status !== pipeline.status
) {
throw new Error("The merge request head or pipeline changed during pagination.");
}
}
return checks;
}
async function appendFailedBridgeOrPipelineChecks(params: {
host: string;
pipelineProject: string;
pipeline: z.infer<typeof gitLabWatchPipelineSchema>;
checks: ChangeRequestSnapshot["checks"];
poll: PerHostReadContext;
}): Promise<void> {
try {
const bridgesResult = await apiGetAllPages({
host: params.host,
endpoint: `projects/${params.pipelineProject}/pipelines/${params.pipeline.id}/bridges`,
itemSchema: gitLabWatchJobSchema,
poll: params.poll,
});
for (const bridge of bridgesResult.items) {
params.checks.push(toWatchCheck(bridge, "bridge"));
}
} catch (error) {
if (!pipelineDetailsUnavailable(error)) throw error;
}
if (!params.checks.some((check) => check.state === "failed")) {
params.checks.push(pipelineFailureCheck(params.pipeline));
}
}
async function readOptionalApprovalCount(params: {
host: string;
endpoint: string;
poll: PerHostReadContext;
}): Promise<ApprovalCount | null> {
try {
const { data: approvals } = await apiGet({
host: params.host,
endpoint: params.endpoint,
schema: gitLabWatchApprovalsSchema,
poll: params.poll,
});
return summarizeApprovalCount(approvals);
} catch {
// The approval system note is complete without an API count.
return null;
}
}
async function readInitialMergeRequest(
identity: GitLabMergeRequestIdentity,
poll: PerHostReadContext,
) {
async function readUsing(host: string) {
const { projectPath, iid } = identity;
const prefix = await readApiPrefix(host);
const relativePath =
prefix && projectPath.startsWith(`${prefix}/`)
? projectPath.slice(prefix.length + 1)
: projectPath;
const encodedProject = encodeURIComponent(
relativePath.includes("/") ? relativePath : projectPath,
);
const mrEndpoint = `projects/${encodedProject}/merge_requests/${iid}`;
const mr = await readMergeRequestMetadata({ host, identity, endpoint: mrEndpoint, poll });
return { host, encodedProject, mrEndpoint, mr };
}
const preferred = await preferredProfileHost(identity);
try {
return await readUsing(preferred);
} catch (error) {
const status = commandErrorStatus(error);
const accessDenied = options.isAuthError(error) || status === 403 || status === 404;
if (preferred === identity.host || !accessDenied) throw error;
return readUsing(identity.host);
}
}
async function readMergeRequest(context: PerHostReadContext): Promise<ChangeRequestSnapshot> {
const identity = parseGitLabMergeRequestUrl(context.url);
const { iid } = identity;
const { host, encodedProject, mrEndpoint, mr } = await readInitialMergeRequest(
identity,
context,
);
const headSha = mr.sha || mr.diff_refs?.head_sha || "";
if (!headSha) {
throw new Error(`GitLab merge request !${iid} did not include a head commit SHA.`);
}
const checks = await readPipelineChecks({
host,
identity,
mrEndpoint,
encodedProject,
mr,
headSha,
poll: context,
});
const discussionsResult = await apiGetAllPages({
host,
endpoint: `projects/${encodedProject}/merge_requests/${iid}/discussions`,
itemSchema: gitLabWatchDiscussionSchema,
poll: context,
});
if (!context.isObserved()) {
throw new Error("Change request observation ended");
}
const { humanActivity, approvalNotes } = parseDiscussionItems(
discussionsResult.items,
mr.web_url,
);
const known = context.knownActivity();
const hasNewApprovalNote =
known !== undefined && approvalNotes.some((note) => !known.has(note.id));
// Fetch /approvals only to enrich a newly observed approval system note with
// current counts — keeping seenActivity as the single persisted owner of
// approval transition baselines.
const approvalCount = hasNewApprovalNote
? await readOptionalApprovalCount({
host,
endpoint: `projects/${encodedProject}/merge_requests/${iid}/approvals`,
poll: context,
})
: null;
const activity: ChangeRequestSnapshot["activity"] = [
...humanActivity,
...approvalNotes.map((note) => ({
id: note.id,
kind: "approval" as const,
url: note.url,
message: formatApprovalNoteMessage(note, approvalCount),
})),
];
return {
state: mapGitLabMrState(mr),
headSha,
checksState: mapGitLabPipelineState(mr.head_pipeline?.status),
checks,
reviewDecision: null,
activity,
};
}
const poller = createPerHostChangeRequestPoller({
hostOf: gitlabChangeRequestHost,
read: readMergeRequest,
now,
pollIntervalMs: options.pollIntervalMs,
initialDelayMs: options.initialDelayMs,
});
return {
resolve: resolveGitLabChangeRequest,
describe: describeGitLabChangeRequest,
observe(url, callbacks) {
return poller.observe(url, callbacks);
},
dispose() {
poller.dispose();
},
};
}
+31 -3
View File
@@ -60,6 +60,7 @@ import {
CHECK_TRAIT_WARNING,
} from "@getpaseo/protocol/check-traits";
import { GITLAB_ACTIVE_PIPELINE_STATUS_SET } from "@getpaseo/protocol/gitlab-pipeline";
import { createGitLabChangeRequestSource } from "./gitlab-change-requests.js";
import { isGitLabStatusFacts, type GitLabStatusFacts } from "./gitlab-facts.js";
const GLAB_ENV = {
@@ -112,6 +113,9 @@ export interface CreateGitLabServiceOptions {
runner?: GlabCommandRunner;
resolveGlabPath?: () => Promise<string | null>;
resolveRemoteUrl?: (cwd: string) => Promise<string | null>;
now?: () => number;
watchPollMs?: number;
watchInitialDelayMs?: number;
}
const GitLabPipelineSchema = z
@@ -925,19 +929,37 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
const resolveGlab = createCachedCliPathResolver(options.resolveGlabPath ?? resolveGlabPath);
const resolveRemoteUrl = options.resolveRemoteUrl ?? defaultResolveRemoteUrl;
async function run(args: string[], runOptions: GlabCommandRunnerOptions): Promise<string> {
async function runRaw(
args: string[],
runOptions: GlabCommandRunnerOptions,
): Promise<GlabCommandResult> {
const glabPath = await resolveGlab();
if (!glabPath) {
throw new GlabCliMissingError();
}
try {
const result = await runner(args, runOptions);
return result.stdout.trim();
return await runner(args, runOptions);
} catch (error) {
throw glabCliRunner.normalizeError(error, { args, cwd: runOptions.cwd });
}
}
async function run(args: string[], runOptions: GlabCommandRunnerOptions): Promise<string> {
const result = await runRaw(args, runOptions);
return result.stdout.trim();
}
const changeRequests = createGitLabChangeRequestSource({
runCommand: runRaw,
isAuthError: (error) => error instanceof GlabAuthenticationError,
isCommandError: (error): error is GlabCommandError => error instanceof GlabCommandError,
createAuthError: (stderr) => new GlabAuthenticationError({ stderr }),
createCommandError: (params) => new GlabCommandError(params),
now: options.now,
pollIntervalMs: options.watchPollMs,
initialDelayMs: options.watchInitialDelayMs,
});
// Centralize parse + validate so a malformed or empty glab payload surfaces as
// a classified GlabCommandError (with args + cwd) instead of a raw
// SyntaxError/ZodError that bypasses the Glab* error classification.
@@ -1486,6 +1508,12 @@ export function createGitLabService(options: CreateGitLabServiceOptions = {}): F
return { success: true };
},
changeRequests,
invalidate(_input: { cwd: string }): void {},
dispose(): void {
changeRequests.dispose();
},
};
}
+74
View File
@@ -9,6 +9,12 @@ async function chooseLanguage(page: Page, language: string) {
await page.getByRole("menuitemradio", { name: language }).click();
}
async function selectHubSourceTab(page: Page, name: string | RegExp) {
const tab = page.getByRole("tab", { name });
await tab.click();
await expect(tab).toHaveAttribute("aria-selected", "true");
}
async function withPageScriptsHeld(page: Page, run: (release: () => void) => Promise<void>) {
let releaseScripts!: () => void;
const scriptsReleased = new Promise<void>((resolve) => {
@@ -109,6 +115,74 @@ test("switches language on the same page, keeping the query and then every link"
await expect(page.locator("html")).toHaveAttribute("lang", "en");
});
for (const {
locale,
prefix,
linearTab,
linearDocsLink,
linearTriggerHeading,
linearAppLink,
linearAppHeading,
webhooksTab,
webhooksDocsLink,
webhooksHeading,
} of [
{
locale: "English",
prefix: "",
linearTab: /^Linear\b/,
linearDocsLink: "Read Linear docs",
linearTriggerHeading: "Linear triggers",
linearAppLink: "Linear app",
linearAppHeading: "Linear for Hub",
webhooksTab: /^Webhooks\b/,
webhooksDocsLink: "Read Webhooks docs",
webhooksHeading: "Inbound webhooks",
},
{
locale: "Chinese",
prefix: "/zh-CN",
linearTab: /^Linear\b/,
linearDocsLink: "阅读 Linear 文档",
linearTriggerHeading: "Linear 触发器",
linearAppLink: "Linear 应用",
linearAppHeading: "为 Hub 配置 Linear",
webhooksTab: /^Webhook\b/,
webhooksDocsLink: "阅读 Webhook 文档",
webhooksHeading: "入站 webhook",
},
]) {
test(`navigates from the ${locale} Hub showcase to Linear and Webhook docs`, async ({ page }) => {
await page.goto(`${prefix}/hub`);
await test.step("opens Linear trigger docs and Linear app setup", async () => {
await selectHubSourceTab(page, linearTab);
const triggerLink = page.getByRole("link", { name: linearDocsLink, exact: true });
await expect(triggerLink).toHaveAttribute("href", `${prefix}/docs/hub/triggers/linear`);
await triggerLink.click();
await expect(
page.getByRole("heading", { name: linearTriggerHeading, level: 1 }),
).toBeVisible();
await expect(page.getByText("linear.comment_created", { exact: true }).first()).toBeVisible();
const appLink = page.locator("main").getByRole("link", { name: linearAppLink, exact: true });
await expect(appLink).toHaveAttribute("href", `${prefix}/docs/hub/self-hosting/linear-app`);
await appLink.click();
await expect(page.getByRole("heading", { name: linearAppHeading, level: 1 })).toBeVisible();
});
await test.step("opens Webhooks trigger docs from the Hub showcase", async () => {
await page.goto(`${prefix}/hub`);
await selectHubSourceTab(page, webhooksTab);
const webhookLink = page.getByRole("link", { name: webhooksDocsLink, exact: true });
await expect(webhookLink).toHaveAttribute("href", `${prefix}/docs/hub/triggers/webhooks`);
await webhookLink.click();
await expect(page.getByRole("heading", { name: webhooksHeading, level: 1 })).toBeVisible();
await expect(page.getByText("webhook.received", { exact: true }).first()).toBeVisible();
});
});
}
test("shows the language as an abbreviation and lists every language by name", async ({ page }) => {
await page.goto("/docs/cli#running-agents");
const button = languageButton(page);
+1
View File
@@ -15,6 +15,7 @@
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
"@fontsource-variable/geist": "^5.3.0",
"@fontsource-variable/plus-jakarta-sans": "^5.3.0",
"@getpaseo/protocol": "*",
"@tanstack/react-router": "^1.170.16",
"@tanstack/react-start": "^1.168.26",
@@ -1,8 +1,10 @@
import { useLoaderData } from "@tanstack/react-router";
import { useTranslation } from "react-i18next";
import { LandingPage } from "~/components/landing-page";
import { type AgentPageSlug, getAgentPage } from "~/data/agent-pages";
import { getTranslator, routeLocale } from "~/i18n";
import { pageMeta } from "~/meta";
import { getPluginCount } from "~/plugins";
export function agentRouteOptions(slug: AgentPageSlug) {
return {
@@ -16,10 +18,18 @@ export function agentRouteOptions(slug: AgentPageSlug) {
locale,
});
},
loader: async () => ({ pluginCount: await getPluginCount() }),
component: function AgentLandingPage() {
const { t } = useTranslation();
const data = useLoaderData({ strict: false }) as { pluginCount?: number | null } | undefined;
const page = getAgentPage(slug, t);
return <LandingPage title={page.title} subtitle={page.subtitle} />;
return (
<LandingPage
title={page.title}
subtitle={page.subtitle}
pluginCount={data?.pluginCount ?? null}
/>
);
},
};
}
@@ -45,6 +45,20 @@ export function SlackIcon(props: React.SVGProps<SVGSVGElement>) {
);
}
export function LinearIcon(props: React.SVGProps<SVGSVGElement>) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
aria-hidden="true"
{...props}
>
<path d="M2.886 4.18A11.982 11.982 0 0 1 11.99 0C18.624 0 24 5.376 24 12.009c0 3.64-1.62 6.903-4.18 9.105L2.887 4.18ZM1.817 5.626l16.556 16.556c-.524.33-1.075.62-1.65.866L.951 7.277c.247-.575.537-1.126.866-1.65ZM.322 9.163l14.515 14.515c-.71.172-1.443.282-2.195.322L0 11.358a12 12 0 0 1 .322-2.195Zm-.17 4.862 9.823 9.824a12.02 12.02 0 0 1-9.824-9.824Z" />
</svg>
);
}
export function OpenCollectiveIcon(props: React.SVGProps<SVGSVGElement>) {
return (
<svg
+16 -6
View File
@@ -2,15 +2,25 @@ import type { ReactNode } from "react";
export function FAQItem({ question, children }: { question: string; children: ReactNode }) {
return (
<details className="group">
<summary className="font-medium text-sm cursor-pointer list-none grid grid-cols-[1.25rem_1fr] items-baseline">
<span className="font-mono text-lg leading-none text-white/40 group-open:hidden">+</span>
<span className="font-mono text-lg leading-none text-white/40 hidden group-open:inline">
<details className="group py-5 first:pt-4 last:pb-4">
<summary className="flex cursor-pointer list-none items-baseline justify-between gap-6 text-[15px] font-medium text-white/90 transition-colors hover:text-white">
<span>{question}</span>
<span
aria-hidden="true"
className="shrink-0 font-mono text-base leading-none text-white/40 transition-colors group-hover:text-white/70 group-open:hidden"
>
+
</span>
<span
aria-hidden="true"
className="hidden shrink-0 font-mono text-base leading-none text-accent-text group-open:inline"
>
−
</span>
{question}
</summary>
<div className="text-sm text-muted-foreground space-y-2 mt-2 pl-5 prose">{children}</div>
<div className="prose mt-3 max-w-2xl space-y-2.5 text-sm leading-relaxed text-muted-foreground">
{children}
</div>
</details>
);
}
@@ -0,0 +1,254 @@
import { Check, CornerDownRight, GitPullRequest, Hash, PlusCircle } from "lucide-react";
import { Trans, useTranslation } from "react-i18next";
import { DiscordIcon } from "~/components/brand-icons";
import {
MoAvatar,
MockupStageWindow,
MockupStep,
OpenInPaseoChip,
PaseoBotAvatar,
type SourceMockupProps,
WindowTrafficLights,
} from "./shared";
const DISCORD_CHANNELS = ["general", "engineering", "bugs", "releases"] as const;
const STEP_DELAYS = {
userMention: 0.06,
threadStart: 0.55,
botWorking: 1.05,
botDone: 1.7,
} as const;
const DISCORD_COMPONENTS = {
mention: (
<span className="rounded-[3px] bg-[#5865F2]/30 px-1 py-[0.5px] font-medium text-[#C9CDFB]">
@paseo-bot
</span>
),
host: (
<span className="rounded-[3px] bg-[#1E1F22] px-1.5 py-[1px] font-mono text-[11px] text-[#DBDEE1]" />
),
issue: <span className="font-mono text-[12px] text-[#00A8FC]">#2799</span>,
};
export function DiscordSourceMockup({ active, reduceMotion }: SourceMockupProps) {
const { t } = useTranslation();
return (
<MockupStageWindow
ariaLabel={t("hub.demo.discord.alt")}
active={active}
reduceMotion={reduceMotion}
className="border-[#3F4147] bg-[#313338]"
>
<DiscordChrome />
<div className="grid min-h-0 flex-1 grid-cols-1 md:grid-cols-[164px_minmax(0,1fr)]">
<DiscordSidebar />
<div className="flex min-h-0 min-w-0 flex-col bg-[#313338]">
<DiscordChannelHeader />
<DiscordMessageFeed />
<DiscordComposer />
</div>
</div>
</MockupStageWindow>
);
}
function DiscordMessageFeed() {
const { t } = useTranslation();
return (
<div className="flex-1 space-y-3 px-4 py-3">
<MockupStep delay={STEP_DELAYS.userMention}>
<DiscordMessage author="mo" time={t("hub.demo.discord.time1")}>
<p>
<Trans i18nKey="hub.demo.discord.userPrompt" components={DISCORD_COMPONENTS} />
</p>
</DiscordMessage>
</MockupStep>
<MockupStep
delay={STEP_DELAYS.threadStart}
className="flex items-center gap-2 pl-2 text-[11.5px] text-[#949BA4]"
>
<CornerDownRight className="h-3.5 w-3.5 shrink-0 text-[#949BA4]" aria-hidden="true" />
<span className="font-medium text-[#F2F3F5]">paseo-bot</span>
<span>{t("hub.demo.discord.startedThread")}</span>
<span className="truncate font-semibold text-[#F2F3F5]">
{t("hub.demo.discord.threadTitle")}
</span>
</MockupStep>
<div className="ml-3 space-y-3 border-l-2 border-[#4E5058] pl-3.5">
<MockupStep delay={STEP_DELAYS.botWorking}>
<DiscordMessage author="paseo-bot" time={t("hub.demo.discord.time1")} bot>
<p className="text-[#DBDEE1]">
<Trans i18nKey="hub.demo.discord.botStarted" components={DISCORD_COMPONENTS} />
</p>
</DiscordMessage>
</MockupStep>
<MockupStep delay={STEP_DELAYS.botDone}>
<DiscordMessage author="paseo-bot" time={t("hub.demo.discord.time2")} bot>
<p className="text-[#DBDEE1]">{t("hub.demo.discord.botFinished")}</p>
<DiscordPrEmbed />
</DiscordMessage>
</MockupStep>
</div>
</div>
);
}
function DiscordPrEmbed() {
const { t } = useTranslation();
return (
<div className="mt-2 space-y-2">
<div className="rounded-[4px] border-l-[4px] border-[#2BAC76] bg-[#2B2D31] px-3 py-2.5">
<div className="flex items-center gap-1.5 text-[12px] font-semibold text-[#00A8FC]">
<GitPullRequest className="h-3.5 w-3.5 shrink-0 text-[#2BAC76]" aria-hidden="true" />
<span>getpaseo/paseo#2825</span>
</div>
<p className="mt-0.5 text-[12px] text-[#DBDEE1]">
fix(worktree): prune orphaned branches on close
</p>
<div className="mt-2 grid grid-cols-3 gap-2 text-[11px]">
<div>
<p className="font-semibold text-[#B5BAC1]">{t("hub.demo.discord.fieldHost")}</p>
<p className="font-mono text-[#DBDEE1]">devbox</p>
</div>
<div>
<p className="font-semibold text-[#B5BAC1]">{t("hub.demo.discord.fieldDiff")}</p>
<p className="font-mono text-[#DBDEE1]">+46 -12</p>
</div>
<div>
<p className="font-semibold text-[#B5BAC1]">{t("hub.demo.discord.fieldChecks")}</p>
<p className="inline-flex items-center gap-1 text-[#57F287]">
<Check className="h-3 w-3" aria-hidden="true" />
{t("hub.demo.shared.testsPassed")}
</p>
</div>
</div>
</div>
<div>
<OpenInPaseoChip variant="discord" />
</div>
</div>
);
}
function DiscordComposer() {
const { t } = useTranslation();
return (
<div
aria-hidden="true"
className="mx-4 mt-auto mb-3 flex items-center gap-2.5 rounded-[8px] bg-[#383A40] px-3 py-2 text-[12.5px] text-[#80848E]"
>
<PlusCircle className="h-4 w-4 shrink-0 text-[#B5BAC1]" />
<span className="truncate">{t("hub.demo.discord.composerPlaceholder")}</span>
</div>
);
}
function DiscordChrome() {
return (
<div className="flex h-9 shrink-0 items-center justify-between border-b border-[#1E1F22] bg-[#1E1F22] px-3.5">
<div className="flex items-center gap-3">
<WindowTrafficLights />
<span className="text-[12px] font-semibold text-[#B5BAC1]">Discord</span>
</div>
<DiscordIcon className="h-3.5 w-3.5 text-[#5865F2]" />
</div>
);
}
function DiscordSidebar() {
const { t } = useTranslation();
return (
<aside
aria-hidden="true"
className="hidden flex-col border-r border-[#1F2023] bg-[#2B2D31] md:flex"
>
<div className="border-b border-[#1F2023] px-3.5 py-2.5 text-[13.5px] font-bold text-[#F2F3F5]">
Paseo
</div>
<div className="space-y-0.5 px-2 py-3 text-[12.5px]">
<p className="px-2 pb-1 text-[10.5px] font-semibold uppercase tracking-wide text-[#949BA4]">
{t("hub.demo.discord.textChannels")}
</p>
{DISCORD_CHANNELS.map((channel) => (
<div key={channel}>
<div
className={`flex items-center gap-1.5 rounded-[5px] px-2 py-1 ${
channel === "engineering"
? "bg-[#404249] font-medium text-[#F2F3F5]"
: "text-[#949BA4]"
}`}
>
<Hash className="h-3.5 w-3.5 shrink-0 opacity-75" />
<span className="truncate">{channel}</span>
</div>
{channel === "engineering" ? (
<div className="mt-0.5 ml-3 flex items-center gap-1.5 border-l border-[#4E5058] py-1 pl-2 text-[11.5px] text-[#DBDEE1]">
<span className="truncate">{t("hub.demo.discord.threadTitle")}</span>
</div>
) : null}
</div>
))}
</div>
</aside>
);
}
function DiscordChannelHeader() {
const { t } = useTranslation();
return (
<div className="flex shrink-0 items-center justify-between gap-3 border-b border-[#26282C] px-4 py-2">
<div className="flex min-w-0 items-center gap-2">
<Hash className="h-4 w-4 shrink-0 text-[#80848E]" aria-hidden="true" />
<span className="text-[14px] font-semibold text-[#F2F3F5]">engineering</span>
<span className="hidden h-3.5 w-px bg-[#3F4147] sm:inline-block" aria-hidden="true" />
<span className="hidden truncate text-[11.5px] text-[#949BA4] sm:inline">
{t("hub.demo.discord.channelTopic")}
</span>
</div>
</div>
);
}
function DiscordMessage({
author,
time,
bot,
children,
}: {
author: string;
time: string;
bot?: boolean;
children: React.ReactNode;
}) {
const { t } = useTranslation();
return (
<div className="flex items-start gap-2.5">
{bot ? (
<PaseoBotAvatar size="md" rounded="rounded-full" className="mt-0.5" />
) : (
<MoAvatar size="md" rounded="rounded-full" className="mt-0.5" />
)}
<div className="min-w-0 flex-1 space-y-0.5">
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-[13.5px] font-semibold text-[#F2F3F5]">{author}</span>
{bot ? (
<span className="inline-flex items-center gap-0.5 rounded-[3px] bg-[#5865F2] px-1.5 py-[1px] text-[9.5px] font-semibold uppercase tracking-wide text-white">
<Check className="h-2.5 w-2.5" aria-hidden="true" />
{t("hub.demo.shared.appBadge")}
</span>
) : null}
<span className="text-[11px] text-[#949BA4]">{time}</span>
</div>
<div className="text-[13px] leading-[1.45] text-[#DBDEE1]">{children}</div>
</div>
</div>
);
}
@@ -0,0 +1,287 @@
import { Check, CircleDot, GitPullRequest, Tag } from "lucide-react";
import { Trans, useTranslation } from "react-i18next";
import { GitHubIcon } from "~/components/brand-icons";
import {
MoAvatar,
MockupStageWindow,
MockupStep,
OpenInPaseoChip,
PaseoBotAvatar,
type SourceMockupProps,
WindowTrafficLights,
} from "./shared";
const STEP_DELAYS = {
issue: 0.06,
labelEvent: 0.55,
botReply: 1.2,
checks: 1.85,
} as const;
const GH_COMPONENTS = {
mention: <span className="font-semibold text-[#58A6FF]">@paseo-bot</span>,
host: (
<span className="rounded-[4px] border border-[#30363D] bg-[#161B22] px-1.5 py-[1px] font-mono text-[11px] text-[#E6EDF3]" />
),
pr: <span className="font-medium text-[#58A6FF] underline decoration-[#58A6FF]/40" />,
code: (
<code className="rounded-[4px] bg-[#21262D] px-1.5 py-[1px] font-mono text-[11.5px] text-[#E6EDF3]" />
),
};
const CHECK_NAMES = ["typecheck", "vitest", "lint", "build"] as const;
export function GitHubSourceMockup({ active, reduceMotion }: SourceMockupProps) {
const { t } = useTranslation();
return (
<MockupStageWindow
ariaLabel={t("hub.demo.github.alt")}
active={active}
reduceMotion={reduceMotion}
className="border-[#30363D] bg-[#0D1117]"
>
<GitHubChrome />
<GitHubIssueHeader />
<div className="grid min-h-0 flex-1 grid-cols-1 sm:grid-cols-[minmax(0,1fr)_156px]">
<GitHubTimeline />
<GitHubSidebar />
</div>
</MockupStageWindow>
);
}
function GitHubTimeline() {
const { t } = useTranslation();
return (
<div className="relative space-y-3 px-4 py-3.5">
<span
aria-hidden="true"
className="pointer-events-none absolute top-11 bottom-6 left-[27px] w-[2px] bg-[#21262D]"
/>
<MockupStep delay={STEP_DELAYS.issue} className="relative">
<GitHubComment
author="mo"
badge={t("hub.demo.github.authorBadge")}
timestamp={t("hub.demo.github.openedAgo")}
>
<p>
<Trans i18nKey="hub.demo.github.issueBody" components={GH_COMPONENTS} />
</p>
</GitHubComment>
</MockupStep>
<MockupStep
delay={STEP_DELAYS.labelEvent}
className="relative flex items-center gap-2.5 pl-1"
>
<span className="relative z-10 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-[#30363D] bg-[#161B22] text-[#8B949E]">
<Tag className="h-3 w-3" aria-hidden="true" />
</span>
<div className="flex flex-wrap items-center gap-1.5 text-[11.5px] text-[#8B949E]">
<span className="font-semibold text-[#E6EDF3]">mo</span>
<span>{t("hub.demo.github.addedLabel")}</span>
<span className="rounded-full border border-[#20744A]/60 bg-[#20744A]/20 px-2 py-[1px] font-mono text-[10.5px] font-medium text-[#6CB17B]">
paseo
</span>
<span>·</span>
<span>{t("hub.demo.github.startedOn")}</span>
</div>
</MockupStep>
<MockupStep delay={STEP_DELAYS.botReply} className="relative">
<GitHubComment
author="paseo-bot"
badge={t("hub.demo.github.botBadge")}
timestamp={t("hub.demo.github.repliedAgo")}
bot
>
<p>
<Trans i18nKey="hub.demo.github.botReply" components={GH_COMPONENTS} />
</p>
<GitHubPrSummaryCard />
</GitHubComment>
</MockupStep>
</div>
);
}
function GitHubPrSummaryCard() {
const { t } = useTranslation();
return (
<MockupStep
delay={STEP_DELAYS.checks}
className="mt-2.5 overflow-hidden rounded-md border border-[#30363D] bg-[#0D1117]"
>
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-[#21262D] bg-[#161B22] px-3 py-2">
<div className="flex min-w-0 items-center gap-1.5">
<GitPullRequest className="h-3.5 w-3.5 shrink-0 text-[#3FB950]" aria-hidden="true" />
<span className="text-[12px] font-semibold text-[#E6EDF3]">
fix(terminal): drain PTY write queue under burst
</span>
<span className="font-mono text-[11px] text-[#8B949E]">#2819</span>
</div>
<span className="shrink-0 font-mono text-[11px]">
<span className="text-[#3FB950]">+84</span> <span className="text-[#F85149]">-19</span>
</span>
</div>
<div className="flex flex-wrap items-center justify-between gap-2 px-3 py-2">
<div className="flex flex-wrap items-center gap-1.5">
<span className="inline-flex items-center gap-1 text-[11.5px] font-medium text-[#3FB950]">
<Check className="h-3.5 w-3.5" aria-hidden="true" />
{t("hub.demo.github.checksPassed")}
</span>
<span className="hidden items-center gap-1 sm:inline-flex">
{CHECK_NAMES.map((name) => (
<span
key={name}
className="rounded border border-[#30363D] bg-[#161B22] px-1.5 py-[1px] font-mono text-[10px] text-[#8B949E]"
>
{name}
</span>
))}
</span>
</div>
<OpenInPaseoChip variant="brand" />
</div>
</MockupStep>
);
}
function GitHubChrome() {
return (
<div className="flex h-9 shrink-0 items-center justify-between border-b border-[#21262D] bg-[#010409] px-3.5">
<div className="flex items-center gap-3">
<WindowTrafficLights />
<div className="flex items-center gap-1.5 text-[12px] text-[#8B949E]">
<GitHubIcon className="h-3.5 w-3.5 text-[#E6EDF3]" />
<span>getpaseo</span>
<span className="text-[#484F58]">/</span>
<span className="font-semibold text-[#E6EDF3]">paseo</span>
</div>
</div>
<div
className="hidden items-center gap-4 text-[11.5px] text-[#8B949E] sm:flex"
aria-hidden="true"
>
<span className="relative py-2 font-medium text-[#E6EDF3]">
Issues
<span className="absolute right-0 -bottom-[3px] left-0 h-[2px] rounded-full bg-[#F78166]" />
</span>
<span>Pull requests</span>
<span>Actions</span>
</div>
</div>
);
}
function GitHubIssueHeader() {
const { t } = useTranslation();
return (
<div className="shrink-0 border-b border-[#21262D] px-4 py-3">
<div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">
<h4 className="text-[15px] font-semibold text-[#E6EDF3]">
{t("hub.demo.github.issueTitle")}
</h4>
<span className="font-mono text-[14px] text-[#8B949E]">#2811</span>
</div>
<div className="mt-1.5 flex flex-wrap items-center gap-2 text-[11.5px] text-[#8B949E]">
<span className="inline-flex items-center gap-1 rounded-full bg-[#238636] px-2.5 py-0.5 text-[11px] font-semibold text-white">
<CircleDot className="h-3 w-3" aria-hidden="true" />
Open
</span>
<span>
<strong className="font-semibold text-[#E6EDF3]">mo</strong>{" "}
{t("hub.demo.github.issueMeta")}
</span>
</div>
</div>
);
}
function GitHubComment({
author,
badge,
timestamp,
bot,
children,
}: {
author: string;
badge: string;
timestamp: string;
bot?: boolean;
children: React.ReactNode;
}) {
return (
<div className="flex items-start gap-2.5">
{bot ? (
<PaseoBotAvatar size="sm" rounded="rounded-full" className="relative z-10 mt-0.5 h-7 w-7" />
) : (
<MoAvatar size="sm" rounded="rounded-full" className="relative z-10 mt-0.5 h-7 w-7" />
)}
<div className="min-w-0 flex-1 overflow-hidden rounded-md border border-[#30363D] bg-[#0D1117]">
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-[#21262D] bg-[#161B22] px-3 py-1.5 text-[11.5px]">
<div className="flex items-center gap-1.5">
<span className="font-semibold text-[#E6EDF3]">{author}</span>
<span className="rounded-full border border-[#30363D] px-1.5 py-[0.5px] text-[10px] font-medium text-[#8B949E]">
{badge}
</span>
</div>
<span className="text-[11px] text-[#8B949E]">{timestamp}</span>
</div>
<div className="px-3 py-2.5 text-[12.5px] leading-[1.5] text-[#C9D1D9]">{children}</div>
</div>
</div>
);
}
function GitHubSidebar() {
const { t } = useTranslation();
return (
<aside
aria-hidden="true"
className="hidden flex-col gap-3.5 border-l border-[#21262D] px-3.5 py-3.5 text-[11.5px] sm:flex"
>
<div className="space-y-1.5 border-b border-[#21262D] pb-3">
<p className="font-medium text-[#8B949E]">{t("hub.demo.github.assignees")}</p>
<div className="flex items-center gap-1.5 text-[#E6EDF3]">
<PaseoBotAvatar size="xs" rounded="rounded-full" />
<span className="font-medium">paseo-bot</span>
</div>
</div>
<div className="space-y-1.5 border-b border-[#21262D] pb-3">
<p className="font-medium text-[#8B949E]">{t("hub.demo.github.labels")}</p>
<div className="flex flex-wrap gap-1">
<span className="rounded-full border border-[#F85149]/40 bg-[#F85149]/15 px-2 py-[1px] text-[10.5px] font-medium text-[#FF7B72]">
bug
</span>
<span className="rounded-full border border-[#D29922]/40 bg-[#D29922]/15 px-2 py-[1px] text-[10.5px] font-medium text-[#E3B341]">
p0
</span>
<span className="rounded-full border border-[#20744A]/60 bg-[#20744A]/20 px-2 py-[1px] text-[10.5px] font-medium text-[#6CB17B]">
paseo
</span>
</div>
</div>
<div className="space-y-1.5 border-b border-[#21262D] pb-3">
<p className="font-medium text-[#8B949E]">{t("hub.demo.github.development")}</p>
<div className="flex items-center gap-1.5 text-[#58A6FF]">
<GitPullRequest className="h-3.5 w-3.5 shrink-0 text-[#3FB950]" />
<span className="font-mono text-[11.5px]">#2819</span>
</div>
</div>
<div className="space-y-1">
<p className="font-medium text-[#8B949E]">{t("hub.demo.github.daemon")}</p>
<span className="inline-block rounded border border-[#30363D] bg-[#161B22] px-1.5 py-0.5 font-mono text-[11px] text-[#E6EDF3]">
macbook-pro
</span>
</div>
</aside>
);
}
@@ -0,0 +1,243 @@
import { AnimatePresence, motion, useInView, useReducedMotion } from "framer-motion";
import { ArrowRight } from "lucide-react";
import * as React from "react";
import { useTranslation } from "react-i18next";
import {
HUB_TRIGGER_SOURCES,
type HubTriggerSource,
type HubTriggerSourceId,
} from "~/components/hub-flow";
import { useLocalizePath } from "~/i18n";
import { DiscordSourceMockup } from "./discord-mockup";
import { GitHubSourceMockup } from "./github-mockup";
import { LinearSourceMockup } from "./linear-mockup";
import { SchedulesSourceMockup } from "./schedules-mockup";
import type { SourceMockupProps } from "./shared";
import { SlackSourceMockup } from "./slack-mockup";
import { WebhooksSourceMockup } from "./webhooks-mockup";
const SHOWCASE_ORDER: readonly HubTriggerSourceId[] = [
"slack",
"github",
"linear",
"discord",
"schedules",
"webhooks",
];
const SOURCE_DOC_PATHS: Record<HubTriggerSourceId, string> = {
slack: "/docs/hub/triggers/slack",
github: "/docs/hub/triggers/github",
linear: "/docs/hub/triggers/linear",
discord: "/docs/hub/triggers/discord",
schedules: "/docs/hub/triggers/schedules",
webhooks: "/docs/hub/triggers/webhooks",
};
const SHOWCASE_SOURCES: readonly HubTriggerSource[] = SHOWCASE_ORDER.map((id) => {
const source = HUB_TRIGGER_SOURCES.find((item) => item.id === id);
if (!source) {
throw new Error(`Missing Hub trigger source metadata for "${id}"`);
}
return source;
});
const SOURCE_MOCKUPS: Record<HubTriggerSourceId, React.ComponentType<SourceMockupProps>> = {
slack: SlackSourceMockup,
github: GitHubSourceMockup,
linear: LinearSourceMockup,
discord: DiscordSourceMockup,
schedules: SchedulesSourceMockup,
webhooks: WebhooksSourceMockup,
};
const PANEL_INITIAL = { opacity: 0, y: 4 } as const;
const PANEL_ANIMATE = { opacity: 1, y: 0 } as const;
const PANEL_EXIT = { opacity: 0, y: -4 } as const;
const PANEL_TRANSITION = { duration: 0.16, ease: "easeOut" } as const;
const STAGE_IN_VIEW_OPTIONS = { once: true, margin: "-60px" } as const;
/**
* Interactive split showcase for Paseo Hub automation sources:
* left clickable pills on desktop (compact pill grid on mobile) paired with a fixed-height
* right stage that swaps between authentic, animated dark-mode mockups with zero layout shift.
*/
export function HubAutomationsShowcase() {
const { t } = useTranslation();
const localize = useLocalizePath();
const reduceMotion = useReducedMotion() === true;
const [selected, setSelected] = React.useState<HubTriggerSourceId>("slack");
const stageRef = React.useRef<HTMLDivElement | null>(null);
const tabRefs = React.useRef<Partial<Record<HubTriggerSourceId, HTMLButtonElement | null>>>({});
const isInView = useInView(stageRef, STAGE_IN_VIEW_OPTIONS);
const ActiveMockup = SOURCE_MOCKUPS[selected];
const registerTabRef = React.useCallback(
(id: HubTriggerSourceId, node: HTMLButtonElement | null) => {
tabRefs.current[id] = node;
},
[],
);
const handleNavigate = React.useCallback((index: number, key: string): boolean => {
let nextIndex: number | null = null;
if (key === "ArrowDown" || key === "ArrowRight") {
nextIndex = (index + 1) % SHOWCASE_SOURCES.length;
} else if (key === "ArrowUp" || key === "ArrowLeft") {
nextIndex = (index - 1 + SHOWCASE_SOURCES.length) % SHOWCASE_SOURCES.length;
} else if (key === "Home") {
nextIndex = 0;
} else if (key === "End") {
nextIndex = SHOWCASE_SOURCES.length - 1;
}
if (nextIndex === null) return false;
const nextId = SHOWCASE_SOURCES[nextIndex].id;
setSelected(nextId);
tabRefs.current[nextId]?.focus();
return true;
}, []);
return (
<div className="grid items-start gap-6 lg:grid-cols-[292px_minmax(0,1fr)] lg:gap-6">
<div className="space-y-2.5">
<div
role="tablist"
aria-label={t("hub.demo.shared.tablistLabel")}
className="grid grid-cols-3 gap-1.5 sm:gap-2 lg:flex lg:flex-col lg:gap-1.5"
>
{SHOWCASE_SOURCES.map((source, index) => (
<SourceTabButton
key={source.id}
source={source}
index={index}
isSelected={source.id === selected}
onSelect={setSelected}
onNavigate={handleNavigate}
registerRef={registerTabRef}
/>
))}
</div>
<p className="text-xs text-muted-foreground lg:hidden">
{t(`hub.sources.${selected}.description`)}
</p>
</div>
<figure ref={stageRef} className="min-w-0 space-y-3">
<div className="relative lg:h-[528px]">
<AnimatePresence mode="wait" initial={false}>
<motion.div
key={selected}
role="tabpanel"
id={`hub-source-panel-${selected}`}
aria-labelledby={`hub-source-tab-${selected}`}
tabIndex={0}
initial={reduceMotion ? false : PANEL_INITIAL}
animate={PANEL_ANIMATE}
exit={reduceMotion ? undefined : PANEL_EXIT}
transition={PANEL_TRANSITION}
className="h-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent-text"
>
<ActiveMockup active={isInView} reduceMotion={reduceMotion} />
</motion.div>
</AnimatePresence>
</div>
<figcaption className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1.5 min-h-[1.25rem] text-sm text-muted-foreground">
<span>{t(`hub.demo.${selected}.caption`)}</span>
<a
href={localize(SOURCE_DOC_PATHS[selected])}
className="inline-flex shrink-0 items-center gap-1.5 text-sm text-white/75 transition-colors hover:text-accent-text"
>
{t("hub.demo.shared.docsLink", { source: t(`hub.sources.${selected}.name`) })}
<ArrowRight className="h-3.5 w-3.5" aria-hidden="true" />
</a>
</figcaption>
</figure>
</div>
);
}
function SourceTabButton({
source,
index,
isSelected,
onSelect,
onNavigate,
registerRef,
}: {
source: HubTriggerSource;
index: number;
isSelected: boolean;
onSelect: (id: HubTriggerSourceId) => void;
onNavigate: (index: number, key: string) => boolean;
registerRef: (id: HubTriggerSourceId, node: HTMLButtonElement | null) => void;
}) {
const { t } = useTranslation();
const { id, Icon } = source;
const setRef = React.useCallback(
(node: HTMLButtonElement | null) => {
registerRef(id, node);
},
[id, registerRef],
);
const handleClick = React.useCallback(() => {
onSelect(id);
}, [id, onSelect]);
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLButtonElement>) => {
if (onNavigate(index, event.key)) {
event.preventDefault();
}
},
[index, onNavigate],
);
return (
<button
ref={setRef}
type="button"
role="tab"
id={`hub-source-tab-${id}`}
aria-selected={isSelected}
aria-controls={`hub-source-panel-${id}`}
tabIndex={isSelected ? 0 : -1}
onClick={handleClick}
onKeyDown={handleKeyDown}
className={`group flex min-h-[42px] cursor-pointer items-center justify-center gap-2 rounded-xl border px-2.5 py-2 text-left transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent-text lg:min-h-0 lg:items-start lg:justify-start lg:gap-3 lg:px-3.5 lg:py-3 ${
isSelected
? "border-brand-green/55 bg-brand-green/[0.13] text-white"
: "border-white/[0.07] bg-white/[0.015] text-white/70 hover:border-white/[0.14] hover:bg-white/[0.035] hover:text-white/90 lg:border-transparent lg:bg-transparent"
}`}
>
<span
className={`shrink-0 transition-colors lg:mt-0.5 ${
isSelected ? "text-accent-text" : "text-white/55 group-hover:text-white/80"
}`}
>
<Icon className="h-4 w-4 lg:h-[18px] lg:w-[18px]" />
</span>
<span className="min-w-0 flex-1">
<span
className={`block truncate text-xs leading-5 font-medium lg:text-sm ${
isSelected ? "text-white" : "text-white/80 group-hover:text-white"
}`}
>
{t(`hub.sources.${id}.name`)}
</span>
<span
className={`mt-0.5 hidden truncate text-xs leading-4 lg:block ${
isSelected ? "text-white/65" : "text-muted-foreground"
}`}
>
{t(`hub.sources.${id}.description`)}
</span>
</span>
</button>
);
}
@@ -0,0 +1 @@
export { HubAutomationsShowcase } from "./hub-automations-showcase";
@@ -0,0 +1,242 @@
import { Check, ChevronRight, GitPullRequest, SignalHigh } from "lucide-react";
import { Trans, useTranslation } from "react-i18next";
import { LinearIcon } from "~/components/brand-icons";
import {
MoAvatar,
MockupStageWindow,
MockupStep,
OpenInPaseoChip,
PaseoBotAvatar,
type SourceMockupProps,
WindowTrafficLights,
} from "./shared";
const STEP_DELAYS = {
assigned: 0.08,
running: 0.65,
comment: 1.35,
} as const;
const LINEAR_COMPONENTS = {
host: (
<span className="rounded bg-[#22252E] px-1.5 py-[1px] font-mono text-[11px] text-[#E3E6F0]" />
),
code: (
<code className="rounded bg-[#22252E] px-1.5 py-[1px] font-mono text-[11px] text-[#C5CCDF]" />
),
};
export function LinearSourceMockup({ active, reduceMotion }: SourceMockupProps) {
const { t } = useTranslation();
return (
<MockupStageWindow
ariaLabel={t("hub.demo.linear.alt")}
active={active}
reduceMotion={reduceMotion}
className="border-[#262932] bg-[#111318]"
>
<LinearChrome />
<div className="grid min-h-0 flex-1 grid-cols-1 sm:grid-cols-[minmax(0,1fr)_172px]">
<LinearIssuePane />
<LinearPropertiesSidebar />
</div>
</MockupStageWindow>
);
}
function LinearIssuePane() {
const { t } = useTranslation();
return (
<div className="flex min-h-0 flex-col px-5 py-4">
<div className="space-y-1.5 border-b border-[#22252E] pb-3.5">
<p className="font-mono text-[11.5px] text-[#8A8F9E]">PAS-418</p>
<h4 className="text-[16px] font-semibold tracking-[-0.01em] text-[#F1F3F8]">
{t("hub.demo.linear.issueTitle")}
</h4>
<p className="text-[12.5px] leading-relaxed text-[#9DA3B4]">
{t("hub.demo.linear.issueDescription")}
</p>
</div>
<LinearActivityFeed />
</div>
);
}
function LinearActivityFeed() {
const { t } = useTranslation();
return (
<div className="mt-3.5 flex-1 space-y-3">
<p className="text-[11px] font-medium uppercase tracking-wider text-[#6D7385]">
{t("hub.demo.linear.activity")}
</p>
<MockupStep
delay={STEP_DELAYS.assigned}
className="flex items-center gap-2 text-[12px] text-[#9DA3B4]"
>
<MoAvatar size="xs" rounded="rounded-full" />
<span className="min-w-0">
<strong className="font-medium text-[#ECEEF4]">mo</strong>{" "}
{t("hub.demo.linear.assignedEvent")}{" "}
<strong className="font-medium text-[#ECEEF4]">paseo-bot</strong>
</span>
<span className="ml-auto shrink-0 text-[11px] text-[#6D7385]">11m</span>
</MockupStep>
<LinearRunStatusRow />
<LinearBotCommentCard />
</div>
);
}
function LinearRunStatusRow() {
const { t } = useTranslation();
return (
<MockupStep
delay={STEP_DELAYS.running}
className="flex items-center gap-2.5 rounded-lg border border-[#242834] bg-[#171A21] px-3 py-2 text-[12px]"
>
<PaseoBotAvatar size="sm" rounded="rounded-full" />
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-center gap-1.5">
<span className="font-medium text-[#ECEEF4]">paseo-bot</span>
<span className="text-[#6D7385]">·</span>
<span className="text-[#9DA3B4]">
<Trans i18nKey="hub.demo.linear.runningOn" components={LINEAR_COMPONENTS} />
</span>
</div>
<p className="mt-0.5 font-mono text-[11px] wrap-anywhere text-[#7D8599]">
{t("hub.demo.linear.traceLine")}
</p>
</div>
<Check className="h-3.5 w-3.5 shrink-0 text-[#6CB17B]" aria-hidden="true" />
</MockupStep>
);
}
function LinearBotCommentCard() {
const { t } = useTranslation();
return (
<MockupStep
delay={STEP_DELAYS.comment}
className="rounded-lg border border-[#262A36] bg-[#161820] p-3.5"
>
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-2">
<PaseoBotAvatar size="sm" rounded="rounded-full" />
<span className="text-[12.5px] font-semibold text-[#F1F3F8]">paseo-bot</span>
<span className="rounded bg-[#252936] px-1.5 py-[1px] text-[10px] font-medium uppercase tracking-wide text-[#9DA3B4]">
{t("hub.demo.shared.appBadge")}
</span>
</div>
<span className="text-[11px] text-[#6D7385]">6m</span>
</div>
<p className="mt-2 text-[12.5px] leading-[1.5] text-[#C5CCDF]">
<Trans i18nKey="hub.demo.linear.botSummary" components={LINEAR_COMPONENTS} />
</p>
<div className="mt-3 flex flex-wrap items-center justify-between gap-2 border-t border-[#242834] pt-2.5">
<span className="inline-flex items-center gap-1.5 rounded-md border border-[#2A2F3D] bg-[#1C1F2A] px-2 py-1 font-mono text-[11px] text-[#C5CCDF]">
<GitPullRequest className="h-3 w-3 text-[#6CB17B]" aria-hidden="true" />
<span>#2822</span>
<span className="text-[#6CB17B]">· {t("hub.demo.shared.testsPassed")}</span>
</span>
<OpenInPaseoChip variant="brand" />
</div>
</MockupStep>
);
}
function LinearChrome() {
return (
<div className="flex h-9 shrink-0 items-center justify-between border-b border-[#22252E] bg-[#15171E] px-3.5">
<div className="flex items-center gap-3">
<WindowTrafficLights />
<div className="flex items-center gap-1 text-[11.5px] text-[#8A8F9E]">
<LinearIcon className="h-3.5 w-3.5 text-[#5E6AD2]" />
<span>Paseo</span>
<ChevronRight className="h-3 w-3 text-[#555B6E]" aria-hidden="true" />
<span>Core</span>
<ChevronRight className="h-3 w-3 text-[#555B6E]" aria-hidden="true" />
<span className="font-mono text-[#E3E6F0]">PAS-418</span>
</div>
</div>
<span className="hidden rounded-full border border-[#5E6AD2]/35 bg-[#5E6AD2]/15 px-2 py-0.5 text-[10.5px] font-medium text-[#A4ACEE] sm:inline-block">
Cycle 14
</span>
</div>
);
}
function LinearPropertiesSidebar() {
const { t } = useTranslation();
return (
<aside
aria-hidden="true"
className="hidden flex-col gap-3.5 border-l border-[#22252E] bg-[#13151B] px-3.5 py-4 text-[11.5px] sm:flex"
>
<p className="text-[11px] font-medium text-[#6D7385]">{t("hub.demo.linear.properties")}</p>
<LinearPropRow label={t("hub.demo.linear.status")}>
<span className="inline-flex items-center gap-1.5 text-[#ECEEF4]">
<span className="h-2.5 w-2.5 rounded-full border-2 border-[#6CB17B] bg-[#6CB17B]/35" />
<span>In Review</span>
</span>
</LinearPropRow>
<LinearPropRow label={t("hub.demo.linear.priority")}>
<span className="inline-flex items-center gap-1.5 text-[#ECEEF4]">
<SignalHigh className="h-3.5 w-3.5 text-[#F2994A]" />
<span>High</span>
</span>
</LinearPropRow>
<LinearPropRow label={t("hub.demo.linear.assignee")}>
<span className="inline-flex items-center gap-1.5 text-[#ECEEF4]">
<PaseoBotAvatar size="xs" rounded="rounded-full" />
<span>paseo-bot</span>
</span>
</LinearPropRow>
<LinearPropRow label={t("hub.demo.linear.creator")}>
<span className="inline-flex items-center gap-1.5 text-[#ECEEF4]">
<MoAvatar size="xs" rounded="rounded-full" />
<span>mo</span>
</span>
</LinearPropRow>
<LinearPropRow label={t("hub.demo.linear.labels")}>
<div className="flex flex-wrap gap-1">
<span className="inline-flex items-center gap-1 rounded-full border border-[#2A2F3D] bg-[#1A1D26] px-2 py-[1px] text-[10.5px] text-[#C5CCDF]">
<span className="h-1.5 w-1.5 rounded-full bg-[#5E6AD2]" />
mobile
</span>
<span className="inline-flex items-center gap-1 rounded-full border border-[#2A2F3D] bg-[#1A1D26] px-2 py-[1px] text-[10.5px] text-[#C5CCDF]">
<span className="h-1.5 w-1.5 rounded-full bg-[#6CB17B]" />
relay
</span>
</div>
</LinearPropRow>
<LinearPropRow label={t("hub.demo.linear.daemon")}>
<span className="rounded border border-[#2A2F3D] bg-[#1A1D26] px-1.5 py-0.5 font-mono text-[10.5px] text-[#C5CCDF]">
devbox
</span>
</LinearPropRow>
</aside>
);
}
function LinearPropRow({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="space-y-1">
<p className="text-[10.5px] text-[#6D7385]">{label}</p>
<div>{children}</div>
</div>
);
}
@@ -0,0 +1,208 @@
import { Check, Clock, GitPullRequest, Hash, TrendingDown } from "lucide-react";
import { Trans, useTranslation } from "react-i18next";
import {
MockupStageWindow,
MockupStep,
OpenInPaseoChip,
PaseoBotAvatar,
type SourceMockupProps,
WindowTrafficLights,
} from "./shared";
import { SlackColorMark } from "./slack-mockup";
const STEP_DELAYS = {
triggered: 0.06,
prOpened: 0.7,
slackDigest: 1.4,
} as const;
const SCHEDULE_COMPONENTS = {
code: (
<code className="rounded bg-white/[0.07] px-1.5 py-[1px] font-mono text-[11px] text-white/90" />
),
pr: <span className="font-medium text-[#1D9BD1] underline decoration-[#1D9BD1]/40" />,
strong: <strong className="font-semibold text-white" />,
};
export function SchedulesSourceMockup({ active, reduceMotion }: SourceMockupProps) {
const { t } = useTranslation();
return (
<MockupStageWindow
ariaLabel={t("hub.demo.schedules.alt")}
active={active}
reduceMotion={reduceMotion}
className="border-white/[0.1] bg-[#121716]"
>
<ScheduleChrome />
<ScheduleHeaderBar />
<div className="flex flex-1 flex-col justify-between gap-3 px-4 py-3.5">
<ScheduleStepsList />
<ScheduleImpactMetrics />
<ScheduleSlackDigestCard />
</div>
</MockupStageWindow>
);
}
function ScheduleChrome() {
const { t } = useTranslation();
return (
<div className="flex min-h-9 shrink-0 items-center justify-between gap-2 border-b border-white/[0.07] bg-[#0D1211] px-3.5 py-1">
<div className="flex min-w-0 items-center gap-3">
<WindowTrafficLights />
<div className="flex min-w-0 items-center gap-1.5 font-mono text-[11.5px] text-white/65">
<Clock className="h-3.5 w-3.5 shrink-0 text-accent-text" aria-hidden="true" />
<span className="wrap-anywhere">.paseo/triggers/daily-ci-optimizer.yml</span>
</div>
</div>
<span className="inline-flex shrink-0 items-center gap-1.5 rounded-full border border-brand-green/50 bg-brand-green/20 px-2 py-0.5 text-[10.5px] font-medium text-accent-text">
<span className="h-1.5 w-1.5 rounded-full bg-[#35C264]" />
{t("hub.demo.schedules.active")}
</span>
</div>
);
}
function ScheduleHeaderBar() {
const { t } = useTranslation();
return (
<div className="flex shrink-0 flex-wrap items-center justify-between gap-2 border-b border-white/[0.07] bg-white/[0.02] px-4 py-2.5">
<div>
<h4 className="text-[14px] font-semibold text-white/95">
{t("hub.demo.schedules.jobTitle")}
</h4>
<p className="text-[11.5px] text-white/55">{t("hub.demo.schedules.cadence")}</p>
</div>
<div className="flex flex-wrap items-center gap-1.5 font-mono text-[11px]">
<span className="rounded border border-white/10 bg-[#0D1211] px-2 py-0.5 text-accent-text">
0 7 * * 1-5
</span>
<span className="rounded border border-white/10 bg-[#0D1211] px-2 py-0.5 text-white/70">
devbox · Claude Code
</span>
</div>
</div>
);
}
function ScheduleStepsList() {
const { t } = useTranslation();
return (
<div className="space-y-3">
<MockupStep delay={STEP_DELAYS.triggered} className="flex items-start gap-2.5">
<span className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-brand-green/45 bg-brand-green/15 text-accent-text">
<Check className="h-3.5 w-3.5" aria-hidden="true" />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2 text-[12px]">
<span className="font-medium text-white/90">{t("hub.demo.schedules.step1Title")}</span>
<span className="font-mono text-[11px] text-white/40">7:00 AM</span>
</div>
<p className="mt-0.5 text-[12px] leading-relaxed text-white/65">
<Trans i18nKey="hub.demo.schedules.step1Detail" components={SCHEDULE_COMPONENTS} />
</p>
</div>
</MockupStep>
<MockupStep delay={STEP_DELAYS.prOpened} className="flex items-start gap-2.5">
<span className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-brand-green/45 bg-brand-green/15 text-accent-text">
<GitPullRequest className="h-3.5 w-3.5" aria-hidden="true" />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center justify-between gap-2 text-[12px]">
<span className="font-medium text-white/90">{t("hub.demo.schedules.step2Title")}</span>
<span className="font-mono text-[11px] text-white/40">7:04 AM</span>
</div>
<SchedulePrPill />
</div>
</MockupStep>
</div>
);
}
function SchedulePrPill() {
const { t } = useTranslation();
return (
<div className="mt-1.5 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-white/[0.08] bg-[#171E1D] px-3 py-2">
<div className="flex min-w-0 items-center gap-1.5 text-[12px]">
<span className="font-medium text-white/90">
perf(ci): cache cargo target & stabilize e2e wait
</span>
<span className="font-mono text-[11px] text-white/45">#2831</span>
</div>
<div className="flex shrink-0 items-center gap-1.5 font-mono text-[10.5px]">
<span className="inline-flex items-center gap-1 rounded bg-[#2BAC76]/15 px-1.5 py-0.5 text-[#6CB17B]">
<TrendingDown className="h-3 w-3" aria-hidden="true" />
CI -38%
</span>
<span className="inline-flex items-center gap-1 rounded border border-white/10 bg-white/[0.04] px-1.5 py-0.5 text-white/70">
<Check className="h-3 w-3 text-[#6CB17B]" aria-hidden="true" />
{t("hub.demo.shared.testsPassed")}
</span>
</div>
</div>
);
}
function ScheduleImpactMetrics() {
const { t } = useTranslation();
return (
<MockupStep
delay={1.05}
className="grid grid-cols-3 divide-x divide-white/[0.07] overflow-hidden rounded-lg border border-white/[0.07] bg-white/[0.02]"
>
<div className="px-3 py-2">
<p className="text-[10.5px] text-white/45">{t("hub.demo.schedules.metricRuntime")}</p>
<p className="mt-0.5 font-mono text-[12px] font-medium text-accent-text">7m 12s → 4m 28s</p>
</div>
<div className="px-3 py-2">
<p className="text-[10.5px] text-white/45">{t("hub.demo.schedules.metricFlake")}</p>
<p className="mt-0.5 font-mono text-[12px] font-medium text-accent-text">18% → 0%</p>
</div>
<div className="px-3 py-2">
<p className="text-[10.5px] text-white/45">{t("hub.demo.schedules.metricCache")}</p>
<p className="mt-0.5 font-mono text-[12px] font-medium text-white/85">94% hit</p>
</div>
</MockupStep>
);
}
function ScheduleSlackDigestCard() {
const { t } = useTranslation();
return (
<MockupStep
delay={STEP_DELAYS.slackDigest}
className="overflow-hidden rounded-lg border border-[#35373B] bg-[#1A1D21]"
>
<div className="flex items-center justify-between border-b border-[#2C2D30] bg-[#14161A] px-3 py-1.5 text-[11px] text-[#ABABAD]">
<span className="inline-flex items-center gap-1.5 font-medium text-[#E5E7EB]">
<SlackColorMark className="h-3 w-3" />
<Hash className="h-3 w-3 text-[#ABABAD]" aria-hidden="true" />
engineering
</span>
<span>{t("hub.demo.schedules.slackPosted")}</span>
</div>
<div className="flex items-start gap-2.5 px-3.5 py-3">
<PaseoBotAvatar size="sm" className="mt-0.5 h-8 w-8" />
<div className="min-w-0 flex-1 space-y-1.5">
<div className="flex items-center gap-1.5">
<span className="text-[13px] font-bold text-[#F8F8F8]">paseo-bot</span>
<span className="rounded-[3px] bg-[#2C2D30] px-1.5 py-[1px] text-[9.5px] font-semibold uppercase tracking-wide text-[#ABABAD]">
{t("hub.demo.shared.appBadge")}
</span>
<span className="text-[11px] text-[#ABABAD]">7:05 AM</span>
</div>
<p className="text-[12.5px] leading-[1.45] text-[#D1D2D3]">
<Trans i18nKey="hub.demo.schedules.slackSummary" components={SCHEDULE_COMPONENTS} />
</p>
<div className="flex flex-wrap items-center gap-2 pt-0.5">
<OpenInPaseoChip variant="slack" />
<span className="text-[11px] text-[#ABABAD]">{t("hub.demo.schedules.notifiedMo")}</span>
</div>
</div>
</div>
</MockupStep>
);
}
@@ -0,0 +1,165 @@
import { motion, type Variants } from "framer-motion";
import type * as React from "react";
import { useTranslation } from "react-i18next";
import { PaseoMark } from "~/components/paseo-brand";
export interface SourceMockupProps {
/** Whether the section is visible or reduced motion is requested. */
active: boolean;
reduceMotion: boolean;
}
export const STEP_VARIANTS: Variants = {
hidden: { opacity: 0, y: 6 },
shown: (delay: number) => ({
opacity: 1,
y: 0,
transition: { delay, duration: 0.32, ease: "easeOut" },
}),
};
type AvatarSize = "xs" | "sm" | "md";
const AVATAR_DIM: Record<AvatarSize, string> = {
xs: "h-4 w-4",
sm: "h-6 w-6",
md: "h-8 w-8 sm:h-9 sm:w-9",
};
const AVATAR_PX: Record<AvatarSize, number> = {
xs: 16,
sm: 24,
md: 36,
};
const BOT_ICON_DIM: Record<AvatarSize, string> = {
xs: "h-2.5 w-2.5",
sm: "h-3.5 w-3.5",
md: "h-4 w-4 sm:h-5 sm:w-5",
};
type OpenChipVariant = "brand" | "slack" | "discord" | "subtle";
const OPEN_CHIP_STYLES: Record<OpenChipVariant, string> = {
brand: "bg-[#20744A] text-white",
slack: "bg-[#007A5A] text-white",
discord: "bg-[#248046] text-white",
subtle: "border border-brand-green/50 bg-brand-green/20 text-[#9FE0B0]",
};
export function MockupStep({
delay,
className,
children,
}: {
delay: number;
className?: string;
children: React.ReactNode;
}) {
return (
<motion.div variants={STEP_VARIANTS} custom={delay} className={className}>
{children}
</motion.div>
);
}
/**
* Animated root container for a single source mockup. Keeps outer dimensions locked to the stage
* so switching tabs or stepping through animations never shifts page layout.
*/
export function MockupStageWindow({
ariaLabel,
active,
reduceMotion,
className = "",
children,
}: {
ariaLabel: string;
active: boolean;
reduceMotion: boolean;
className?: string;
children: React.ReactNode;
}) {
return (
<motion.div
role="img"
aria-label={ariaLabel}
initial={reduceMotion ? "shown" : "hidden"}
animate={reduceMotion || active ? "shown" : "hidden"}
className={`flex h-full flex-col overflow-hidden rounded-xl border shadow-[0_24px_64px_-24px_rgba(0,0,0,0.75)] ${className}`}
>
{children}
</motion.div>
);
}
/** Mo's photo avatar used consistently across all source mockups. */
export function MoAvatar({
size = "md",
rounded = "rounded-[6px]",
className = "",
}: {
size?: AvatarSize;
rounded?: string;
className?: string;
}) {
const px = AVATAR_PX[size];
return (
<img
src="/9viSwGkz_400x400.jpg"
alt=""
width={px}
height={px}
loading="lazy"
decoding="async"
className={`shrink-0 object-cover ${AVATAR_DIM[size]} ${rounded} ${className}`}
/>
);
}
/**
* Paseo bot avatar using the canonical Paseo butterfly mark (`PaseoMark`).
* Used consistently for `paseo-bot` across Slack, GitHub, Linear, Discord, Schedules, and Webhooks.
*/
export function PaseoBotAvatar({
size = "md",
rounded = "rounded-[6px]",
className = "",
}: {
size?: AvatarSize;
rounded?: string;
className?: string;
}) {
return (
<span
aria-hidden="true"
className={`inline-flex shrink-0 items-center justify-center border border-white/14 bg-[#101615] ${AVATAR_DIM[size]} ${rounded} ${className}`}
>
<PaseoMark className={`${BOT_ICON_DIM[size]} text-white`} />
</span>
);
}
/** Consistent "Open in Paseo" action chip rendered inside source mockups. */
export function OpenInPaseoChip({ variant = "brand" }: { variant?: OpenChipVariant }) {
const { t } = useTranslation();
return (
<span
className={`inline-flex items-center gap-1.5 rounded-[5px] px-2.5 py-1 text-[11.5px] font-medium ${OPEN_CHIP_STYLES[variant]}`}
>
<PaseoMark className="h-3.5 w-3.5 shrink-0 text-current" />
<span>{t("hub.demo.shared.openInPaseo")}</span>
</span>
);
}
/** macOS-style window traffic lights for desktop-style mockup headers. */
export function WindowTrafficLights() {
return (
<div className="flex items-center gap-1.5" aria-hidden="true">
<span className="h-2.5 w-2.5 rounded-full bg-[#FF5F57]/85" />
<span className="h-2.5 w-2.5 rounded-full bg-[#FEBC2E]/85" />
<span className="h-2.5 w-2.5 rounded-full bg-[#28C840]/85" />
</div>
);
}
@@ -0,0 +1,380 @@
import { motion, type Variants } from "framer-motion";
import {
AtSign,
Check,
ChevronDown,
ChevronLeft,
ChevronRight,
Code,
GitPullRequest,
Hash,
Plus,
Search,
SendHorizontal,
SquarePen,
} from "lucide-react";
import type { ReactNode } from "react";
import { Trans, useTranslation } from "react-i18next";
import { PaseoMark } from "~/components/paseo-brand";
import {
MoAvatar,
MockupStageWindow,
MockupStep,
OpenInPaseoChip,
PaseoBotAvatar,
type SourceMockupProps,
WindowTrafficLights,
} from "./shared";
const DEMO_ISSUES = [
{ id: "#2811", title: "Terminal output drops under load" },
{ id: "#2804", title: "Relay reconnect loop on Android after sleep" },
{ id: "#2799", title: "Worktree cleanup leaves stale branches" },
] as const;
const SIDEBAR_CHANNELS = ["general", "engineering", "incidents", "releases"] as const;
const STEP_DELAYS = {
firstPrompt: 0.06,
firstReply: 0.65,
followUp: 1.35,
finalReply: 2.05,
} as const;
const TYPING_VARIANTS: Variants = {
hidden: { opacity: 0 },
shown: {
opacity: [0, 1, 1, 0, 0, 1, 1, 0],
transition: {
duration: 2.4,
times: [0, 0.08, 0.24, 0.28, 0.56, 0.62, 0.84, 0.9],
ease: "linear",
},
},
};
const SLACK_COMPONENTS = {
mention: <SlackMention />,
host: (
<span className="rounded-[3px] border border-white/10 bg-[#222529] px-1.5 py-[1px] font-mono text-[11.5px] text-[#E8912D]" />
),
pr: <span className="font-medium text-[#1D9BD1] underline decoration-[#1D9BD1]/40" />,
};
export function SlackSourceMockup({ active, reduceMotion }: SourceMockupProps) {
const { t } = useTranslation();
return (
<MockupStageWindow
ariaLabel={t("hub.demo.slack.alt")}
active={active}
reduceMotion={reduceMotion}
className="border-[#35373B] bg-[#1A1D21]"
>
<SlackWindowChrome />
<div className="grid min-h-0 flex-1 grid-cols-1 md:grid-cols-[164px_minmax(0,1fr)]">
<SlackSidebar />
<div className="flex min-h-0 min-w-0 flex-col bg-[#1A1D21]">
<SlackChannelHeader />
<SlackMessageFeed />
<SlackComposer />
<SlackTypingStatus reduced={reduceMotion} />
</div>
</div>
</MockupStageWindow>
);
}
function SlackWindowChrome() {
const { t } = useTranslation();
return (
<div className="flex h-9 shrink-0 items-center justify-between border-b border-[#2C2D30] bg-[#121016] px-3.5">
<div className="flex items-center gap-3">
<WindowTrafficLights />
<div className="hidden items-center gap-1 text-[#ABABAD]/60 sm:flex" aria-hidden="true">
<ChevronLeft className="h-3.5 w-3.5" />
<ChevronRight className="h-3.5 w-3.5" />
</div>
</div>
<div className="flex h-6 w-44 items-center gap-1.5 rounded-[5px] bg-white/[0.08] px-2.5 text-[11px] text-[#ABABAD] sm:w-56">
<Search className="h-3 w-3 shrink-0 text-[#ABABAD]/75" aria-hidden="true" />
<span className="truncate">{t("hub.demo.slack.searchPlaceholder")}</span>
</div>
<SlackColorMark className="h-3.5 w-3.5 shrink-0" />
</div>
);
}
function SlackSidebar() {
const { t } = useTranslation();
return (
<aside
aria-hidden="true"
className="hidden flex-col border-r border-[#2C2D30] bg-[#19171D] md:flex"
>
<div className="flex items-center justify-between border-b border-white/[0.07] px-3 py-2.5">
<div className="flex items-center gap-1 text-[13.5px] font-bold text-[#F8F8F8]">
<span>Paseo</span>
<ChevronDown className="h-3.5 w-3.5 text-[#ABABAD]" />
</div>
<SquarePen className="h-3.5 w-3.5 text-[#ABABAD]" />
</div>
<div className="space-y-4 px-2 py-3 text-[12.5px]">
<div className="space-y-0.5">
<p className="px-2 pb-1 text-[11px] font-medium text-[#ABABAD]/75">
{t("hub.demo.slack.channels")}
</p>
{SIDEBAR_CHANNELS.map((channel) => (
<div
key={channel}
className={`flex items-center gap-1.5 rounded-[6px] px-2 py-1 ${
channel === "engineering" ? "bg-[#1164A3] font-medium text-white" : "text-[#ABABAD]"
}`}
>
<Hash className="h-3.5 w-3.5 shrink-0 opacity-80" />
<span className="truncate">{channel}</span>
</div>
))}
</div>
<div className="space-y-0.5">
<p className="px-2 pb-1 text-[11px] font-medium text-[#ABABAD]/75">
{t("hub.demo.slack.apps")}
</p>
<div className="flex items-center gap-2 rounded-[6px] px-2 py-1 text-[#D1D2D3]">
<span className="relative flex h-4 w-4 shrink-0 items-center justify-center rounded-[4px] bg-[#101615] ring-1 ring-white/15">
<PaseoMark className="h-2.5 w-2.5 text-white" />
<span className="absolute -right-0.5 -bottom-0.5 h-1.5 w-1.5 rounded-full bg-[#2BAC76] ring-1 ring-[#19171D]" />
</span>
<span className="truncate">paseo-bot</span>
</div>
</div>
</div>
</aside>
);
}
function SlackChannelHeader() {
const { t } = useTranslation();
return (
<div className="flex shrink-0 items-center justify-between gap-3 border-b border-[#2C2D30] px-4 py-2">
<div className="flex min-w-0 items-center gap-2">
<div className="flex items-center gap-1 text-[14px] font-bold text-[#F8F8F8]">
<Hash className="h-3.5 w-3.5 shrink-0 text-[#D1D2D3]" aria-hidden="true" />
<span>engineering</span>
</div>
<span className="hidden truncate text-[11.5px] text-[#ABABAD] sm:inline">
{t("hub.demo.slack.channelTopic")}
</span>
</div>
<div
aria-hidden="true"
className="flex shrink-0 items-center gap-1.5 rounded-[5px] border border-[#35373B] px-2 py-0.5 text-[11px] text-[#ABABAD]"
>
<div className="flex -space-x-1">
<MoAvatar size="xs" rounded="rounded-[3px]" className="ring-1 ring-[#1A1D21]" />
<span className="flex h-4 w-4 items-center justify-center rounded-[3px] bg-[#101615] ring-1 ring-[#1A1D21]">
<PaseoMark className="h-2.5 w-2.5 text-white" />
</span>
</div>
<span className="tabular-nums">4</span>
</div>
</div>
);
}
function SlackMessageFeed() {
const { t } = useTranslation();
return (
<div className="flex-1 space-y-2.5 px-4 py-2.5">
<MockupStep delay={STEP_DELAYS.firstPrompt}>
<SlackMessage author="mo" time="9:41 AM">
<p>
<Trans i18nKey="hub.demo.slack.showIssues" components={SLACK_COMPONENTS} />
</p>
</SlackMessage>
</MockupStep>
<div className="ml-2.5 sm:ml-3.5">
<MockupStep
delay={STEP_DELAYS.firstReply}
className="space-y-1.5 border-l-2 border-[#2C2D30] pb-2.5 pl-3 sm:pl-3.5"
>
<div className="flex items-center gap-2 text-[11px]">
<span className="font-medium text-[#1D9BD1]">{t("hub.demo.slack.threadReplies")}</span>
<span className="h-px flex-1 bg-[#2C2D30]" aria-hidden="true" />
</div>
<SlackMessage author="paseo-bot" time="9:41 AM" bot>
<p>{t("hub.demo.slack.issuesOpen")}</p>
<ul className="mt-1 space-y-0.5 border-l-[3px] border-[#36C5F0] pl-2.5 text-[12px]">
{DEMO_ISSUES.map((issue) => (
<li key={issue.id} className="flex flex-wrap items-baseline gap-x-1.5">
<span className="font-mono text-[11.5px] font-medium text-[#1D9BD1]">
{issue.id}
</span>
<span className="text-[#D1D2D3]">{issue.title}</span>
</li>
))}
</ul>
</SlackMessage>
</MockupStep>
<MockupStep
delay={STEP_DELAYS.followUp}
className="border-l-2 border-[#2C2D30] pb-2.5 pl-3 sm:pl-3.5"
>
<SlackMessage author="mo" time="9:43 AM">
<p>
<Trans i18nKey="hub.demo.slack.createPr" components={SLACK_COMPONENTS} />
</p>
</SlackMessage>
</MockupStep>
<MockupStep
delay={STEP_DELAYS.finalReply}
className="border-l-2 border-[#2C2D30] pl-3 sm:pl-3.5"
>
<SlackMessage author="paseo-bot" time="9:48 AM" bot>
<p>
<Trans i18nKey="hub.demo.slack.ranOn" components={SLACK_COMPONENTS} />
</p>
<SlackPrAttachment />
</SlackMessage>
</MockupStep>
</div>
</div>
);
}
function SlackPrAttachment() {
const { t } = useTranslation();
return (
<div className="mt-1.5 space-y-1.5 border-l-[3px] border-[#2BAC76] pl-2.5">
<div className="flex flex-wrap items-center gap-1.5">
<span className="inline-flex items-center gap-1 rounded-[4px] bg-[#2BAC76]/15 px-2 py-0.5 font-mono text-[11px] text-[#4CD99B]">
<GitPullRequest className="h-3 w-3" aria-hidden="true" />
{t("hub.demo.slack.filesChanged")}
</span>
<span className="inline-flex items-center gap-1 rounded-[4px] border border-[#35373B] bg-[#222529] px-2 py-0.5 font-mono text-[11px] text-[#ABABAD]">
<Check className="h-3 w-3 text-[#2BAC76]" aria-hidden="true" />
{t("hub.demo.shared.testsPassed")}
</span>
</div>
<div>
<OpenInPaseoChip variant="slack" />
</div>
</div>
);
}
function SlackMessage({
author,
time,
bot,
children,
}: {
author: string;
time: string;
bot?: boolean;
children: ReactNode;
}) {
const { t } = useTranslation();
return (
<div className="flex items-start gap-2.5">
{bot ? (
<PaseoBotAvatar size="sm" className="mt-0.5 h-8 w-8" />
) : (
<MoAvatar size="sm" className="mt-0.5 h-8 w-8" />
)}
<div className="min-w-0 flex-1 space-y-0.5">
<div className="flex flex-wrap items-center gap-1.5">
<span className="text-[13px] font-bold text-[#F8F8F8]">{author}</span>
{bot ? (
<span className="rounded-[3px] bg-[#2C2D30] px-1.5 py-[1px] text-[9.5px] font-semibold uppercase tracking-wide text-[#ABABAD]">
{t("hub.demo.shared.appBadge")}
</span>
) : null}
<span className="text-[10.5px] text-[#ABABAD]">{time}</span>
</div>
<div className="text-[12.5px] leading-[1.42] text-[#D1D2D3]">{children}</div>
</div>
</div>
);
}
function SlackMention() {
return (
<span className="rounded-[3px] bg-[#1D9BD1]/20 px-1 py-[1px] font-medium text-[#1D9BD1]">
@paseo-bot
</span>
);
}
function SlackComposer() {
const { t } = useTranslation();
return (
<div
aria-hidden="true"
className="mx-4 mt-auto rounded-[8px] border border-[#35373B] bg-[#222529]"
>
<div className="px-3 py-1.5 text-[12.5px] text-[#ABABAD]/70">
{t("hub.demo.slack.composerPlaceholder")}
</div>
<div className="flex items-center justify-between border-t border-white/[0.06] px-2.5 py-1">
<div className="flex items-center gap-2.5 text-[#ABABAD]/60">
<Plus className="h-3.5 w-3.5" />
<AtSign className="h-3.5 w-3.5" />
<Code className="h-3.5 w-3.5" />
</div>
<span className="inline-flex h-5 w-6 items-center justify-center rounded-[4px] bg-[#007A5A]/80 text-white">
<SendHorizontal className="h-3 w-3" />
</span>
</div>
</div>
);
}
function SlackTypingStatus({ reduced }: { reduced: boolean }) {
const { t } = useTranslation();
return (
<div aria-hidden="true" className="flex h-6 shrink-0 items-center px-4 pb-1">
{reduced ? null : (
<motion.span
variants={TYPING_VARIANTS}
className="inline-flex items-center gap-1.5 text-[11px] text-[#ABABAD]"
>
<span className="h-1.5 w-1.5 animate-pulse rounded-full bg-[#2BAC76]" />
{t("hub.demo.slack.typing")}
</motion.span>
)}
</div>
);
}
export function SlackColorMark(props: React.SVGProps<SVGSVGElement>) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true" {...props}>
<path
fill="#E01E5A"
d="M5.042 15.165a2.528 2.528 0 0 1-2.52 2.523A2.528 2.528 0 0 1 0 15.165a2.527 2.527 0 0 1 2.522-2.52h2.52v2.52zM6.313 15.165a2.527 2.527 0 0 1 2.521-2.52 2.527 2.527 0 0 1 2.521 2.52v6.313A2.528 2.528 0 0 1 8.834 24a2.528 2.528 0 0 1-2.521-2.522v-6.313z"
/>
<path
fill="#36C5F0"
d="M8.834 5.042a2.528 2.528 0 0 1-2.521-2.52A2.528 2.528 0 0 1 8.834 0a2.528 2.528 0 0 1 2.521 2.522v2.52H8.834zM8.834 6.313a2.528 2.528 0 0 1 2.521 2.521 2.528 2.528 0 0 1-2.521 2.521H2.522A2.528 2.528 0 0 1 0 8.834a2.528 2.528 0 0 1 2.522-2.521h6.312z"
/>
<path
fill="#2EB67D"
d="M18.956 8.834a2.528 2.528 0 0 1 2.522-2.521A2.528 2.528 0 0 1 24 8.834a2.528 2.528 0 0 1-2.522 2.521h-2.522V8.834zM17.688 8.834a2.528 2.528 0 0 1-2.523 2.521 2.527 2.527 0 0 1-2.52-2.521V2.522A2.527 2.527 0 0 1 15.165 0a2.528 2.528 0 0 1 2.523 2.522v6.312z"
/>
<path
fill="#ECB22E"
d="M15.165 18.956a2.528 2.528 0 0 1 2.523 2.522A2.528 2.528 0 0 1 15.165 24a2.527 2.527 0 0 1-2.52-2.522v-2.522h2.52zM15.165 17.688a2.527 2.527 0 0 1-2.52-2.523 2.526 2.526 0 0 1 2.52-2.52h6.313A2.527 2.527 0 0 1 24 15.165a2.528 2.528 0 0 1-2.522 2.523h-6.313z"
/>
</svg>
);
}

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