@neuralnomads/codenomad-dev 0.18.0-dev-20260715-07e8ce68 → 0.18.0-dev-20260718-8f6aa44b

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 (94) hide show
  1. package/README.md +12 -0
  2. package/THIRD_PARTY_NOTICES.md +26 -0
  3. package/dist/auth/manager.js +1 -1
  4. package/dist/events/bus.js +13 -0
  5. package/dist/events/bus.test.js +37 -0
  6. package/dist/filesystem/__tests__/search-cache.test.js +5 -5
  7. package/dist/filesystem/search-cache.js +1 -1
  8. package/dist/index.js +58 -56
  9. package/dist/index.test.js +62 -0
  10. package/dist/opencode-update/service.js +150 -0
  11. package/dist/opencode-update/service.test.js +107 -0
  12. package/dist/server/__tests__/remote-proxy.test.js +151 -47
  13. package/dist/server/http-server.js +9 -1
  14. package/dist/server/remote-proxy.js +91 -34
  15. package/dist/server/routes/opencode-update.js +37 -0
  16. package/dist/server/routes/opencode-update.test.js +34 -0
  17. package/dist/server/routes/remote-servers.js +1 -1
  18. package/dist/server/routes/usage.js +18 -0
  19. package/dist/server/routes/usage.test.js +26 -0
  20. package/dist/server/routes/workspaces.js +32 -1
  21. package/dist/server/routes/workspaces.test.js +113 -0
  22. package/dist/server/tls.js +2 -2
  23. package/dist/settings/binaries.js +4 -1
  24. package/dist/settings/binaries.test.js +19 -0
  25. package/dist/shutdown.js +83 -0
  26. package/dist/shutdown.test.js +148 -0
  27. package/dist/ui/remote-ui.js +2 -2
  28. package/dist/usage/providers/api-key.js +171 -0
  29. package/dist/usage/providers/google.js +171 -0
  30. package/dist/usage/providers/minimax.js +109 -0
  31. package/dist/usage/providers/oauth.js +111 -0
  32. package/dist/usage/providers/special.js +148 -0
  33. package/dist/usage/service.js +83 -0
  34. package/dist/usage/service.test.js +59 -0
  35. package/dist/usage/shared.js +130 -0
  36. package/dist/usage/shared.test.js +33 -0
  37. package/dist/usage/types.js +1 -0
  38. package/dist/workspaces/__tests__/spawn.test.js +64 -7
  39. package/dist/workspaces/__tests__/workspace-identity.test.js +99 -139
  40. package/dist/workspaces/binary-path.test.js +10 -0
  41. package/dist/workspaces/instance-client.js +4 -3
  42. package/dist/workspaces/launch-cleanup.test.js +29 -0
  43. package/dist/workspaces/manager.js +399 -192
  44. package/dist/workspaces/manager.test.js +290 -0
  45. package/dist/workspaces/process-identity.darwin.test.js +88 -0
  46. package/dist/workspaces/process-identity.js +431 -0
  47. package/dist/workspaces/process-identity.test.js +111 -0
  48. package/dist/workspaces/runtime.js +471 -138
  49. package/dist/workspaces/runtime.test.js +278 -0
  50. package/dist/workspaces/spawn.js +86 -15
  51. package/package.json +1 -1
  52. package/public/assets/{FilesTab-EPvldvn1.js → FilesTab-B0-DlSCT.js} +2 -2
  53. package/public/assets/{GitChangesTab-ofjovmv2.js → GitChangesTab-CxjbNBVr.js} +2 -2
  54. package/public/assets/{SplitFilePanel-CyoPkcLd.js → SplitFilePanel-CLQb-6uX.js} +1 -1
  55. package/public/assets/StatusTab-CBGAuhmp.js +1 -0
  56. package/public/assets/{align-justify-Bcf1-ZOl.js → align-justify-s5mnjsP0.js} +1 -1
  57. package/public/assets/{bundle-full-D5dzvToA.js → bundle-full-lwIMY5om.js} +1 -1
  58. package/public/assets/{diff-viewer-DViXCI-4.js → diff-viewer-CDtmFe6e.js} +1 -1
  59. package/public/assets/{git-diff-vendor-CSgooKT_.js → git-diff-vendor-CYS3ApzA.js} +1 -1
  60. package/public/assets/index-6ABz_Izb.js +1 -0
  61. package/public/assets/index-BPdjM9ZI.css +1 -0
  62. package/public/assets/index-BQK8um1r.js +1 -0
  63. package/public/assets/index-BkUAI4ZY.js +1 -0
  64. package/public/assets/index-D8bkUvEd.js +2 -0
  65. package/public/assets/index-DY_sbCt9.js +1 -0
  66. package/public/assets/index-DhmUOdAI.js +1 -0
  67. package/public/assets/{index-UbL8tz_V.js → index-DupnEKCQ.js} +1 -1
  68. package/public/assets/index-HhZzWWha.js +1 -0
  69. package/public/assets/{index-lf4nUOU1.js → index-lBAEWdAF.js} +1 -1
  70. package/public/assets/index-nVII4VJz.js +1 -0
  71. package/public/assets/index-p1Sble5V.js +1 -0
  72. package/public/assets/{loading-CZ_tt3h0.js → loading-h8DvUqqc.js} +1 -1
  73. package/public/assets/main-BxUSjoWA.js +68 -0
  74. package/public/assets/{markdown-G11aN6hz.js → markdown-Djug_spc.js} +55 -44
  75. package/public/assets/monaco-viewer-lkUcsK65.js +26 -0
  76. package/public/assets/{tool-call-BsSXWErm.js → tool-call-C4YH896w.js} +32 -32
  77. package/public/assets/{unified-picker-BRNI3UvE.js → unified-picker-DwNZOVlY.js} +1 -1
  78. package/public/assets/{wrap-text-B7up-uv7.js → wrap-text-BLVYxvcj.js} +1 -1
  79. package/public/index.html +5 -5
  80. package/public/loading.html +5 -5
  81. package/public/sw.js +1 -1
  82. package/public/assets/StatusTab-Bgu1Fh24.js +0 -1
  83. package/public/assets/index-3KsjbWGP.js +0 -1
  84. package/public/assets/index-B0WK8-cF.js +0 -1
  85. package/public/assets/index-BDv_iVtj.js +0 -1
  86. package/public/assets/index-BMvFMsuy.css +0 -1
  87. package/public/assets/index-BjxZvyb9.js +0 -2
  88. package/public/assets/index-BleKf9Nj.js +0 -1
  89. package/public/assets/index-CiIQ43NW.js +0 -1
  90. package/public/assets/index-DBquqL6Q.js +0 -1
  91. package/public/assets/index-yf9zolv4.js +0 -1
  92. package/public/assets/index-ypaL7i_s.js +0 -1
  93. package/public/assets/main-CAkg_fp_.js +0 -68
  94. package/public/assets/monaco-viewer-CZefBfct.js +0 -26
