Skip to content
Closed
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.
75 changes: 75 additions & 0 deletions conformance/control-homes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
{
"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"] }
}
]
}
4 changes: 3 additions & 1 deletion packages/cli/src/control/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2845,7 +2845,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
22 changes: 22 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,27 @@ 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("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
61 changes: 54 additions & 7 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 @@ -639,12 +639,47 @@ export function resolveHome(session: string, dirs: readonly string[]): HomeChoic
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 linked = oneThroughLinks(session, live);
if (linked) return { transcript: linked };
return {
ambiguous: [...new Set(all.map(homeName))].sort(),
live: [...new Set(live.map(homeName))].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 linkedFolder = (dir: string, name: string): boolean => {
try {
return lstatSync(path.join(dir, name)).isSymbolicLink();
} catch {
/* v8 ignore next -- the folder was just read through; gone since, treat as unlinked */
return false;
}
};

/** 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(session: string, live: readonly Transcript[]): Transcript | null {
if (live.length < 2) return null;
if (new Set(live.map((t) => realOf(t.file))).size !== 1) return null;
const rows = new Set(live.flatMap((t) => liveRecords(session, t.configDir).map((r) => realOf(r.file))));
if (rows.size !== 1) return null;
const own = live.find((t) => !linkedFolder(t.configDir, "projects") && !linkedFolder(t.configDir, "sessions"));
return own ?? (live[0] as Transcript);
}

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 +805,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 +830,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
139 changes: 138 additions & 1 deletion packages/core/test/claude-live-record.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,15 @@
// Which one process holds a Claude Code session, and which account it belongs to when
// more than one has its transcript (spec/CONTROL.md §6, Homes; §6.3 `inbox`). Registry
// rows are files in a temp dir; the live pid is this test process's own.
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { afterAll, describe, expect, it } from "vitest";
import { findTranscripts, liveRecord, liveRecords, resolveHome } from "../src/adapters/claude-code-control.js";

const here = path.dirname(fileURLToPath(import.meta.url));

const tmp = mkdtempSync(path.join(os.tmpdir(), "sp-live-record-"));
afterAll(() => rmSync(tmp, { recursive: true, force: true }));

Expand Down Expand Up @@ -151,4 +154,138 @@ describe("resolveHome", () => {
});
expect([a, b].every((d) => path.isAbsolute(d))).toBe(true);
});

/** A second login that links its `projects/` (and `sessions/`) to `owner`'s. */
const linkedTo = (name: string, owner: string, folders = ["projects", "sessions"]) => {
const dir = path.join(tmp, name);
mkdirSync(dir, { recursive: true });
for (const f of folders) symlinkSync(path.join(owner, f), path.join(dir, f));
return dir;
};

it("accounts sharing their folders by symlink, one process live: that session, in the account owning the folders", () => {
const owner = home("link-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] });
const a = linkedTo("link-a", owner);
const b = linkedTo("link-b", owner);
expect(findTranscripts(SESSION, [a, owner, b])).toHaveLength(3);
expect(resolveHome(SESSION, [a, owner, b])).toEqual({
transcript: {
file: path.join(owner, "projects", PROJECT, `${SESSION}.jsonl`),
configDir: owner,
project: PROJECT,
},
});
});

it("one registry file seen through linked accounts is one live row, named for the account preferred", () => {
const owner = home("row-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] });
const a = linkedTo("row-a", owner);
expect(liveRecords(SESSION, [a, owner]).map((r) => r.configDir)).toEqual([a]);
expect(liveRecords(SESSION, [a, owner], owner).map((r) => r.configDir)).toEqual([owner]);
expect(liveRecord(SESSION, [a, owner], owner)?.configDir).toBe(owner);
// A second process in an account of its own is still a second row.
const other = home("row-other", { session: SESSION, rows: [{ pid: process.ppid, sessionId: SESSION }] });
expect(liveRecord(SESSION, [a, owner, other], owner)).toBeNull();
});

it("shared folders and nothing live: still ambiguous, since a copy would need an account", () => {
const owner = home("cold-own", { session: SESSION });
mkdirSync(path.join(owner, "sessions"), { recursive: true });
const a = linkedTo("cold-a", owner);
expect(resolveHome(SESSION, [owner, a])).toEqual({ ambiguous: ["cold-a", "cold-own"], live: [] });
});

it("one transcript by symlink but two processes, each in its own registry: still ambiguous", () => {
const owner = home("pair-own", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] });
const other = linkedTo("pair-b", owner, ["projects"]);
mkdirSync(path.join(other, "sessions"), { recursive: true });
writeFileSync(
path.join(other, "sessions", `${process.ppid}.json`),
JSON.stringify({ pid: process.ppid, sessionId: SESSION }),
);
expect(resolveHome(SESSION, [owner, other])).toEqual({
ambiguous: ["pair-b", "pair-own"],
live: ["pair-b", "pair-own"],
});
});

it("all accounts linked to a shared store outside dirs: picks the first account in dirs", () => {
const shared = home("ext-shared", { session: SESSION, rows: [{ pid: process.pid, sessionId: SESSION }] });
const first = linkedTo("ext-first", shared);
const second = linkedTo("ext-second", shared);
expect(resolveHome(SESSION, [first, second])).toEqual({
transcript: {
file: path.join(first, "projects", PROJECT, `${SESSION}.jsonl`),
configDir: first,
project: PROJECT,
},
});
});
});

