From 0e64d304fbf0956f0ed3fd70285def0f2f2c532b Mon Sep 17 00:00:00 2001 From: parsilver Date: Sat, 14 Nov 2026 19:26:27 +0700 Subject: [PATCH 1/5] fix(service): retry launchd bootstrap and keep the log private Reinstalling over a running agent failed: bootout returns before the old agent has stopped, and bootstrap refuses until it has. Bootstrap is now tried up to ten times, a second apart, and reports the last error. An existing service.log is set to 0600 on install, not only a new one. The systemd unit no longer orders itself after network-online.target, which a user unit cannot reach, and the release checkout drops the job token. Tested with the service tests: retry after bootout exit 36, give-up after ten tries, a 0644 log made 0600, the unit snapshot, and a check that every release checkout sets persist-credentials: false. --- .github/workflows/release.yml | 2 + src/cli/service.ts | 32 +++++++++++----- test/service.test.ts | 69 ++++++++++++++++++++++++++++++++--- 3 files changed, 87 insertions(+), 16 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6a958ff..651fc5e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,6 +17,8 @@ jobs: timeout-minutes: 15 steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + with: + persist-credentials: false - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: bun-version: 1.4.2 diff --git a/src/cli/service.ts b/src/cli/service.ts index 6008d5d..e730b6a 100644 --- a/src/cli/service.ts +++ b/src/cli/service.ts @@ -1,6 +1,6 @@ import { chmodSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; -import type { Run } from "../client/run.ts"; +import type { Ran, Run } from "../client/run.ts"; /** What a background service runs and where its files go; built once from the CLI's context. */ export interface ServiceSpec { @@ -53,14 +53,19 @@ export function thisProgram(execPath: string, argv: string[]): string[] { class ServiceError extends Error {} +function failure(done: Ran, what: string): ServiceError { + const detail = done.stderr.trim() || done.stdout.trim() || `exit ${done.status ?? "timeout"}`; + return new ServiceError(`${what} failed: ${detail.slice(0, 500)}`); +} + function must(run: Run, command: string, args: string[], what: string): void { const done = run(command, args); - if (done.status !== 0) { - const detail = done.stderr.trim() || done.stdout.trim() || `exit ${done.status ?? "timeout"}`; - throw new ServiceError(`${what} failed: ${detail.slice(0, 500)}`); - } + if (done.status !== 0) throw failure(done, what); } +/** How often `bootstrap` is tried, a second apart, while an old agent is still booting out. */ +const BOOTSTRAP_TRIES = 10; + function writePrivate(path: string, content: string | Buffer): void { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, content, { mode: 0o600 }); @@ -130,12 +135,21 @@ export const launchd: ServiceManager = { kind: "launchd", install(spec, run) { const target = `gui/${spec.uid}`; - // launchd would create the log readable by everyone; create it first, readable by the user. + // launchd would create the log readable by everyone; create it first, readable by the user, + // and take back a log an older install left readable by everyone. const log = join(spec.home, "service.log"); - if (!existsSync(log)) writePrivate(log, ""); + if (existsSync(log)) chmodSync(log, 0o600); + else writePrivate(log, ""); writePrivate(launchdPlistPath(spec), launchdPlist(spec)); run("launchctl", ["bootout", `${target}/${launchdLabel(spec)}`]); - must(run, "launchctl", ["bootstrap", target, launchdPlistPath(spec)], "launchctl bootstrap"); + // bootout returns before a running agent has stopped, and bootstrap fails until it has. + for (let tries = 1; ; tries += 1) { + const done = run("launchctl", ["bootstrap", target, launchdPlistPath(spec)]); + if (done.status === 0) return; + if (tries === BOOTSTRAP_TRIES) throw failure(done, "launchctl bootstrap"); + // Through the same runner as launchctl, so a test's runner does not wait. + run("sleep", ["1"]); + } }, uninstall(spec, run) { run("launchctl", ["bootout", `gui/${spec.uid}/${launchdLabel(spec)}`]); @@ -168,8 +182,6 @@ export function systemdUnit(spec: ServiceSpec): string { .join("\n"); return `[Unit] Description=Tether: runs connected apps' tasks with Claude Code -After=network-online.target -Wants=network-online.target [Service] Type=simple diff --git a/test/service.test.ts b/test/service.test.ts index 379ed4d..ca7c90c 100644 --- a/test/service.test.ts +++ b/test/service.test.ts @@ -1,4 +1,4 @@ -import { existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -29,8 +29,6 @@ describe("the systemd user unit", () => { expect(systemdUnit(SPEC)).toMatchInlineSnapshot(` "[Unit] Description=Tether: runs connected apps' tasks with Claude Code - After=network-online.target - Wants=network-online.target [Service] Type=simple @@ -163,7 +161,8 @@ class ServiceRun { readonly calls: string[] = []; out = ""; err = ""; - answers: Record = {}; + /** Answers by command prefix; a list is answered in turn, its last answer repeating. */ + answers: Record = {}; constructor(readonly platform: NodeJS.Platform) {} @@ -183,8 +182,9 @@ class ServiceRun { readonly run: Run = (command, args) => { const line = [command, ...args].join(" "); this.calls.push(line); - const answer = Object.entries(this.answers).find(([prefix]) => line.startsWith(prefix)); - return answer?.[1] ?? { status: 0, stdout: "", stderr: "" }; + const answer = Object.entries(this.answers).find(([prefix]) => line.startsWith(prefix))?.[1]; + if (!Array.isArray(answer)) return answer ?? { status: 0, stdout: "", stderr: "" }; + return (answer.length > 1 ? answer.shift() : answer[0]) as Ran; }; exec(action: string, env: Record = {}): Promise { @@ -298,6 +298,63 @@ describe("tether service on macOS", () => { }); }); +describe("tether service on macOS, over an agent already loaded", () => { + const busy: Ran = { status: 5, stdout: "", stderr: "Bootstrap failed: 5: Input/output error" }; + const ok: Ran = { status: 0, stdout: "", stderr: "" }; + + it("makes an existing log readable only by the user", async () => { + const s = new ServiceRun("darwin").connected(); + writeFileSync(join(s.home, "service.log"), "earlier output\n", { mode: 0o644 }); + chmodSync(join(s.home, "service.log"), 0o644); + expect(await s.exec("install")).toBe(0); + expect(statSync(join(s.home, "service.log")).mode & 0o777).toBe(0o600); + expect(readFileSync(join(s.home, "service.log"), "utf8")).toBe("earlier output\n"); + }); + + it("waits and bootstraps again while the old agent is still being booted out", async () => { + const s = new ServiceRun("darwin").connected(); + s.answers["launchctl bootout"] = { + status: 36, + stdout: "", + stderr: "Operation now in progress", + }; + s.answers["launchctl bootstrap"] = [busy, busy, ok]; + expect(await s.exec("install")).toBe(0); + expect(s.calls.map((call) => call.split(" ").slice(0, 2).join(" "))).toEqual([ + "launchctl bootout", + "launchctl bootstrap", + "sleep 1", + "launchctl bootstrap", + "sleep 1", + "launchctl bootstrap", + ]); + }); + + it("gives up after ten tries and says what launchctl printed", async () => { + const s = new ServiceRun("darwin").connected(); + s.answers["launchctl bootstrap"] = busy; + expect(await s.exec("install")).toBe(1); + expect(s.calls.filter((call) => call.startsWith("launchctl bootstrap"))).toHaveLength(10); + expect(s.err).toMatch(/launchctl bootstrap failed: Bootstrap failed: 5: Input\/output error/); + }); +}); + +describe("the release workflow", () => { + it("does not leave the job's token in the checkout", () => { + const workflow = readFileSync( + new URL("../.github/workflows/release.yml", import.meta.url), + "utf8", + ); + const checkouts = workflow + .split("- uses: ") + .filter((step) => step.startsWith("actions/checkout")); + expect(checkouts.length).toBeGreaterThan(0); + for (const step of checkouts) { + expect(step.split("\n - ")[0]).toMatch(/with:\s*\n\s*persist-credentials: false/); + } + }); +}); + describe("tether service on Windows", () => { it("creates the task from XML, runs it, and deletes it again", async () => { const s = new ServiceRun("win32").connected(); From 25eb724a12bddf43adec3cb8a2d5b982e4c9267f Mon Sep 17 00:00:00 2001 From: parsilver Date: Sat, 14 Nov 2026 19:26:27 +0700 Subject: [PATCH 2/5] fix(client): report keychain failures and keep the task log bounded doctor now prints a FAIL line with the store's reason when the keychain holding a credential cannot be read, instead of exiting with a bare error. Keychain.set returns why it refused a secret, and connect and start warn with that reason when the credential stays in credentials.json. security -i reports only its exit status, since its stdin carries the secret. The task log keeps at most 200 characters of an app's title. A task log that cannot be written no longer skips releasing the task's slot and budget reservation: the outcome is settled first, the reservation released, and the log write fails on its own line, once. tether start cuts service.log to its last 1 MB once it passes 5 MB, at start and every ten minutes; not on Windows, where cmd's >> keeps its offset. Tested with new keychain, store and CLI tests, each seen failing first. --- src/cli/doctor.ts | 9 +++- src/cli/main.ts | 36 ++++++++++++++-- src/client/keychain.ts | 44 +++++++++++++------ src/client/store.ts | 72 ++++++++++++++++++++++++++----- src/client/worker.ts | 28 +++++++----- test/cli.test.ts | 97 ++++++++++++++++++++++++++++++++++++++++-- test/keychain.test.ts | 74 +++++++++++++++++++++++++------- test/store.test.ts | 39 +++++++++++++++-- 8 files changed, 339 insertions(+), 60 deletions(-) diff --git a/src/cli/doctor.ts b/src/cli/doctor.ts index 8269084..55b9f33 100644 --- a/src/cli/doctor.ts +++ b/src/cli/doctor.ts @@ -33,7 +33,14 @@ export async function doctor(deps: DoctorDeps): Promise { deps.out.line(`${level.padEnd(6)}${text}`); }; await checkAgent(deps, say); - const apps = deps.store.apps(); + let apps: AppRecord[]; + try { + apps = deps.store.apps(); + } catch (error) { + // A locked or unreachable keychain, or an unreadable credentials.json: the store says which. + say("FAIL", (error as Error).message); + return 1; + } if (apps.length === 0) say("warn", "No apps connected. Run: tether connect "); for (const app of apps) await checkApp(deps, app, say); return failed ? 1 : 0; diff --git a/src/cli/main.ts b/src/cli/main.ts index 8252d75..72b7325 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -191,7 +191,7 @@ async function connect(ctx: Context, value: string): Promise { ctx.out.line("Waiting for approval..."); const approved = await pollPairing(ctx, client, started); ctx.secrets.add(approved.credential); - const where = ctx.store.saveApp({ + const { where, warning } = ctx.store.saveApp({ origin, name: client.app.name, device: approved.device, @@ -203,6 +203,7 @@ async function connect(ctx: Context, value: string): Promise { `Connected to ${client.app.name} as "${approved.account.name}" (device "${approved.device.name}").`, ); ctx.out.line(`The device credential is in ${where}.`); + if (warning) ctx.err.line(warning); ctx.out.line(`If that is not your account, run: tether disconnect ${origin}`); return 0; } @@ -253,8 +254,10 @@ async function pollOnce( async function start(ctx: Context, args: string[]): Promise { const concurrency = parseCount(args, "concurrency", 1, 16); - ctx.store.moveToKeychain(); + const refused = ctx.store.moveToKeychain(); const records = ctx.store.apps(); + for (const record of records) ctx.secrets.add(record.credential); + for (const warning of refused) ctx.err.line(warning); if (records.length === 0) throw new Error("No apps connected. Run: tether connect "); const running = ctx.store.runState(); if (running && isAlive(running.pid)) { @@ -279,7 +282,34 @@ async function start(ctx: Context, args: string[]): Promise { agentVersion, signal, }); - return worker.run(records); + const trimming = trimServiceLog(ctx); + try { + return await worker.run(records); + } finally { + clearInterval(trimming); + } +} + +/** How often a running `tether start` checks the size of the service log. */ +const SERVICE_LOG_CHECK_MS = 10 * 60_000; + +/** + * Keeps service.log, which the background service writes, under its size limit: now and every + * ten minutes. Not on Windows, where cmd's `>>` keeps writing at its old offset after a cut. + */ +function trimServiceLog(ctx: Context): NodeJS.Timeout | undefined { + if ((ctx.io.platform ?? process.platform) === "win32") return undefined; + const trim = () => { + try { + ctx.store.trimServiceLog(); + } catch (error) { + ctx.err.line(`Could not trim the service log: ${(error as Error).message}`); + } + }; + trim(); + const timer = setInterval(trim, SERVICE_LOG_CHECK_MS); + timer.unref(); + return timer; } /** The command's only option, `-- `, a whole number from 1 to `max`; no positionals. */ diff --git a/src/client/keychain.ts b/src/client/keychain.ts index be752e7..6f7cf8d 100644 --- a/src/client/keychain.ts +++ b/src/client/keychain.ts @@ -8,8 +8,11 @@ export interface Keychain { readonly name: string; /** The secret, or undefined when the keychain does not hold one; throws KeychainUnavailable. */ get(origin: string): string | undefined; - /** False when the keychain refused the secret: the caller keeps it somewhere else. */ - set(origin: string, secret: string): boolean; + /** + * Stores the secret; returns why the keychain refused it, or undefined once it holds it. A + * refused secret is the caller's to keep somewhere else. The reason never holds the secret. + */ + set(origin: string, secret: string): string | undefined; delete(origin: string): void; } @@ -20,6 +23,18 @@ function quoted(value: string): string | undefined { const MAC_NOT_FOUND = 44; +/** Why a write that the tool accepted still failed: it does not give the same secret back. */ +function readBack(keychain: Keychain, origin: string, secret: string): string | undefined { + try { + return keychain.get(origin) === secret + ? undefined + : `${keychain.name} did not give the credential back`; + } catch (error) { + if (error instanceof KeychainUnavailable) return error.message; + throw error; + } +} + /** The macOS login keychain through `/usr/bin/security`; `service` names this Tether home's items. */ export function macKeychain(service: string, exec: Run = run): Keychain { const keychain: Keychain = { @@ -35,15 +50,15 @@ export function macKeychain(service: string, exec: Run = run): Keychain { set: (origin, secret) => { const account = quoted(origin); const password = quoted(secret); - if (!account || !password) return false; + if (!account || !password) { + return "the origin or credential holds a character `security -i` cannot take"; + } // `security -i` reads its commands from stdin, which keeps the secret out of argv. const line = `add-generic-password -U -s ${service} -a ${account} -l ${quoted(`Tether ${origin}`)} -w ${password}\n`; - if (exec("security", ["-i"], line).status !== 0) return false; - try { - return keychain.get(origin) === secret; - } catch { - return false; - } + const done = exec("security", ["-i"], line); + // Only the status: security may echo the command line, and with it the secret. + if (done.status !== 0) return `security exited ${done.status ?? "timeout"}`; + return readBack(keychain, origin, secret); }, delete: (origin) => { exec("security", ["delete-generic-password", "-s", service, "-a", origin]); @@ -68,12 +83,13 @@ export function secretToolKeychain(service: string, exec: Run = run): Keychain { }, set: (origin, secret) => { const args = ["store", `--label=Tether ${origin}`, ...attributes(origin)]; - if (exec("secret-tool", args, secret).status !== 0) return false; - try { - return keychain.get(origin) === secret; - } catch { - return false; + const done = exec("secret-tool", args, secret); + if (done.status !== 0) { + // The secret went only to stdin, which secret-tool does not echo; its stderr says why. + const why = done.stderr.trim().split("\n")[0]?.slice(0, 200); + return `secret-tool exited ${done.status ?? "timeout"}${why ? `: ${why}` : ""}`; } + return readBack(keychain, origin, secret); }, delete: (origin) => { exec("secret-tool", ["clear", ...attributes(origin)]); diff --git a/src/client/store.ts b/src/client/store.ts index 4f4e70f..c003da8 100644 --- a/src/client/store.ts +++ b/src/client/store.ts @@ -56,6 +56,11 @@ export interface TaskLogEntry { const TASK_LOG_KEEP = 1000; const TASK_LOG_TRIM_BYTES = 1_000_000; +/** The longest title, in characters, the task log keeps: the app sets it, so it is not trusted. */ +const TASK_LOG_TITLE_MAX = 200; +/** Past this size the service log is cut to about its last SERVICE_LOG_KEEP_BYTES. */ +const SERVICE_LOG_MAX_BYTES = 5_000_000; +const SERVICE_LOG_KEEP_BYTES = 1_000_000; /** Whether the file's last byte is not a newline; false for a missing or empty file. */ function endsTorn(file: string): boolean { @@ -168,22 +173,41 @@ export class Store { return { ...record, credential }; } - /** Saves the app; returns where its credential went (the keychain's name or the file's path). */ - saveApp(record: AppRecord): string { + /** + * Saves the app. `where` names the place its credential went: the keychain or the file. A + * `warning` says the keychain refused it and why; with no keychain at all the file is the place. + */ + saveApp(record: AppRecord): { where: string; warning?: string } { const others = this.stored().filter((app) => app.origin !== record.origin); const { credential, ...rest } = record; - if (this.#keychain?.set(record.origin, credential)) { + const refused = this.#keychain?.set(record.origin, credential); + if (this.#keychain && refused === undefined) { this.write("credentials.json", { apps: [...others, { ...rest, credential_in: "keychain" }] }); - return this.#keychain.name; + return { where: this.#keychain.name }; } this.write("credentials.json", { apps: [...others, record] }); - return this.path("credentials.json"); + const where = this.path("credentials.json"); + if (!this.#keychain) return { where }; + const name = this.#keychain.name.replace(/^./, (first) => first.toUpperCase()); + return { + where, + warning: `${name} refused the credential for ${record.origin} (${refused}), so it is in ${where}, readable only by you.`, + }; } - /** Moves credentials an older Tether, or a refused keychain, left in the file into the keychain. */ - moveToKeychain(): void { - if (!this.#keychain) return; - for (const app of this.stored()) if ("credential" in app) this.saveApp(app); + /** + * Moves credentials an older Tether, or a refused keychain, left in the file into the keychain; + * returns a warning for each one the keychain refuses again. + */ + moveToKeychain(): string[] { + if (!this.#keychain) return []; + const warnings: string[] = []; + for (const app of this.stored()) { + if (!("credential" in app)) continue; + const { warning } = this.saveApp(app); + if (warning) warnings.push(warning); + } + return warnings; } removeApp(origin: string): void { @@ -222,7 +246,8 @@ export class Store { const file = this.path("tasks.jsonl"); // A crash mid-append leaves a line without its newline; start on a fresh line after it. const torn = endsTorn(file) ? "\n" : ""; - appendFileSync(file, `${torn}${JSON.stringify(entry)}\n`, { mode: 0o600 }); + const title = Array.from(entry.title).slice(0, TASK_LOG_TITLE_MAX).join(""); + appendFileSync(file, `${torn}${JSON.stringify({ ...entry, title })}\n`, { mode: 0o600 }); if (statSync(file).size > TASK_LOG_TRIM_BYTES) { const kept = this.taskLog(TASK_LOG_KEEP).map((entry) => JSON.stringify(entry)); const temp = this.path(`.tasks.jsonl.${process.pid}.tmp`); @@ -231,6 +256,33 @@ export class Store { } } + /** + * Cuts service.log to its last lines once it passes about 5 MB. The file is rewritten in place, + * not renamed: launchd and the Windows `>>` redirect append, so the running service keeps + * writing at the new end of the same file. + */ + trimServiceLog(): void { + const file = this.path("service.log"); + let size: number; + try { + size = statSync(file).size; + } catch { + return; + } + if (size <= SERVICE_LOG_MAX_BYTES) return; + const tail = Buffer.alloc(SERVICE_LOG_KEEP_BYTES); + const fd = openSync(file, "r"); + try { + readSync(fd, tail, 0, tail.length, size - tail.length); + } finally { + closeSync(fd); + } + // Start on a whole line: the first one in the tail is most likely cut. + const kept = tail.subarray(tail.indexOf(0x0a) + 1); + writeFileSync(file, kept, { mode: 0o600 }); + chmodSync(file, 0o600); + } + /** The last `limit` finished tasks, oldest first; a line that does not parse is skipped. */ taskLog(limit: number): TaskLogEntry[] { let text: string; diff --git a/src/client/worker.ts b/src/client/worker.ts index 36e24a1..339b029 100644 --- a/src/client/worker.ts +++ b/src/client/worker.ts @@ -298,20 +298,26 @@ export class Worker { ended, }); const settled = done - .then((result) => { - log(result.costUsd, result.ended); - return result.costUsd === undefined ? reservation : result.costUsd; - }) - .catch((error: unknown) => { - this.#opts.log.line(`${record.name} ${claim.task.id} ${(error as Error).message}`); - log(undefined, "error"); - return reservation; - }) - .then((spent) => { + .then( + (result) => result, + (error: unknown) => { + this.#opts.log.line(`${record.name} ${claim.task.id} ${(error as Error).message}`); + return { costUsd: undefined, ended: "error" }; + }, + ) + .then(({ costUsd, ended }) => { this.#reserved.set(record.origin, (this.#reserved.get(record.origin) ?? 0) - reservation); - this.#opts.store.addUsage(localDate(new Date()), record.origin, { tasks: 0, usd: spent }); this.#running.delete(key); this.#slots.give(); + try { + log(costUsd, ended); + } catch (error) { + this.#opts.log.line( + `${record.name} ${claim.task.id} could not be written to the task log: ${(error as Error).message}`, + ); + } + const spent = costUsd === undefined ? reservation : costUsd; + this.#opts.store.addUsage(localDate(new Date()), record.origin, { tasks: 0, usd: spent }); this.publish(); }); this.#running.set(key, { diff --git a/test/cli.test.ts b/test/cli.test.ts index bd2847b..d287948 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -2,6 +2,7 @@ import { spawn } from "node:child_process"; import { chmodSync, existsSync, + mkdirSync, mkdtempSync, readFileSync, statSync, @@ -13,8 +14,8 @@ import { dirname, join } from "node:path"; import { setTimeout as sleep } from "node:timers/promises"; import { afterAll, describe, expect, it } from "vitest"; import { main } from "../src/cli/main.ts"; -import type { Keychain } from "../src/client/keychain.ts"; -import { type AppRecord, Store } from "../src/client/store.ts"; +import { type Keychain, KeychainUnavailable } from "../src/client/keychain.ts"; +import { type AppRecord, localDate, Store } from "../src/client/store.ts"; import { type FakeApp, type FakeAppOptions, startFakeApp } from "./fake-app/server.ts"; const FAKE_CLAUDE = new URL("./fake-claude/claude.mjs", import.meta.url).pathname; @@ -177,6 +178,28 @@ afterAll(async () => { await Promise.all(cleanups.map((cleanup) => cleanup())); }); +/** A keychain that refuses every write, as a locked keyring does, and holds nothing. */ +function refusingKeychain(): Keychain { + return { + name: "the test keychain", + get: () => undefined, + set: () => "the test keychain is locked", + delete: () => {}, + }; +} + +/** A keychain that cannot be asked at all, as a locked or unreachable one. */ +function lockedKeychain(): Keychain { + return { + name: "the test keychain", + get: () => { + throw new KeychainUnavailable("the test keychain did not answer (36)"); + }, + set: () => "the test keychain is locked", + delete: () => {}, + }; +} + async function harness(options: Partial = {}): Promise { const h = await new Harness().start(options); cleanups.push(() => h.app.close()); @@ -219,11 +242,15 @@ describe.concurrent("tether connect", () => { h.keychain = { name: "the test keychain", get: (origin) => items.get(origin), - set: (origin, secret) => items.set(origin, secret) !== undefined, + set: (origin, secret) => { + items.set(origin, secret); + return undefined; + }, delete: (origin) => items.delete(origin), }; expect(await h.connect()).toBe(0); expect(h.out).toContain("The device credential is in the test keychain."); + expect(h.err).toBe(""); const [credential] = items.values(); expect(credential).toMatch(/^tdc_/); expect(readFileSync(join(h.home, "credentials.json"), "utf8")).not.toContain(credential); @@ -232,6 +259,17 @@ describe.concurrent("tether connect", () => { h.expectNoSecrets(); }); + it("warns, with the reason, when the keychain refuses the credential and it stays in the file", async () => { + const h = await harness(); + h.keychain = refusingKeychain(); + expect(await h.connect()).toBe(0); + expect(h.err).toMatch( + /The test keychain refused the credential for .* \(the test keychain is locked\), so it is in .*credentials\.json, readable only by you\./, + ); + expect(h.out).toMatch(/The device credential is in .*credentials\.json\./); + h.expectNoSecrets(); + }); + it("stops when the user denies the device", async () => { const h = await harness(); const done = h.run(["connect", h.app.url]); @@ -376,6 +414,42 @@ describe.concurrent("tether start", () => { h.expectNoSecrets(); }); + it("warns, with the reason, when the keychain refuses a credential it moves out of the file", async () => { + const h = await paired(); + h.keychain = refusingKeychain(); + h.err = ""; + startTether(h); + await until(() => /claim/.test(h.sent.map((s) => s.path).join(" "))); + expect(h.err).toMatch( + /The test keychain refused the credential for .* \(the test keychain is locked\), so it is in .*credentials\.json/, + ); + h.expectNoSecrets(); + }); + + it("still frees the slot and the budget, and says so once, when the task log cannot be written", async () => { + const h = await paired(); + mkdirSync(join(h.home, "tasks.jsonl")); + const first = h.enqueue({}); + const second = h.enqueue({}); + startTether(h); + await untilAsync(async () => (await h.status(first.id)).status === "completed"); + await untilAsync(async () => (await h.status(second.id)).status === "completed"); + await until(() => (h.out.match(/could not be written to the task log/g) ?? []).length >= 2); + await sleep(300); + expect(h.out.match(/could not be written to the task log/g)).toHaveLength(2); + expect(h.out).toMatch(new RegExp(`${first.id} could not be written to the task log`)); + expect(h.store().usage(localDate(new Date())).total.tasks).toBe(2); + }); + + it("cuts an oversized service log to its last lines when it starts", async () => { + const h = await paired(); + const file = join(h.home, "service.log"); + writeFileSync(file, `${"old line\n".repeat(700_000)}last line\n`); + startTether(h); + await until(() => statSync(file).size < 1_000_001); + expect(readFileSync(file, "utf8").endsWith("old line\nlast line\n")).toBe(true); + }); + it("grants only the intersection with local policy: Bash is never granted", async () => { const h = await paired(); const task = h.enqueue({ tools: { requested: ["Bash", "WebSearch"] } }); @@ -761,6 +835,23 @@ describe.concurrent("tether doctor", () => { expect(h.out).toMatch(/^FAIL {2}Fake App .*could not be reached/m); }); + it("fails, saying why, when the keychain that holds a credential cannot be read", async () => { + const h = await paired(); + const file = join(h.home, "credentials.json"); + const stored = JSON.parse(readFileSync(file, "utf8")); + const { credential: _, ...app } = stored.apps[0]; + writeFileSync(file, JSON.stringify({ apps: [{ ...app, credential_in: "keychain" }] })); + h.keychain = lockedKeychain(); + h.out = ""; + h.err = ""; + expect(await h.run(["doctor"])).toBe(1); + expect(h.out).toMatch(/^ok {4}Claude Code is signed in/m); + expect(h.out).toMatch( + /^FAIL {2}The credential for .* is in the keychain, but the test keychain did not answer \(36\)\. Unlock the keychain/m, + ); + expect(h.err).toBe(""); + }); + it("says when no app is connected, without failing", async () => { const h = await harness(); expect(await h.run(["doctor"])).toBe(0); diff --git a/test/keychain.test.ts b/test/keychain.test.ts index 84b785c..d2cc4ec 100644 --- a/test/keychain.test.ts +++ b/test/keychain.test.ts @@ -33,9 +33,9 @@ function memoryKeychain(refuse = false): Keychain & { items: Map items, get: (origin) => items.get(origin), set: (origin, secret) => { - if (refuse) return false; + if (refuse) return "the test keychain is locked"; items.set(origin, secret); - return true; + return undefined; }, delete: (origin) => { items.delete(origin); @@ -55,8 +55,8 @@ describe("credentials with a keychain", () => { it("keeps the credential in the keychain and out of the file, and reads it back", () => { const dir = home(); const keychain = memoryKeychain(); - const where = new Store(dir, keychain).saveApp(record()); - expect(where).toBe("the test keychain"); + const saved = new Store(dir, keychain).saveApp(record()); + expect(saved).toEqual({ where: "the test keychain" }); expect(keychain.items.get("https://paper.example")).toBe(SECRET); expect(onDisk(dir)).not.toContain(SECRET); expect(JSON.parse(onDisk(dir)).apps[0].credential_in).toBe("keychain"); @@ -95,7 +95,7 @@ describe("credentials with a keychain", () => { const dir = home(); writeFileSync(join(dir, "credentials.json"), JSON.stringify({ apps: [record()] })); const keychain = memoryKeychain(); - new Store(dir, keychain).moveToKeychain(); + expect(new Store(dir, keychain).moveToKeychain()).toEqual([]); expect(onDisk(dir)).not.toContain(SECRET); expect(new Store(dir, keychain).apps()).toEqual([record()]); }); @@ -111,13 +111,27 @@ describe("credentials without a keychain", () => { it("falls back to the file, readable only by the user, when the keychain refuses", () => { const dir = home(); const keychain = memoryKeychain(true); - const where = new Store(dir, keychain).saveApp(record()); - expect(where).toBe(join(dir, "credentials.json")); + const saved = new Store(dir, keychain).saveApp(record()); + expect(saved.where).toBe(join(dir, "credentials.json")); + expect(saved.warning).toBe( + `The test keychain refused the credential for https://paper.example (the test keychain is locked), so it is in ${join(dir, "credentials.json")}, readable only by you.`, + ); expect(JSON.parse(onDisk(dir)).apps[0].credential).toBe(SECRET); expect(statSync(join(dir, "credentials.json")).mode & 0o777).toBe(0o600); expect(new Store(dir, keychain).apps()).toEqual([record()]); }); + it("warns about each credential the keychain refuses when moving them", () => { + const dir = home(); + writeFileSync(join(dir, "credentials.json"), JSON.stringify({ apps: [record()] })); + const warnings = new Store(dir, memoryKeychain(true)).moveToKeychain(); + expect(warnings).toHaveLength(1); + expect(warnings[0]).toMatch( + /refused the credential for https:\/\/paper\.example \(the test keychain is locked\)/, + ); + expect(warnings[0]).not.toContain(SECRET); + }); + it("says to pair again when a keychain record is read with no keychain at all", () => { const dir = home(); new Store(dir, memoryKeychain()).saveApp(record()); @@ -132,9 +146,9 @@ describe("credentials without a keychain", () => { expect(store.apps()).toEqual([]); }); - it("uses the file when there is no keychain", () => { + it("uses the file, without a warning, when there is no keychain", () => { const dir = home(); - expect(new Store(dir).saveApp(record())).toBe(join(dir, "credentials.json")); + expect(new Store(dir).saveApp(record())).toEqual({ where: join(dir, "credentials.json") }); expect(new Store(dir).apps()).toEqual([record()]); }); @@ -191,7 +205,7 @@ describe.each([ it("stores, reads and deletes a secret, which only ever travels on stdin", () => { const exec = fakeRun(); const keychain = make("tether", exec); - expect(keychain.set("https://paper.example", SECRET)).toBe(true); + expect(keychain.set("https://paper.example", SECRET)).toBeUndefined(); expect(keychain.get("https://paper.example")).toBe(SECRET); keychain.delete("https://paper.example"); expect(keychain.get("https://paper.example")).toBeUndefined(); @@ -204,12 +218,14 @@ describe.each([ ["-i", "store"].includes(args[0] ?? "") ? { status: 0, stdout: "", stderr: "" } : { status: 1, stdout: "", stderr: "keyring locked" }; - expect(make("tether", writeOnly).set("https://paper.example", SECRET)).toBe(false); + expect(make("tether", writeOnly).set("https://paper.example", SECRET)).toMatch( + /did not answer \(1\)/, + ); }); it("reports a refused write, and a read it could not make as unavailable, not missing", () => { const keychain = make("tether", broken); - expect(keychain.set("https://paper.example", SECRET)).toBe(false); + expect(keychain.set("https://paper.example", SECRET)).toMatch(/exited 1/); expect(() => keychain.get("https://paper.example")).toThrow(KeychainUnavailable); }); }); @@ -217,16 +233,44 @@ describe.each([ describe("the macOS keychain's stdin command", () => { it("refuses a secret it cannot quote rather than send a broken command", () => { const exec = fakeRun(); - expect(macKeychain("tether", exec).set("https://paper.example", 'a"b')).toBe(false); - expect(macKeychain("tether", exec).set("https://paper.example", "a\\b")).toBe(false); + const reason = "the origin or credential holds a character `security -i` cannot take"; + expect(macKeychain("tether", exec).set("https://paper.example", 'a"b')).toBe(reason); + expect(macKeychain("tether", exec).set("https://paper.example", "a\\b")).toBe(reason); expect(exec.calls).toEqual([]); }); }); +describe("the reason a keychain gives for refusing a secret", () => { + it("names only the exit status of `security -i`, whose stdin holds the secret", () => { + const echoes: Run = (_, args, input) => + args[0] === "-i" + ? { status: 2, stdout: input ?? "", stderr: `parse error near ${input}` } + : { status: 44, stdout: "", stderr: "" }; + const reason = macKeychain("tether", echoes).set("https://paper.example", SECRET); + expect(reason).toBe("security exited 2"); + }); + + it("says when the macOS keychain gives back something else than it was given", () => { + const wrong: Run = (_, args) => + args[0] === "-i" + ? { status: 0, stdout: "", stderr: "" } + : { status: 0, stdout: "another\n", stderr: "" }; + expect(macKeychain("tether", wrong).set("https://paper.example", SECRET)).toBe( + "the macOS keychain did not give the credential back", + ); + }); + + it("says why secret-tool could not store it, from its first line of stderr", () => { + expect(secretToolKeychain("tether", broken).set("https://paper.example", SECRET)).toBe( + "secret-tool exited 1: Cannot autolaunch D-Bus without X11", + ); + }); +}); + describe("the macOS keychain's quoting", () => { it("stores a secret with spaces in it", () => { const exec = fakeRun(); - expect(macKeychain("tether", exec).set("https://paper.example", "a b c")).toBe(true); + expect(macKeychain("tether", exec).set("https://paper.example", "a b c")).toBeUndefined(); expect(macKeychain("tether", exec).get("https://paper.example")).toBe("a b c"); }); }); diff --git a/test/store.test.ts b/test/store.test.ts index 5034393..5fab13c 100644 --- a/test/store.test.ts +++ b/test/store.test.ts @@ -11,7 +11,7 @@ function entry(n: number): TaskLogEntry { appName: "Paper", id: `tsk_${n}`, type: "paper.summarise", - title: "x".repeat(900), + title: "x".repeat(150), durationMs: 1000, costUsd: 0.01, ended: "complete", @@ -21,11 +21,11 @@ function entry(n: number): TaskLogEntry { describe("the task log", () => { it("keeps the last 1000 tasks once it passes about 1 MB", () => { const store = new Store(mkdtempSync(join(tmpdir(), "tether-store-"))); - for (let n = 1; n <= 1200; n += 1) store.logTask(entry(n)); + for (let n = 1; n <= 4000; n += 1) store.logTask(entry(n)); const file = join(store.home, "tasks.jsonl"); expect(statSync(file).size).toBeLessThanOrEqual(1_100_000); const all = store.taskLog(1000); - expect(all.at(-1)?.id).toBe("tsk_1200"); + expect(all.at(-1)?.id).toBe("tsk_4000"); expect(all.length).toBeLessThanOrEqual(1000); expect(all.length).toBeGreaterThan(900); expect(statSync(file).mode & 0o777).toBe(0o600); @@ -56,4 +56,37 @@ describe("the task log", () => { store.logTask(entry(2)); expect(store.taskLog(10).map((e) => e.id)).toEqual(["tsk_1", "tsk_2"]); }); + + it("keeps at most 200 characters of an app's title", () => { + const store = new Store(mkdtempSync(join(tmpdir(), "tether-store-"))); + store.logTask({ ...entry(1), title: `${"t".repeat(199)}\u{1F600}${"x".repeat(5000)}` }); + const [logged] = store.taskLog(1); + expect(Array.from(logged?.title ?? "")).toHaveLength(200); + expect(logged?.title.endsWith("\u{1F600}")).toBe(true); + }); +}); + +describe("the service log", () => { + it("keeps the last part of the log, from a line start, once it passes the limit", () => { + const store = new Store(mkdtempSync(join(tmpdir(), "tether-store-"))); + const file = join(store.home, "service.log"); + const lines = Array.from({ length: 60_000 }, (_, n) => `line ${n} ${"y".repeat(90)}`); + writeFileSync(file, `${lines.join("\n")}\n`, { mode: 0o644 }); + store.trimServiceLog(); + const kept = readFileSync(file, "utf8"); + expect(kept.length).toBeLessThanOrEqual(1_000_000); + expect(kept.length).toBeGreaterThan(900_000); + expect(kept.startsWith("line ")).toBe(true); + expect(kept.endsWith(`line 59999 ${"y".repeat(90)}\n`)).toBe(true); + expect(statSync(file).mode & 0o777).toBe(0o600); + }); + + it("leaves a log under the limit, and a missing one, alone", () => { + const store = new Store(mkdtempSync(join(tmpdir(), "tether-store-"))); + store.trimServiceLog(); + const file = join(store.home, "service.log"); + writeFileSync(file, "started\n"); + store.trimServiceLog(); + expect(readFileSync(file, "utf8")).toBe("started\n"); + }); }); From c5c212f2e316f3e95da1b22a89e6136a13dd3720 Mon Sep 17 00:00:00 2001 From: parsilver Date: Sat, 14 Nov 2026 19:44:30 +0700 Subject: [PATCH 3/5] test(client): pin the first-line reason secret-tool gives A mutation run showed the optional chain on the first stderr line was never needed and nothing checked that later lines are dropped. The reason now keeps the first line by replacing the rest, and a test pins both a multi-line and an empty stderr. --- src/client/keychain.ts | 5 ++++- test/keychain.test.ts | 15 +++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/client/keychain.ts b/src/client/keychain.ts index 6f7cf8d..260d7b7 100644 --- a/src/client/keychain.ts +++ b/src/client/keychain.ts @@ -86,7 +86,10 @@ export function secretToolKeychain(service: string, exec: Run = run): Keychain { const done = exec("secret-tool", args, secret); if (done.status !== 0) { // The secret went only to stdin, which secret-tool does not echo; its stderr says why. - const why = done.stderr.trim().split("\n")[0]?.slice(0, 200); + const why = done.stderr + .trim() + .replace(/\n[\s\S]*/, "") + .slice(0, 200); return `secret-tool exited ${done.status ?? "timeout"}${why ? `: ${why}` : ""}`; } return readBack(keychain, origin, secret); diff --git a/test/keychain.test.ts b/test/keychain.test.ts index d2cc4ec..eca84df 100644 --- a/test/keychain.test.ts +++ b/test/keychain.test.ts @@ -260,6 +260,21 @@ describe("the reason a keychain gives for refusing a secret", () => { ); }); + it("keeps only the first line of what secret-tool printed, and says nothing more when it printed nothing", () => { + const chatty: Run = () => ({ + status: 3, + stdout: "", + stderr: "No such secret collection\nat line 2\n", + }); + expect(secretToolKeychain("tether", chatty).set("https://paper.example", SECRET)).toBe( + "secret-tool exited 3: No such secret collection", + ); + const quiet: Run = () => ({ status: 3, stdout: "", stderr: "" }); + expect(secretToolKeychain("tether", quiet).set("https://paper.example", SECRET)).toBe( + "secret-tool exited 3", + ); + }); + it("says why secret-tool could not store it, from its first line of stderr", () => { expect(secretToolKeychain("tether", broken).set("https://paper.example", SECRET)).toBe( "secret-tool exited 1: Cannot autolaunch D-Bus without X11", From f10f49facfab0bd81155cb6bfc77df365d5acf39 Mon Sep 17 00:00:00 2001 From: parsilver Date: Sat, 14 Nov 2026 19:58:42 +0700 Subject: [PATCH 4/5] test: pin the service log limit and the spend a finished task records Mutation runs left two gaps: a log of exactly 5 MB was not checked to stay whole, and nothing checked that a finished task adds what it reported spending rather than its reserved budget. Both are pinned now; the mutants on those lines are killed. --- test/cli.test.ts | 12 +++++++++++- test/store.test.ts | 6 +++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/test/cli.test.ts b/test/cli.test.ts index d287948..3e1355e 100644 --- a/test/cli.test.ts +++ b/test/cli.test.ts @@ -438,7 +438,17 @@ describe.concurrent("tether start", () => { await sleep(300); expect(h.out.match(/could not be written to the task log/g)).toHaveLength(2); expect(h.out).toMatch(new RegExp(`${first.id} could not be written to the task log`)); - expect(h.store().usage(localDate(new Date())).total.tasks).toBe(2); + const usage = h.store().usage(localDate(new Date())).total; + expect(usage.tasks).toBe(2); + // What the two tasks reported spending, not their reserved budgets. + let reported = 0; + for (const id of [first.id, second.id]) { + const complete = h.reports(id).find((s) => s.path.endsWith("/complete")); + reported += + (complete?.body as { usage?: { cost_usd: number } } | undefined)?.usage?.cost_usd ?? 0; + } + expect(reported).toBeGreaterThan(0); + expect(usage.usd).toBeCloseTo(reported, 6); }); it("cuts an oversized service log to its last lines when it starts", async () => { diff --git a/test/store.test.ts b/test/store.test.ts index 5fab13c..14b42a1 100644 --- a/test/store.test.ts +++ b/test/store.test.ts @@ -81,12 +81,16 @@ describe("the service log", () => { expect(statSync(file).mode & 0o777).toBe(0o600); }); - it("leaves a log under the limit, and a missing one, alone", () => { + it("leaves a log at or under the limit, and a missing one, alone", () => { const store = new Store(mkdtempSync(join(tmpdir(), "tether-store-"))); store.trimServiceLog(); const file = join(store.home, "service.log"); writeFileSync(file, "started\n"); store.trimServiceLog(); expect(readFileSync(file, "utf8")).toBe("started\n"); + const atLimit = `${"z".repeat(4_999_999)}\n`; + writeFileSync(file, atLimit); + store.trimServiceLog(); + expect(statSync(file).size).toBe(5_000_000); }); }); From 728addf7dea6ade6b8d4db8fa9b47720399812f3 Mon Sep 17 00:00:00 2001 From: parsilver Date: Sat, 14 Nov 2026 20:20:57 +0700 Subject: [PATCH 5/5] refactor(cli): load the apps to run in one place start had grown two loops for the keychain warnings and the redactor. They move with the empty check into connectedApps, which brings start's CRAP score from 19.1 to 6.6 on the targeted coverage run. Behaviour is unchanged: the start and keychain tests pass as before. --- src/cli/main.ts | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/cli/main.ts b/src/cli/main.ts index 72b7325..b3eb19e 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -254,11 +254,7 @@ async function pollOnce( async function start(ctx: Context, args: string[]): Promise { const concurrency = parseCount(args, "concurrency", 1, 16); - const refused = ctx.store.moveToKeychain(); - const records = ctx.store.apps(); - for (const record of records) ctx.secrets.add(record.credential); - for (const warning of refused) ctx.err.line(warning); - if (records.length === 0) throw new Error("No apps connected. Run: tether connect "); + const records = connectedApps(ctx); const running = ctx.store.runState(); if (running && isAlive(running.pid)) { throw new Error(`Tether is already running (pid ${running.pid}).`); @@ -312,6 +308,19 @@ function trimServiceLog(ctx: Context): NodeJS.Timeout | undefined { return timer; } +/** + * The apps to run, after moving file credentials into the keychain; warns about each one the + * keychain refused once its credential is known to the redactor. + */ +function connectedApps(ctx: Context): AppRecord[] { + const refused = ctx.store.moveToKeychain(); + const records = ctx.store.apps(); + for (const record of records) ctx.secrets.add(record.credential); + for (const warning of refused) ctx.err.line(warning); + if (records.length === 0) throw new Error("No apps connected. Run: tether connect "); + return records; +} + /** The command's only option, `-- `, a whole number from 1 to `max`; no positionals. */ function parseCount(args: string[], name: string, fallback: number, max: number): number { try {