Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(server): managed Claude accounts on the Server Edition

enes9366f02ec363
diff --git a/CLAUDE.md b/CLAUDE.md
index f1560be0b..92c0902a6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1320,7 +1320,7 @@ else, and its context links must keep classifying across restarts).
child env so a stray env key can't shadow the account. A **missing** account dir → warn +
silent system fallback.
- **Login flow** — Settings → Accounts → **Add** creates a `pending` account and drops a canvas
- **login node** that runs `claude /login` under the account dir. Main polls the dir's
+ **login node** that runs `claude /login` under the account dir. Core polls the dir's
`.claude.json` (`LOGIN_POLL_MS` 2 s, up to `LOGIN_TIMEOUT_MS` 5 min) for `oauthAccount.email`;
on capture the account flips out of `pending` with its email as the default label. Account
removal cancels any pending wait + `markDirty`. **Codex accounts have the same two halves** —
@@ -1334,9 +1334,31 @@ else, and its context links must keep classifying across restarts).
no listener is a silent no-op, which is how the Codex half shipped inert (#346) — pinned now by
`renderer/lib/nodeterm-events.test.ts`, which fails on any `nodeterm:*` event that is sent but
never heard.
+ - **The lifecycle is CORE, and both shells register it** (issue #313) —
+ `core/claude-accounts-service.ts` owns the four `claude-accounts:*` channels (add / wait-login
+ / cancel-wait / remove) behind `platform().handle`; `main/claude-accounts.ts` is a thin desktop
+ wrapper and `registerCoreHandlers` calls the same `registerClaudeAccountsIpc()`. Two optional
+ deps carry everything core cannot reach: `installSkill` (desktop passes `installCanvasSkillInto`
+ — the server passes none, because **canvas control is not wired on that shell at all**, so a
+ per-account SKILL.md would point at nothing) and `remote`, a **thunk** resolving the SSH legs
+ (desktop's manager is created after the registration, and the server has none — in both cases
+ an `AccountCtx` carrying a `projectId` degrades to the LOCAL path, which is the pre-existing
+ behavior this preserves). **Three surfaces:** Desktop unchanged (same channels, same shapes,
+ same remote fallbacks); **Server Edition** now full — real `buildClaudeAccountsApi` over the
+ ws-bridge (the 5-min `waitLogin` is a straight passthrough because RpcClient has no request
+ timeout), minus SSH accounts and the canvas skill; **Mobile: N/A** — the phone launches with
+ the accounts the agent-status mirror advertises and never mints one. **Managed CODEX accounts
+ stay desktop-only** and their bridge namespace stays an `E_UNSUPPORTED` stub: the switch verbs
+ authorize the owning window by Electron WebContents id, which has no meaning over a WS
+ connection. The Settings section now *names* that refusal instead of leaving an unhandled
+ promise rejection — a spinner that stops and says nothing reads as a dead button.
- **Hook install** — the managed hook is merged into **each account dir's** `settings.json` at
add-account **and** at app launch (local, shared `install-helper.ts`) / via
- `RemoteHooks.installIntoAccountDir` (remote), so every identity reports agent status.
+ `RemoteHooks.installIntoAccountDir` (remote), so every identity reports agent status. The
+ launch-time loop is ONE function (`installHooksIntoLocalAccounts`, beside the service) that
+ both shells call — the desktop passing the canvas skill as its `extra`. A second copy is the
+ drift this file warns about elsewhere: the Server Edition shipped without the per-account leg
+ entirely, so a managed account there reported no agent status at all.
- **Account-aware readers** — transcript resolution is scoped per account (`transcriptRootFor`
picks the account dir's `projects/`, composite cache key includes `accountId`); the same
threading runs through the session-name poll, restart handoff, and `ChatPanel` (the ⌘M
diff --git a/docs/SERVER.md b/docs/SERVER.md
index c5c71fe77..30f52ef3a 100644
--- a/docs/SERVER.md
+++ b/docs/SERVER.md
@@ -529,6 +529,35 @@ than a generic failure, see above), full **two-master flow-control coordination*
a single actuator with the renderer), and the web folder picker's **hardcoded start
directory**.
+### Managed Claude accounts
+
+Managed Claude accounts (several logged-in Claude identities side by side, each with its own
+`CLAUDE_CONFIG_DIR`) **work in the browser**. Selecting one always did — env injection, the
+transcript readers, the usage rows and the account pickers are all `src/core` — but the
+*lifecycle* was welded to `ipcMain`, so a browser-only deployment could pick an account it had no
+way to create (issue #313).
+
+- **The lifecycle is core.** `src/core/claude-accounts-service.ts` owns the four
+ `claude-accounts:*` channels (add / wait-login / cancel-wait / remove) and registers them
+ through the platform seam, so **both shells serve them**: `src/main/claude-accounts.ts` is now a
+ thin desktop wrapper, and `registerCoreHandlers` calls the same `registerClaudeAccountsIpc()`.
+ The browser reaches them through a real `buildClaudeAccountsApi` in the ws-bridge instead of the
+ old `E_UNSUPPORTED` stub. `waitLogin` is a straight passthrough of a poll that runs up to five
+ minutes — safe because the WS RpcClient has no request timeout, so a pending request rejects
+ only when the socket drops.
+- **Per-account hooks are installed at boot and at add.** A managed account carries its own
+ `settings.json` (Claude Code resolves it relative to `CLAUDE_CONFIG_DIR`), so the managed status
+ hook has to be written there too or that account reports no agent status at all. `startServer`
+ runs the same per-account loop the desktop does right after `installManagedAgentHooks()`, and
+ `add` installs into the fresh dir up front.
+- **The canvas skill is desktop-only.** Canvas control is not wired on this edition at all (the
+ hook server answers `control unavailable` by name), so the service takes the skill installer as
+ an optional dep and the server passes none — a per-account `SKILL.md` here would point at
+ nothing.
+- **No remote (SSH) accounts.** The Server Edition has no SSH-project manager, so an account
+ context carrying a `projectId` takes the **local** path — the same degrade the desktop takes
+ before its manager exists.
+
### Managed Codex accounts (S6)
The Server Edition **arms the Codex record-signing secret** but does **not** host the
@@ -549,6 +578,15 @@ account-management IPC — that surface is desktop-driven over SSH.
- **Fail-closed, both ways.** With no secret armed (unwritable key file), the record layer throws
rather than writing anything unsigned, and Codex nodes keep working bare. A machine with **no** managed
accounts is byte-for-byte the pre-S6 layout (a bare-root record per thread).
+- **A browser-only deployment therefore cannot manage Codex accounts** — the case issue #313 is
+ about. Managed **Claude** accounts moved into core (above); Codex did not follow, and the reason
+ is not effort: its switch verbs (`switchThread` / `commitSwitch` / `finishSwitch` /
+ `rollbackSwitch`) authorize the owning window by Electron **WebContents id**, which has no
+ meaning over a WS connection where every browser tab is an equally anonymous socket. Hosting
+ them headless needs a connection-identity redesign first, not a handler port. Until then the
+ `codexAccounts` namespace stays an `E_UNSUPPORTED` stub in the bridge and the Settings section
+ says so by name rather than failing silently — an unhandled rejection there previously stopped
+ the spinner and showed nothing.
## Manual browser smoke checklist
diff --git a/src/core/claude-accounts-service.test.ts b/src/core/claude-accounts-service.test.ts
new file mode 100644
index 000000000..5f7bd7dc5
--- /dev/null
+++ b/src/core/claude-accounts-service.test.ts
@@ -0,0 +1,182 @@
+/**
+ * Issue #313 — the managed-Claude-account LIFECYCLE lives in core, so both shells serve it.
+ *
+ * Every one of these cases drives the shipped registration through the platform seam
+ * (`fakePlatform().handlers[...]`), i.e. exactly what `ipcMain.handle` / the server's WS dispatch
+ * invoke. Registering with NO deps is the Server Edition's own configuration: no canvas skill
+ * (canvas control is not wired there) and no SSH manager, so a ctx carrying a projectId must still
+ * take the local path.
+ *
+ * MUTATION: drop the `installSkill` call, or let `remoteFor` treat a projectId alone as remote →
+ * the skill case and the local-fallback case redden.
+ */
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { existsSync, mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { IPC } from '../shared/ipc'
+import { registerClaudeAccountsIpc, installHooksIntoLocalAccounts } from './claude-accounts-service'
+import { accountConfigDir } from './claude-accounts-core'
+
+// The hook + TUI writers are exercised by their own suites; here they only have to be OBSERVED,
+// and a real write would touch the account dir this file then asserts about.
+const installed: string[] = []
+const tui: string[] = []
+vi.mock('./agents/hooks/claude', () => ({
+ installClaudeHooksInto: (dir: string) => {
+ installed.push(dir)
+ },
+ ensureClaudeFullscreenTuiInto: async (dir: string) => {
+ tui.push(dir)
+ }
+}))
+
+let fake: FakePlatform
+let userDataDir: string
+
+const call = (channel: string, ...args: unknown[]): Promise<any> =>
+ Promise.resolve(fake.handlers[channel](...args))
+
+beforeEach(() => {
+ installed.length = 0
+ tui.length = 0
+ userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nt-accounts-'))
+ fake = fakePlatform({ userDataDir })
+ initPlatform(fake)
+})
+afterEach(() => {
+ resetPlatformForTests()
+ rmSync(userDataDir, { recursive: true, force: true })
+})
+
+describe('registerClaudeAccountsIpc — the four channels', () => {
+ it('registers exactly the four claude-accounts channels', () => {
+ registerClaudeAccountsIpc()
+ expect(Object.keys(fake.handlers).sort()).toEqual(
+ [
+ IPC.claudeAccountsAdd,
+ IPC.claudeAccountsCancelWait,
+ IPC.claudeAccountsRemove,
+ IPC.claudeAccountsWaitLogin
+ ].sort()
+ )
+ })
+
+ it('add() creates the config dir under userData, installs the hook and returns the id', async () => {
+ const skilled: string[] = []
+ registerClaudeAccountsIpc({ installSkill: (d) => skilled.push(d) })
+ const res = await call(IPC.claudeAccountsAdd)
+ expect(res.id).toMatch(/^[A-Za-z0-9-]+$/)
+ expect(res.configDir).toBe(accountConfigDir(userDataDir, res.id))
+ expect(existsSync(res.configDir)).toBe(true)
+ expect(installed).toEqual([res.configDir])
+ expect(skilled).toEqual([res.configDir])
+ expect(tui).toEqual([res.configDir])
+ })
+
+ it('add() without an installSkill dep (the Server Edition) writes no skill', async () => {
+ registerClaudeAccountsIpc()
+ const res = await call(IPC.claudeAccountsAdd)
+ expect(existsSync(res.configDir)).toBe(true)
+ expect(installed).toEqual([res.configDir])
+ })
+
+ it('waitLogin resolves once .claude.json carries an oauthAccount email', async () => {
+ registerClaudeAccountsIpc({ pollMs: 5 })
+ const { id, configDir } = await call(IPC.claudeAccountsAdd)
+ const pending = call(IPC.claudeAccountsWaitLogin, id)
+ setTimeout(() => {
+ writeFileSync(
+ path.join(configDir, '.claude.json'),
+ JSON.stringify({ oauthAccount: { emailAddress: '[email protected]' } })
+ )
+ }, 20)
+ await expect(pending).resolves.toEqual({ email: '[email protected]' })
+ })
+
+ it('cancelWaitLogin makes an in-flight wait resolve null', async () => {
+ registerClaudeAccountsIpc({ pollMs: 5 })
+ const { id } = await call(IPC.claudeAccountsAdd)
+ const pending = call(IPC.claudeAccountsWaitLogin, id)
+ await new Promise((r) => setTimeout(r, 20))
+ await call(IPC.claudeAccountsCancelWait, id)
+ await expect(pending).resolves.toBeNull()
+ })
+
+ it('remove() deletes the account dir', async () => {
+ registerClaudeAccountsIpc()
+ const { id, configDir } = await call(IPC.claudeAccountsAdd)
+ writeFileSync(path.join(configDir, '.credentials.json'), '{}')
+ await call(IPC.claudeAccountsRemove, id)
+ expect(existsSync(configDir)).toBe(false)
+ })
+
+ it('a traversing id is refused, not resolved outside the accounts root', async () => {
+ registerClaudeAccountsIpc({ pollMs: 5 })
+ await expect(call(IPC.claudeAccountsRemove, '../x')).rejects.toThrow(/invalid account id/)
+ await expect(call(IPC.claudeAccountsWaitLogin, '../x')).rejects.toThrow(/invalid account id/)
+ })
+})
+
+describe('the remote leg is resolved lazily, and its absence falls back to LOCAL', () => {
+ it('a ctx with a projectId takes the remote leg when one is wired', async () => {
+ const calls: string[] = []
+ registerClaudeAccountsIpc({
+ pollMs: 5,
+ remote: () => ({
+ add: async (projectId, id) => {
+ calls.push(`add:${projectId}:${id}`)
+ return { configDir: `~/.nodeterm/claude-accounts/${id}`, versionSupported: true }
+ },
+ readLogin: async () => JSON.stringify({ oauthAccount: { email: '[email protected]' } }),
+ remove: async (projectId, id) => {
+ calls.push(`rm:${projectId}:${id}`)
+ }
+ })
+ })
+ const res = await call(IPC.claudeAccountsAdd, { projectId: 'p1' })
+ expect(res.configDir).toBe(`~/.nodeterm/claude-accounts/${res.id}`)
+ // Nothing local was created or installed for a remote account.
+ expect(existsSync(accountConfigDir(userDataDir, res.id))).toBe(false)
+ expect(installed).toEqual([])
+ await expect(call(IPC.claudeAccountsWaitLogin, res.id, { projectId: 'p1' })).resolves.toEqual({
+ })
+ await call(IPC.claudeAccountsRemove, res.id, { projectId: 'p1' })
+ expect(calls).toEqual([`add:p1:${res.id}`, `rm:p1:${res.id}`])
+ })
+
+ it('a ctx with a projectId but NO wired remote takes the local path (Server Edition)', async () => {
+ registerClaudeAccountsIpc({ remote: () => undefined })
+ const res = await call(IPC.claudeAccountsAdd, { projectId: 'p1' })
+ expect(res.configDir).toBe(accountConfigDir(userDataDir, res.id))
+ expect(existsSync(res.configDir)).toBe(true)
+ })
+})
+
+describe('installHooksIntoLocalAccounts', () => {
+ it('installs into every LOCAL account dir and skips host-scoped ones', () => {
+ const extra: string[] = []
+ installHooksIntoLocalAccounts(
+ [{ id: 'aaa' }, { id: 'bbb', host: 'user@example' }, { id: 'ccc' }],
+ (d) => extra.push(d)
+ )
+ const dirs = ['aaa', 'ccc'].map((id) => accountConfigDir(userDataDir, id))
+ expect(installed).toEqual(dirs)
+ expect(extra).toEqual(dirs)
+ expect(tui).toEqual(dirs)
+ })
+
+ it('one failing account never stops the rest (boot must not be blocked)', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ mkdirSync(path.join(userDataDir, 'claude-accounts'), { recursive: true })
+ installHooksIntoLocalAccounts([{ id: 'aaa' }, { id: '../evil' }, { id: 'ccc' }])
+ expect(installed).toEqual(
+ ['aaa', 'ccc'].map((id) => accountConfigDir(userDataDir, id))
+ )
+ expect(warn).toHaveBeenCalled()
+ warn.mockRestore()
+ })
+})
diff --git a/src/core/claude-accounts-service.ts b/src/core/claude-accounts-service.ts
new file mode 100644
index 000000000..1b8e0ec30
--- /dev/null
+++ b/src/core/claude-accounts-service.ts
@@ -0,0 +1,185 @@
+// Impure lifecycle for managed Claude accounts: config-dir creation/deletion, login capture
+// (poll .claude.json), CLI version check, per-account hook install. The account LIST lives in
+// settings.json (renderer-owned via useSettings); this module only owns the filesystem.
+//
+// Lives in core so BOTH shells serve it. Before this the four channels were registered only by
+// src/main, so the Server Edition's bridge answered E_UNSUPPORTED for every one of them: a
+// browser-only deployment could select a managed account (env injection, transcript readers,
+// usage and the pickers are all core already) but could never CREATE, log into or remove one
+// (issue #313).
+import { randomUUID } from 'crypto'
+import { promises as fs } from 'fs'
+import path from 'path'
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+import { IPC } from '../shared/ipc'
+import { isSupportedClaudeVersion, parseLoginCapture } from './claude-accounts-core'
+import { claudeConfigDirFor } from './claude-config-dir'
+import { installClaudeHooksInto, ensureClaudeFullscreenTuiInto } from './agents/hooks/claude'
+import { findInLoginPath } from './pty-manager'
+import { platform } from './platform'
+
+const execFileP = promisify(execFile)
+const LOGIN_POLL_MS = 2000
+const LOGIN_TIMEOUT_MS = 5 * 60 * 1000
+
+/**
+ * Optional per-call SSH context. When `projectId` is present AND that project has a live
+ * ControlMaster, the account is a REMOTE one: its config dir + login capture + removal happen on the
+ * host over ssh instead of on the local filesystem. The renderer passes it only for accounts scoped
+ * to an SSH project (`ClaudeAccount.host`); local accounts omit it entirely (unchanged behavior).
+ */
+export interface AccountCtx {
+ projectId?: string
+}
+
+/** The three remote legs, as the shell implements them (desktop: SshProjectManager). */
+export interface ClaudeAccountsRemote {
+ add(
+ projectId: string,
+ id: string
+ ): Promise<{ configDir: string; versionSupported: boolean } | null>
+ readLogin(projectId: string, id: string): Promise<string | null>
+ remove(projectId: string, id: string): Promise<void>
+}
+
+export interface ClaudeAccountsDeps {
+ /**
+ * Install the canvas-control skill into a freshly created account dir. Claude Code resolves
+ * skills relative to CLAUDE_CONFIG_DIR, so a managed account needs its own copy. DESKTOP ONLY:
+ * canvas control is not wired on the Server Edition at all (its hook server answers
+ * `control unavailable` by name), so there is nothing for a skill file to reach there.
+ */
+ installSkill?: (configDir: string) => void
+ /**
+ * Resolves the live remote legs, or undefined when SSH is not wired / not yet created. A THUNK
+ * rather than a plain object because that is the fact the local fallback turns on: desktop
+ * creates its SshProjectManager after this registration, and an `AccountCtx` carrying a
+ * projectId while no manager exists must degrade to the LOCAL path (pre-existing behavior).
+ * The Server Edition passes none, so every call takes that same local path.
+ */
+ remote?: () => ClaudeAccountsRemote | undefined
+ /** Login poll interval. Injectable so tests need not wait out the 2 s production cadence. */
+ pollMs?: number
+}
+
+const waiters = new Map<string, { cancelled: boolean }>()
+
+async function checkClaudeVersion(): Promise<boolean> {
+ // The < 2.1 warning is about the shared macOS Keychain service; on Linux/Windows
+ // credentials are files inside each config dir, so no version collides.
+ if (process.platform !== 'darwin') return true
+ try {
+ const claude = await findInLoginPath('claude')
+ if (!claude) return false
+ const { stdout } = await execFileP(claude, ['--version'], { timeout: 5000 })
+ return isSupportedClaudeVersion(stdout.trim())
+ } catch {
+ return false
+ }
+}
+
+/** Register the four `claude-accounts:*` channels on the core platform seam. */
+export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {
+ const pollMs = deps.pollMs ?? LOGIN_POLL_MS
+ // Resolve the live remote legs for a context, or null when the context is local / not connected.
+ const remoteFor = (ctx?: AccountCtx): { r: ClaudeAccountsRemote; projectId: string } | null => {
+ const projectId = ctx?.projectId
+ const r = deps.remote?.()
+ return projectId && r ? { r, projectId } : null
+ }
+
+ platform().handle(IPC.claudeAccountsAdd, async (ctx?: AccountCtx) => {
+ const id = randomUUID()
+ const remote = remoteFor(ctx)
+ if (remote) {
+ // REMOTE account: create the config dir + install the status hook on the host. No local dir
+ // and no local hook install — the session runs entirely on the remote host.
+ const res = await remote.r.add(remote.projectId, id)
+ // Null means the project wasn't connected / mkdir failed: still return the id so the renderer
+ // can show the pending row; the login node will surface the connection error itself.
+ return { id, configDir: res?.configDir ?? '', versionSupported: res?.versionSupported ?? true }
+ }
+ const configDir = claudeConfigDirFor(id)
+ await fs.mkdir(configDir, { recursive: true })
+ // Install the managed hook (+ the canvas skill where the shell has one) up front so the very
+ // first session in this account already reports status (badges/notifications/subagent viz)
+ // and can control the canvas (Claude resolves both relative to CLAUDE_CONFIG_DIR, not ~/.claude).
+ installClaudeHooksInto(configDir)
+ deps.installSkill?.(configDir)
+ // Ensure fullscreen TUI in the new account dir (write-if-absent, version-gated). Best-effort,
+ // off the response path — the memoized probe + write both fail open.
+ void ensureClaudeFullscreenTuiInto(configDir)
+ const versionSupported = await checkClaudeVersion()
+ return { id, configDir, versionSupported }
+ })
+
+ platform().handle(IPC.claudeAccountsWaitLogin, async (id: string, ctx?: AccountCtx) => {
+ const remote = remoteFor(ctx)
+ // Local path: `claudeConfigDirFor` also validates the id shape (rejects traversal).
+ const configDir = remote ? null : claudeConfigDirFor(id)
+ const w = { cancelled: false }
+ waiters.set(id, w)
+ const deadline = Date.now() + LOGIN_TIMEOUT_MS
+ try {
+ while (!w.cancelled && Date.now() < deadline) {
+ try {
+ const raw = remote
+ ? await remote.r.readLogin(remote.projectId, id)
+ : await fs.readFile(path.join(configDir as string, '.claude.json'), 'utf-8')
+ const captured = raw ? parseLoginCapture(raw) : null
+ if (captured) return captured
+ } catch {
+ // not written yet — keep polling
+ }
+ await new Promise((r) => setTimeout(r, pollMs))
+ }
+ return null
+ } finally {
+ waiters.delete(id)
+ }
+ })
+
+ platform().handle(IPC.claudeAccountsCancelWait, (id: string) => {
+ const w = waiters.get(id)
+ if (w) w.cancelled = true
+ })
+
+ platform().handle(IPC.claudeAccountsRemove, async (id: string, ctx?: AccountCtx) => {
+ const remote = remoteFor(ctx)
+ if (remote) {
+ // Best-effort remote cleanup; if the project isn't connected the manager no-ops and the
+ // renderer still drops the account from its list (the dir is orphaned, harmless).
+ await remote.r.remove(remote.projectId, id)
+ return
+ }
+ const configDir = claudeConfigDirFor(id) // id validation prevents traversal
+ await fs.rm(configDir, { recursive: true, force: true })
+ })
+}
+
+/**
+ * Install the managed hook + fullscreen-TUI setting into every LOCAL managed account dir. Managed
+ * accounts each carry their own settings.json (Claude Code resolves it relative to
+ * CLAUDE_CONFIG_DIR), so an app update's new hook version must reach them too. Best-effort per
+ * account: one failing account must never block launch (matches installManagedAgentHooks'
+ * fail-open). `extra` is the shell's per-account addition — desktop installs the canvas skill.
+ */
+export function installHooksIntoLocalAccounts(
+ accounts: readonly { id: string; host?: string }[],
+ extra?: (configDir: string) => void
+): void {
+ for (const acct of accounts) {
+ if (acct.host) continue // remote accounts live on another host; nothing to install locally
+ try {
+ const configDir = claudeConfigDirFor(acct.id)
+ installClaudeHooksInto(configDir)
+ extra?.(configDir)
+ // Off the critical path: it awaits the memoized CLI probe, then writes fail-open. (The
+ // system ~/.claude is handled by installManagedAgentHooks, which covers both shells.)
+ void ensureClaudeFullscreenTuiInto(configDir)
+ } catch (e) {
+ console.warn(`[agent-hooks] account ${acct.id} hook install failed`, e)
+ }
+ }
+}
diff --git a/src/main/claude-accounts.ts b/src/main/claude-accounts.ts
index 77f850b0b..ab6fad529 100644
--- a/src/main/claude-accounts.ts
+++ b/src/main/claude-accounts.ts
@@ -1,131 +1,30 @@
-// Impure lifecycle for managed Claude accounts: config-dir creation/deletion, login
-// capture (poll .claude.json), CLI version check, hook install. The account LIST lives in
-// settings.json (renderer-owned via useSettings); this module only owns the filesystem.
-import { randomUUID } from 'crypto'
-import { promises as fs } from 'fs'
-import path from 'path'
-import { execFile } from 'child_process'
-import { promisify } from 'util'
-import { ipcMain } from 'electron'
-import { IPC } from '../shared/ipc'
-import { isSupportedClaudeVersion, parseLoginCapture } from '../core/claude-accounts-core'
-import { claudeConfigDirFor } from '../core/claude-config-dir'
-import { installClaudeHooksInto, ensureClaudeFullscreenTuiInto } from '../core/agents/hooks/claude'
+// Desktop wiring for the managed-Claude-account lifecycle. The lifecycle itself lives in
+// src/core/claude-accounts-service.ts so the Server Edition serves the same four channels
+// (issue #313); this file supplies only the two things core cannot reach — the canvas-control
+// skill installer (which imports electron's `app`) and the SSH project manager.
+import { registerClaudeAccountsIpc } from '../core/claude-accounts-service'
import { installCanvasSkillInto } from './canvas-control'
-import { findInLoginPath } from '../core/pty-manager'
import type { SshProjectManager } from './remote-ssh/ssh-project'
-const execFileP = promisify(execFile)
-const LOGIN_POLL_MS = 2000
-const LOGIN_TIMEOUT_MS = 5 * 60 * 1000
-
// Re-exported for this module's other consumers (claude-usage.ts) so their import path is
// unchanged; the implementation now lives in core (../core/claude-config-dir).
export { claudeConfigDirFor } from '../core/claude-config-dir'
-/**
- * Optional per-call SSH context. When `projectId` is present AND that project has a live
- * ControlMaster, the account is a REMOTE one: its config dir + login capture + removal happen on the
- * host over ssh instead of on the local filesystem. The renderer passes it only for accounts scoped
- * to an SSH project (`ClaudeAccount.host`); local accounts omit it entirely (unchanged behavior).
- */
-interface AccountCtx {
- projectId?: string
-}
-
-const waiters = new Map<string, { cancelled: boolean }>()
-
-async function checkClaudeVersion(): Promise<boolean> {
- // The < 2.1 warning is about the shared macOS Keychain service; on Linux/Windows
- // credentials are files inside each config dir, so no version collides.
- if (process.platform !== 'darwin') return true
- try {
- const claude = await findInLoginPath('claude')
- if (!claude) return false
- const { stdout } = await execFileP(claude, ['--version'], { timeout: 5000 })
- return isSupportedClaudeVersion(stdout.trim())
- } catch {
- return false
- }
-}
-
/**
* @param getSshManager Lazily resolves the SSH project manager (created after this init in index.ts).
* Returns undefined when SSH isn't wired — every remote path then falls back to local behavior.
*/
export function initClaudeAccounts(getSshManager?: () => SshProjectManager | undefined): void {
- // Resolve the live remote manager for a context, or null when the context is local / not connected.
- const remoteFor = (ctx?: AccountCtx): { mgr: SshProjectManager; projectId: string } | null => {
- const projectId = ctx?.projectId
- const mgr = getSshManager?.()
- return projectId && mgr ? { mgr, projectId } : null
- }
-
- ipcMain.handle(IPC.claudeAccountsAdd, async (_e, ctx?: AccountCtx) => {
- const id = randomUUID()
- const remote = remoteFor(ctx)
- if (remote) {
- // REMOTE account: create the config dir + install the status hook on the host. No local dir
- // and no local hook install — the session runs entirely on the remote host.
- const res = await remote.mgr.remoteAccountAdd(remote.projectId, id)
- // Null means the project wasn't connected / mkdir failed: still return the id so the renderer
- // can show the pending row; the login node will surface the connection error itself.
- return { id, configDir: res?.configDir ?? '', versionSupported: res?.versionSupported ?? true }
- }
- const configDir = claudeConfigDirFor(id)
- await fs.mkdir(configDir, { recursive: true })
- // Install the managed hook + canvas skill up front so the very first session in this
- // account already reports status (badges/notifications/subagent viz) and can control
- // the canvas (Claude resolves skills relative to CLAUDE_CONFIG_DIR, not ~/.claude).
- installClaudeHooksInto(configDir)
- installCanvasSkillInto(configDir)
- // Ensure fullscreen TUI in the new account dir (write-if-absent, version-gated). Best-effort,
- // off the response path — the memoized probe + write both fail open.
- void ensureClaudeFullscreenTuiInto(configDir)
- const versionSupported = await checkClaudeVersion()
- return { id, configDir, versionSupported }
- })
-
- ipcMain.handle(IPC.claudeAccountsWaitLogin, async (_e, id: string, ctx?: AccountCtx) => {
- const remote = remoteFor(ctx)
- // Local path: `claudeConfigDirFor` also validates the id shape (rejects traversal).
- const configDir = remote ? null : claudeConfigDirFor(id)
- const w = { cancelled: false }
- waiters.set(id, w)
- const deadline = Date.now() + LOGIN_TIMEOUT_MS
- try {
- while (!w.cancelled && Date.now() < deadline) {
- try {
- const raw = remote
- ? await remote.mgr.remoteAccountReadLogin(remote.projectId, id)
- : await fs.readFile(path.join(configDir as string, '.claude.json'), 'utf-8')
- const captured = raw ? parseLoginCapture(raw) : null
- if (captured) return captured
- } catch {
- // not written yet — keep polling
- }
- await new Promise((r) => setTimeout(r, LOGIN_POLL_MS))
+ registerClaudeAccountsIpc({
+ installSkill: installCanvasSkillInto,
+ remote: () => {
+ const mgr = getSshManager?.()
+ if (!mgr) return undefined
+ return {
+ add: (projectId, id) => mgr.remoteAccountAdd(projectId, id),
+ readLogin: (projectId, id) => mgr.remoteAccountReadLogin(projectId, id),
+ remove: (projectId, id) => mgr.remoteAccountRemove(projectId, id)
}
- return null
- } finally {
- waiters.delete(id)
- }
- })
-
- ipcMain.handle(IPC.claudeAccountsCancelWait, (_e, id: string) => {
- const w = waiters.get(id)
- if (w) w.cancelled = true
- })
-
- ipcMain.handle(IPC.claudeAccountsRemove, async (_e, id: string, ctx?: AccountCtx) => {
- const remote = remoteFor(ctx)
- if (remote) {
- // Best-effort remote cleanup; if the project isn't connected the manager no-ops and the
- // renderer still drops the account from its list (the dir is orphaned, harmless).
- await remote.mgr.remoteAccountRemove(remote.projectId, id)
- return
}
- const configDir = claudeConfigDirFor(id) // id validation prevents traversal
- await fs.rm(configDir, { recursive: true, force: true })
})
}
diff --git a/src/main/index.ts b/src/main/index.ts
index 69cd84334..a84748690 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -243,7 +243,7 @@ import {
isSafeRemoteTranscriptPath,
remoteAccountConfigDirAbs
} from '../core/claude-accounts-core'
-import { installClaudeHooksInto, ensureClaudeFullscreenTuiInto } from '../core/agents/hooks/claude'
+import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'
import { createPairingService } from './pairing-service'
import {
initRemoteHost,
@@ -2328,21 +2328,10 @@ app.whenReady().then(async () => {
installManagedAgentHooks()
// Managed accounts each carry their own settings.json AND skills/ (Claude Code resolves both
// relative to CLAUDE_CONFIG_DIR) — re-install the hook + canvas skill there too (idempotent),
- // so an app update's new versions reach every account dir. Best-effort: one failing account
- // must never block launch (match installManagedAgentHooks' fail-open).
- for (const acct of settingsStore.get().claudeAccounts ?? []) {
- if (acct.host) continue // remote accounts live on another host; nothing to install locally
- try {
- installClaudeHooksInto(claudeConfigDirFor(acct.id))
- installCanvasSkillInto(claudeConfigDirFor(acct.id))
- // Ensure fullscreen TUI in this account dir (write-if-absent, version-gated). Off the
- // critical path: it awaits the memoized CLI probe, then writes fail-open. (The system
- // ~/.claude is handled by installManagedAgentHooks above, which covers Server Edition too.)
- void ensureClaudeFullscreenTuiInto(claudeConfigDirFor(acct.id))
- } catch (e) {
- console.warn(`[agent-hooks] account ${acct.id} hook install failed`, e)
- }
- }
+ // so an app update's new versions reach every account dir. The loop is shared with the Server
+ // Edition's boot (src/core/claude-accounts-service.ts); the canvas skill is the desktop's own
+ // addition, because canvas control is not wired on that shell at all.
+ installHooksIntoLocalAccounts(settingsStore.get().claudeAccounts ?? [], installCanvasSkillInto)
// Fan a normalized agent event to BOTH consumers: the renderer's agentStatus store (canvas badge)
// and the mobile-facing mirror. Named so the deterministic-approval answer handler below can reuse
// it for the optimistic flip.
diff --git a/src/renderer/bridge/ws-bridge.namespaces.test.ts b/src/renderer/bridge/ws-bridge.namespaces.test.ts
index dbc7960c7..91e0012c6 100644
--- a/src/renderer/bridge/ws-bridge.namespaces.test.ts
+++ b/src/renderer/bridge/ws-bridge.namespaces.test.ts
@@ -1,7 +1,14 @@
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'
-import { buildFilesApi, buildRealApi, buildSessionMemoryApi } from './ws-bridge'
+import {
+ buildClaudeAccountsApi,
+ buildFilesApi,
+ buildRealApi,
+ buildSessionMemoryApi
+} from './ws-bridge'
+import { buildStubApi } from './stubs'
+import { E_UNSUPPORTED } from '../../shared/rpc'
import { IPC } from '../../shared/ipc'
function fakeClient() {
@@ -150,3 +157,51 @@ describe('buildRealApi: sessionMemory', () => {
expect(install).toContain('...buildSessionMemoryApi(client)')
})
})
+
+/**
+ * Issue #313: the managed-Claude-account lifecycle moved into src/core, so the server registers
+ * the same four channels the desktop does. Before that every member rejected E_UNSUPPORTED from
+ * the stub — a browser deployment could SELECT a managed account but never create or remove one.
+ */
+describe('buildClaudeAccountsApi', () => {
+ it('all four members request the real channels, ctx included', async () => {
+ const c = fakeClient()
+ const { claudeAccounts } = buildClaudeAccountsApi(c as never)
+ await claudeAccounts.add()
+ await claudeAccounts.add({ projectId: 'p1' })
+ await claudeAccounts.waitLogin('a1')
+ await claudeAccounts.waitLogin('a1', { projectId: 'p1' })
+ await claudeAccounts.cancelWaitLogin('a1')
+ await claudeAccounts.remove('a1', { projectId: 'p1' })
+ expect(c.calls).toEqual([
+ { kind: 'request', method: IPC.claudeAccountsAdd, args: [undefined] },
+ { kind: 'request', method: IPC.claudeAccountsAdd, args: [{ projectId: 'p1' }] },
+ { kind: 'request', method: IPC.claudeAccountsWaitLogin, args: ['a1', undefined] },
+ { kind: 'request', method: IPC.claudeAccountsWaitLogin, args: ['a1', { projectId: 'p1' }] },
+ { kind: 'request', method: IPC.claudeAccountsCancelWait, args: ['a1'] },
+ { kind: 'request', method: IPC.claudeAccountsRemove, args: ['a1', { projectId: 'p1' }] }
+ ])
+ })
+
+ // Same trap as buildSessionMemoryApi's: buildStubApi() already satisfies `claudeAccounts`, so a
+ // dropped spread compiles and the stub silently wins in every browser session.
+ it('is spread into the assembled window.nodeTerminal', () => {
+ const src = readFileSync(join(__dirname, 'ws-bridge.ts'), 'utf8')
+ const install = src.slice(src.indexOf('export async function installWsBridge'))
+ expect(install).toContain('...buildClaudeAccountsApi(client)')
+ })
+
+ // The Codex half is deliberately NOT ported: its switch verbs authorize the owning window by
+ // Electron WebContents id, which has no meaning over a WS connection. It must keep REFUSING with
+ // the coded error rather than silently no-opping — that code is what the Settings section reads
+ // to say "manage them from the desktop app" instead of a generic failure.
+ it('codexAccounts stays an E_UNSUPPORTED stub', async () => {
+ const s = buildStubApi()
+ await expect(s.codexAccounts.add()).rejects.toMatchObject({ code: E_UNSUPPORTED })
+ await expect(s.codexAccounts.waitLogin('a1')).rejects.toMatchObject({ code: E_UNSUPPORTED })
+ await expect(s.codexAccounts.cancelWaitLogin('a1')).rejects.toMatchObject({
+ code: E_UNSUPPORTED
+ })
+ await expect(s.codexAccounts.remove('a1')).rejects.toMatchObject({ code: E_UNSUPPORTED })
+ })
+})
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 21ebcb00d..695c6e14c 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -847,6 +847,39 @@ export function buildTranscriptApi(
}
}
+/**
+ * Managed CLAUDE accounts over the WS bridge (issue #313). REAL, not a stub: the lifecycle moved
+ * into `src/core/claude-accounts-service.ts`, so the server registers the same four channels the
+ * desktop does and the browser can create, log into and remove accounts. Deliberately NOT added to
+ * `relay-api.ts` — a relay tab drives someone else's machine, and minting an account there would
+ * create it on the HOST while this renderer's settings.json records it as one of its own.
+ *
+ * `waitLogin` is a straight passthrough of a poll that runs up to 5 minutes. That is safe because
+ * RpcClient has no request timeout: a pending request rejects only when the socket drops, which is
+ * exactly the outcome the caller wants (the login row stays pending and offers Retry).
+ *
+ * The `codexAccounts` namespace stays STUBBED (E_UNSUPPORTED). Its switch verbs authorize the
+ * owning window by Electron WebContents id, which has no meaning over a WS connection — porting it
+ * needs a connection-identity design, not a builder.
+ */
+export function buildClaudeAccountsApi(client: RpcClient): Pick<NodeTerminalApi, 'claudeAccounts'> {
+ return {
+ claudeAccounts: {
+ add: (ctx) =>
+ client.request(IPC.claudeAccountsAdd, ctx) as Promise<{
+ id: string
+ configDir: string
+ versionSupported: boolean
+ }>,
+ waitLogin: (id, ctx) =>
+ client.request(IPC.claudeAccountsWaitLogin, id, ctx) as Promise<{ email: string } | null>,
+ cancelWaitLogin: (id) =>
+ client.request(IPC.claudeAccountsCancelWait, id) as Promise<void>,
+ remove: (id, ctx) => client.request(IPC.claudeAccountsRemove, id, ctx) as Promise<void>
+ }
+ }
+}
+
/** WS URL for the current page: same host, `/ws`, ws→http / wss→https. */
function wsUrl(): string {
const scheme = location.protocol === 'https:' ? 'wss' : 'ws'
@@ -963,6 +996,7 @@ export async function installWsBridge(): Promise<boolean> {
...buildUsageApi(client),
...buildSessionMemoryApi(client),
...buildGitHubApi(client),
+ ...buildClaudeAccountsApi(client),
codex: buildCodexApi(client),
// `claude` is assembled from two builders: `cliCaps` from the relay-shared one, and the
// transcript reader from the Server-Edition-only one (which also supplies `chat`).
diff --git a/src/renderer/components/settings/sections/AccountsSection.tsx b/src/renderer/components/settings/sections/AccountsSection.tsx
index df8b58615..ecd1425e2 100644
--- a/src/renderer/components/settings/sections/AccountsSection.tsx
+++ b/src/renderer/components/settings/sections/AccountsSection.tsx
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react'
import type { ClaudeAccount } from '@shared/types'
import type { CodexAccount } from '@shared/codex-account'
+import { E_UNSUPPORTED } from '@shared/rpc'
import { sshHostKey } from '@shared/ssh'
import { useSettings } from '../../../state/settings'
import { useSystemAccount } from '../../../state/systemAccount'
@@ -39,6 +40,11 @@ const ROWS = {
}
const ENTRIES = Object.values(ROWS)
+/** The bridge's "this shell registers no such handler" rejection (renderer/bridge/stubs.ts). It is
+ * a fact about the SURFACE, not about this account — worth a different sentence than a failure. */
+const isUnsupported = (e: unknown): boolean =>
+ !!e && typeof e === 'object' && (e as { code?: string }).code === E_UNSUPPORTED
+
/** One machine's card in the accounts UI: a connectivity dot, the machine label, a Local/SSH pill,
* and (for a remote machine) its `user@host` subtitle. Children are the provider account rows. */
function MachinePanel({
@@ -167,6 +173,7 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.
}, [])
const [pendingRemoveCodex, setPendingRemoveCodex] = useState<CodexAccount | null>(null)
const [addingCodex, setAddingCodex] = useState(false)
+ const [codexAddError, setCodexAddError] = useState<string | null>(null)
// The reachable machines: this Mac first, then every saved SSH server unioned with the active
// project's own server (deduped by host key). Accounts partition onto them by `host`.
@@ -226,6 +233,7 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.
const onAddCodexAccount = async (): Promise<void> => {
if (addingCodex) return
setAddingCodex(true)
+ setCodexAddError(null)
try {
const added = await window.nodeTerminal.codexAccounts.add()
const account: CodexAccount = { id: added.id, label: 'New Codex account', pending: true }
@@ -239,6 +247,16 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.
applyResolvedCodexAccounts(accs, [{ id: added.id, email: captured.email }])
)
}
+ } catch (e) {
+ // Without this the browser's E_UNSUPPORTED rejection was an UNHANDLED promise rejection: the
+ // spinner stopped and nothing else happened, which reads as a dead button. Managed Claude
+ // accounts now work in the browser, so a user who just added one has every reason to expect
+ // the button beneath it to work too — say why it does not.
+ setCodexAddError(
+ isUnsupported(e)
+ ? 'Managed Codex accounts are not available in the browser yet — manage them from the desktop app.'
+ : 'Could not set up the Codex account.'
+ )
} finally {
setAddingCodex(false)
}
@@ -383,14 +401,19 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.
let added: { id: string; versionSupported: boolean }
try {
added = await window.nodeTerminal.claudeAccounts.add(projectId ? { projectId } : undefined)
- } catch {
+ } catch (e) {
// The remote path does not reject on a failed setup (it answers with an empty configDir and
// lets the login node report the connection error), so reaching here means the call itself
// never landed. Say so: after a spinner, silence is the one outcome that teaches nothing.
+ // E_UNSUPPORTED is a separate sentence because it is a fact about the surface, not this
+ // account: the Server Edition serves these channels now, but a relay tab still refuses them
+ // and so does a server binary older than that change.
setAddError(
- host
- ? `Could not set up an account on ${host}. Is the project still connected?`
- : 'Could not set up the account.'
+ isUnsupported(e)
+ ? 'Managed Claude accounts are not available on this surface — manage them from the desktop app or the Server Edition directly.'
+ : host
+ ? `Could not set up an account on ${host}. Is the project still connected?`
+ : 'Could not set up the account.'
)
return
} finally {
@@ -654,6 +677,9 @@ export function AccountsSection({ isActive }: { isActive: boolean }): React.JSX.
'Add Codex account'
)}
</Button>
+ {codexAddError ? (
+ <p className="text-[12px] text-[color:var(--danger)]">{codexAddError}</p>
+ ) : null}
</div>
) : (
<p className="text-[12px] leading-relaxed text-muted">
diff --git a/src/server/handlers/index.test.ts b/src/server/handlers/index.test.ts
index f101a9492..f1ef829f9 100644
--- a/src/server/handlers/index.test.ts
+++ b/src/server/handlers/index.test.ts
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import fs from 'fs'
import os from 'os'
import path from 'path'
@@ -11,6 +11,17 @@ import { initPlatform, resetPlatformForTests } from '../../core/platform'
import { DownloadTickets } from '../../core/download-tickets'
import { projectImagesDir } from '../../core/canvas-images'
+// The per-account hook writers are exercised by src/core/claude-accounts-service.test.ts. Observe
+// them here instead of running them: the real installer writes into the USER's `~/.nodeterm`, and
+// a unit test has no business touching the machine it runs on.
+const hookInstalls: string[] = []
+vi.mock('../../core/agents/hooks/claude', () => ({
+ installClaudeHooksInto: (dir: string) => {
+ hookInstalls.push(dir)
+ },
+ ensureClaudeFullscreenTuiInto: async () => {}
+}))
+
let repo: string, platform: ServerPlatform, ui: number
beforeEach(() => {
repo = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-git-'))
@@ -142,3 +153,45 @@ describe('registerCoreHandlers (download tickets)', () => {
expect(await call(IPC.filesDownloadTicket, path.join(repo, 'a.txt'))).toBeNull()
})
})
+
+/**
+ * Issue #313 — a browser-only deployment must be able to MANAGE managed Claude accounts, not just
+ * select them. Registration lives in `registerCoreHandlers` because the lifecycle is core now; the
+ * Server Edition wires neither an `installSkill` (canvas control is not wired here) nor a `remote`
+ * (no SSH-project manager), so an account with a projectId still lands locally.
+ */
+describe('registerCoreHandlers (managed Claude accounts, #313)', () => {
+ beforeEach(() => {
+ hookInstalls.length = 0
+ })
+
+ it('add() creates the config dir under this host userData and remove() deletes it', async () => {
+ const added = (await call(IPC.claudeAccountsAdd)) as { id: string; configDir: string }
+ expect(added.configDir).toBe(path.join(repo, 'claude-accounts', added.id))
+ expect(fs.existsSync(added.configDir)).toBe(true)
+ // The hook the account needs to report agent status at all is installed with the dir.
+ expect(hookInstalls).toEqual([added.configDir])
+ await call(IPC.claudeAccountsRemove, added.id)
+ expect(fs.existsSync(added.configDir)).toBe(false)
+ })
+
+ it('a ctx projectId still takes the local path — this shell has no SSH manager', async () => {
+ const added = (await call(IPC.claudeAccountsAdd, { projectId: 'p1' })) as { configDir: string }
+ expect(added.configDir).toBe(path.join(repo, 'claude-accounts', path.basename(added.configDir)))
+ expect(fs.existsSync(added.configDir)).toBe(true)
+ })
+
+ // The long-poll cannot be driven to completion in a unit test, so prove REGISTRATION instead: a
+ // bad id makes the handler throw (E_HANDLER), where an unregistered channel answers E_NO_HANDLER.
+ it('waitLogin and cancelWait are registered (not E_NO_HANDLER)', async () => {
+ const res = await platform.dispatch(ui, {
+ t: 'req',
+ id: 1,
+ method: IPC.claudeAccountsWaitLogin,
+ args: ['../escape']
+ })
+ expect(res.ok).toBe(false)
+ expect((res as { error: { code: string } }).error.code).toBe('E_HANDLER')
+ await expect(call(IPC.claudeAccountsCancelWait, 'nobody')).resolves.toBeNull()
+ })
+})
diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.ts
index 9e2658466..23e33956b 100644
--- a/src/server/handlers/index.ts
+++ b/src/server/handlers/index.ts
@@ -10,6 +10,7 @@ import { claudeCliCaps, registerClaudeCliIpc } from '../../core/claude-cli'
import { registerCodexIdentityIpc } from '../../core/codex-identity-caps'
import { UNKNOWN_CODEX_IDENTITY_CAPS } from '@shared/types'
import { startUsageService } from '../../core/usage/usage-service'
+import { registerClaudeAccountsIpc } from '../../core/claude-accounts-service'
import { codexUsageAccounts } from '../../core/codex-accounts-core'
import { codexHomeFor } from '../../core/codex-config-dir'
import {
@@ -90,6 +91,15 @@ export function registerCoreHandlers(
// degrade: it never launches an app-server, it only lets the record layer sign.
registerCodexIdentityIpc(() => UNKNOWN_CODEX_IDENTITY_CAPS)
+ // Managed CLAUDE accounts (issue #313). The lifecycle is core, so a browser-only deployment can
+ // create, log into and remove them exactly as the desktop does — env injection, the transcript
+ // readers, usage and the account pickers were already core and had nothing to bind to here.
+ // No `installSkill`: canvas control is not wired on this edition (its hook server answers
+ // `control unavailable` by name), so a per-account skill file would point at nothing.
+ // No `remote`: the Server Edition has no SSH-project manager, so an `AccountCtx` carrying a
+ // projectId takes the LOCAL path — the same degrade desktop takes before its manager exists.
+ registerClaudeAccountsIpc()
+
// Claude subscription usage. Previously desktop-only — the browser bridge answered `null`, so
// the pill never rendered in the Server Edition. The poll runs UNGATED here (the default), not
// browser-gated: the phone reads this host's agent-status mirror over plain SSH with no browser
diff --git a/src/server/index.ts b/src/server/index.ts
index ea4083651..b83b224d7 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -57,6 +57,7 @@ import {
syntheticAnsweredEvent
} from '../core/agents/pending-approvals'
import { installManagedAgentHooks } from '../core/agents/hooks'
+import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'
import {
initAgentStatusMirror,
flush as flushAgentStatusMirror,
@@ -516,6 +517,11 @@ export async function startServer(
} catch (e) {
console.warn('[nodeterm-server] managed hook install failed', e)
}
+ // Managed Claude accounts each carry their OWN settings.json (Claude Code resolves it relative
+ // to CLAUDE_CONFIG_DIR), so the hook has to be re-installed there as well or a managed account
+ // reports no agent status at all. Same loop the desktop runs, minus the canvas skill: canvas
+ // control is not wired on this edition. Per-account fail-open lives inside the helper.
+ installHooksIntoLocalAccounts(settingsStore.get().claudeAccounts ?? [])
}
await hookServer.start()
// Canvas control does not exist on this edition, and saying so BY NAME is the whole point: the