feat(run,notifications,profiles): stop sending prompts nobody typed, and fix notification + profile delivery

Run console:
- Picking a pipeline no longer pre-writes anything into the prompt box
  (`promptPrefill` in `LaneConsolePane.tsx` is gone — it wrote the driving
  slash command on a claude lane and a stage checklist on a codex one).
  Whatever sits in that box is sent as a real prompt the moment the run
  starts, so the box is the user's alone now.
- Resuming a session sends NO prompt at all (`handleStart` in `RunSetup.tsx`):
  the resumed session carries its own transcript, and leftover text in the box
  fired an extra turn into it.

Notifications:
- `client/src/lib/notify.ts` is now the ONE sender, used by both
  `useNotifications` and Settings' test button, and it reports where the
  notification landed: `POST /api/push/send` answering `{native:false,pushed:0}`
  means it went NOWHERE, so the client falls back to a local notification
  instead of counting the 200 as delivered.
- A notification carries the lane that raised it (`/workspace?lane=<id>`), and
  Workspace selects that lane on arrival.

Profiles:
- `server/lib/cc-profiles.js` reads and writes the macOS login Keychain item
  `Claude Code-credentials`, where the `claude` CLI actually keeps
  `claudeAiOauth` on darwin — a switch used to rewrite a file nothing reads.
  The file stays the fallback, is kept in step only when it already exists, and
  `AGENTHUB_CC_KEYCHAIN=0` pins it (tests set it).

