@vellumai/cli 0.8.5 → 0.8.7-dev.202606052118.34cd356

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/AGENTS.md +6 -0
  2. package/bun.lock +8 -0
  3. package/knip.json +6 -1
  4. package/node_modules/@vellumai/environments/bun.lock +24 -0
  5. package/node_modules/@vellumai/environments/package.json +18 -0
  6. package/node_modules/@vellumai/environments/src/__tests__/package-boundary.test.ts +95 -0
  7. package/node_modules/@vellumai/environments/src/index.ts +11 -0
  8. package/{src/lib/environments → node_modules/@vellumai/environments/src}/seeds.ts +5 -9
  9. package/node_modules/@vellumai/environments/tsconfig.json +20 -0
  10. package/node_modules/@vellumai/local-mode/bun.lock +29 -0
  11. package/node_modules/@vellumai/local-mode/package.json +22 -0
  12. package/node_modules/@vellumai/local-mode/src/__tests__/environment.test.ts +116 -0
  13. package/node_modules/@vellumai/local-mode/src/__tests__/gateway-proxy.test.ts +79 -0
  14. package/node_modules/@vellumai/local-mode/src/__tests__/hatch.test.ts +108 -0
  15. package/node_modules/@vellumai/local-mode/src/__tests__/package-boundary.test.ts +104 -0
  16. package/node_modules/@vellumai/local-mode/src/__tests__/wake.test.ts +66 -0
  17. package/node_modules/@vellumai/local-mode/src/config.ts +66 -0
  18. package/node_modules/@vellumai/local-mode/src/environment.ts +62 -0
  19. package/node_modules/@vellumai/local-mode/src/gateway-proxy.ts +109 -0
  20. package/node_modules/@vellumai/local-mode/src/guardian-token.ts +122 -0
  21. package/node_modules/@vellumai/local-mode/src/hatch.ts +92 -0
  22. package/node_modules/@vellumai/local-mode/src/index.ts +48 -0
  23. package/node_modules/@vellumai/local-mode/src/lockfile-contract.test.ts +173 -0
  24. package/node_modules/@vellumai/local-mode/src/lockfile-contract.ts +114 -0
  25. package/node_modules/@vellumai/local-mode/src/lockfile.test.ts +235 -0
  26. package/node_modules/@vellumai/local-mode/src/lockfile.ts +133 -0
  27. package/node_modules/@vellumai/local-mode/src/retire.ts +58 -0
  28. package/node_modules/@vellumai/local-mode/src/util.ts +102 -0
  29. package/node_modules/@vellumai/local-mode/src/wake.ts +78 -0
  30. package/node_modules/@vellumai/local-mode/tsconfig.json +16 -0
  31. package/package.json +12 -1
  32. package/src/__tests__/assistant-client-refresh.test.ts +182 -0
  33. package/src/__tests__/backup.test.ts +38 -0
  34. package/src/__tests__/clean.test.ts +179 -0
  35. package/src/__tests__/client-token.test.ts +87 -0
  36. package/src/__tests__/client-tui-refresh.test.ts +170 -0
  37. package/src/__tests__/cloudflare-tunnel.test.ts +137 -0
  38. package/src/__tests__/connect-import.test.ts +317 -0
  39. package/src/__tests__/devices.test.ts +272 -0
  40. package/src/__tests__/env-drift.test.ts +32 -44
  41. package/src/__tests__/flags.test.ts +248 -0
  42. package/src/__tests__/guardian-token.test.ts +126 -2
  43. package/src/__tests__/multi-local.test.ts +1 -1
  44. package/src/__tests__/orphan-detection.test.ts +8 -6
  45. package/src/__tests__/pair.test.ts +271 -0
  46. package/src/__tests__/paired-lifecycle.test.ts +116 -0
  47. package/src/__tests__/recover.test.ts +307 -0
  48. package/src/__tests__/segments-to-plain-text.test.ts +37 -0
  49. package/src/__tests__/tui-midsession-refresh.test.ts +166 -0
  50. package/src/__tests__/unpair.test.ts +163 -0
  51. package/src/__tests__/wake.test.ts +215 -0
  52. package/src/commands/backup.ts +2 -0
  53. package/src/commands/client.ts +569 -39
  54. package/src/commands/connect/import.ts +217 -0
  55. package/src/commands/connect.ts +31 -0
  56. package/src/commands/devices.ts +247 -0
  57. package/src/commands/env.ts +1 -1
  58. package/src/commands/flags.ts +269 -0
  59. package/src/commands/gateway/token.ts +73 -0
  60. package/src/commands/gateway.ts +29 -0
  61. package/src/commands/logs.ts +6 -18
  62. package/src/commands/pair.ts +222 -0
  63. package/src/commands/ps.ts +57 -41
  64. package/src/commands/recover.ts +47 -9
  65. package/src/commands/restore.ts +8 -1
  66. package/src/commands/retire.ts +23 -70
  67. package/src/commands/rollback.ts +2 -14
  68. package/src/commands/sleep.ts +7 -0
  69. package/src/commands/ssh.ts +5 -24
  70. package/src/commands/teleport.ts +34 -26
  71. package/src/commands/tunnel.ts +46 -2
  72. package/src/commands/unpair.ts +118 -0
  73. package/src/commands/upgrade.ts +8 -16
  74. package/src/commands/wake.ts +75 -45
  75. package/src/components/DefaultMainScreen.tsx +100 -14
  76. package/src/index.ts +22 -0
  77. package/src/lib/__tests__/lifecycle-reporter.test.ts +59 -0
  78. package/src/lib/__tests__/step-runner.test.ts +49 -1
  79. package/src/lib/assistant-client.ts +58 -37
  80. package/src/lib/assistant-config.ts +28 -3
  81. package/src/lib/cloudflare-tunnel.ts +276 -0
  82. package/src/lib/config-utils.ts +24 -3
  83. package/src/lib/confirm-action.ts +57 -0
  84. package/src/lib/docker.ts +82 -8
  85. package/src/lib/environments/__tests__/paths.test.ts +2 -1
  86. package/src/lib/environments/__tests__/seeds.test.ts +2 -1
  87. package/src/lib/environments/paths.ts +1 -1
  88. package/src/lib/environments/resolve.ts +11 -35
  89. package/src/lib/guardian-token.ts +132 -9
  90. package/src/lib/hatch-local.ts +75 -33
  91. package/src/lib/http-client.ts +1 -3
  92. package/src/lib/lifecycle-reporter.ts +31 -0
  93. package/src/lib/local.ts +193 -298
  94. package/src/lib/orphan-detection.ts +9 -5
  95. package/src/lib/pgrep.ts +5 -1
  96. package/src/lib/platform-client.ts +97 -49
  97. package/src/lib/process.ts +109 -39
  98. package/src/lib/retire-local.ts +28 -14
  99. package/src/lib/segments-to-plain-text.ts +35 -0
  100. package/src/lib/step-runner.ts +67 -7
  101. package/src/lib/sync-cloud-assistants.ts +17 -0
  102. /package/{src/lib/environments → node_modules/@vellumai/environments/src}/types.ts +0 -0
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Tests for the `cloud: "paired"` lifecycle guards: `vellum wake`/`vellum sleep`
3
+ * must refuse a remote pairing with a clear "managed on its host machine"
4
+ * message instead of treating it as an on-machine process.
5
+ */
6
+ import {
7
+ afterAll,
8
+ afterEach,
9
+ beforeEach,
10
+ describe,
11
+ expect,
12
+ spyOn,
13
+ test,
14
+ } from "bun:test";
15
+ import { mkdtempSync, rmSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+
19
+ const testDir = mkdtempSync(join(tmpdir(), "paired-lifecycle-test-"));
20
+ const ORIGINAL_LOCKFILE_DIR = process.env.VELLUM_LOCKFILE_DIR;
21
+ const ORIGINAL_CONFIG_HOME = process.env.XDG_CONFIG_HOME;
22
+ const ORIGINAL_ARGV = [...process.argv];
23
+
24
+ import { saveAssistantEntry } from "../lib/assistant-config.js";
25
+ import { retire } from "../commands/retire.js";
26
+ import { sleep } from "../commands/sleep.js";
27
+ import { wake } from "../commands/wake.js";
28
+
29
+ function seedPairedEntry(): void {
30
+ saveAssistantEntry({
31
+ assistantId: "px",
32
+ name: "Paired Box",
33
+ runtimeUrl: "http://10.0.0.9:7830",
34
+ cloud: "paired",
35
+ paired: true,
36
+ species: "vellum",
37
+ });
38
+ }
39
+
40
+ /** Run `fn` with console.error + process.exit spied; return {exited, errors}. */
41
+ async function runGuarded(
42
+ fn: () => Promise<void>,
43
+ ): Promise<{ exited: boolean; errors: string }> {
44
+ const errors: string[] = [];
45
+ const errSpy = spyOn(console, "error").mockImplementation(
46
+ (...a: unknown[]) => {
47
+ errors.push(a.join(" "));
48
+ },
49
+ );
50
+ const exitSpy = spyOn(process, "exit").mockImplementation(((c?: number) => {
51
+ throw new Error(`exit:${c}`);
52
+ }) as never);
53
+ let exited = false;
54
+ try {
55
+ await fn();
56
+ } catch (e) {
57
+ exited = (e as Error).message === "exit:1";
58
+ } finally {
59
+ errSpy.mockRestore();
60
+ exitSpy.mockRestore();
61
+ }
62
+ return { exited, errors: errors.join("\n") };
63
+ }
64
+
65
+ describe("paired lifecycle guards", () => {
66
+ beforeEach(() => {
67
+ process.env.VELLUM_LOCKFILE_DIR = testDir;
68
+ process.env.XDG_CONFIG_HOME = testDir;
69
+ seedPairedEntry();
70
+ });
71
+
72
+ afterEach(() => {
73
+ process.argv = [...ORIGINAL_ARGV];
74
+ if (ORIGINAL_LOCKFILE_DIR === undefined)
75
+ delete process.env.VELLUM_LOCKFILE_DIR;
76
+ else process.env.VELLUM_LOCKFILE_DIR = ORIGINAL_LOCKFILE_DIR;
77
+ if (ORIGINAL_CONFIG_HOME === undefined) delete process.env.XDG_CONFIG_HOME;
78
+ else process.env.XDG_CONFIG_HOME = ORIGINAL_CONFIG_HOME;
79
+ });
80
+
81
+ afterAll(() => {
82
+ rmSync(testDir, { recursive: true, force: true });
83
+ });
84
+
85
+ test("wake refuses a paired entry with a host-machine message", async () => {
86
+ process.argv = ["bun", "vellum", "wake", "px"];
87
+ const { exited, errors } = await runGuarded(wake);
88
+
89
+ expect(exited).toBe(true);
90
+ expect(errors).toContain("paired from another machine");
91
+ expect(errors).toContain("vellum client px");
92
+ // It must NOT fall through to the generic local/docker guard.
93
+ expect(errors).not.toContain("only works with local and docker");
94
+ });
95
+
96
+ test("sleep refuses a paired entry with a host-machine message", async () => {
97
+ process.argv = ["bun", "vellum", "sleep", "px"];
98
+ const { exited, errors } = await runGuarded(sleep);
99
+
100
+ expect(exited).toBe(true);
101
+ expect(errors).toContain("paired from another machine");
102
+ expect(errors).toContain("vellum client px");
103
+ expect(errors).not.toContain("only works with local and docker");
104
+ });
105
+
106
+ test("retire refuses a paired entry and points to unpair", async () => {
107
+ process.argv = ["bun", "vellum", "retire", "px", "--yes"];
108
+ const { exited, errors } = await runGuarded(retire);
109
+
110
+ expect(exited).toBe(true);
111
+ expect(errors).toContain("paired from another machine");
112
+ expect(errors).toContain("vellum unpair");
113
+ // It must NOT fall through to the generic "Unknown cloud type" path.
114
+ expect(errors).not.toContain("Unknown cloud type");
115
+ });
116
+ });
@@ -0,0 +1,307 @@
1
+ import {
2
+ afterAll,
3
+ afterEach,
4
+ beforeAll,
5
+ beforeEach,
6
+ describe,
7
+ expect,
8
+ mock,
9
+ spyOn,
10
+ test,
11
+ } from "bun:test";
12
+ import {
13
+ existsSync,
14
+ mkdirSync,
15
+ mkdtempSync,
16
+ rmSync,
17
+ writeFileSync,
18
+ } from "node:fs";
19
+ import { homedir, tmpdir } from "node:os";
20
+ import { basename, join } from "node:path";
21
+
22
+ import type { AssistantEntry } from "../lib/assistant-config.js";
23
+ import * as localModule from "../lib/local.js";
24
+ import * as stepRunnerModule from "../lib/step-runner.js";
25
+
26
+ // Captured real exports — afterAll restores these so module mocks don't
27
+ // leak into other test files in the same `bun test` run.
28
+ const realLocal = {
29
+ generateLocalSigningKey: localModule.generateLocalSigningKey,
30
+ startLocalDaemon: localModule.startLocalDaemon,
31
+ startGateway: localModule.startGateway,
32
+ };
33
+ const realExec = stepRunnerModule.exec;
34
+
35
+ // Prevent real daemon / gateway from starting
36
+ const startLocalDaemonMock = mock(async () => {});
37
+ const startGatewayMock = mock(async () => {});
38
+
39
+ // Capture exec calls without running real tar
40
+ const execMock = mock(async (_cmd: string, _args: string[]) => {});
41
+
42
+ beforeAll(() => {
43
+ mock.module("../lib/local.js", () => ({
44
+ generateLocalSigningKey: () => "deadbeefdeadbeefdeadbeefdeadbeef",
45
+ startLocalDaemon: startLocalDaemonMock,
46
+ startGateway: startGatewayMock,
47
+ }));
48
+ mock.module("../lib/step-runner.js", () => ({ exec: execMock }));
49
+ });
50
+
51
+ afterAll(() => {
52
+ mock.module("../lib/local.js", () => realLocal);
53
+ mock.module("../lib/step-runner.js", () => ({ exec: realExec }));
54
+ });
55
+
56
+ import { recover } from "../commands/recover.js";
57
+
58
+ // ── Test fixtures ─────────────────────────────────────────────────────────────
59
+
60
+ const testDir = mkdtempSync(join(tmpdir(), "cli-recover-test-"));
61
+ const originalArgv = [...process.argv];
62
+ const originalLockfileDir = process.env.VELLUM_LOCKFILE_DIR;
63
+ const originalXdgData = process.env.XDG_DATA_HOME;
64
+
65
+ // Directories that getRetiredDir() will use when XDG_DATA_HOME is overridden
66
+ const retiredDir = join(testDir, "vellum", "retired");
67
+
68
+ function makeEntry(assistantId: string, instanceDir: string): AssistantEntry {
69
+ return {
70
+ assistantId,
71
+ runtimeUrl: "http://127.0.0.1:7831",
72
+ cloud: "local",
73
+ resources: {
74
+ instanceDir,
75
+ daemonPort: 7801,
76
+ gatewayPort: 7831,
77
+ qdrantPort: 6334,
78
+ cesPort: 7790,
79
+ },
80
+ };
81
+ }
82
+
83
+ function writeArchiveFixtures(
84
+ name: string,
85
+ entry: AssistantEntry,
86
+ ): {
87
+ archivePath: string;
88
+ metadataPath: string;
89
+ extractedPath: string;
90
+ } {
91
+ mkdirSync(retiredDir, { recursive: true });
92
+ const archivePath = join(retiredDir, `${name}.tar.gz`);
93
+ const metadataPath = join(retiredDir, `${name}.json`);
94
+ // The staging dir is what tar extracts — <archive>.staging relative to retiredDir
95
+ const extractedPath = join(retiredDir, basename(archivePath) + ".staging");
96
+
97
+ // Write a placeholder archive file (exec is mocked; content doesn't matter)
98
+ writeFileSync(archivePath, "");
99
+ writeFileSync(metadataPath, JSON.stringify(entry, null, 2) + "\n");
100
+ // Create the staging dir that tar would have created
101
+ mkdirSync(extractedPath, { recursive: true });
102
+
103
+ return { archivePath, metadataPath, extractedPath };
104
+ }
105
+
106
+ let consoleLogSpy: ReturnType<typeof spyOn>;
107
+ let consoleErrorSpy: ReturnType<typeof spyOn>;
108
+ let exitSpy: ReturnType<typeof spyOn>;
109
+
110
+ beforeEach(() => {
111
+ // Route lockfile and retired archives to the temp directory
112
+ process.env.VELLUM_LOCKFILE_DIR = testDir;
113
+ process.env.XDG_DATA_HOME = testDir;
114
+ // Write an empty lockfile so saveAssistantEntry has a dir to write to
115
+ mkdirSync(testDir, { recursive: true });
116
+ writeFileSync(
117
+ join(testDir, ".vellum.lock.json"),
118
+ JSON.stringify({ assistants: [] }) + "\n",
119
+ );
120
+
121
+ consoleLogSpy = spyOn(console, "log").mockImplementation(() => {});
122
+ consoleErrorSpy = spyOn(console, "error").mockImplementation(() => {});
123
+ exitSpy = spyOn(process, "exit").mockImplementation((_code?: number) => {
124
+ throw new Error(`process.exit(${_code})`);
125
+ });
126
+
127
+ execMock.mockClear();
128
+ startLocalDaemonMock.mockClear();
129
+ startGatewayMock.mockClear();
130
+ });
131
+
132
+ afterEach(() => {
133
+ process.argv = [...originalArgv];
134
+ process.env.VELLUM_LOCKFILE_DIR = originalLockfileDir;
135
+ process.env.XDG_DATA_HOME = originalXdgData;
136
+ consoleLogSpy.mockRestore();
137
+ consoleErrorSpy.mockRestore();
138
+ exitSpy.mockRestore();
139
+ // Clean up per-test artifacts inside testDir/vellum/
140
+ if (existsSync(join(testDir, "vellum"))) {
141
+ rmSync(join(testDir, "vellum"), { recursive: true, force: true });
142
+ }
143
+ });
144
+
145
+ // Runs after all tests finish
146
+ afterAll(() => {
147
+ rmSync(testDir, { recursive: true, force: true });
148
+ process.argv = [...originalArgv];
149
+ if (originalLockfileDir !== undefined) {
150
+ process.env.VELLUM_LOCKFILE_DIR = originalLockfileDir;
151
+ } else {
152
+ delete process.env.VELLUM_LOCKFILE_DIR;
153
+ }
154
+ if (originalXdgData !== undefined) {
155
+ process.env.XDG_DATA_HOME = originalXdgData;
156
+ } else {
157
+ delete process.env.XDG_DATA_HOME;
158
+ }
159
+ });
160
+
161
+ // ── Tests ─────────────────────────────────────────────────────────────────────
162
+
163
+ describe("recover --help", () => {
164
+ test("prints usage, description, and examples then exits 0", async () => {
165
+ process.argv = ["bun", "vellum", "recover", "--help"];
166
+ await expect(recover()).rejects.toThrow("process.exit(0)");
167
+ const output = consoleLogSpy.mock.calls.flat().join("\n");
168
+ expect(output).toContain("Usage: vellum recover <name>");
169
+ expect(output).toContain("Examples:");
170
+ expect(output).toContain("vellum recover");
171
+ });
172
+ });
173
+
174
+ describe("recover error cases", () => {
175
+ test("exits 1 when no name is given", async () => {
176
+ process.argv = ["bun", "vellum", "recover"];
177
+ await expect(recover()).rejects.toThrow("process.exit(1)");
178
+ expect(consoleErrorSpy.mock.calls[0][0]).toContain("Usage:");
179
+ });
180
+
181
+ test("exits 1 when archive is missing", async () => {
182
+ process.argv = ["bun", "vellum", "recover", "ghost-assistant"];
183
+ await expect(recover()).rejects.toThrow("process.exit(1)");
184
+ expect(consoleErrorSpy.mock.calls[0][0]).toContain(
185
+ "No retired archive found for 'ghost-assistant'",
186
+ );
187
+ });
188
+
189
+ test("throws when metadata has no resources", async () => {
190
+ const name = "no-resources";
191
+ mkdirSync(retiredDir, { recursive: true });
192
+ writeFileSync(join(retiredDir, `${name}.tar.gz`), "");
193
+ const entry: Partial<AssistantEntry> = {
194
+ assistantId: name,
195
+ runtimeUrl: "http://127.0.0.1:7831",
196
+ cloud: "local",
197
+ // resources intentionally omitted
198
+ };
199
+ writeFileSync(
200
+ join(retiredDir, `${name}.json`),
201
+ JSON.stringify(entry, null, 2) + "\n",
202
+ );
203
+ process.argv = ["bun", "vellum", "recover", name];
204
+ await expect(recover()).rejects.toThrow("missing resource configuration");
205
+ });
206
+
207
+ test("exits 1 when target .vellum/ already exists", async () => {
208
+ const name = "already-exists";
209
+ const instanceDir = join(testDir, name);
210
+ const entry = makeEntry(name, instanceDir);
211
+ writeArchiveFixtures(name, entry);
212
+ // Pre-create the collision path that recover checks
213
+ mkdirSync(join(instanceDir, ".vellum"), { recursive: true });
214
+ process.argv = ["bun", "vellum", "recover", name];
215
+ await expect(recover()).rejects.toThrow("process.exit(1)");
216
+ expect(consoleErrorSpy.mock.calls[0][0]).toContain("already exists");
217
+ });
218
+ });
219
+
220
+ describe("recover extraction path — default instance (instanceDir === homedir())", () => {
221
+ test("extracts to retiredDir and renames staging dir to instanceDir/.vellum", async () => {
222
+ const name = "default-instance";
223
+ // Default instance: instanceDir is the real home directory
224
+ const entry = makeEntry(name, homedir());
225
+ const { archivePath, extractedPath } = writeArchiveFixtures(name, entry);
226
+
227
+ const expectedTargetDir = join(homedir(), ".vellum");
228
+
229
+ process.argv = ["bun", "vellum", "recover", name];
230
+ await recover();
231
+
232
+ // exec must have been called with -C retiredDir, NOT -C homedir()
233
+ expect(execMock).toHaveBeenCalledTimes(1);
234
+ const [cmd, args] = execMock.mock.calls[0] as [string, string[]];
235
+ expect(cmd).toBe("tar");
236
+ expect(args).toContain("-C");
237
+ const cIndex = args.indexOf("-C");
238
+ expect(args[cIndex + 1]).toBe(retiredDir);
239
+ expect(args[cIndex + 1]).not.toBe(homedir());
240
+
241
+ // Staging dir was renamed to the correct target
242
+ expect(existsSync(extractedPath)).toBe(false);
243
+ expect(existsSync(expectedTargetDir)).toBe(true);
244
+
245
+ // Archive and metadata were cleaned up
246
+ expect(existsSync(archivePath)).toBe(false);
247
+
248
+ // Daemon and gateway were started
249
+ expect(startLocalDaemonMock).toHaveBeenCalledTimes(1);
250
+ expect(startGatewayMock).toHaveBeenCalledTimes(1);
251
+
252
+ // Clean up so we don't leave a .vellum dir in the real home dir
253
+ rmSync(expectedTargetDir, { recursive: true, force: true });
254
+ });
255
+ });
256
+
257
+ describe("recover extraction path — named instance (instanceDir !== homedir())", () => {
258
+ test("extracts to retiredDir and renames staging dir to instanceDir directly", async () => {
259
+ const name = "named-instance";
260
+ const instanceDir = join(testDir, "custom-location", name);
261
+ const entry = makeEntry(name, instanceDir);
262
+ const { archivePath, extractedPath } = writeArchiveFixtures(name, entry);
263
+
264
+ // Named instance: targetDir is instanceDir itself (not instanceDir/.vellum)
265
+ const expectedTargetDir = instanceDir;
266
+ // Parent dir must exist for renameSync
267
+ mkdirSync(join(testDir, "custom-location"), { recursive: true });
268
+
269
+ process.argv = ["bun", "vellum", "recover", name];
270
+ await recover();
271
+
272
+ // exec must have been called with -C retiredDir
273
+ expect(execMock).toHaveBeenCalledTimes(1);
274
+ const [cmd, args] = execMock.mock.calls[0] as [string, string[]];
275
+ expect(cmd).toBe("tar");
276
+ const cIndex = args.indexOf("-C");
277
+ expect(args[cIndex + 1]).toBe(retiredDir);
278
+
279
+ // Staging dir was renamed to instanceDir (not instanceDir/.vellum)
280
+ expect(existsSync(extractedPath)).toBe(false);
281
+ expect(existsSync(expectedTargetDir)).toBe(true);
282
+
283
+ // Archive cleaned up
284
+ expect(existsSync(archivePath)).toBe(false);
285
+
286
+ // Daemon and gateway were started
287
+ expect(startLocalDaemonMock).toHaveBeenCalledTimes(1);
288
+ expect(startGatewayMock).toHaveBeenCalledTimes(1);
289
+ });
290
+
291
+ test("creates parent directories of instanceDir when they do not exist", async () => {
292
+ const name = "deep-nested-instance";
293
+ // Use a path whose parent directory does not yet exist
294
+ const instanceDir = join(testDir, "new-parent", "deeper", name);
295
+ const entry = makeEntry(name, instanceDir);
296
+ const { archivePath, extractedPath } = writeArchiveFixtures(name, entry);
297
+
298
+ process.argv = ["bun", "vellum", "recover", name];
299
+ await recover();
300
+
301
+ expect(existsSync(extractedPath)).toBe(false);
302
+ expect(existsSync(instanceDir)).toBe(true);
303
+ expect(existsSync(archivePath)).toBe(false);
304
+
305
+ rmSync(instanceDir, { recursive: true, force: true });
306
+ });
307
+ });
@@ -0,0 +1,37 @@
1
+ import { describe, test, expect } from "bun:test";
2
+ import { segmentsToPlainText } from "../lib/segments-to-plain-text.js";
3
+
4
+ describe("segmentsToPlainText", () => {
5
+ test("returns empty string for missing or empty segments", () => {
6
+ // GIVEN a message whose history payload carries no text segments
7
+ // WHEN deriving its flat body
8
+ // THEN it is the empty string (matching the daemon's old empty `content`)
9
+ expect(segmentsToPlainText(undefined)).toBe("");
10
+ expect(segmentsToPlainText([])).toBe("");
11
+ });
12
+
13
+ test("returns a single segment unchanged", () => {
14
+ // GIVEN a plain-text message with one segment
15
+ // WHEN deriving its flat body
16
+ // THEN the segment is returned verbatim
17
+ expect(segmentsToPlainText(["Real reply."])).toBe("Real reply.");
18
+ });
19
+
20
+ test("joins adjacent segments with a single inserted space", () => {
21
+ // GIVEN segments split at a tool_use boundary with no surrounding whitespace
22
+ // WHEN deriving the flat body
23
+ // THEN a single space is inserted between them
24
+ expect(segmentsToPlainText(["before", "after"])).toBe("before after");
25
+ });
26
+
27
+ test("does not double-space when either side already has whitespace", () => {
28
+ // GIVEN segments where one side already ends/starts with whitespace
29
+ // WHEN deriving the flat body
30
+ // THEN no extra space is inserted (mirrors daemon joinWithSpacing)
31
+ expect(segmentsToPlainText(["before ", "after"])).toBe("before after");
32
+ expect(segmentsToPlainText(["before", " after"])).toBe("before after");
33
+ expect(segmentsToPlainText(["line one\n", "line two"])).toBe(
34
+ "line one\nline two",
35
+ );
36
+ });
37
+ });
@@ -0,0 +1,166 @@
1
+ /**
2
+ * Tests for maybeRefreshAuthHeaders: the TUI's mid-session 401 -> refresh of a
3
+ * PAIRED assistant's guardian token, mutating the shared auth headers in place.
4
+ * Scoped to cloud:"paired"; skips local/docker, platform session auth, ephemeral
5
+ * --token, and access-only tokens.
6
+ */
7
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
8
+ import { mkdtempSync, rmSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+
12
+ const ORIGINAL_XDG = process.env.XDG_CONFIG_HOME;
13
+ const ORIGINAL_ENV = process.env.VELLUM_ENVIRONMENT;
14
+ const ORIGINAL_LOCKFILE_DIR = process.env.VELLUM_LOCKFILE_DIR;
15
+ const ORIGINAL_FETCH = globalThis.fetch;
16
+
17
+ import { maybeRefreshAuthHeaders } from "../components/DefaultMainScreen";
18
+ import { saveAssistantEntry } from "../lib/assistant-config";
19
+ import { saveGuardianToken } from "../lib/guardian-token";
20
+
21
+ const RUNTIME = "http://10.0.0.9:7830";
22
+ const future = () => new Date(Date.now() + 60 * 60 * 1000).toISOString();
23
+
24
+ function seedEntry(cloud: string): void {
25
+ saveAssistantEntry({
26
+ assistantId: "px",
27
+ name: "Paired",
28
+ runtimeUrl: RUNTIME,
29
+ cloud,
30
+ paired: cloud === "paired",
31
+ species: "vellum",
32
+ });
33
+ }
34
+
35
+ function seedToken(accessToken: string, refreshToken: string): void {
36
+ saveGuardianToken("px", {
37
+ guardianPrincipalId: "imported",
38
+ accessToken,
39
+ accessTokenExpiresAt: future(),
40
+ refreshToken,
41
+ refreshTokenExpiresAt: refreshToken ? future() : 0,
42
+ refreshAfter: "",
43
+ isNew: false,
44
+ deviceId: "dev",
45
+ leasedAt: new Date().toISOString(),
46
+ });
47
+ }
48
+
49
+ function stubRefresh(ok: boolean): { hit: () => boolean } {
50
+ let called = false;
51
+ globalThis.fetch = (async (url: unknown, _init?: RequestInit) => {
52
+ if (String(url).includes("/v1/guardian/refresh")) {
53
+ called = true;
54
+ return new Response(
55
+ ok ? JSON.stringify({ accessToken: "new-acc" }) : "x",
56
+ {
57
+ status: ok ? 200 : 401,
58
+ headers: { "content-type": "application/json" },
59
+ },
60
+ );
61
+ }
62
+ return new Response("", { status: 200 });
63
+ }) as typeof fetch;
64
+ return { hit: () => called };
65
+ }
66
+
67
+ describe("maybeRefreshAuthHeaders", () => {
68
+ let tempHome: string;
69
+
70
+ beforeEach(() => {
71
+ tempHome = mkdtempSync(join(tmpdir(), "tui-midsession-test-"));
72
+ process.env.XDG_CONFIG_HOME = tempHome;
73
+ // Isolate the lockfile too — saveAssistantEntry writes the prod lockfile
74
+ // (~/.vellum.lock.json) unless VELLUM_LOCKFILE_DIR is set, which would
75
+ // mutate the real user/CI lockfile.
76
+ process.env.VELLUM_LOCKFILE_DIR = tempHome;
77
+ delete process.env.VELLUM_ENVIRONMENT;
78
+ });
79
+
80
+ afterEach(() => {
81
+ globalThis.fetch = ORIGINAL_FETCH;
82
+ if (ORIGINAL_XDG === undefined) delete process.env.XDG_CONFIG_HOME;
83
+ else process.env.XDG_CONFIG_HOME = ORIGINAL_XDG;
84
+ if (ORIGINAL_LOCKFILE_DIR === undefined)
85
+ delete process.env.VELLUM_LOCKFILE_DIR;
86
+ else process.env.VELLUM_LOCKFILE_DIR = ORIGINAL_LOCKFILE_DIR;
87
+ if (ORIGINAL_ENV === undefined) delete process.env.VELLUM_ENVIRONMENT;
88
+ else process.env.VELLUM_ENVIRONMENT = ORIGINAL_ENV;
89
+ rmSync(tempHome, { recursive: true, force: true });
90
+ });
91
+
92
+ test("refreshes a paired assistant and mutates the auth header in place", async () => {
93
+ seedEntry("paired");
94
+ seedToken("old-acc", "ref");
95
+ const refresh = stubRefresh(true);
96
+ const auth = { Authorization: "Bearer old-acc" };
97
+
98
+ const ok = await maybeRefreshAuthHeaders(RUNTIME, "px", auth);
99
+
100
+ expect(ok).toBe(true);
101
+ expect(auth.Authorization).toBe("Bearer new-acc");
102
+ expect(refresh.hit()).toBe(true);
103
+ });
104
+
105
+ test("does NOT refresh a local assistant (scoped to paired only)", async () => {
106
+ seedEntry("local");
107
+ seedToken("old-acc", "ref"); // even with a refreshable token
108
+ const refresh = stubRefresh(true);
109
+ const auth = { Authorization: "Bearer old-acc" };
110
+
111
+ const ok = await maybeRefreshAuthHeaders(RUNTIME, "px", auth);
112
+
113
+ expect(ok).toBe(false);
114
+ expect(auth.Authorization).toBe("Bearer old-acc");
115
+ expect(refresh.hit()).toBe(false);
116
+ });
117
+
118
+ test("skips platform session auth (no Authorization header)", async () => {
119
+ seedEntry("paired");
120
+ seedToken("old-acc", "ref");
121
+ const refresh = stubRefresh(true);
122
+ const auth = { "X-Session-Token": "sess" };
123
+
124
+ const ok = await maybeRefreshAuthHeaders(RUNTIME, "px", auth);
125
+
126
+ expect(ok).toBe(false);
127
+ expect(refresh.hit()).toBe(false);
128
+ });
129
+
130
+ test("skips an ephemeral token that does not match the store", async () => {
131
+ seedEntry("paired");
132
+ seedToken("stored-acc", "ref");
133
+ const refresh = stubRefresh(true);
134
+ const auth = { Authorization: "Bearer ephemeral-acc" };
135
+
136
+ const ok = await maybeRefreshAuthHeaders(RUNTIME, "px", auth);
137
+
138
+ expect(ok).toBe(false);
139
+ expect(auth.Authorization).toBe("Bearer ephemeral-acc");
140
+ expect(refresh.hit()).toBe(false);
141
+ });
142
+
143
+ test("skips an access-only token (no refresh credential)", async () => {
144
+ seedEntry("paired");
145
+ seedToken("old-acc", ""); // no refresh token
146
+ const refresh = stubRefresh(true);
147
+ const auth = { Authorization: "Bearer old-acc" };
148
+
149
+ const ok = await maybeRefreshAuthHeaders(RUNTIME, "px", auth);
150
+
151
+ expect(ok).toBe(false);
152
+ expect(refresh.hit()).toBe(false);
153
+ });
154
+
155
+ test("returns false and leaves auth unchanged when refresh fails", async () => {
156
+ seedEntry("paired");
157
+ seedToken("old-acc", "ref");
158
+ stubRefresh(false); // refresh endpoint returns non-ok
159
+ const auth = { Authorization: "Bearer old-acc" };
160
+
161
+ const ok = await maybeRefreshAuthHeaders(RUNTIME, "px", auth);
162
+
163
+ expect(ok).toBe(false);
164
+ expect(auth.Authorization).toBe("Bearer old-acc");
165
+ });
166
+ });