describe("homes (conformance/control-homes.json)", () => {
type SpecDir = {
name: string;
transcript?: boolean;
live?: ("self" | "parent")[];
link_projects?: string;
link_sessions?: string;
};
type HomesVector = {
cases: {
name: string;
stores?: SpecDir[];
accounts: SpecDir[];
expect: { home: string } | { ambiguous: string[]; live: string[] } | null;
}[];
};
const vectors = JSON.parse(
readFileSync(path.resolve(here, "../../../conformance/control-homes.json"), "utf8"),
) as HomesVector;
const pidOf = (k: "self" | "parent") => (k === "self" ? process.pid : process.ppid);

for (const [i, c] of vectors.cases.entries()) {
it(c.name, () => {
const root = path.join(tmp, `vec-${i}`);
mkdirSync(root, { recursive: true });
const all = [...(c.stores ?? []), ...c.accounts];
const byName = new Map<string, string>();
for (const a of all) {
const dir = path.join(root, a.name);
mkdirSync(dir, { recursive: true });
byName.set(a.name, dir);
if (a.transcript) {
mkdirSync(path.join(dir, "projects", PROJECT), { recursive: true });
writeFileSync(path.join(dir, "projects", PROJECT, `${SESSION}.jsonl`), "");
}
if (a.live !== undefined) {
mkdirSync(path.join(dir, "sessions"), { recursive: true });
for (const k of a.live) {
const pid = pidOf(k);
writeFileSync(path.join(dir, "sessions", `${pid}.json`), JSON.stringify({ pid, sessionId: SESSION }));
}
}
}
for (const a of all) {
const dir = byName.get(a.name) as string;
if (a.link_projects)
symlinkSync(path.join(byName.get(a.link_projects) as string, "projects"), path.join(dir, "projects"));
if (a.link_sessions)
symlinkSync(path.join(byName.get(a.link_sessions) as string, "sessions"), path.join(dir, "sessions"));
}
const dirs = c.accounts.map((a) => byName.get(a.name) as string);
const got = resolveHome(SESSION, dirs);
if (c.expect === null) expect(got).toBeNull();
else if ("home" in c.expect) {
const expectedDir = byName.get(c.expect.home) as string;
expect(got).toEqual({
transcript: {
file: path.join(expectedDir, "projects", PROJECT, `${SESSION}.jsonl`),
configDir: expectedDir,
project: PROJECT,
},
});
} else expect(got).toEqual(c.expect);
});
}
});
Loading
Loading