The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(cli): restart daemon after sign-in (#1576)
Danny Wardcb48119e5362
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex fe9a1e457..775366ed2 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -1358,18 +1358,16 @@ async function logout(): Promise<void> {* route to the same end (a mutable id, a live re-bind) touches the socket, the E2EE identity and the* local binding at once, and the daemon already survives a restart cleanly for every update.*- * No-op when nothing is running (`harness start` boots on the new session by itself) or when the daemon- * already wears the right id (a `harness login` on a computer that was signed in all along) — unless the- * sign-in itself stopped it (`stoppedDaemon`: `login --force` stops a signed-in daemon before switching- * accounts). That one is started again on the new session: left down, the computer was off the account- * until someone ran `harness start`, and the web showed it offline.+ * If it was running before sign-in, or `login --force` stopped it before switching accounts, bring it back+ * when sign-in leaves it down. A clean exit is intentional to launchd and systemd, so their restart policy+ * does not bring a daemon back after its identity changes.*/-async function restartDaemonForIdentity(stoppedDaemon = false): Promise<void> {+async function restartDaemonForIdentity(restartIfDown = false): Promise<void> {// OUR daemon, by its pid file and private socket. A login in another HOME must never restart a// different OS user's daemon just because it happens to hold the default TCP port.const pid = readPid()if (!pid || !isAlive(pid)) {- if (!stoppedDaemon) return+ if (!restartIfDown) returnconsole.log(' starting the daemon again on this account…')await launch(false) // prints the status block and exitsreturn@@ -2735,17 +2733,21 @@ switch (cmd) {// git's credential helper in a Swarm agent's session (docs/swarm-github-app.md); git runs it, people do not.gitCredentialCommand(rest).then(code => { process.exitCode = code }).catch(onError)break- case 'login':+ case 'login': {// The result line goes out FIRST (loginCommand prints it), then the daemon is swapped onto the// account: the desktop app reads that line and does not wait for a restart it observes anyway.+ // Capture before sign-in: the daemon can exit cleanly when its identity changes, and the installed+ // service treats a clean exit as an intentional stop.+ const daemonWasRunning = isDaemonRunning()loginCommand(foreground, flags.includes('--force'), flags.includes('--json'), {entryPoint: entryPointFlag(),ticket: flags.find((f) => f.startsWith('--ticket='))?.slice('--ticket='.length) || undefined,method: signInMethodFlag(flags) ?? (flags.includes('--json') || !process.stdin.isTTY ? undefined : 'ask'),})- .then((outcome) => outcome.signedIn ? restartDaemonForIdentity(outcome.stoppedDaemon) : undefined)+ .then((outcome) => outcome.signedIn ? restartDaemonForIdentity(outcome.stoppedDaemon || daemonWasRunning) : undefined).catch(onError)break+ }case 'auth':if (args[0] !== 'status') { console.error('Unknown command: auth ' + (args[0] ?? '')); usage(1) }else authStatusCommand(flags.includes('--json')).catch(onError)diff --git a/cli/src/loginForceRace.spec.ts b/cli/src/loginForceRace.spec.tsindex 12b1f1dea..07a66716a 100644--- a/cli/src/loginForceRace.spec.ts+++ b/cli/src/loginForceRace.spec.ts@@ -78,7 +78,7 @@ function seedSession(root: string, account: { accessToken: string; machineId: st/** A daemon as `login --force` and `start` see one: a live process named by the pid file. It idles* until it is stopped, which is all a stand-in has to do — the stop needs something to kill. */function idleDaemon(root: string): { pid: number; exited: Promise<void> } {- const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore' })+ const child = spawn(process.execPath, ['-e', "process.on('SIGTERM', () => process.exit(0)); setInterval(() => {}, 1000)"], { stdio: 'ignore' })children.push(child)mkdirSync(join(root, 'data'), { recursive: true })writeFileSync(join(root, 'data', 'adapter.pid'), `${child.pid}\n`)@@ -87,27 +87,34 @@ function idleDaemon(root: string): { pid: number; exited: Promise<void> } {interface CliRun {stdout: () => string+ respond: (line: string) => void+ closeInput: () => void/** Exit status, once every stdio pipe has drained. */exit: Promise<number | null>/** Resolves once stdout satisfies `test`; rejects if the process ends without it ever doing so. */until: (test: (stdout: string) => boolean) => Promise<void>}-function runCli(root: string, args: string[], backendBase: string): CliRun {+function runCli(root: string, args: string[], backendBase: string, acceptsInput = false): CliRun {const child = spawn(process.execPath, [TSX, CLI_SOURCE, ...args], {- cwd: CLI_ROOT, env: envFor(root, backendBase), stdio: ['ignore', 'pipe', 'pipe'],+ cwd: CLI_ROOT, env: envFor(root, backendBase), stdio: [acceptsInput ? 'pipe' : 'ignore', 'pipe', 'pipe'],})children.push(child)let stdout = ''const watchers = new Set<() => void>()- child.stdout.on('data', (chunk: Buffer) => {+ child.stdout?.on('data', (chunk: Buffer) => {stdout += chunk.toString()for (const watch of [...watchers]) watch()})- child.stderr.on('data', () => { /* drained: a full pipe would stall the child */ })+ child.stderr?.on('data', () => { /* drained: a full pipe would stall the child */ })const exit = new Promise<number | null>((resolve) => child.once('close', (code) => resolve(code)))return {stdout: () => stdout,+ respond: (line) => {+ if (!child.stdin) throw new Error('this CLI run does not accept input')+ child.stdin.write(line)+ },+ closeInput: () => child.stdin?.end(),exit,until: (test) => new Promise((resolve, reject) => {const watch = (): void => {@@ -219,3 +226,48 @@ describe('login --force beside a start that lands mid-sign-in', () => {.toMatchObject({ accessToken: 'tok_new', machineId: 'm_new', signInEpoch: expect.stringMatching(/^[0-9a-f]{32}@\d+$/), signInAcct: 'acct_new' })}, 30_000)})++describe('login after a running daemon exits cleanly during sign-in', () => {+ it('harness login --code starts it again after the new session is saved', async () => {+ const root = tempRoot()+ const daemon = idleDaemon(root)+ let approve = false+ const backend = await fakeBackend((req, body) => {+ switch (req.url) {+ case '/api/auth/qr/start':+ return { data: { code: 'hnq_code', pollToken: 'poll_1', expiresIn: 300, spokenCode: '123456' } }+ case '/api/auth/qr/poll':+ return { data: approve ? { status: 'approved', email: '[email protected]' } : { status: 'pending' } }+ case '/api/auth/qr/claim':+ return { data: { token: 'tok_new', refreshToken: 'refresh_new', expiresIn: 3600, autonomousEnv: 'prod', email: '[email protected]' } }+ case '/api/auth/me':+ return { data: { user: { id: 'acct_new' } } }+ case '/api/machines/resolve-computer':+ return { data: { machine: { machineId: 'm_new' } } }+ default:+ return { status: 404, error: 'not stubbed' }+ }+ })++ const login = runCli(root, ['login', '--code', '--json'], backend.base, true)+ await login.until((out) => out.includes('"type":"code"'))++ // The daemon exits cleanly after the account changes; a successful exit keeps the unit stopped.+ process.kill(daemon.pid, 'SIGTERM')+ await daemon.exited+ approve = true+ await login.until((out) => out.includes('"type":"confirm"'))+ login.respond('yes\n')+ await login.until((out) => out.includes('"type":"result","status":"success"'))+ login.closeInput()+ await login.exit++ expect(login.stdout()).toContain('starting the daemon again on this account')+ const results = login.stdout().trim().split('\n').filter((line) => line.startsWith('{'))+ .map((line) => JSON.parse(line) as { type: string; status?: string })+ .filter((line) => line.type === 'result')+ expect(results).toEqual([expect.objectContaining({ type: 'result', status: 'success' })])+ expect(JSON.parse(readFileSync(join(root, 'auth', 'session.json'), 'utf8')))+ .toMatchObject({ accessToken: 'tok_new', machineId: 'm_new', signInAcct: 'acct_new' })+ }, 30_000)+})