Tests: npm run test:server (1820 pass), client vitest (553 pass).
This commit is contained in:
2026-09-21 15:15:22 +07:00
parent 9156781d75
commit 64017c6ca5
29 changed files with 527 additions and 170 deletions
+4
View File
@@ -38,5 +38,9 @@
"Bash(claude --version)",
"Bash(gh pr *)"
]
},
"env": {
"ANTHROPIC_BASE_URL": "",
"ANTHROPIC_AUTH_TOKEN": ""
}
}
+25 -14
View File
@@ -347,7 +347,7 @@ graph TD
| `lib/cc-reload.js` | Types `/reload-plugins` / `/reload-skills` into the Claude Code sessions the dashboard already has open, over `tmux send-keys` (reusing `tmux.js`'s `sendText`). Both slash commands are scoped BY CLAUDE CODE to the session that runs them, so a session cannot be reloaded from the outside and no background process can do it on a session's behalf — typing into a live pane is the only real mechanism. Deliberately spawns NO `claude` process: a one-shot `claude -p "/reload-plugins"` would reload only its own short-lived session, exit, and leave a junk session in the dashboard's history, so this module creates no sessions at all. Skips panes sitting at a shell prompt (the text would run as a shell command) and addresses `claude` lanes only, since Codex has no such command. Sends to a busy pane on purpose — tmux queues the keystrokes into the REPL's input buffer, so a late reload still lands, where skipping busy panes would leave exactly the sessions in active use running stale code. The command set is a fixed constant, never caller-supplied: a pane's stdin is an arbitrary-code boundary. Never throws |
| `lib/cc-update-all.js` | Starts and reports on the "Update all" batch, whose work lives in the detached `scripts/cc-update-all-helper.js`. Detached for a structural reason: the batch ends with the plugin THIS dashboard runs from, and that step's `plugin-bootstrap.js --force` SIGTERMs this very server, so an in-process loop would die with the remaining plugins unrun and nothing left to report. Order is marketplaces → every other plugin → AgentHub last → one reload. The worker journals every step transition to `cc-update-all.json` under the runtime dir — outside the plugin cache the update replaces — so whichever server is alive can serve progress from it; the POST's response is only an acknowledgement. `readUpdateAll()` DERIVES an `abandoned` status for a `running` journal older than `STALE_MS` (1 h), because a detached worker killed by a reboot leaves nobody to write the terminal entry and the button would otherwise stay wedged forever. `isRunning()` gates a concurrent batch, since two `claude plugin update` chains over one config dir race |
| `routes/cc-config.js` | HTTP surface for the Claude Config Explorer. Read endpoints for every surface (skills, agents, commands, output-styles, plugins, marketplaces, mcp, hooks, hook-scripts, keybindings, statusline, settings, memory, file, overview), plus mutation endpoints (`PUT /file`, `DELETE /file`, and a structured `PUT /keybindings`) that delegate to `cc-mutate.js`, plus a `GET /backups` listing for the recovery modal, plus the auth-profile routes (`GET/POST/PATCH/DELETE /profiles`, `POST /profiles/activate`) that delegate to `cc-profiles.js`, plus `POST /profiles/usage` (a POST because answering it refreshes and rewrites that profile's stored OAuth tokens — see `cc-usage.js`), plus the install-wide update surface: `GET/POST /plugins/update-all` (a DETACHED batch — every marketplace, then every plugin, then a reload, with THIS dashboard's own plugin last because its bootstrap restarts the server; progress is polled from an on-disk journal, never from the POST's response) and `POST /reload` (types `/reload-plugins`+`/reload-skills` into the live lane panes; see `cc-reload.js`). After every successful PUT/DELETE the route broadcasts `cc_config_changed` over the WebSocket so any open `/cc-config` tab refetches without polling. All errors return structured `{error: {code, message}}` shapes mapped to 400/404/413/500 statuses |
| `lib/cc-profiles.js` | Named Claude Code **auth profiles** — swap which Anthropic account (and therefore which quota) the local `claude` CLI runs as. A profile is exactly two identity artifacts: `claudeAiOauth` out of `<CLAUDE_HOME>/.credentials.json`, and `oauthAccount` + `userID` out of the `.claude.json` config file(s) (`<CLAUDE_HOME>.json` and `<CLAUDE_HOME>/.claude.json`, each key-merged in place and only when it already exists, so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never read or written here — that is what makes a switch keep the whole workspace and change only the account; `mcpOAuth` stays put too (machine MCP tokens, not account identity). Stored one JSON file per profile under `<CLAUDE_HOME>/agenthub-profiles/` (dir `0700`, files `0600`), holding live OAuth tokens, so **no route ever returns token material** — `listProfiles()` answers identity metadata only. A profile carries two names: `name`, the filename and the id every route takes, and `label`, the free-form display name (spaces and diacritics fine, since it never touches a path) that `renameProfile()` edits in place without moving the file. One account is one profile — `saveProfile()` refuses `EDUPLICATE` rather than making a second copy, because duplicates both report themselves active, and `deleteProfile()` blocks only the LAST copy of the live account so a duplicate stays cleanable. Cannot mint credentials (only `claude auth login` can): a new profile is captured by logging in, then snapshotting. `activateProfile()` re-snapshots the outgoing account first so refreshed tokens are not lost, and refuses (`EUNSAVED`) to switch away from an account that was never saved — that would discard the only copy of its credentials. Atomic temp + rename at `0600` |
| `lib/cc-profiles.js` | Named Claude Code **auth profiles** — swap which Anthropic account (and therefore which quota) the local `claude` CLI runs as. A profile is exactly two identity artifacts: `claudeAiOauth` out of `<CLAUDE_HOME>/.credentials.json` (on **macOS**: out of the login Keychain item `Claude Code-credentials`, which is what the CLI reads there — the file is only a fallback, and `AGENTHUB_CC_KEYCHAIN=0` pins it), and `oauthAccount` + `userID` out of the `.claude.json` config file(s) (`<CLAUDE_HOME>.json` and `<CLAUDE_HOME>/.claude.json`, each key-merged in place and only when it already exists, so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never read or written here — that is what makes a switch keep the whole workspace and change only the account; `mcpOAuth` stays put too (machine MCP tokens, not account identity). Stored one JSON file per profile under `<CLAUDE_HOME>/agenthub-profiles/` (dir `0700`, files `0600`), holding live OAuth tokens, so **no route ever returns token material** — `listProfiles()` answers identity metadata only. A profile carries two names: `name`, the filename and the id every route takes, and `label`, the free-form display name (spaces and diacritics fine, since it never touches a path) that `renameProfile()` edits in place without moving the file. One account is one profile — `saveProfile()` refuses `EDUPLICATE` rather than making a second copy, because duplicates both report themselves active, and `deleteProfile()` blocks only the LAST copy of the live account so a duplicate stays cleanable. Cannot mint credentials (only `claude auth login` can): a new profile is captured by logging in, then snapshotting. `activateProfile()` re-snapshots the outgoing account first so refreshed tokens are not lost, and refuses (`EUNSAVED`) to switch away from an account that was never saved — that would discard the only copy of its credentials. Atomic temp + rename at `0600` |
| `lib/cc-usage.js` | How much of an account's quota is spent, for the profile switcher — the number that decides which saved profile is worth switching to. No local source exists (the credentials file has `subscriptionType`/`rateLimitTier` and nothing else), so it asks `GET https://api.anthropic.com/api/oauth/usage`, the same endpoint the CLI's own `/usage` reads, with that profile's OAuth token. Two rules: a profile's token is sent to Anthropic and nowhere else — what leaves the module is two percentages and two reset times, never token material — and **nothing here runs on a poll**. Any profile that is not the active one normally holds an expired access token, so answering means refreshing it, and the refresh ROTATES the stored refresh token; the new pair is written back through `cc-profiles.writeProfile()` because a dropped refresh leaves an account that needs a fresh `claude auth login`. A still-valid token is used as-is and rewrites nothing; a 401 on a token that looked valid is retried once through the refresh |
| `lib/cc-watcher.js` | Best-effort `fs.watch` over `~/.claude/` (recursive where the platform / Node version honors it — macOS / Windows always; Linux from Node 20) plus `~/.claude.json`. Coalesces bursts at 500 ms and broadcasts `cc_config_changed` with `{ source: "fs", paths: [...] }` so the Config Explorer picks up changes from external tools (CLI installs a plugin, manual `settings.json` edits, dropping a new skill) without a manual refresh. Started from `server/index.js` after the HTTP server boots; failures are caught and logged so a flaky watcher can't take the server down |
| `lib/codex-discovery.js` | Read-only discovery of the Codex CLI's file-backed config surfaces for the Codex Config panel — the Codex counterpart of `cc-discovery.js`. Surfaces: skills (`<root>/skills/<name>/SKILL.md`), agents (`<root>/agents/*.toml`), rules (`<root>/rules/*`), memory (`AGENTS.md` at user `~/.codex` + project root), config (`config.toml` at user + project `.codex/`). No filesystem watcher counterpart to `cc-watcher.js` exists for Codex. `readFileSafe()` re-validates path containment (leaf/ancestor symlink-escape guard) independent of the write side's own check. Codex's scope union is `"user"` \| `"project"` only — it has no `"project-local"` settings layer and no per-project file-based auto-memory store |
@@ -1577,15 +1577,14 @@ last node carries `detect` rules, so a lane can never be auto-declared `done`.
### Codex evidence reliability (`server/lib/codex-nudge.js`)
Auto-advance moves the ring but can never supply evidence; only the session's
own `agenthub stage --evidence` call can, so three mechanisms make that more likely
without weakening declared-wins/inferred-never-`done`:
own `agenthub stage --evidence` call can, so two mechanisms make that more likely
without weakening declared-wins/inferred-never-`done`. (Opening-prompt priming
used to be a third: `LaneConsolePane.tsx` pre-filled the prompt box from the
lane's pipeline — the driving slash command on a Claude lane, a plain-text
stage checklist on a codex one. It is gone: whatever sits in that box is sent
as a real prompt when the run starts, so the box now stays empty and the
prompt is the user's alone.)
- **Opening-prompt priming** (`LaneConsolePane.tsx`'s `promptPrefill`): a codex
pane's first prompt is pre-filled with a plain-text checklist of
`agenthub stage <stage> --tool codex` calls, one per node of `Lane.pipeline_nodes`
— the same up-front nudge a Claude lane gets from its pre-filled
`/agenthub:ship-feature-lane` skill command, in plain text since Codex has no
slash commands.
- **`AGENTS.md` stage block** (`server/lib/lane-agents.js`): on a `codex` lane,
`agenthub lanes agents install` writes a marker-delimited
`<!-- agenthub:stage:start -->` section into `<lane cwd>/AGENTS.md` instead of
@@ -1913,7 +1912,7 @@ graph TD
| Component | Responsibility |
| --- | --- |
| **VAPID Pipeline** | Uses the `web-push` library on the server. VAPID keys are auto-generated on first run and persisted to `data/vapid-keys.json` to ensure subscription continuity. |
| **Service Worker** | Located at `client/public/sw.js`. It runs independently of the dashboard tab, listening for `push` events from the browser's push service. It handles `notificationclick` to focus/open the dashboard. |
| **Service Worker** | Located at `client/public/sw.js`. It runs independently of the dashboard tab, listening for `push` events from the browser's push service. It handles `notificationclick` by navigating (`client.navigate`, falling back to `clients.openWindow`) an existing dashboard tab to the notification's `data.url` before focusing it — so a click lands on the lane that raised it, not just whichever tab happened to be open. |
| **macOS Audio Support** | Notifications are explicitly sent with `silent: false` and `sound: "default"`. This overrides macOS behavior that would otherwise suppress audio for web notifications. |
| **Subscription Management** | The dashboard registers the service worker and requests a `PushSubscription`. This subscription (endpoint and keys) is stored in the `push_subscriptions` table, indexed by endpoint. |
| **Event Routing** | When a WebSocket event (e.g., `session_created`) is broadcast, the server also triggers `sendPushToAll()`, which iterates through active subscriptions and sends signed VAPID payloads. |
@@ -1934,6 +1933,16 @@ flowchart TD
style SHOW fill:#10b981,stroke:#34d399,color:#fff
```
### Delivery fallback
`POST /api/push/send` answering `200` means the request was **accepted**, not that anyone was notified: it reports `{ok, native, pushed, failed}`, and a browser that never subscribed (no service worker, a non-secure origin such as `http://<lan-ip>:4820`, a push service the server cannot reach) gets `native:false, pushed:0`. `notify()` in `useNotifications.ts` therefore treats "delivered" as `native || pushed > 0` and otherwise shows the notification locally through the service worker / `Notification` — a fetch that merely resolved is not proof. The fallback is skipped when the push did land, so nothing is shown twice.
Note the browser-side floor this cannot lift: the `Notification` API needs a secure context, so open the dashboard on `http://localhost` (secure by definition) or behind HTTPS — on a bare LAN IP no notification of any kind is possible.
### Click-through to the lane
Every `notify()` call in `useNotifications.ts` resolves a per-event `url` — `/workspace?lane=<id>` — by matching the event's `session_id` against a lane whose `session_id` currently equals it (a lightweight lane cache the hook keeps synced off `lane_update` broadcasts, seeded once via `GET /api/lanes`). `POST /api/push/send`'s optional `url` field carries that path through the VAPID payload as `data.url`; `sw.js`'s `notificationclick` handler reads it back to navigate. The `Workspace` page consumes `?lane=<id>` in a one-shot effect (selects the lane, then strips the param via `replace: true` so it doesn't override a later manual lane switch). No lane match (event predates lane tracking, or the lane was removed) — `url` stays `undefined` and the click just focuses the dashboard, the prior behavior.
### Preference Storage
Notification preferences remain in `localStorage` (`agent-monitor-notifications`) for UI-side filtering, while the actual push delivery is managed by the server-side subscription store.
@@ -1941,10 +1950,12 @@ Notification preferences remain in `localStorage` (`agent-monitor-notifications`
| Preference | UI Key | Logic |
| --- | --- | --- |
| Master Toggle | `enabled` | Controls whether the subscription is active |
| New Session | `onNewSession` | Filtered during push fan-out |
| Session Error | `onSessionError` | Filtered during push fan-out |
| Session Complete | `onSessionComplete` | Filtered during push fan-out |
| Subagent Spawn | `onSubagentSpawn` | Filtered during push fan-out |
| New Session | `onNewSession` | Filtered client-side in `useNotifications` |
| Session Error | `onSessionError` | Filtered client-side in `useNotifications` |
| Awaiting Input | `onAwaitingInput` | `Notification` events — Claude is blocked on the user. Default ON |
| Turn Complete | `onTurnComplete` | `Stop` events — Claude finished a turn. Default ON |
| Session Complete | `onSessionComplete` | `SessionEnd` events. Filtered client-side |
| Subagent Spawn | `onSubagentSpawn` | Filtered client-side in `useNotifications` |
### Service Worker Caching
+1 -1
View File
File diff suppressed because one or more lines are too long
+3 -3
View File
@@ -242,9 +242,9 @@ also **advances the declared stage** — the one place an inference moves the bl
`current` ring, because a Codex session has no hook and nothing else would ever
move it. What a Codex lane cannot get for free is *evidence*: an auto-advanced
node stays amber (`passed-no-evidence`), never green, since only the session
itself can say what it finished. Three things help it get there: the run console
pre-fills a codex pane's opening prompt with a stage-declaration checklist built
from its own pipeline nodes, `agenthub lanes agents install` writes the same
itself can say what it finished. Two things help it get there (the run console
no longer pre-fills anything into the prompt box — that box is the user's to
type): `agenthub lanes agents install` writes the stage-declaration
instructions as a marker-delimited block in the lane's `AGENTS.md`, and a 60s
sweep (`DASHBOARD_CODEX_NUDGE_MS`, `0` disables) types a one-line reminder into
a lane's pane if its current stage sits without evidence for more than two
+7 -1
View File
@@ -87,13 +87,19 @@ self.addEventListener("push", (event) => {
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const url = event.notification.data?.url;
event.waitUntil(
clients.matchAll({ type: "window" }).then((windowClients) => {
for (const client of windowClients) {
if (client.focus) {
if ("focus" in client) {
// Reuse an already-open tab instead of stacking a new one — that's
// also why `navigate` (same-origin only) beats postMessage: it works
// even if the page hasn't wired up a listener for this.
if (url && "navigate" in client) client.navigate(url).catch(() => {});
return client.focus();
}
}
if (url && clients.openWindow) return clients.openWindow(url);
})
);
});
+4 -29
View File
@@ -129,7 +129,6 @@ export function LaneConsolePane({
useEffect(() => {
const { activeRuns: runs } = latest.current;
setPrompt("");
lastPrefill.current = "";
setResumeSession(null);
setError(null);
setBusy(null);
@@ -138,34 +137,10 @@ export function LaneConsolePane({
refreshList();
}, [laneId, refreshList]);
// Pre-fill the prompt with the slash command the lane's pipeline template
// names as its driver, so picking the 16-node pipeline starts the 16-step
// skill and the 8-node one the 8-step skill. Only overwrites a prompt the
// user hasn't touched (still exactly the previous prefill), so switching
// templates never eats a typed requirement. Must be declared AFTER the
// lane-switch effect: on a lane change that one clears both first.
const lastPrefill = useRef("");
// Claude gets a slash command it can execute (`pipeline_skill`), which itself
// declares stage at every step. Codex has no slash commands — the same
// string would read as literal prose — so it gets the equivalent priming a
// different way: a plain-text checklist of this lane's own pipeline node ids,
// read directly off `pipeline_nodes` so it always matches the template in
// use. Without SOME opening nudge a codex lane's declared stage depends
// entirely on AGENTS.md being read on its own, which is easy to miss.
const promptPrefill =
laneTool === "codex"
? currentLane?.pipeline_nodes?.length
? `Declare progress as you go: run \`agenthub stage <stage> --tool codex --evidence "..."\` immediately at each real transition through this pipeline — ${currentLane.pipeline_nodes.map((n) => n.id).join(" -> ")}. Then, your task:\n\n`
: ""
: currentLane?.pipeline_skill || "";
useEffect(() => {
const next = promptPrefill && laneTool === "claude" ? `${promptPrefill} ` : promptPrefill;
setPrompt((p) => (p === lastPrefill.current ? next : p));
lastPrefill.current = next;
// `laneId` is a dep too: switching between two lanes on the SAME template
// leaves `promptPrefill` unchanged, and the switch effect just cleared the
// prompt — without it the new lane would open with an empty box.
}, [promptPrefill, laneTool, laneId]);
// Picking a pipeline template writes NOTHING into the prompt box: a prefilled
// slash command (or the codex stage-checklist prose) is sent as soon as the
// run starts, which is an extra prompt nobody asked for. The prompt is the
// user's to type; the pipeline is declared by `agenthub stage` instead.
// The switch effect above only sees whatever `activeRuns` the page already
// had loaded at that instant. Remounting this page (navigating away and
+4 -1
View File
@@ -360,7 +360,10 @@ function handleStart(props: RunSetupProps, session?: Session) {
effort: props.effort || undefined,
resumeSessionId: codex ? undefined : resume?.id || undefined,
resumeLast: codex && !resume ? true : undefined,
initialPrompt: props.prompt || undefined,
// A resume continues a session that already has its own history — sending
// whatever is sitting in the prompt box would fire an extra turn nobody
// asked for, so a resume carries no prompt at all.
initialPrompt: resume ? undefined : props.prompt || undefined,
});
}
@@ -195,40 +195,11 @@ describe("LaneConsolePane", () => {
expect(screen.queryByTestId("pane-empty")).not.toBeInTheDocument();
});
it("pre-fills the prompt with the pipeline's driving skill, and keeps a typed prompt when the template changes", async () => {
const lane = { ...LANE, pipeline_skill: "/agenthub:ship-feature" };
const props = { ...baseProps(), lanes: [lane] };
const { rerender } = render(<LaneConsolePane {...props} />);
const prompt = screen.getByPlaceholderText(/ask claude/i) as HTMLTextAreaElement;
await waitFor(() => expect(prompt.value).toBe("/agenthub:ship-feature "));
// Untouched prefill follows the template switch.
const laneShip = { ...lane, pipeline_skill: "/agenthub:ship-feature-lane" };
rerender(<LaneConsolePane {...props} lanes={[laneShip]} />);
await waitFor(() => expect(prompt.value).toBe("/agenthub:ship-feature-lane "));
// A typed requirement is never eaten by a later template switch.
fireEvent.change(prompt, { target: { value: "/agenthub:ship-feature-lane add a button" } });
rerender(<LaneConsolePane {...props} lanes={[lane]} />);
await waitFor(() => expect(prompt.value).toBe("/agenthub:ship-feature-lane add a button"));
});
it("never pre-fills a claude slash command into a codex pane", async () => {
// pipeline_skill is a Claude Code slash command. Codex would take it as
// literal prose and run nothing, which is how a codex lane sits for half an
// hour with an untouched pipeline map. No pipeline_nodes here either, so
// there's nothing to build a stage checklist from — the box stays empty.
const lane = { ...LANE, tool: "codex" as const, pipeline_skill: "/agenthub:ship-feature-lane" };
render(<LaneConsolePane {...baseProps()} lanes={[lane]} />);
const prompt = screen.getByPlaceholderText(/ask claude/i) as HTMLTextAreaElement;
await waitFor(() => expect(prompt.value).toBe(""));
});
it("pre-fills a codex pane with a stage-declaration checklist built from its own pipeline nodes", async () => {
// Codex has no slash commands, so it can't run pipeline_skill as-is — it
// gets the same priming Claude gets (an opening nudge to declare stage)
// as plain text instead, naming this lane's actual node ids.
const lane = {
it("never pre-fills the prompt from the lane's pipeline, for either tool", async () => {
// Picking a pipeline used to write its driving slash command (claude) or a
// stage checklist (codex) into the box — an extra prompt sent on start.
const claudeLane = { ...LANE, pipeline_skill: "/agenthub:ship-feature" };
const codexLane = {
...LANE,
tool: "codex" as const,
pipeline_skill: "/agenthub:ship-feature-lane",
@@ -243,11 +214,23 @@ describe("LaneConsolePane", () => {
{ id: "tests", label: "Tests", icon: "check", gate: false, state: "pending" as const },
],
};
render(<LaneConsolePane {...baseProps()} lanes={[lane]} />);
const props = { ...baseProps(), lanes: [claudeLane] };
const { rerender } = render(<LaneConsolePane {...props} />);
const prompt = screen.getByPlaceholderText(/ask claude/i) as HTMLTextAreaElement;
await waitFor(() => expect(prompt.value).toContain("agenthub stage <stage> --tool codex"));
expect(prompt.value).toContain("implement -> tests");
expect(prompt.value).not.toContain("/agenthub:ship-feature-lane");
await waitFor(() => expect(prompt.value).toBe(""));
// A typed requirement still survives a template switch.
fireEvent.change(prompt, { target: { value: "add a button" } });
rerender(
<LaneConsolePane
{...props}
lanes={[{ ...claudeLane, pipeline_skill: "/agenthub:ship-feature-lane" }]}
/>
);
await waitFor(() => expect(prompt.value).toBe("add a button"));
rerender(<LaneConsolePane {...props} lanes={[codexLane]} />);
await waitFor(() => expect(prompt.value).toBe("add a button"));
});
it("renders an empty placeholder with selector when laneId is null but showLaneSelector is true (split-view)", () => {
@@ -234,6 +234,27 @@ describe("RunSetup — resume picker scopes sessions to the selected lane", () =
);
});
it("sends no prompt when resuming, even with text in the box", async () => {
const { api } = await import("../../../lib/api");
vi.mocked(api.sessions.list).mockResolvedValue({
sessions: [
{ id: "sess-in-lane", cwd: "/Users/tester/lane-a", started_at: "", status: "completed" },
],
total: 1,
limit: 100,
offset: 0,
} as never);
const { spies } = renderSetup({ laneCwd: "/Users/tester/lane-a", prompt: "leftover text" });
fireEvent.click(screen.getByText(i18n.t("run:resume.resumeOption")));
fireEvent.click(screen.getByText(i18n.t("run:resume.pickSession")));
fireEvent.click(await screen.findByText("/Users/tester/lane-a"));
// The resumed session is the input; anything left in the box would be an
// extra turn the user never asked for.
expect(spies.onStart.mock.calls[0]?.[0]?.initialPrompt).toBeUndefined();
});
it("falls back to the typed cwd when no lane is selected", async () => {
const { api } = await import("../../../lib/api");
renderSetup({ laneCwd: undefined, cwd: "/Users/tester" });
@@ -36,7 +36,9 @@ describe("useNotifications", () => {
localStorage.clear();
// notify() posts to /api/push/send first and only falls back to a local
// Notification when that throws, so the fetch spy is what we assert on.
fetchMock = vi.fn().mockResolvedValue({ ok: true });
fetchMock = vi
.fn()
.mockResolvedValue({ ok: true, json: async () => ({ ok: true, native: true, pushed: 1 }) });
vi.stubGlobal("fetch", fetchMock);
vi.stubGlobal(
"Notification",
@@ -76,6 +78,32 @@ describe("useNotifications", () => {
expect(sentTitles()[0]).toBe("Claude Finished Responding");
});
it("shows a local notification when the push landed nowhere", async () => {
// What a browser with no push subscription gets back: HTTP 200, zero
// deliveries. Before this, the 200 alone counted as success and the user
// saw nothing at all.
fetchMock.mockResolvedValue({
ok: true,
json: async () => ({ ok: true, native: false, pushed: 0, failed: 0 }),
});
enable();
renderHook(() => useNotifications());
emit("Stop", "Done");
await vi.waitFor(() => expect(Notification).toHaveBeenCalledTimes(1));
expect(vi.mocked(Notification).mock.calls[0]?.[0]).toBe("Claude Finished Responding");
});
it("does not double up when the push was delivered", async () => {
enable();
renderHook(() => useNotifications());
emit("Stop", "Done");
await vi.waitFor(() => expect(sentTitles()).toHaveLength(1));
await new Promise((r) => setTimeout(r, 20));
expect(Notification).not.toHaveBeenCalled();
});
it("stays silent while notifications are disabled", async () => {
renderHook(() => useNotifications());
+48 -39
View File
@@ -24,6 +24,7 @@
* - `../i18n`
* - `../lib/eventBus`
* - `../lib/push`
* - `../lib/notify`
* - `../lib/types`
*
* ## Public surface
@@ -48,43 +49,14 @@
*
* ----------------------------------------------------------------------------- */
import { useEffect } from "react";
import { useEffect, useRef } from "react";
import i18n from "../i18n";
import { api } from "../lib/api";
import { eventBus } from "../lib/eventBus";
import { subscribeToPush } from "../lib/push";
import { notify } from "../lib/notify";
import { loadNotifPrefs } from "../lib/notifPrefs";
import type { WSMessage, Session, Agent, DashboardEvent } from "../lib/types";
/**
* Shows a browser notification, preferring a server-relayed push (so it can
* arrive even if this tab isn't the active one, or the browser is backgrounded)
* and falling back to a local service-worker/`Notification` call if the
* server is unreachable. No-ops when the user hasn't granted permission.
* @param title Notification title.
* @param body Notification body text.
*/
async function notify(title: string, body: string) {
if (!("Notification" in window) || Notification.permission !== "granted") return;
try {
await fetch("/api/push/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title, body }),
});
} catch {
// Server unreachable - fall back to local notification
try {
if ("serviceWorker" in navigator) {
const registration = await navigator.serviceWorker.ready;
await registration.showNotification(title, { body, icon: "/favicon.ico", silent: false });
} else {
new Notification(title, { body, icon: "/favicon.ico" });
}
} catch {
// Silently ignore
}
}
}
import type { WSMessage, Session, Agent, DashboardEvent, Lane } from "../lib/types";
/**
* Wires the dashboard's {@link eventBus} up to browser notifications, per the
@@ -96,13 +68,40 @@ async function notify(title: string, body: string) {
* already been granted, so push delivery survives a page reload.
*/
export function useNotifications() {
// A lane's `session_id` is its current/last-run session — matching on it
// is how a click lands on the lane that actually raised the notification,
// instead of just focusing whichever browser tab was already open.
const lanesRef = useRef<Lane[]>([]);
useEffect(() => {
const prefs = loadNotifPrefs();
if (prefs.enabled && "Notification" in window && Notification.permission === "granted") {
subscribeToPush().catch(() => {});
}
api.lanes
.list()
.then((r) => (lanesRef.current = r.lanes))
.catch(() => {});
function laneUrlForSession(sessionId: string): string | undefined {
const lane = lanesRef.current.find((l) => l.session_id === sessionId);
return lane ? `/workspace?lane=${lane.id}` : undefined;
}
return eventBus.subscribe((msg: WSMessage) => {
if (msg.type === "lane_update") {
const payload = msg.data as { lane?: Lane; removed?: number };
if (payload.lane) {
const i = lanesRef.current.findIndex((l) => l.id === payload.lane!.id);
if (i === -1) lanesRef.current = [...lanesRef.current, payload.lane];
else lanesRef.current = lanesRef.current.map((l, idx) => (idx === i ? payload.lane! : l));
} else if (payload.removed !== undefined) {
lanesRef.current = lanesRef.current.filter((l) => l.id !== payload.removed);
}
return;
}
const prefs = loadNotifPrefs();
if (!prefs.enabled) return;
@@ -112,7 +111,8 @@ export function useNotifications() {
const s = msg.data as Session;
notify(
i18n.t("errors:notifications.newSession"),
s.name || `${i18n.t("errors:notifications.sessionDefault")}${s.id.slice(0, 8)}`
s.name || `${i18n.t("errors:notifications.sessionDefault")}${s.id.slice(0, 8)}`,
laneUrlForSession(s.id)
);
break;
}
@@ -121,7 +121,8 @@ export function useNotifications() {
if (s.status === "error" && prefs.onSessionError) {
notify(
i18n.t("errors:notifications.sessionError"),
s.name || `${i18n.t("errors:notifications.sessionDefault")}${s.id.slice(0, 8)}`
s.name || `${i18n.t("errors:notifications.sessionDefault")}${s.id.slice(0, 8)}`,
laneUrlForSession(s.id)
);
}
break;
@@ -130,12 +131,17 @@ export function useNotifications() {
if (!prefs.onSubagentSpawn) return;
const a = msg.data as Agent;
if (a.type === "subagent") {
notify(i18n.t("errors:notifications.subagentSpawned"), a.name);
notify(
i18n.t("errors:notifications.subagentSpawned"),
a.name,
laneUrlForSession(a.session_id)
);
}
break;
}
case "new_event": {
const ev = msg.data as DashboardEvent;
const url = laneUrlForSession(ev.session_id);
// The two states where Claude is BLOCKED on the user get their own
// flags (issue #29): `Notification` is a permission prompt or a
// question, `Stop` is the end of a turn. Both used to hang off
@@ -144,17 +150,20 @@ export function useNotifications() {
if (ev.event_type === "Notification" && prefs.onAwaitingInput) {
notify(
i18n.t("errors:notifications.awaitingInput"),
ev.summary || i18n.t("errors:notifications.defaultBody")
ev.summary || i18n.t("errors:notifications.defaultBody"),
url
);
} else if (ev.event_type === "Stop" && prefs.onTurnComplete) {
notify(
i18n.t("errors:notifications.finishedResponding"),
ev.summary || i18n.t("errors:notifications.readyForInput")
ev.summary || i18n.t("errors:notifications.readyForInput"),
url
);
} else if (ev.event_type === "SessionEnd" && prefs.onSessionComplete) {
notify(
i18n.t("errors:notifications.sessionCompleted"),
ev.summary || i18n.t("errors:notifications.sessionClosed")
ev.summary || i18n.t("errors:notifications.sessionClosed"),
url
);
}
break;
+1 -1
View File
@@ -49,7 +49,7 @@
"addLaneToolClaude": "Claude Code",
"addLaneToolCodex": "Codex",
"addLaneToolHint": "Which CLI drives this lane. Cannot be changed later.",
"addLaneWriteDocsHint": "Opens the lane's terminal on creation and runs the /sg-all:sg-md-writing skill there.",
"addLaneWriteDocsHint": "On creation, opens the lane's terminal and runs /sg-all:sg-md-writing there: creates CLAUDE.md/AGENTS.md if missing, or updates them concisely if they already exist.",
"addLaneWriteDocsLabel": "Create/update readme file",
"autoStage": "auto: {{stage}}",
"browse.button": "Browse",
+4
View File
@@ -84,7 +84,11 @@
"sessionComplete": "Session completes",
"sessionError": "Session errors",
"subagentSpawned": "Subagent spawned",
"testBlocked": "The browser has not granted notification permission.",
"testBody": "Notifications are working!",
"testFailed": "Nothing could be shown.",
"testLocal": "Your browser has no push subscription, so this was shown locally. Web Push needs a secure origin (localhost or HTTPS) and a registered service worker.",
"testSent": "Sent via push — check your notification centre.",
"testTitle": "Agent Monitor",
"title": "Notifications",
"turnComplete": "Claude finishes a turn"
+1 -1
View File
@@ -49,7 +49,7 @@
"addLaneToolClaude": "Claude Code",
"addLaneToolCodex": "Codex",
"addLaneToolHint": "CLI nào điều khiển lane này. Không thể thay đổi sau này.",
"addLaneWriteDocsHint": "Khi tạo lane sẽ mở terminal của lane và chạy skill /sg-all:sg-md-writing tại đó.",
"addLaneWriteDocsHint": "Khi tạo lane sẽ mở terminal và chạy skill /sg-all:sg-md-writing: tạo CLAUDE.md/AGENTS.md nếu chưa có, hoặc cập nhật ngắn gọn nếu đã có.",
"addLaneWriteDocsLabel": "Tạo/cập nhật file readme",
"autoStage": "tự động: {{stage}}",
"browse.button": "Duyệt",
+4
View File
@@ -84,7 +84,11 @@
"sessionComplete": "Phiên hoàn tất",
"sessionError": "Phiên gặp lỗi",
"subagentSpawned": "Subagent được tạo",
"testBlocked": "Trình duyệt chưa cấp quyền thông báo.",
"testBody": "Thông báo đang hoạt động!",
"testFailed": "Không hiển thị được thông báo nào.",
"testLocal": "Trình duyệt chưa đăng ký push nên thông báo được hiện tại chỗ. Web Push cần origin bảo mật (localhost hoặc HTTPS) và service worker đã đăng ký.",
"testSent": "Đã gửi qua push — kiểm tra trung tâm thông báo.",
"testTitle": "Agent Monitor",
"title": "Thông báo",
"turnComplete": "Claude trả lời xong"
+1 -1
View File
@@ -28,7 +28,7 @@ export interface NotifPrefs {
// needs to know when they are the blocker). The rest stay as they were.
export const defaultNotifPrefs: NotifPrefs = {
enabled: false,
onNewSession: true,
onNewSession: false,
onSessionError: true,
onAwaitingInput: true,
onTurnComplete: true,
+85
View File
@@ -0,0 +1,85 @@
/**
* @file Shows a browser notification — the single `notify()` both
* `useNotifications` (live events) and Settings' "Send Test Notification"
* button call, so the test proves the real delivery path and can report
* where it actually landed instead of a bare fire-and-forget.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
export type NotifyVia = "native" | "push" | "local" | "blocked" | "none";
export interface NotifyError {
statusCode?: number;
message?: string;
}
export interface NotifyResult {
via: NotifyVia;
errors: NotifyError[];
}
/**
* Prefers a server-relayed push (so it can arrive even if this tab isn't the
* active one, or the browser is backgrounded) and falls back to a local
* service-worker/`Notification` call when the server didn't deliver.
* @param title Notification title.
* @param body Notification body text.
* @param url Same-origin path to focus/navigate to on click (e.g. the lane
* that raised this notification). Omit for notifications with no target.
*/
export async function notify(title: string, body: string, url?: string): Promise<NotifyResult> {
if (!("Notification" in window) || Notification.permission !== "granted") {
return { via: "blocked", errors: [] };
}
const errors: NotifyError[] = [];
// A 200 from /api/push/send means the request was ACCEPTED, not that anything
// reached the user: with no push subscription (no service worker, a
// non-secure origin, a browser that never subscribed) or a push service the
// server cannot reach, it answers `{ok:true, native:false, pushed:0}` and
// nobody is notified. Only `native` or `pushed > 0` is actual delivery —
// anything else falls through to the local notification below, which is why
// the fallback is keyed on the RESULT rather than on fetch throwing.
try {
const res = await fetch("/api/push/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title, body, url }),
});
const result = res.ok ? await res.json().catch(() => null) : null;
if (result?.native) return { via: "native", errors };
if (result && result.pushed > 0) return { via: "push", errors };
if (!res.ok) errors.push({ statusCode: res.status });
} catch (e) {
errors.push({ message: e instanceof Error ? e.message : String(e) });
}
try {
// Vector, not `/favicon.ico` (32x32 raster) — crisp at whatever size the
// OS renders it, matching the icon server/lib/push.js already sends.
const data = url ? { url } : undefined;
if ("serviceWorker" in navigator) {
const registration = await navigator.serviceWorker.ready;
await registration.showNotification(title, {
body,
icon: "/favicon.svg",
silent: false,
data,
});
} else {
const n = new Notification(title, { body, icon: "/favicon.svg", data });
if (url) {
// No service worker to catch the click here — navigate this tab directly.
n.onclick = () => {
window.focus();
window.location.assign(url);
};
}
}
return { via: "local", errors };
} catch (e) {
errors.push({ message: e instanceof Error ? e.message : String(e) });
return { via: "none", errors };
}
}
+35 -18
View File
@@ -112,6 +112,7 @@ import { sagiPrefs } from "../components/Sagi/prefs";
import { fmt, fmtCost, getCurrentLocale } from "../lib/format";
import { subscribeToPush, unsubscribeFromPush } from "../lib/push";
import { loadNotifPrefs, saveNotifPrefs, type NotifPrefs } from "../lib/notifPrefs";
import { notify } from "../lib/notify";
import { Tip } from "../components/Tip";
import { ImportHistory } from "../components/ImportHistory";
import { RemoteSources } from "../components/RemoteSources";
@@ -569,7 +570,10 @@ export function Settings() {
const perm = await Notification.requestPermission();
if (perm === "granted") {
updateNotifPrefs({ enabled: true });
await subscribeToPush();
// A browser with no service worker / on a non-secure origin rejects here;
// notifications still work through the local fallback in useNotifications,
// so this must not blow up the enable flow.
await subscribeToPush().catch(() => {});
}
};
@@ -1554,14 +1558,6 @@ export function Settings() {
label={t("notifications.awaitingInput")}
/>
</div>
<div className="flex items-center gap-3 bg-surface-2 rounded-lg px-3.5 py-3">
<MessageSquare className="w-4 h-4 text-accent flex-shrink-0" />
<Toggle
checked={notifPrefs.onTurnComplete}
onChange={(v) => updateNotifPrefs({ onTurnComplete: v })}
label={t("notifications.turnComplete")}
/>
</div>
<div className="flex items-center gap-3 bg-surface-2 rounded-lg px-3.5 py-3">
<Play className="w-4 h-4 text-status-success flex-shrink-0" />
<Toggle
@@ -1570,6 +1566,14 @@ export function Settings() {
label={t("notifications.newSession")}
/>
</div>
<div className="flex items-center gap-3 bg-surface-2 rounded-lg px-3.5 py-3">
<MessageSquare className="w-4 h-4 text-accent flex-shrink-0" />
<Toggle
checked={notifPrefs.onTurnComplete}
onChange={(v) => updateNotifPrefs({ onTurnComplete: v })}
label={t("notifications.turnComplete")}
/>
</div>
<div className="flex items-center gap-3 bg-surface-2 rounded-lg px-3.5 py-3">
<CheckCircle className="w-4 h-4 text-violet-400 flex-shrink-0" />
<Toggle
@@ -1599,15 +1603,27 @@ export function Settings() {
<div className="pt-3 border-t border-border">
<button
onClick={async () => {
if (!("Notification" in window) || Notification.permission !== "granted")
return;
await fetch("/api/push/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: t("notifications.testTitle"),
body: t("notifications.testBody"),
}),
// Same notify() the live events use, so the test proves the
// real path — and reports WHERE it landed, since a push that
// reaches nobody used to look exactly like success.
const r = await notify(
t("notifications.testTitle"),
t("notifications.testBody")
);
const reason = r.errors
.map((e) => [e.statusCode, e.message].filter(Boolean).join(" "))
.join("; ");
setActionResult({
key: "notif-test",
isError: r.via === "none" || r.via === "blocked",
message:
r.via === "push" || r.via === "native"
? t("notifications.testSent")
: r.via === "local"
? t("notifications.testLocal")
: r.via === "blocked"
? t("notifications.testBlocked")
: `${t("notifications.testFailed")}${reason ? ` (${reason})` : ""}`,
});
}}
className="inline-flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-md text-fg-secondary hover:text-fg-primary hover:bg-surface-4 border border-border transition-colors"
@@ -1615,6 +1631,7 @@ export function Settings() {
<Zap className="w-3 h-3" />
{t("notifications.sendTest")}
</button>
<div className="mt-2">{actionBanner(["notif-test"])}</div>
</div>
</div>
)}
+22
View File
@@ -41,6 +41,7 @@
* ----------------------------------------------------------------------------- */
import { useCallback, useEffect, useState, useSyncExternalStore } from "react";
import { useSearchParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Plus, Square, Columns2, Grid2x2, Pencil } from "lucide-react";
import { api } from "../lib/api";
@@ -198,6 +199,7 @@ function ConsoleArea({
export function Workspace() {
const { t: tLanes } = useTranslation("lanes");
const wsConnected = useSyncExternalStore(eventBus.onConnection, () => eventBus.connected);
const [searchParams, setSearchParams] = useSearchParams();
// Lane state
const [lanes, setLanes] = useState<Lane[]>([]);
@@ -274,6 +276,26 @@ export function Workspace() {
}
}, []);
// Deep link from a notification click (`/workspace?lane=<id>`, see
// useNotifications' laneUrlForSession): once that lane is in the loaded
// list, select it and drop the param so a later manual lane switch sticks.
useEffect(() => {
const laneParam = searchParams.get("lane");
if (laneParam === null || lanes.length === 0) return;
const paramId = Number(laneParam);
if (lanes.some((l) => l.id === paramId)) {
setSelectedLaneId(paramId);
}
setSearchParams(
(prev) => {
const next = new URLSearchParams(prev);
next.delete("lane");
return next;
},
{ replace: true }
);
}, [lanes, searchParams, setSearchParams]);
useEffect(() => {
Promise.all([api.run.binary("claude"), api.run.binary("codex")])
.then(([claude, codex]) => setBinaryStatus({ claude, codex }))
+1 -1
View File
@@ -1694,7 +1694,7 @@ Batch `status` is `running`, `done`, `partial` (finished, at least one step fail
`PUT /api/cc-config/keybindings` edits `~/.claude/keybindings.json` from a structured list of context groups (`{ groups: [{ context, bindings: [{ key, action }] }] }`). The server backs the file up first (under `<CLAUDE_HOME>/cc-config-backups/keybindings/`), preserves any top-level metadata (`$schema`/`$docs`), and replaces only the `bindings` array; duplicate contexts or duplicate keys within a context return `EBADCONTENT`. `keybindings.json` is replaced wholesale here because the live CLI does not rewrite it mid-session; `settings.json`, which it does, is only ever key-merged (see `PATCH /settings` above).
**Auth profiles (`/profiles*`).** A *profile* is one Anthropic account — one quota — under a name. Switching swaps exactly two identity artifacts and nothing else: `claudeAiOauth` inside `<CLAUDE_HOME>/.credentials.json`, and `oauthAccount` + `userID` inside the `.claude.json` config file(s) (`<CLAUDE_HOME>.json` and `<CLAUDE_HOME>/.claude.json`, each rewritten only if it already exists, key-merged so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never read or written here — that is what makes a switch keep the whole workspace and change only the account. `mcpOAuth` also stays put: those are the machine's MCP server tokens, not account identity.
**Auth profiles (`/profiles*`).** A *profile* is one Anthropic account — one quota — under a name. Switching swaps exactly two identity artifacts and nothing else: `claudeAiOauth` inside `<CLAUDE_HOME>/.credentials.json`, and `oauthAccount` + `userID` inside the `.claude.json` config file(s) (`<CLAUDE_HOME>.json` and `<CLAUDE_HOME>/.claude.json`, each rewritten only if it already exists, key-merged so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never read or written here — that is what makes a switch keep the whole workspace and change only the account. `mcpOAuth` also stays put: those are the machine's MCP server tokens, not account identity. On **macOS** the live `claudeAiOauth` is NOT that file — the `claude` CLI keeps it in the login Keychain (generic password, service `Claude Code-credentials`, account `$USER`), read/written via `/usr/bin/security`; the file is only a fallback (and is kept in step when one already exists). `AGENTHUB_CC_KEYCHAIN=0` pins the file.
Profiles live one JSON file per profile under `<CLAUDE_HOME>/agenthub-profiles/` (dir `0700`, files `0600`) and hold live OAuth tokens, so **no route ever returns token material** — `GET /profiles` answers `{ items, active }` with identity metadata only (`name`, `label`, `savedAt`, `active`, `accountUuid`, `email`, `displayName`, `organization`, `seatTier`, `subscriptionType`, `expiresAt`).
+2 -2
View File
@@ -54,7 +54,7 @@ Both modes' path field has a **Browse** button next to it, opening a small folde
A lane is driven by a tool: **Claude** (default) or **Codex**, chosen in the "+ Add lane" modal and immutable once the lane exists. A lane's tool determines which CLI is spawned when a run starts.
- **`claude` (default)** — `claude` binary is invoked; the session's hooks, messages, and tool calls flow through the dashboard. Claude lanes render Sessions, Analytics, cost, and stage-detection badges; liveness is tracked by the Claude Code session.
- **`codex` (experimental)** — `codex` binary is invoked instead. The Run Setup panel shows fields for model, sandbox, and approval mode instead of the Claude session picker, and offers "Resume last Codex run" instead of picking a session. Resume uses `codex resume --last`. Codex lanes render stage-detection badges too, fed from Codex's own rollout journals rather than hooks (see "Stage detection"), but no Sessions/Analytics/cost — and the console never pre-fills the pipeline's Claude slash command into a codex pane.
- **`codex` (experimental)** — `codex` binary is invoked instead. The Run Setup panel shows fields for model, sandbox, and approval mode instead of the Claude session picker, and offers "Resume last Codex run" instead of picking a session. Resume uses `codex resume --last`. Codex lanes render stage-detection badges too, fed from Codex's own rollout journals rather than hooks (see "Stage detection"), but no Sessions/Analytics/cost. (The console pre-fills nothing into the prompt box, for either tool.)
### How Codex arguments map
@@ -386,7 +386,7 @@ Run history is per lane, queryable via `GET /api/run/history?laneId=<n>`.
The **working directory** field tracks the selected lane's own `cwd` specifically, and re-syncs as soon as that path is known rather than only when the selection changes — a pane can render before `GET /api/lanes` has answered (split view restores its pane lanes from `localStorage`), and its lane id never changes afterwards. `RunSetup` submits that string verbatim to `POST /api/lanes/:id/start`, so a cwd left over from the previous lane or from the home default would start the run in the wrong folder. The home suggestion is used only while no lane is selected at all.
**Picking a session to resume starts it right away.** In the setup form's Fresh/Resume switch, choosing a session from the resume picker fires the start immediately — `POST /api/lanes/:id/start` with that `resumeSessionId` and the session's own `cwd` — and the pane switches straight to the terminal. A resume carries its own transcript, so there is nothing to type first: the prompt box stays optional for resumes (the Run button no longer requires it) and required for fresh runs. Type into the tmux terminal once it's attached.
**Picking a session to resume starts it right away.** In the setup form's Fresh/Resume switch, choosing a session from the resume picker fires the start immediately — `POST /api/lanes/:id/start` with that `resumeSessionId` and the session's own `cwd` — and the pane switches straight to the terminal. A resume carries its own transcript, so there is nothing to type first: the prompt box stays optional for resumes (the Run button no longer requires it) and required for fresh runs. A resume also **sends no prompt at all** — whatever is left in that box is dropped rather than fired as an extra turn into the session being continued. Type into the tmux terminal once it's attached.
### Active runs list
+22 -3
View File
@@ -4014,7 +4014,7 @@ components:
required:
- title
- body
description: Notification content to broadcast. Both fields are mandatory; a missing title or body yields a 400. The same title/body is delivered to every reachable surface (native Electron notification + all stored Web Push subscriptions).
description: Notification content to broadcast. `title`/`body` are mandatory; a missing one yields a 400. The same content is delivered to every reachable surface (native Electron notification + all stored Web Push subscriptions).
properties:
title:
type: string
@@ -4024,6 +4024,10 @@ components:
type: string
description: Notification body text.
example: Your Claude Code session finished with 3 subagents.
url:
type: string
description: Optional same-origin path the Web Push delivery navigates to on click, via the service worker's `notificationclick` handler (`client/public/sw.js`). Ignored by the native Electron leg, which has no click handling. Omit for notifications with no specific target.
example: /workspace?lane=3
PushSendResponse:
type: object
required:
@@ -4053,6 +4057,21 @@ components:
minimum: 0
description: Count of Web Push sends that were rejected. Subscriptions rejected with HTTP 410 (Gone) are deleted from `push_subscriptions` as part of this request.
example: 1
errors:
type: array
description: Why the rejected sends were rejected, straight from the push service (capped at 3). Diagnostic only - it never includes the subscription endpoint, which is a capability URL. Drives the Settings test-notification banner, so a delivery that reached nobody names its reason instead of looking like success.
items:
type: object
properties:
statusCode:
type: integer
nullable: true
description: HTTP status the push service answered with, when there was one.
example: 403
message:
type: string
description: Response body or error message, truncated to 200 characters.
example: UnauthorizedRegistration
SessionsFacetsResponse:
type: object
description: 'Facet values for the Sessions page filter UI: the distinct working directories (cwd) and the distinct data-source ids seen across all sessions.'
@@ -8953,7 +8972,7 @@ paths:
- CcConfig
summary: Switch the local CLI to another Anthropic account
description: |-
Makes a saved profile the live account. Swaps EXACTLY two identity artifacts and nothing else: `claudeAiOauth` inside `<CLAUDE_HOME>/.credentials.json`, and `oauthAccount` + `userID` inside the `.claude.json` config file(s) (key-merged in place, and only where the file already exists, so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never touched - that is what makes a switch keep the whole workspace and change only the quota. `mcpOAuth` stays put too (machine MCP tokens, not account identity).
Makes a saved profile the live account. Swaps EXACTLY two identity artifacts and nothing else: `claudeAiOauth` inside `<CLAUDE_HOME>/.credentials.json` (on macOS: the login Keychain item `Claude Code-credentials`, which is where the CLI reads it), and `oauthAccount` + `userID` inside the `.claude.json` config file(s) (key-merged in place, and only where the file already exists, so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never touched - that is what makes a switch keep the whole workspace and change only the quota. `mcpOAuth` stays put too (machine MCP tokens, not account identity).
The outgoing account is re-snapshotted into its own profile FIRST, so tokens Claude Code refreshed since its last save are not lost. A switch takes effect for NEW Claude Code sessions only, and a session still running will rewrite the config on exit - close them first.
operationId: ccConfigActivateProfile
@@ -11086,7 +11105,7 @@ paths:
tags:
- Push
summary: Broadcast a notification to all surfaces
description: 'Dispatches a notification to every reachable surface at once: it fires a native OS notification via Electron''s main-process Notification API when the server is hosted inside the desktop app, AND sends an encrypted Web Push delivery to every stored subscription. Both legs run unconditionally so whichever surface the user is on receives the alert — under `npm start` the native leg is a no-op, and under the desktop app the Web Push leg is typically a no-op (Electron has no FCM credentials, so `push_subscriptions` is empty). Subscriptions rejected with HTTP 410 (Gone) are pruned from `push_subscriptions` during the request. The response reports `{ native, pushed, failed }` so the caller can tell a real delivery from a silent no-op. No authentication (local-first). A missing `title` or `body` returns 400; an unexpected dispatch error returns 500.'
description: 'Dispatches a notification to every reachable surface at once: it fires a native OS notification via Electron''s main-process Notification API when the server is hosted inside the desktop app, AND sends an encrypted Web Push delivery to every stored subscription. Both legs run unconditionally so whichever surface the user is on receives the alert — under `npm start` the native leg is a no-op, and under the desktop app the Web Push leg is typically a no-op (Electron has no FCM credentials, so `push_subscriptions` is empty). Subscriptions rejected with HTTP 410 (Gone) are pruned from `push_subscriptions` during the request. The response reports `{ native, pushed, failed, errors }` so the caller can tell a real delivery from a silent no-op, and can show WHY a rejected delivery failed. No authentication (local-first). A missing `title` or `body` returns 400; an unexpected dispatch error returns 500.'
operationId: pushSend
requestBody:
required: true
+3 -4
View File
@@ -583,10 +583,9 @@ journal's mtime, under the guard hook ingestion uses (no `run_id`, only from
Getting a codex lane's *declared* stage to actually happen is a separate
problem — only the session itself can call `agenthub stage`, and unlike a Claude
lane it has no slash command to pre-fill. `LaneConsolePane.tsx` pre-fills a
codex pane's opening prompt with a plain-text checklist instead, one
`agenthub stage <stage> --tool codex` line per node of the lane's own
`pipeline_nodes`. As a safety net beyond that opening nudge,
lane it has no slash command to pre-fill — and the run console pre-fills
nothing into the prompt box any more, for either tool, since anything sitting
there is sent as a real prompt on start. What is left is
`server/lib/codex-nudge.js`'s `sweepCodexNudges()` runs on an unref'd 60s
interval (`DASHBOARD_CODEX_NUDGE_MS`, `0` disables): when a codex lane's fresh
`detected_stage` has sat ahead of its declared `stage` for at least two
+53
View File
@@ -11,6 +11,9 @@ const fs = require("node:fs");
const SUITE_ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-cc-profiles-"));
process.env.CLAUDE_HOME = path.join(SUITE_ROOT, ".claude");
// File-backed by default, so running this suite on a Mac never reads or rewrites
// the developer's real login Keychain. The Keychain path has its own test below.
process.env.AGENTHUB_CC_KEYCHAIN = "0";
const { describe, it, beforeEach, after } = require("node:test");
const assert = require("node:assert/strict");
@@ -325,6 +328,56 @@ describe("cc-profiles", () => {
);
});
it("switches the account in the macOS Keychain, where the CLI actually reads it", () => {
const cp = require("node:child_process");
const realExec = cp.execFileSync;
const realPlatform = process.platform;
Object.defineProperty(process, "platform", { value: "darwin", configurable: true });
process.env.AGENTHUB_CC_KEYCHAIN = "1";
// A fake `security` binary backed by one string — the keychain item.
let item = null;
cp.execFileSync = (_bin, args) => {
if (args[0] === "find-generic-password") {
if (item === null) throw new Error("SecKeychainSearchCopyNext: not found");
return item;
}
if (args[0] === "add-generic-password") {
item = args[args.indexOf("-w") + 1];
return "";
}
throw new Error(`unexpected security verb ${args[0]}`);
};
try {
// Logged in as A, Keychain-only: no `.credentials.json` exists at all.
login("uuid-a", "a@example.com");
fs.rmSync(CREDS, { force: true });
item = JSON.stringify({
claudeAiOauth: { accessToken: "at-uuid-a", refreshToken: "rt-uuid-a" },
});
profiles.saveProfile("work");
login("uuid-b", "b@example.com");
fs.rmSync(CREDS, { force: true });
item = JSON.stringify({
claudeAiOauth: { accessToken: "at-uuid-b", refreshToken: "rt-uuid-b" },
});
profiles.saveProfile("personal");
assert.equal(profiles.listProfiles().items.find((p) => p.active).name, "personal");
const result = profiles.activateProfile("work");
assert.equal(JSON.parse(item).claudeAiOauth.accessToken, "at-uuid-a");
assert.ok(
result.written.some((w) => w.includes("Keychain")),
"the switch must report the Keychain as written"
);
assert.equal(fs.existsSync(CREDS), false, "no .credentials.json is invented on macOS");
} finally {
cp.execFileSync = realExec;
Object.defineProperty(process, "platform", { value: realPlatform, configurable: true });
process.env.AGENTHUB_CC_KEYCHAIN = "0";
}
});
it("reports a corrupt live credentials file rather than guessing", () => {
fs.mkdirSync(HOME, { recursive: true });
fs.writeFileSync(CREDS, "{nope");
+85 -6
View File
@@ -5,7 +5,8 @@
* anything else in the Claude home.
*
* A profile is exactly the two identity artifacts and nothing more:
* - `claudeAiOauth` out of `<CLAUDE_HOME>/.credentials.json`
* - `claudeAiOauth` out of `<CLAUDE_HOME>/.credentials.json` — or, on macOS,
* out of the login Keychain item the CLI actually reads there
* - `oauthAccount` + `userID` out of the `.claude.json` config file(s)
* Skills, subagents, commands, memory, plugins, marketplaces, MCP servers,
* settings and session history all live elsewhere under CLAUDE_HOME and are
@@ -23,10 +24,59 @@
*/
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const cp = require("node:child_process");
const { getClaudeHome } = require("./claude-home");
/**
* On macOS the `claude` CLI keeps `claudeAiOauth` in the login Keychain, NOT in
* `<CLAUDE_HOME>/.credentials.json` — a file there is absent or a stale leftover
* from an older build. Reading/writing only the file on a Mac is why a switch
* reported success while the CLI kept running as the previous account.
*/
const KEYCHAIN_SERVICE = "Claude Code-credentials";
const KEYCHAIN_LABEL = `macOS Keychain (${KEYCHAIN_SERVICE})`;
/** Off with AGENTHUB_CC_KEYCHAIN=0 — tests, and anyone pinning the file. */
function keychainEnabled() {
return process.platform === "darwin" && process.env.AGENTHUB_CC_KEYCHAIN !== "0";
}
function keychainArgs(verb) {
return [verb, "-s", KEYCHAIN_SERVICE, "-a", os.userInfo().username];
}
/** The keychain item's JSON, or null when there is none / it is unreadable. */
function readKeychain() {
try {
const out = cp.execFileSync(
"/usr/bin/security",
[...keychainArgs("find-generic-password"), "-w"],
{
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}
);
const parsed = JSON.parse(out.trim());
return parsed && typeof parsed === "object" ? parsed : null;
} catch {
return null;
}
}
function writeKeychain(value) {
// ponytail: the secret rides in argv (`security` has no stdin mode), so it is
// briefly visible in `ps` on a shared machine. Upgrade path is a native
// keychain binding if that ever matters.
cp.execFileSync(
"/usr/bin/security",
[...keychainArgs("add-generic-password"), "-U", "-w", JSON.stringify(value)],
{ stdio: "ignore" }
);
}
/**
* A profile's `name` is its filename, so the charset is deliberately narrow.
* It is an internal identifier: what the user reads and edits is `label`, which
@@ -84,9 +134,38 @@ function writeJson(file, value) {
fs.renameSync(tmp, file);
}
/**
* The live credentials blob and where it came from. The Keychain wins on macOS
* when it holds an item; everything else (and a Mac whose CLI still uses the
* file) falls back to `.credentials.json`.
*/
function readCredentials() {
if (keychainEnabled()) {
const kc = readKeychain();
if (kc) return { creds: kc, keychain: true };
}
return { creds: readJson(credentialsPath()), keychain: false };
}
/** Write credentials back to the store they were read from. Returns what was written. */
function writeCredentials(creds, keychain) {
if (!keychain) {
writeJson(credentialsPath(), creds);
return [credentialsPath()];
}
writeKeychain(creds);
// A stale file beside the Keychain would still name the old account; keep it
// in step when it exists, never create one.
if (fs.existsSync(credentialsPath())) {
writeJson(credentialsPath(), creds);
return [KEYCHAIN_LABEL, credentialsPath()];
}
return [KEYCHAIN_LABEL];
}
/** The account identity currently on disk. `oauth`/`account` may be null. */
function readActiveAuth() {
const creds = readJson(credentialsPath());
const { creds, keychain } = readCredentials();
let account = null;
let userID = null;
for (const file of configPaths()) {
@@ -97,7 +176,7 @@ function readActiveAuth() {
break;
}
}
return { oauth: (creds && creds.claudeAiOauth) || null, account, userID };
return { oauth: (creds && creds.claudeAiOauth) || null, account, userID, keychain };
}
/** Token-free description of an account, safe to send to the browser. */
@@ -344,12 +423,12 @@ function activateProfile(name) {
}
const written = [];
const creds = readJson(credentialsPath()) || {};
const { creds: live, keychain } = readCredentials();
const creds = live || {};
// Only the Claude account slot moves; `mcpOAuth` holds this machine's MCP
// server tokens, which are not part of the account identity.
creds.claudeAiOauth = target.credentials;
writeJson(credentialsPath(), creds);
written.push(credentialsPath());
written.push(...writeCredentials(creds, keychain));
for (const file of configPaths()) {
const cfg = readJson(file);
+9 -1
View File
@@ -82,8 +82,12 @@ function showNativeNotificationIfElectron(title, body) {
*
* Returns `{ native, pushed, failed }` so the caller can surface what actually
* happened in its API response — silent failures stop looking like success.
*
* @param {string} [url] Same-origin path (e.g. `/workspace?lane=3`) the
* service worker's `notificationclick` handler navigates to. Undefined for
* notifications with no specific target.
*/
async function sendPushToAll(db, title, body) {
async function sendPushToAll(db, title, body, url) {
const native = showNativeNotificationIfElectron(title, body);
const subscriptions = db.prepare("SELECT * FROM push_subscriptions").all();
@@ -102,6 +106,10 @@ async function sendPushToAll(db, title, body) {
badge: "/favicon.svg",
silent: false,
sound: "default",
// `data` is the standard NotificationOptions field notificationclick reads
// back via `event.notification.data`; omitted entirely when there's no url
// so `event.notification.data` stays undefined rather than `{url: undefined}`.
...(url ? { data: { url } } : {}),
});
const results = await Promise.allSettled(
subscriptions.map((sub) =>
+1 -1
View File
@@ -2623,7 +2623,7 @@ const paths = {
tags: ["CcConfig"],
summary: "Switch the local CLI to another Anthropic account",
description:
"Makes a saved profile the live account. Swaps EXACTLY two identity artifacts and nothing else: `claudeAiOauth` inside `<CLAUDE_HOME>/.credentials.json`, and `oauthAccount` + `userID` inside the `.claude.json` config file(s) (key-merged in place, and only where the file already exists, so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never touched - that is what makes a switch keep the whole workspace and change only the quota. `mcpOAuth` stays put too (machine MCP tokens, not account identity).\n\nThe outgoing account is re-snapshotted into its own profile FIRST, so tokens Claude Code refreshed since its last save are not lost. A switch takes effect for NEW Claude Code sessions only, and a session still running will rewrite the config on exit - close them first.",
"Makes a saved profile the live account. Swaps EXACTLY two identity artifacts and nothing else: `claudeAiOauth` inside `<CLAUDE_HOME>/.credentials.json` (on macOS: the login Keychain item `Claude Code-credentials`, which is where the CLI reads it), and `oauthAccount` + `userID` inside the `.claude.json` config file(s) (key-merged in place, and only where the file already exists, so `projects`/`numStartups`/everything else survives). Skills, subagents, commands, memory, plugins, marketplaces, MCP servers and settings are never touched - that is what makes a switch keep the whole workspace and change only the quota. `mcpOAuth` stays put too (machine MCP tokens, not account identity).\n\nThe outgoing account is re-snapshotted into its own profile FIRST, so tokens Claude Code refreshed since its last save are not lost. A switch takes effect for NEW Claude Code sessions only, and a session still running will rewrite the config on exit - close them first.",
operationId: "ccConfigActivateProfile",
requestBody: {
required: true,
+29 -2
View File
@@ -121,7 +121,7 @@ const schemas = {
type: "object",
required: ["title", "body"],
description:
"Notification content to broadcast. Both fields are mandatory; a missing title or body yields a 400. The same title/body is delivered to every reachable surface (native Electron notification + all stored Web Push subscriptions).",
"Notification content to broadcast. `title`/`body` are mandatory; a missing one yields a 400. The same content is delivered to every reachable surface (native Electron notification + all stored Web Push subscriptions).",
properties: {
title: {
type: "string",
@@ -133,6 +133,12 @@ const schemas = {
description: "Notification body text.",
example: "Your Claude Code session finished with 3 subagents.",
},
url: {
type: "string",
description:
"Optional same-origin path the Web Push delivery navigates to on click, via the service worker's `notificationclick` handler (`client/public/sw.js`). Ignored by the native Electron leg, which has no click handling. Omit for notifications with no specific target.",
example: "/workspace?lane=3",
},
},
},
@@ -168,6 +174,27 @@ const schemas = {
"Count of Web Push sends that were rejected. Subscriptions rejected with HTTP 410 (Gone) are deleted from `push_subscriptions` as part of this request.",
example: 1,
},
errors: {
type: "array",
description:
"Why the rejected sends were rejected, straight from the push service (capped at 3). Diagnostic only - it never includes the subscription endpoint, which is a capability URL. Drives the Settings test-notification banner, so a delivery that reached nobody names its reason instead of looking like success.",
items: {
type: "object",
properties: {
statusCode: {
type: "integer",
nullable: true,
description: "HTTP status the push service answered with, when there was one.",
example: 403,
},
message: {
type: "string",
description: "Response body or error message, truncated to 200 characters.",
example: "UnauthorizedRegistration",
},
},
},
},
},
},
};
@@ -287,7 +314,7 @@ const paths = {
tags: ["Push"],
summary: "Broadcast a notification to all surfaces",
description:
"Dispatches a notification to every reachable surface at once: it fires a native OS notification via Electron's main-process Notification API when the server is hosted inside the desktop app, AND sends an encrypted Web Push delivery to every stored subscription. Both legs run unconditionally so whichever surface the user is on receives the alert — under `npm start` the native leg is a no-op, and under the desktop app the Web Push leg is typically a no-op (Electron has no FCM credentials, so `push_subscriptions` is empty). Subscriptions rejected with HTTP 410 (Gone) are pruned from `push_subscriptions` during the request. The response reports `{ native, pushed, failed }` so the caller can tell a real delivery from a silent no-op. No authentication (local-first). A missing `title` or `body` returns 400; an unexpected dispatch error returns 500.",
"Dispatches a notification to every reachable surface at once: it fires a native OS notification via Electron's main-process Notification API when the server is hosted inside the desktop app, AND sends an encrypted Web Push delivery to every stored subscription. Both legs run unconditionally so whichever surface the user is on receives the alert — under `npm start` the native leg is a no-op, and under the desktop app the Web Push leg is typically a no-op (Electron has no FCM credentials, so `push_subscriptions` is empty). Subscriptions rejected with HTTP 410 (Gone) are pruned from `push_subscriptions` during the request. The response reports `{ native, pushed, failed, errors }` so the caller can tell a real delivery from a silent no-op, and can show WHY a rejected delivery failed. No authentication (local-first). A missing `title` or `body` returns 400; an unexpected dispatch error returns 500.",
operationId: "pushSend",
requestBody: {
required: true,
+2 -2
View File
@@ -34,7 +34,7 @@ router.delete("/subscribe", (req, res) => {
});
router.post("/send", async (req, res) => {
const { title, body } = req.body;
const { title, body, url } = req.body;
if (!title || !body) {
return res.status(400).json({ error: { message: "Missing title or body" } });
}
@@ -43,7 +43,7 @@ router.post("/send", async (req, res) => {
// { native: true|false, pushed: <count>, failed: <count> }
// so a silent "no subscribers, no Electron host" no-op stops looking like
// success on the client side.
const result = await sendPushToAll(db, title, body);
const result = await sendPushToAll(db, title, body, typeof url === "string" ? url : undefined);
res.json({ ok: true, ...result });
} catch (err) {
res.status(500).json({ error: { message: err.message } });