@@ -0,0 +1,130 @@
1
+ import fs from "fs";
2
+ import os from "os";
3
+ import path from "path";
4
+ const REQUEST_TIMEOUT_MS = 15_000;
5
+ function authFileCandidates() {
6
+ const home = os.homedir();
7
+ const candidates = [
8
+ process.env.OPENCODE_AUTH_FILE,
9
+ process.env.OPENCODE_DATA_DIR ? path.join(process.env.OPENCODE_DATA_DIR, "auth.json") : undefined,
10
+ process.env.XDG_DATA_HOME ? path.join(process.env.XDG_DATA_HOME, "opencode", "auth.json") : undefined,
11
+ path.join(home, ".local", "share", "opencode", "auth.json"),
12
+ process.env.LOCALAPPDATA ? path.join(process.env.LOCALAPPDATA, "opencode", "Data", "auth.json") : undefined,
13
+ process.env.APPDATA ? path.join(process.env.APPDATA, "opencode", "auth.json") : undefined,
14
+ path.join(home, "Library", "Application Support", "opencode", "auth.json"),
15
+ ];
16
+ return Array.from(new Set(candidates.filter((candidate) => Boolean(candidate))));
17
+ }
18
+ export function readOpenCodeAuth() {
19
+ for (const candidate of authFileCandidates()) {
20
+ try {
21
+ const parsed = JSON.parse(fs.readFileSync(candidate, "utf8"));
22
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
23
+ return parsed;
24
+ }
25
+ catch (error) {
26
+ if (error.code !== "ENOENT")
27
+ continue;
28
+ }
29
+ }
30
+ return {};
31
+ }
32
+ export function getAuthEntry(aliases) {
33
+ const auth = readOpenCodeAuth();
34
+ for (const alias of aliases) {
35
+ const value = auth[alias];
36
+ if (typeof value === "string" && value.trim())
37
+ return { token: value.trim() };
38
+ if (value && typeof value === "object" && !Array.isArray(value))
39
+ return value;
40
+ }
41
+ return null;
42
+ }
43
+ export function getString(value) {
44
+ return typeof value === "string" && value.trim() ? value.trim() : null;
45
+ }
46
+ export function getCredential(aliases, fields) {
47
+ const entry = getAuthEntry(aliases);
48
+ if (!entry)
49
+ return null;
50
+ for (const field of fields) {
51
+ const value = getString(entry[field]);
52
+ if (value)
53
+ return value;
54
+ }
55
+ return null;
56
+ }
57
+ export function asObject(value) {
58
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
59
+ }
60
+ export function toNumber(value) {
61
+ if (typeof value === "number" && Number.isFinite(value))
62
+ return value;
63
+ if (typeof value === "string" && value.trim()) {
64
+ const parsed = Number(value);
65
+ return Number.isFinite(parsed) ? parsed : null;
66
+ }
67
+ return null;
68
+ }
69
+ export function toTimestamp(value) {
70
+ if (typeof value === "number" && Number.isFinite(value))
71
+ return value < 1_000_000_000_000 ? value * 1000 : value;
72
+ if (typeof value === "string" && value.trim()) {
73
+ const parsed = Date.parse(value);
74
+ return Number.isNaN(parsed) ? null : parsed;
75
+ }
76
+ return null;
77
+ }
78
+ export function toUsageWindow(input) {
79
+ const usedPercent = input.usedPercent === null ? null : Math.max(0, Math.min(100, input.usedPercent));
80
+ return {
81
+ usedPercent,
82
+ remainingPercent: usedPercent === null ? null : 100 - usedPercent,
83
+ windowSeconds: input.windowSeconds ?? null,
84
+ resetAt: input.resetAt ?? null,
85
+ ...(input.valueLabel ? { valueLabel: input.valueLabel } : {}),
86
+ };
87
+ }
88
+ export function resolveWindowLabel(windowSeconds) {
89
+ if (!windowSeconds)
90
+ return "usage";
91
+ if (windowSeconds % 86_400 === 0) {
92
+ const days = windowSeconds / 86_400;
93
+ return days === 7 ? "weekly" : `${days}d`;
94
+ }
95
+ if (windowSeconds % 3600 === 0)
96
+ return `${windowSeconds / 3600}h`;
97
+ return `${windowSeconds}s`;
98
+ }
99
+ export function result(providerId, providerName, input) {
100
+ return {
101
+ providerId,
102
+ providerName,
103
+ ok: input.ok,
104
+ configured: input.configured,
105
+ usage: input.usage ?? null,
106
+ fetchedAt: Date.now(),
107
+ ...(input.error ? { error: input.error } : {}),
108
+ };
109
+ }
110
+ export function notConfigured(providerId, providerName) {
111
+ return result(providerId, providerName, { ok: false, configured: false, error: "Not configured" });
112
+ }
113
+ export async function fetchJson(url, init = {}) {
114
+ const response = await fetch(url, { ...init, signal: init.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
115
+ if (!response.ok)
116
+ throw new Error(`Provider returned HTTP ${response.status}`);
117
+ return response.json();
118
+ }
119
+ export async function safeFetch(providerId, providerName, operation) {
120
+ try {
121
+ return result(providerId, providerName, { ok: true, configured: true, usage: await operation() });
122
+ }
123
+ catch (error) {
124
+ return result(providerId, providerName, {
125
+ ok: false,
126
+ configured: true,
127
+ error: error instanceof Error ? error.message : "Request failed",
128
+ });
129
+ }
130
+ }
@@ -0,0 +1,33 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import { getCredential, readOpenCodeAuth, toTimestamp, toUsageWindow } from "./shared";
7
+ test("reads the explicit OpenCode auth file without exposing credentials through the API", () => {
8
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-usage-"));
9
+ const authFile = path.join(directory, "auth.json");
10
+ const previous = process.env.OPENCODE_AUTH_FILE;
11
+ fs.writeFileSync(authFile, JSON.stringify({ anthropic: { type: "oauth", access: "secret-token" } }));
12
+ process.env.OPENCODE_AUTH_FILE = authFile;
13
+ try {
14
+ assert.equal(readOpenCodeAuth().anthropic.access, "secret-token");
15
+ assert.equal(getCredential(["anthropic"], ["access"]), "secret-token");
16
+ }
17
+ finally {
18
+ if (previous === undefined)
19
+ delete process.env.OPENCODE_AUTH_FILE;
20
+ else
21
+ process.env.OPENCODE_AUTH_FILE = previous;
22
+ fs.rmSync(directory, { recursive: true, force: true });
23
+ }
24
+ });
25
+ test("normalizes percentages and timestamps", () => {
26
+ assert.deepEqual(toUsageWindow({ usedPercent: 120, resetAt: null }), {
27
+ usedPercent: 100,
28
+ remainingPercent: 0,
29
+ windowSeconds: null,
30
+ resetAt: null,
31
+ });
32
+ assert.equal(toTimestamp(1_700_000_000), 1_700_000_000_000);
33
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -1,6 +1,9 @@
1
1
  import assert from "node:assert/strict";
2
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import path from "node:path";
2
5
  import { describe, it } from "node:test";
3
- import { buildWindowsSpawnSpec, buildWslSignalSpec, parseWslUncPath, resolveWslWorkingDirectory } from "../spawn";
6
+ import { buildWindowsSpawnSpec, parseWslUncPath, resolveWslWorkingDirectory } from "../spawn";
4
7
  describe("parseWslUncPath", () => {
5
8
  it("parses WSL UNC paths into distro and linux path", () => {
6
9
  assert.deepEqual(parseWslUncPath(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`), {
@@ -30,6 +33,62 @@ describe("resolveWslWorkingDirectory", () => {
30
33
  });
31
34
  });
32
35
  describe("buildWindowsSpawnSpec", () => {
36
+ it("classifies native executables separately from script and shell wrappers", () => {
37
+ assert.equal(buildWindowsSpawnSpec("opencode.exe", []).processKind, "windows-direct");
38
+ assert.equal(buildWindowsSpawnSpec("opencode.cmd", []).processKind, "windows-wrapper");
39
+ assert.equal(buildWindowsSpawnSpec("powershell.exe", []).processKind, "windows-wrapper");
40
+ });
41
+ it("conservatively classifies bare commands as wrappers", () => {
42
+ assert.equal(buildWindowsSpawnSpec("opencode", []).processKind, "windows-wrapper");
43
+ });
44
+ it("resolves a bare cmd shim from a quoted PATH entry and wraps its absolute path", { skip: process.platform !== "win32" }, () => {
45
+ const root = mkdtempSync(path.join(tmpdir(), "codenomad-spawn-"));
46
+ const cwd = path.join(root, "workspace");
47
+ const bin = path.join(root, "bin with spaces");
48
+ mkdirSync(cwd);
49
+ mkdirSync(bin);
50
+ const shim = path.join(bin, "opencode.cmd");
51
+ writeFileSync(shim, "@echo off\r\n");
52
+ try {
53
+ const spec = buildWindowsSpawnSpec("opencode", ["serve"], {
54
+ cwd,
55
+ env: { Path: `"${bin}"`, PathExt: ".CMD;.EXE", ComSpec: "test-cmd.exe" },
56
+ });
57
+ assert.equal(spec.command, "test-cmd.exe");
58
+ assert.equal(spec.processKind, "windows-wrapper");
59
+ assert.equal(spec.options.windowsVerbatimArguments, true);
60
+ assert.match(spec.args[3] ?? "", new RegExp(escapeRegex(path.win32.resolve(shim)), "i"));
61
+ }
62
+ finally {
63
+ rmSync(root, { recursive: true, force: true });
64
+ }
65
+ });
66
+ it("honors PATHEXT precedence when both native and shim files exist", { skip: process.platform !== "win32" }, () => {
67
+ const root = mkdtempSync(path.join(tmpdir(), "codenomad-spawn-"));
68
+ writeFileSync(path.join(root, "opencode.cmd"), "@echo off\r\n");
69
+ writeFileSync(path.join(root, "opencode.exe"), "");
70
+ try {
71
+ const spec = buildWindowsSpawnSpec("opencode", [], {
72
+ cwd: root,
73
+ env: { PATH: "", PATHEXT: ".EXE;.CMD" },
74
+ });
75
+ assert.equal(spec.command.toLowerCase(), path.win32.resolve(root, "opencode.exe").toLowerCase());
76
+ assert.equal(spec.processKind, "windows-direct");
77
+ }
78
+ finally {
79
+ rmSync(root, { recursive: true, force: true });
80
+ }
81
+ });
82
+ it("leaves an unresolved bare command unchanged without injecting a shell", () => {
83
+ const spec = buildWindowsSpawnSpec("missing-opencode", ["serve"], {
84
+ cwd: String.raw `C:\missing-workspace`,
85
+ env: { PATH: "", PATHEXT: ".CMD;.EXE", ComSpec: "must-not-run.exe" },
86
+ });
87
+ assert.equal(spec.command, "missing-opencode");
88
+ assert.deepEqual(spec.args, ["serve"]);
89
+ assert.equal(spec.processKind, "windows-wrapper");
90
+ assert.equal(spec.options.windowsVerbatimArguments, undefined);
91
+ });
33
92
  it("wraps WSL binaries with wsl.exe and propagates required env vars", () => {
34
93
  const spec = buildWindowsSpawnSpec(String.raw `\\wsl.localhost\Ubuntu\home\dev\.opencode\bin\opencode`, ["serve", "--port", "0"], {
35
94
  cwd: String.raw `\\wsl.localhost\Ubuntu\home\dev\workspace`,
@@ -142,7 +201,7 @@ describe("buildWindowsSpawnSpec", () => {
142
201
  "--exec",
143
202
  "sh",
144
203
  "-lc",
145
- `printf '%s%s\\n' '__CODENOMAD_WSL_PID__:' "$$" && cd "$1" && shift && exec "$@"`,
204
+ `codenomad_pgid=$(ps -o pgid= -p "$$" 2>/dev/null | tr -d '[:space:]'); codenomad_start=$(awk '{print $22}' "/proc/$$/stat" 2>/dev/null); codenomad_boot=$(cat /proc/sys/kernel/random/boot_id 2>/dev/null); test -n "$codenomad_pgid" && test -n "$codenomad_start" && test -n "$codenomad_boot" && printf '%s%s:%s:%s:%s\\n' '__CODENOMAD_WSL_PID__:' "$$" "$codenomad_pgid" "$codenomad_start" "$codenomad_boot" && cd "$1" && shift && exec "$@"`,
146
205
  "codenomad-wsl-launch",
147
206
  "/home/dev/workspace",
148
207
  "/home/dev/.opencode/bin/opencode",
@@ -150,9 +209,7 @@ describe("buildWindowsSpawnSpec", () => {
150
209
  ]);
151
210
  assert.equal(spec.wsl?.pidMarker, "__CODENOMAD_WSL_PID__:");
152
211
  });
153
- it("builds the WSL kill command for tracked Linux PIDs", () => {
154
- const spec = buildWslSignalSpec("Ubuntu", 4321, "SIGTERM");
155
- assert.equal(spec.command, "wsl.exe");
156
- assert.deepEqual(spec.args, ["--distribution", "Ubuntu", "--exec", "kill", "-TERM", "4321"]);
157
- });
158
212
  });
213
+ function escapeRegex(value) {
214
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
215
+ }
@@ -8,14 +8,16 @@ import { EventBus } from "../../events/bus";
8
8
  import { WorkspaceManager } from "../manager";
9
9
  import { normalizeWorkspaceIdentityPath, resolveWorkspaceIdentity } from "../workspace-identity";
10
10
  const temporaryDirectories = [];
11
+ const runtimeResult = (pid = 123) => ({
12
+ pid,
13
+ port: 4321,
14
+ exitPromise: new Promise(() => undefined),
15
+ getLastOutput: () => "",
16
+ });
11
17
  function deferred() {
12
18
  let resolve;
13
- let reject;
14
- const promise = new Promise((resolvePromise, rejectPromise) => {
15
- resolve = resolvePromise;
16
- reject = rejectPromise;
17
- });
18
- return { promise, resolve, reject };
19
+ const promise = new Promise((resolvePromise) => { resolve = resolvePromise; });
20
+ return { promise, resolve };
19
21
  }
20
22
  afterEach(async () => {
21
23
  await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })));
@@ -34,170 +36,128 @@ function createManager(rootDir) {
34
36
  const manager = new WorkspaceManager({
35
37
  rootDir,
36
38
  settings: { getOwner: () => ({ environmentVariables: {} }) },
37
- binaryResolver: {
38
- resolveDefault: () => ({ path: process.execPath, label: "Node.js", version: process.version }),
39
- },
39
+ binaryResolver: { resolve: () => ({ path: process.execPath, label: "Node.js", version: process.version }) },
40
40
  eventBus: new EventBus(logger),
41
41
  logger,
42
42
  getServerBaseUrl: () => "http://127.0.0.1:3000",
43
43
  });
44
- const internal = manager;
45
- internal.runtime.launch = async () => ({
46
- pid: 123,
47
- port: 4321,
48
- exitPromise: new Promise(() => { }),
49
- getLastOutput: () => "",
50
- });
51
- internal.waitForWorkspaceReadiness = async () => undefined;
44
+ manager.runtime.launch = async () => runtimeResult();
45
+ manager.runtime.stop = async () => undefined;
46
+ manager.waitForWorkspaceReadiness = async () => undefined;
52
47
  return manager;
53
48
  }
49
+ async function waitForOwners(manager, count) {
50
+ while ([...manager.pendingWorkspaceCreations.values()][0]?.ownership.size !== count) {
51
+ await new Promise((resolve) => setImmediate(resolve));
52
+ }
53
+ }
54
+ async function createSharedLaunch() {
55
+ const { root, target, link } = await createLinkedWorkspace();
56
+ const manager = createManager(root);
57
+ const launchGate = deferred();
58
+ let launches = 0;
59
+ manager.runtime.launch = async () => {
60
+ launches += 1;
61
+ await launchGate.promise;
62
+ return runtimeResult();
63
+ };
64
+ const leader = manager.create(target, undefined, { requestId: "leader" });
65
+ const follower = manager.create(link, undefined, { requestId: "follower" });
66
+ await waitForOwners(manager, 2);
67
+ return { manager, launchGate, leader, follower, launches: () => launches };
68
+ }
54
69
  describe("workspace identity", () => {
55
- it("normalizes Windows drive and UNC paths without affecting POSIX case", () => {
70
+ it("normalizes Windows paths without affecting POSIX case", () => {
56
71
  assert.equal(normalizeWorkspaceIdentityPath("C:\\Projects\\CodeNomad\\", "win32"), "c:\\projects\\codenomad\\");
57
72
  assert.equal(normalizeWorkspaceIdentityPath(String.raw `\\Server\Share\Repo`, "win32"), String.raw `\\server\share\repo`);
58
73
  assert.equal(normalizeWorkspaceIdentityPath("/Projects/CodeNomad/", "linux"), "/Projects/CodeNomad/");
59
74
  });
60
- it("resolves a symlink and its target to the same canonical launch path", async () => {
75
+ it("canonicalizes aliases and falls back to an absolute identity for missing paths", async () => {
61
76
  const { root, target, link } = await createLinkedWorkspace();
62
- const targetResult = await resolveWorkspaceIdentity(target, root);
63
- const linkResult = await resolveWorkspaceIdentity(link, root);
77
+ const [targetResult, linkResult, missing] = await Promise.all([
78
+ resolveWorkspaceIdentity(target, root),
79
+ resolveWorkspaceIdentity(link, root),
80
+ resolveWorkspaceIdentity("missing", root),
81
+ ]);
82
+ const expectedMissing = path.resolve(root, "missing");
64
83
  assert.equal(linkResult.identityKey, targetResult.identityKey);
65
84
  assert.equal(linkResult.workspacePath, targetResult.workspacePath);
66
- assert.notEqual(linkResult.workspacePath, path.normalize(link));
67
- });
68
- it("falls back to a normalized absolute identity when realpath fails", async () => {
69
- const root = await mkdtemp(path.join(os.tmpdir(), "codenomad-workspace-missing-"));
70
- temporaryDirectories.push(root);
71
- const result = await resolveWorkspaceIdentity("missing", root);
72
- const expected = path.resolve(root, "missing");
73
- assert.equal(result.workspacePath, expected);
74
- assert.equal(result.identityKey, normalizeWorkspaceIdentityPath(expected));
75
- });
76
- it("atomically reuses an active workspace reached through a symlink", async () => {
77
- const { root, target, link } = await createLinkedWorkspace();
78
- const manager = createManager(root);
79
- const [targetResult, linkResult] = await Promise.all([manager.create(target), manager.create(link)]);
80
- assert.equal(Number(targetResult.created) + Number(linkResult.created), 1);
81
- assert.equal(targetResult.workspace.id, linkResult.workspace.id);
82
- assert.equal(manager.list().length, 1);
85
+ assert.equal(missing.workspacePath, expectedMissing);
86
+ assert.equal(missing.identityKey, normalizeWorkspaceIdentityPath(expectedMissing));
83
87
  });
84
- it("shares an in-flight startup between canonical aliases", async () => {
88
+ it("deduplicates active canonical aliases", async () => {
85
89
  const { root, target, link } = await createLinkedWorkspace();
86
90
  const manager = createManager(root);
87
- let launches = 0;
88
- manager.runtime.launch = async () => {
89
- launches += 1;
90
- await new Promise((resolve) => setTimeout(resolve, 20));
91
- return {
92
- pid: 123,
93
- port: 4321,
94
- exitPromise: new Promise(() => { }),
95
- getLastOutput: () => "",
96
- };
97
- };
98
91
  const [first, second] = await Promise.all([manager.create(target), manager.create(link)]);
99
- assert.equal(launches, 1);
100
92
  assert.equal(Number(first.created) + Number(second.created), 1);
101
93
  assert.equal(first.workspace.id, second.workspace.id);
102
- assert.equal(first.workspace.status, "ready");
103
- assert.equal(second.workspace.status, "ready");
94
+ assert.equal(manager.list().length, 1);
95
+ });
96
+ it("shares one in-flight launch between canonical aliases", async () => {
97
+ const shared = await createSharedLaunch();
98
+ shared.launchGate.resolve();
99
+ const [leader, follower] = await Promise.all([shared.leader, shared.follower]);
100
+ assert.equal(shared.launches(), 1);
101
+ assert.equal(leader.workspace.id, follower.workspace.id);
102
+ assert.equal(Number(leader.created) + Number(follower.created), 1);
103
+ assert.equal(leader.workspace.status, "ready");
104
104
  });
105
- it("releases a failed identity reservation so creation can be retried", async () => {
105
+ for (const cancelledRole of ["leader", "follower"]) {
106
+ it(`detaches a cancelled ${cancelledRole} without stopping its shared owner`, async () => {
107
+ const shared = await createSharedLaunch();
108
+ await shared.manager.cancelCreationRequest(cancelledRole);
109
+ shared.launchGate.resolve();
110
+ const cancelled = shared[cancelledRole];
111
+ const survivor = shared[cancelledRole === "leader" ? "follower" : "leader"];
112
+ await assert.rejects(cancelled, new RegExp(`creation request ${cancelledRole} was cancelled`));
113
+ const result = await survivor;
114
+ assert.equal(shared.launches(), 1);
115
+ assert.equal(result.workspace.requestId, cancelledRole === "leader" ? "follower" : "leader");
116
+ assert.equal(shared.manager.list().length, 1);
117
+ });
118
+ }
119
+ for (const releasedRole of ["leader", "follower"]) {
120
+ it(`retains shared ownership when the ${releasedRole} releases and the other owner cancels`, async () => {
121
+ const shared = await createSharedLaunch();
122
+ shared.launchGate.resolve();
123
+ const [leader, follower] = await Promise.all([shared.leader, shared.follower]);
124
+ assert.equal(leader.workspace.id, follower.workspace.id);
125
+ assert.equal(shared.manager.releaseCreationRequest(leader.workspace.id, releasedRole), true);
126
+ await shared.manager.cancelCreationRequest(releasedRole === "leader" ? "follower" : "leader");
127
+ assert.equal(shared.manager.list().length, 1);
128
+ assert.equal(shared.manager.get(leader.workspace.id)?.requestId, undefined);
129
+ });
130
+ }
131
+ it("releases a failed canonical reservation for retry", async () => {
106
132
  const { root, target, link } = await createLinkedWorkspace();
107
133
  const manager = createManager(root);
134
+ const launchGate = deferred();
108
135
  let launches = 0;
109
136
  manager.runtime.launch = async () => {
110
137
  launches += 1;
111
- await new Promise((resolve) => setTimeout(resolve, 20));
138
+ await launchGate.promise;
112
139
  throw new Error("launch failed");
113
140
  };
114
- const failed = await Promise.allSettled([manager.create(target), manager.create(link)]);
115
- assert.deepEqual(failed.map((result) => result.status), ["rejected", "rejected"]);
141
+ const failures = [
142
+ manager.create(target, undefined, { requestId: "first" }),
143
+ manager.create(link, undefined, { requestId: "second" }),
144
+ ];
145
+ await waitForOwners(manager, 2);
146
+ launchGate.resolve();
147
+ assert.deepEqual((await Promise.allSettled(failures)).map((result) => result.status), ["rejected", "rejected"]);
116
148
  assert.equal(launches, 1);
117
- manager.runtime.launch = async () => ({
118
- pid: 456,
119
- port: 5432,
120
- exitPromise: new Promise(() => { }),
121
- getLastOutput: () => "",
122
- });
123
- const retry = await manager.create(target);
124
- assert.equal(retry.created, true);
125
- assert.equal(retry.workspace.status, "ready");
126
- });
127
- it("allows an explicit second workspace for the same canonical path", async () => {
128
- const { root, target, link } = await createLinkedWorkspace();
129
- const manager = createManager(root);
130
- const [first, second] = await Promise.all([
131
- manager.create(target, undefined, { forceNew: true }),
132
- manager.create(link, undefined, { forceNew: true }),
133
- ]);
134
- assert.equal(first.created, true);
135
- assert.equal(second.created, true);
136
- assert.notEqual(first.workspace.id, second.workspace.id);
137
- assert.equal(manager.list().length, 2);
149
+ manager.runtime.launch = async () => runtimeResult(456);
150
+ assert.equal((await manager.create(target)).created, true);
138
151
  });
139
- it("keeps the canonical reservation when a forced duplicate is deleted", async () => {
152
+ it("allows forced canonical duplicates without replacing the reusable workspace", async () => {
140
153
  const { root, target, link } = await createLinkedWorkspace();
141
154
  const manager = createManager(root);
142
- const normalLaunch = deferred();
143
- const forcedLaunch = deferred();
144
- let launches = 0;
145
- manager.runtime.launch = () => {
146
- launches += 1;
147
- return launches === 1 ? normalLaunch.promise : forcedLaunch.promise;
148
- };
149
- const first = manager.create(target);
150
- while (manager.list().length < 1) {
151
- await new Promise((resolve) => setImmediate(resolve));
152
- }
153
- const forced = manager.create(link, undefined, { forceNew: true });
154
- const forcedRejected = assert.rejects(forced, /Workspace creation cancelled/);
155
- while (manager.list().length < 2) {
156
- await new Promise((resolve) => setImmediate(resolve));
157
- }
158
- const forcedWorkspace = manager.list().find((workspace) => workspace.id !== manager.list()[0].id);
159
- await manager.delete(forcedWorkspace.id);
160
- const reused = manager.create(link);
161
- normalLaunch.resolve({ pid: 123, port: 4321, exitPromise: new Promise(() => { }), getLastOutput: () => "" });
162
- forcedLaunch.resolve({ pid: 456, port: 5432, exitPromise: new Promise(() => { }), getLastOutput: () => "" });
163
- const [firstResult, reusedResult] = await Promise.all([first, reused]);
164
- await forcedRejected;
165
- assert.equal(launches, 2);
166
- assert.equal(firstResult.workspace.id, reusedResult.workspace.id);
167
- assert.equal(reusedResult.created, false);
168
- });
169
- it("cancels an in-flight startup when its workspace is deleted", async () => {
170
- const { root, target } = await createLinkedWorkspace();
171
- const manager = createManager(root);
172
- const launch = deferred();
173
- manager.runtime.launch = () => launch.promise;
174
- const events = [];
175
- manager.options.eventBus.onEvent((event) => events.push(event));
176
- const creation = manager.create(target);
177
- const creationRejected = assert.rejects(creation, /Workspace creation cancelled/);
178
- while (manager.list().length === 0) {
179
- await new Promise((resolve) => setImmediate(resolve));
180
- }
181
- const workspaceId = manager.list()[0].id;
182
- await manager.delete(workspaceId);
183
- launch.resolve({ pid: 123, port: 4321, exitPromise: new Promise(() => { }), getLastOutput: () => "" });
184
- await creationRejected;
185
- assert.equal(manager.get(workspaceId), undefined);
186
- assert.equal(events.filter((event) => event.type === "workspace.stopped" && event.workspaceId === workspaceId).length, 1);
187
- });
188
- it("waits for and cancels forced creations during shutdown", async () => {
189
- const { root, target } = await createLinkedWorkspace();
190
- const manager = createManager(root);
191
- const launch = deferred();
192
- manager.runtime.launch = () => launch.promise;
193
- const creation = manager.create(target, undefined, { forceNew: true });
194
- const creationRejected = assert.rejects(creation, /Workspace creation cancelled/);
195
- while (manager.list().length === 0) {
196
- await new Promise((resolve) => setImmediate(resolve));
197
- }
198
- const shutdown = manager.shutdown();
199
- launch.resolve({ pid: 123, port: 4321, exitPromise: new Promise(() => { }), getLastOutput: () => "" });
200
- await Promise.all([creationRejected, shutdown]);
201
- assert.equal(manager.list().length, 0);
155
+ const normal = await manager.create(target);
156
+ const forced = await manager.create(link, undefined, { forceNew: true });
157
+ assert.notEqual(normal.workspace.id, forced.workspace.id);
158
+ await manager.delete(forced.workspace.id);
159
+ const reused = await manager.create(link);
160
+ assert.equal(reused.created, false);
161
+ assert.equal(reused.workspace.id, normal.workspace.id);
202
162
  });
203
163
  });
@@ -0,0 +1,10 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { binaryPathsEqual } from "./manager";
4
+ test("matches regular Windows binary paths without case sensitivity", () => {
5
+ assert.equal(binaryPathsEqual(String.raw `C:\Tools\OpenCode.cmd`, String.raw `c:\tools\opencode.CMD`, "win32"), true);
6
+ });
7
+ test("matches WSL distro names without changing Linux path casing", () => {
8
+ assert.equal(binaryPathsEqual(String.raw `\\wsl.localhost\Ubuntu\home\dev\OpenCode`, String.raw `\\wsl$\ubuntu\home\dev\OpenCode`, "win32"), true);
9
+ assert.equal(binaryPathsEqual(String.raw `\\wsl.localhost\Ubuntu\home\dev\OpenCode`, String.raw `\\wsl$\ubuntu\home\dev\opencode`, "win32"), false);
10
+ });
@@ -1,6 +1,6 @@
1
1
  import { createOpencodeClient } from "@opencode-ai/sdk/v2/client";
2
2
  const INSTANCE_HOST = "127.0.0.1";
3
- const LOOPBACK_TIMEOUT_MS = 10000;
3
+ const LOOPBACK_TIMEOUT_MS = 10_000;
4
4
  /**
5
5
  * Creates an OpenCode SDK client for direct loopback communication with a
6
6
  * running workspace instance.
@@ -18,7 +18,7 @@ const LOOPBACK_TIMEOUT_MS = 10000;
18
18
  * call or cache per instance as needed. Returns `null` when the instance has
19
19
  * no open port yet.
20
20
  */
21
- export function createInstanceClient(workspaceManager, instanceId) {
21
+ export function createInstanceClient(workspaceManager, instanceId, options = {}) {
22
22
  const port = workspaceManager.getInstancePort(instanceId);
23
23
  if (!port)
24
24
  return null;
@@ -28,12 +28,13 @@ export function createInstanceClient(workspaceManager, instanceId) {
28
28
  headers.authorization = authorization;
29
29
  }
30
30
  const workspace = workspaceManager.get(instanceId);
31
+ const timeoutMs = options.timeoutMs ?? LOOPBACK_TIMEOUT_MS;
31
32
  return createOpencodeClient({
32
33
  baseUrl: `http://${INSTANCE_HOST}:${port}/`,
33
34
  headers,
34
35
  fetch: (url, init) => fetch(url, {
35
36
  ...init,
36
- signal: init?.signal ?? AbortSignal.timeout(LOOPBACK_TIMEOUT_MS),
37
+ signal: init?.signal ?? AbortSignal.timeout(timeoutMs),
37
38
  }),
38
39
  ...(workspace?.path ? { directory: workspace.path } : {}),
39
40
  });
@@ -0,0 +1,29 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawnSync } from "node:child_process";
3
+ import { describe, it } from "node:test";
4
+ import { LAUNCH_CLEANUP_TOKEN_ENV, probeLaunchCleanupToken, signalLaunchCleanupToken } from "./process-identity";
5
+ const result = (stdout) => ({ pid: 1, output: [null, stdout, ""], stdout, stderr: "", status: 0, signal: null });
6
+ describe("launch cleanup token adapter", () => {
7
+ it("passes the exact token to the bounded Linux environ probe", () => {
8
+ const token = "a".repeat(64), calls = [];
9
+ const run = ((command, args, options) => { calls.push(command, args, options); return result("CODENOMAD_PROCESS|5000|1|4242|150|boot-a|150\n"); });
10
+ const probe = probeLaunchCleanupToken(run, token, 25);
11
+ assert.equal(probe.ok && probe.processes.get(5000)?.startOrder, "150");
12
+ assert.equal(calls[0], "sh");
13
+ assert.deepEqual([calls[2].timeout, calls[1].includes(LAUNCH_CLEANUP_TOKEN_ENV), calls[1].includes(token)], [25, true, true]);
14
+ assert.match(calls[1][1], /\/proc\/\$1\/environ/);
15
+ assert.doesNotMatch(calls[1][1], /\bseq\b/);
16
+ });
17
+ it("executes a successful empty Linux token probe", { skip: process.platform !== "linux" }, () => {
18
+ const probe = probeLaunchCleanupToken(spawnSync, "f".repeat(64), 1_000);
19
+ assert.deepEqual(probe, { ok: true, processes: new Map() });
20
+ });
21
+ it("signals every exact-token target and rejects malformed records", () => {
22
+ const rows = "CODENOMAD_TARGET|4242|1|4242|100|boot-a|100\nCODENOMAD_TARGET|5000|1|4242|150|boot-a|150\nCODENOMAD_RESULT|1\n";
23
+ const run = (() => result(rows));
24
+ const cleanup = signalLaunchCleanupToken(run, "b".repeat(64), "SIGKILL", 25);
25
+ assert.deepEqual([cleanup.ok, cleanup.targets.map(({ pid }) => pid)], [true, [4242, 5000]]);
26
+ const malformed = (() => result("5000|1|4242|150|boot-a|150|truncated\n"));
27
+ assert.equal(probeLaunchCleanupToken(malformed, "c".repeat(64), 25).ok, false);
28
+ });
29
+ });