Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/linked-homes-one-session.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"sessionpipe": patch
"sessionpipe-core": patch
---

Control: a message for a Claude Code session is no longer refused `ambiguous_home` when several accounts share one `projects/` tree and live-session registry by symlink. Each finds the same transcript and the same live record, so the machine takes that one session (spec/CONTROL.md §6.1). Two transcripts, two processes, or nothing live is still refused.
5 changes: 5 additions & 0 deletions conformance/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@
written, when a run of it is known to have ended, when its own hooks last spoke of a turn
running in it, and when a run that was asked to copy it and may have run in it ended. Run by
`packages/cli/test/control-daemon.test.ts`.
- `control-homes.json` — which Claude Code account a session id belongs to when a machine has
more than one config dir, including accounts that share `projects/` and `sessions/` by symlink
(spec/CONTROL.md §6.1): `{ stores?, accounts, expect }`, the backing folders and config dirs
with transcripts, live rows and symlinks, and `{ home }`, `{ ambiguous, live }`, or null. Run
by `packages/core/test/claude-live-record.test.ts`.
- `control-session-ids.json` — which Claude Code session an id names (spec/CONTROL.md §6):
`{ filed, asked, found, taken }`, the transcripts in a project folder, the id a command
names, the file that is that session's (its exact name, or none), and whether the id is
Expand Down
100 changes: 100 additions & 0 deletions conformance/control-homes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
{
"spec": "CONTROL.md §6.1 Homes",
"note": "Which Claude Code account a session id belongs to when a machine has more than one config dir. `stores` names backing folders outside `accounts` (for the all-links case); each entry in `accounts` is a config dir in the order the machine lists them, with `transcript` (holds the session's transcript), `live` (live registry rows, named `self` or `parent` so two processes are distinct), and `link_projects` / `link_sessions` (symlinked to another named store or account). `expect` is `{ \"home\": <name> }`, `{ \"ambiguous\": [...], \"live\": [...] }` (directory names only, sorted), or null when no account has the session.",
"cases": [
{
"name": "one account has the transcript, no live process needed",
"accounts": [{ "name": "only", "transcript": true }],
"expect": { "home": "only" }
},
{
"name": "no account has the transcript",
"accounts": [{ "name": "empty" }],
"expect": null
},
{
"name": "two accounts, one holds it open",
"accounts": [
{ "name": "cold", "transcript": true },
{ "name": "live", "transcript": true, "live": ["self"] }
],
"expect": { "home": "live" }
},
{
"name": "two accounts, neither live: ambiguous",
"accounts": [
{ "name": "b", "transcript": true },
{ "name": "a", "transcript": true }
],
"expect": { "ambiguous": ["a", "b"], "live": [] }
},
{
"name": "three accounts, two live and one cold: ambiguous, naming the two live",
"accounts": [
{ "name": "a", "transcript": true, "live": ["self"] },
{ "name": "b", "transcript": true, "live": ["parent"] },
{ "name": "c", "transcript": true }
],
"expect": { "ambiguous": ["a", "b", "c"], "live": ["a", "b"] }
},
{
"name": "linked accounts sharing projects/ and sessions/, one live process: chosen under the owner",
"accounts": [
{ "name": "linked-a", "link_projects": "own", "link_sessions": "own" },
{ "name": "own", "transcript": true, "live": ["self"] },
{ "name": "linked-b", "link_projects": "own", "link_sessions": "own" }
],
"expect": { "home": "own" }
},
{
"name": "all accounts link to a shared folder none of them owns, one live process: first account in dirs",
"stores": [{ "name": "shared", "transcript": true, "live": ["self"] }],
"accounts": [
{ "name": "first", "link_projects": "shared", "link_sessions": "shared" },
{ "name": "second", "link_projects": "shared", "link_sessions": "shared" }
],
"expect": { "home": "first" }
},
{
"name": "linked accounts, nothing live: still ambiguous",
"accounts": [
{ "name": "own", "transcript": true, "live": [] },
{ "name": "linked", "link_projects": "own", "link_sessions": "own" }
],
"expect": { "ambiguous": ["linked", "own"], "live": [] }
},
{
"name": "linked projects/ but separate registries with two live processes: still ambiguous",
"accounts": [
{ "name": "own", "transcript": true, "live": ["self"] },
{ "name": "other", "link_projects": "own", "live": ["parent"] }
],
"expect": { "ambiguous": ["other", "own"], "live": ["other", "own"] }
},
{
"name": "separate projects/ (two real transcripts) with linked sessions/: still ambiguous",
"accounts": [
{ "name": "own", "transcript": true, "live": ["self"] },
{ "name": "other", "transcript": true, "link_sessions": "own" }
],
"expect": { "ambiguous": ["other", "own"], "live": ["other", "own"] }
},
{
"name": "linked projects/ and sessions/ with two live processes in the shared registry: still ambiguous",
"accounts": [
{ "name": "own", "transcript": true, "live": ["self", "parent"] },
{ "name": "linked", "link_projects": "own", "link_sessions": "own" }
],
"expect": { "ambiguous": ["linked", "own"], "live": ["linked", "own"] }
},
{
"name": "linked accounts sharing one live session plus a third cold account with its own transcript: chosen under the owner",
"accounts": [
{ "name": "cold", "transcript": true },
{ "name": "linked", "link_projects": "own", "link_sessions": "own" },
{ "name": "own", "transcript": true, "live": ["self"] }
],
"expect": { "home": "own" }
}
]
}
4 changes: 3 additions & 1 deletion packages/cli/src/control/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2923,7 +2923,9 @@ export class ControlDaemon {
code: "stale",
detail: `a message written into a live session must arrive within ${INBOX_FRESH_MS / 1000} s of being signed, and this one is dated ${Math.round(age / 1000)} s from now`,
};
const rec = liveRecord(target, this.deps.claudeDirs());
// Every account, so a second process in another one still refuses; a row two
// accounts see through linked folders is one row, named for the account resolved.
const rec = liveRecord(target, this.deps.claudeDirs(), place.transcript.configDir);
const cls = peerClass(this.modeOf(key));
const why = inbox.vetInbox(rec, {
sessionClass: cls,
Expand Down
81 changes: 81 additions & 0 deletions packages/cli/test/control-inbox.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
mkdtempSync,
readFileSync,
rmSync,
symlinkSync,
utimesSync,
writeFileSync,
} from "node:fs";
Expand Down Expand Up @@ -292,6 +293,86 @@ describe.runIf(unix)("a message into a live session's own inbox", () => {
expect(rx.hellos.at(-1)?.modes).toContain("inbox");
});

it("accounts that share their folders by symlink: written in place, in the account that owns them", async () => {
// A second login whose `projects/` and `sessions/` are links to the first: both
// accounts find the one transcript and the one registry row. Listed first, so a
// lookup that took the first account it found would vet against the wrong one (its
// own settings say nothing of bypass) and fork instead.
row();
const linked = path.join(tmp, "home-linked");
mkdirSync(linked, { recursive: true });
symlinkSync(path.join(configDir, "projects"), path.join(linked, "projects"));
symlinkSync(path.join(configDir, "sessions"), path.join(linked, "sessions"));
await startDaemon({ extra: { claudeDirs: () => [linked, configDir] } });
await sawMode("bypassPermissions");
const q = await rx.send({ session: SESSION, kind: "prompt", text: "through the links?" });
await wrote(1);
expect(frameIn()).toContain(markOf(q.id));
answered(markOf(q.id));
await ask(sock, { op: "event", session: SESSION, event: "UserPromptSubmit", mode: "bypassPermissions" }, 500);
expect(await rx.waitAck(q.id)).toMatchObject({ outcome: "delivered", mode: "inbox" });
expect(() => readFileSync(claudeLog, "utf8")).toThrow();
});

it("all accounts linked to an external shared store: takes the first account and uses its settings", async () => {
row();
const first = path.join(tmp, "home-ext-1");
const second = path.join(tmp, "home-ext-2");
for (const dir of [first, second]) {
mkdirSync(dir, { recursive: true });
symlinkSync(path.join(configDir, "projects"), path.join(dir, "projects"));
symlinkSync(path.join(configDir, "sessions"), path.join(dir, "sessions"));
}
homeDefault("bypassPermissions", {}, first);
await startDaemon({ extra: { claudeDirs: () => [first, second] } });
await sawMode("bypassPermissions");
const q = await rx.send({ session: SESSION, kind: "prompt", text: "all links?" });
await wrote(1);
expect(frameIn()).toContain(markOf(q.id));
answered(markOf(q.id));
await ask(sock, { op: "event", session: SESSION, event: "UserPromptSubmit", mode: "bypassPermissions" }, 500);
expect(await rx.waitAck(q.id)).toMatchObject({ outcome: "delivered", mode: "inbox" });
expect(() => readFileSync(claudeLog, "utf8")).toThrow();
});

it("linked accounts plus a second live process in an unlinked account: refuses the inbox lane (no_record)", async () => {
row();
const linked = path.join(tmp, "home-linked-2");
mkdirSync(linked, { recursive: true });
symlinkSync(path.join(configDir, "projects"), path.join(linked, "projects"));
symlinkSync(path.join(configDir, "sessions"), path.join(linked, "sessions"));
const other = path.join(tmp, "home-other");
row({ pid: process.ppid }, other);
await startDaemon({ extra: { claudeDirs: () => [linked, configDir, other] } });
await sawMode("bypassPermissions");
const q = await rx.send({ session: SESSION, kind: "prompt", text: "two processes?" });
expect(await rx.waitAck(q.id, 15_000)).toMatchObject({ outcome: "delivered", mode: "fork" });
expect(written).toEqual([]);
expect(log.some((l) => l.includes("no_record"))).toBe(true);
});

it("unlinked live process in another account: refuses the inbox lane (other_home)", async () => {
const other = path.join(tmp, "home-other-live");
row({}, other);
await startDaemon({ extra: { claudeDirs: () => [configDir, other] } });
await sawMode("bypassPermissions");
const q = await rx.send({ session: SESSION, kind: "prompt", text: "wrong account?" });
expect(await rx.waitAck(q.id, 15_000)).toMatchObject({ outcome: "delivered", mode: "resume" });
expect(written).toEqual([]);
expect(log.some((l) => l.includes("other_home"))).toBe(true);
});

it("cancel with linked accounts still sees the open interactive session and refuses to signal it", async () => {
row();
const linked = path.join(tmp, "home-linked-cancel");
mkdirSync(linked, { recursive: true });
symlinkSync(path.join(configDir, "projects"), path.join(linked, "projects"));
symlinkSync(path.join(configDir, "sessions"), path.join(linked, "sessions"));
await startDaemon({ extra: { claudeDirs: () => [linked, configDir] } });
const stop = await rx.send({ kind: "cancel", session: SESSION, text: undefined });
expect(await rx.waitAck(stop.id, 15_000)).toMatchObject({ outcome: "unsupported" });
});

it("says nothing about the platform when nobody asked it to: this computer's own", async () => {
row();
// Whatever this computer is, the row is one the mode can use there: a Mac vets the
Expand Down
72 changes: 62 additions & 10 deletions packages/core/src/adapters/claude-code-control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
// spacesheep CLI's machine listener (lib/machine.js, 1.22), which ran it in
// production first.
import { execFile, execFileSync } from "node:child_process";
import { closeSync, openSync, readdirSync, readFileSync, readSync, statSync } from "node:fs";
import { closeSync, lstatSync, openSync, readdirSync, readFileSync, readSync, realpathSync, statSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { PICTURE_TYPES, type Picture, type PictureLimits, picturesFor } from "../control/pictures.js";
Expand Down Expand Up @@ -637,14 +637,54 @@ export function resolveHome(session: string, dirs: readonly string[]): HomeChoic
const all = findTranscripts(session, dirs);
if (!all.length) return null;
if (all.length === 1) return { transcript: all[0] as Transcript };
const live = all.filter((t) => liveRecords(session, t.configDir).length > 0);
if (live.length === 1) return { transcript: live[0] as Transcript };
const live = all.map((t) => ({ t, rows: liveRecords(session, t.configDir) })).filter((x) => x.rows.length > 0);
if (live.length === 1) return { transcript: (live[0] as { t: Transcript }).t };
const linked = oneThroughLinks(live);
if (linked) return { transcript: linked };
return {
ambiguous: [...new Set(all.map(homeName))].sort(),
live: [...new Set(live.map(homeName))].sort(),
live: [...new Set(live.map((x) => homeName(x.t)))].sort(),
};
}

const realOf = (p: string): string => {
try {
return realpathSync(p);
} catch {
/* v8 ignore next -- the file was just read; gone since, keep its path */
return p;
}
};
const isLink = (p: string): boolean => {
try {
return lstatSync(path.resolve(p)).isSymbolicLink();
} catch {
/* v8 ignore next -- the folder was just read through; gone since, treat as not owning */
return true;
}
};

/** Accounts that share one `projects/` and one `sessions/` folder by symlink (several
* logins on one machine, one history) each find the same transcript and the same live
* row. That is one session held by one process, not a choice between accounts: a message
* goes into that process, whichever directory names it. Collapsed only when every live
* copy is one file on disk and every live row one registry file, so a real choice (two
* files, or two processes) still refuses, and with nothing live it still refuses, since a
* copy would need an account. The one kept is the account whose folders are its own. */
function oneThroughLinks(live: readonly { t: Transcript; rows: LiveRecord[] }[]): Transcript | null {
if (live.length < 2) return null;
if (new Set(live.map((x) => realOf(x.t.file))).size !== 1) return null;
const rows = new Set(live.flatMap((x) => x.rows.map((r) => realOf(r.file))));
if (rows.size !== 1) return null;
const own = live.find(
({ t }) =>
!isLink(t.configDir) &&
!isLink(path.join(t.configDir, "projects")) &&
!isLink(path.join(t.configDir, "sessions")),
);
return (own ?? (live[0] as { t: Transcript })).t;
}

const projectName = (cwd: string) => cwd.replace(/[^a-zA-Z0-9]/g, "-");

/** The folder a session runs in, from its transcript's own records (never from a
Expand Down Expand Up @@ -770,9 +810,14 @@ const registryRow = (file: string, configDir: string, j: Record<string, unknown>
};

/** Every live registry row for this session, across the config dirs given. A row whose
* pid is gone is not one: the file outlives the process. */
export function liveRecords(session: string, dirs: string | readonly string[]): LiveRecord[] {
* pid is gone is not one: the file outlives the process. One registry file seen through
* several dirs (accounts that link `sessions/` to one folder) is one row, not one per
* account: kept as `prefer`'s copy when that dir is among them, so the row names the
* account the caller resolved the session to (the `other_home` check compares the two),
* else as the first dir's. */
export function liveRecords(session: string, dirs: string | readonly string[], prefer?: string): LiveRecord[] {
const out: LiveRecord[] = [];
const at = new Map<string, number>();
for (const dir of typeof dirs === "string" ? [dirs] : dirs) {
let names: string[] = [];
try {
Expand All @@ -790,17 +835,24 @@ export function liveRecords(session: string, dirs: string | readonly string[]):
}
if (String(j.sessionId) !== session) continue;
const row = registryRow(file, dir, j);
if (pidAlive(row.pid)) out.push(row);
if (!pidAlive(row.pid)) continue;
const real = realOf(file);
const seen = at.get(real);
if (seen === undefined) {
at.set(real, out.length);
out.push(row);
} else if (prefer !== undefined && path.resolve(dir) === path.resolve(prefer)) out[seen] = row;
}
}
return out;
}

/** The ONE live process that holds this session, or null. Two rows — two accounts, or
* two processes in one — is a refusal rather than a guess: a lane that writes into a
* live session has to know which process it is writing to (spec/CONTROL.md §6.3). */
export function liveRecord(session: string, dirs: string | readonly string[]): LiveRecord | null {
const all = liveRecords(session, dirs);
* live session has to know which process it is writing to (spec/CONTROL.md §6.3).
* `prefer` is the account the session was resolved to (`liveRecords`). */
export function liveRecord(session: string, dirs: string | readonly string[], prefer?: string): LiveRecord | null {
const all = liveRecords(session, dirs, prefer);
return all.length === 1 ? (all[0] as LiveRecord) : null;
}

Expand Down
Loading
Loading