Skip to content

Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.

fix(brain): land the finished push in Trail instead of a local page (#417)

anirudhkumar-nanonets352f0af959fb
diff --git a/src/brain/signup.ts b/src/brain/signup.ts
index 2ec8582b..815b96bd 100644
--- a/src/brain/signup.ts
+++ b/src/brain/signup.ts
@@ -111,8 +111,11 @@ export async function startHandoff(): Promise<Handoff> {
return;
}
- res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
- res.end(donePage(true));
+ // 303 so the browser issues a plain GET, and Location built from
+ // GRAFT_BRAIN_URL rather than anything the query carried — the same reason
+ // the Trail side builds its callback rather than being told one.
+ res.writeHead(303, { location: brainUrl(brainId), "cache-control": "no-store" });
+ res.end();
// No `baseUrl` stored, matching `connect`: GRAFT_BRAIN_URL is read again on
// every use, so persisting it here would only freeze a host that the env
// var is already free to move.
@@ -159,9 +162,27 @@ export async function startHandoff(): Promise<Handoff> {
};
}
+/** The Trail front end this machine is pointed at, without a trailing slash.
+ *
+ * Read at the moment it is needed rather than captured once, matching the rest
+ * of the brain code: GRAFT_BRAIN_URL is free to move between calls. */
+export function webBaseUrl(baseUrl?: string): string {
+ return (process.env.GRAFT_BRAIN_URL || baseUrl || DEFAULT_WEB_BASE_URL).replace(/\/+$/, "");
+}
+
+/** Where the browser is sent once the handoff has been accepted.
+ *
+ * Back into Trail, at the brain it just made. The alternative — leaving the
+ * person on a local page that says "go back to your terminal" — ends the flow
+ * on a blank throwaway served by a port that is about to close, at exactly the
+ * moment the brain starts being mined and there is something to watch. */
+export function brainUrl(brainId: string, baseUrl?: string): string {
+ return `${webBaseUrl(baseUrl)}/brain/${encodeURIComponent(brainId)}`;
+}
+
/** Where to send the browser for a repo's brain. */
export function signupUrl(opts: { repo: string; port: number; state: string; baseUrl?: string }): string {
- const base = (process.env.GRAFT_BRAIN_URL || opts.baseUrl || DEFAULT_WEB_BASE_URL).replace(/\/+$/, "");
+ const base = webBaseUrl(opts.baseUrl);
const q = new URLSearchParams({
step: "repo",
graft_repo: opts.repo,
diff --git a/test/brain-signup.test.ts b/test/brain-signup.test.ts
index ef7f2773..d368f5b7 100644
--- a/test/brain-signup.test.ts
+++ b/test/brain-signup.test.ts
@@ -90,3 +90,24 @@ test("signup url: GRAFT_BRAIN_URL points signup at staging too", () => {
else process.env.GRAFT_BRAIN_URL = before;
}
});
+
+// The browser's last stop is Trail, not a local page that is about to stop
+// answering. Ending on "go back to your terminal" wasted the one moment the
+// brain is actually being built and there is something on screen worth seeing.
+test('the accepted handoff sends the browser back into Trail, at its new brain', async () => {
+ process.env.GRAFT_BRAIN_URL = 'http://localhost:5173';
+ const handoff = await startHandoff();
+ try {
+ const res = await fetch(
+ `http://127.0.0.1:${handoff.port}${CALLBACK_PATH}?state=${encodeURIComponent(handoff.state)}&brain=abc-123&token=gbt_1.xyz`,
+ { redirect: 'manual' },
+ );
+ assert.equal(res.status, 303);
+ assert.equal(res.headers.get('location'), 'http://localhost:5173/brain/abc-123');
+ const got = await handoff.wait(1000);
+ assert.deepEqual(got, { link: { brainId: 'abc-123', token: 'gbt_1.xyz' } });
+ } finally {
+ handoff.close();
+ delete process.env.GRAFT_BRAIN_URL;
+ }
+});
diff --git a/test/claude-shim-resolve.test.ts b/test/claude-shim-resolve.test.ts
index fd8b571d..0e05c729 100644
--- a/test/claude-shim-resolve.test.ts
+++ b/test/claude-shim-resolve.test.ts
@@ -31,15 +31,51 @@ function fakeInstall(root: string, name: string, version: string): string {
return distClaude;
}
+/**
+ * Cuts the two candidates this fixture does not control out of the child.
+ *
+ * The shim probes four places, and only the first two — the baked dir and the
+ * project's `node_modules` — are ones a test builds. The other two find
+ * whatever `@nanonets/graft` is installed on the machine running the suite:
+ *
+ * - `<execDir>/../lib` is the nvm layout, so on any developer box with a
+ * global graft it resolves to the real package. That install is newer than
+ * the fixtures, so `best()` correctly preferred it, loaded the real
+ * `hooks.js` — which writes no marker — and every assertion here read back
+ * `null`. Green on CI, red on a laptop, for a reason that had nothing to do
+ * with the behaviour under test.
+ * - `npm root -g` is the same leak by another route, reached when the cheap
+ * candidates all miss.
+ *
+ * `process.execPath` is repointed through a `--require` preload rather than by
+ * symlinking a real node: `/proc/self/exe` resolves symlinks on Linux, so the
+ * filesystem trick would isolate macOS and quietly do nothing on the CI leg
+ * that matters. `npm_config_prefix` is what `npm root -g` answers from, so
+ * pointing it at an empty fixture dir leaves npm working and finding nothing —
+ * safer than emptying `PATH`, which on Windows also hides the `cmd.exe` that
+ * `shell: true` needs.
+ *
+ * Same intent as `homeEnv`: the child sees the fixture, never the runner.
+ */
+function isolate(root: string): { preload: string; env: NodeJS.ProcessEnv } {
+ const preload = join(root, 'no-ambient-graft.cjs');
+ const execPath = join(root, 'node-prefix', 'bin', 'node');
+ writeFileSync(preload, `Object.defineProperty(process, 'execPath', { value: ${JSON.stringify(execPath)}, configurable: true });\n`);
+ const prefix = join(root, 'npm-prefix');
+ mkdirSync(prefix, { recursive: true });
+ return { preload, env: { npm_config_prefix: prefix } };
+}
+
/** Runs the shim with the given baked dir and project dir; returns the version
* of the install that actually got loaded (or null if none did). */
function runShim(root: string, bakedDir: string, projectDir: string): string | null {
const shimPath = join(root, 'graft-hooks.cjs');
const marker = join(root, 'loaded.txt');
writeFileSync(shimPath, hooksShim(bakedDir));
- const res = spawnSync(process.execPath, [shimPath, 'session-start'], {
+ const { preload, env } = isolate(root);
+ const res = spawnSync(process.execPath, ['--require', preload, shimPath, 'session-start'], {
encoding: 'utf8',
- env: { ...process.env, MARKER: marker, CLAUDE_PROJECT_DIR: projectDir },
+ env: { ...process.env, ...env, MARKER: marker, CLAUDE_PROJECT_DIR: projectDir },
});
assert.equal(res.status, 0, `shim exited ${res.status}: ${res.stderr}`);
return existsSync(marker) ? readFileSync(marker, 'utf8') : null;
@@ -81,3 +117,15 @@ test('no candidate at all exits quietly — a hook must never fail the session',
mkdirSync(join(root, 'project'), { recursive: true });
assert.equal(runShim(root, join(root, 'nowhere'), join(root, 'project')), null);
});
+
+// Guards the isolation itself. `isolate` repoints the exec dir at the fixture
+// rather than disabling that probe, so the nvm-layout candidate must still be
+// live — just rooted somewhere the test built. Without this, someone deleting
+// the preload would see every assertion above still pass on CI (which has no
+// global graft) and the laptop-only failure would come straight back.
+test('the exec-dir probe reads the fixture prefix, not the machine install', () => {
+ const root = tmpRepo('shim-execdir');
+ fakeInstall(join(root, 'node-prefix', 'lib', 'node_modules', '@nanonets'), 'graft', '99.0.0');
+ fakeInstall(join(root, 'project', 'node_modules', '@nanonets'), 'graft', '0.9.1');
+ assert.equal(runShim(root, join(root, 'nowhere'), join(root, 'project')), '99.0.0');
+});