@neuralnomads/codenomad 0.18.0 → 0.19.0

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 (135) 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/background-processes/manager.js +15 -30
  5. package/dist/background-processes/manager.test.js +123 -0
  6. package/dist/config/schema.js +2 -1
  7. package/dist/config/schema.test.js +13 -0
  8. package/dist/events/bus.js +17 -0
  9. package/dist/events/bus.test.js +37 -0
  10. package/dist/filesystem/__tests__/search-cache.test.js +20 -8
  11. package/dist/filesystem/__tests__/search.test.js +53 -0
  12. package/dist/filesystem/search-cache.js +6 -10
  13. package/dist/filesystem/search.js +22 -9
  14. package/dist/index.js +77 -58
  15. package/dist/index.test.js +62 -0
  16. package/dist/opencode-plugin/codenomad-opencode-plugin.tgz +0 -0
  17. package/dist/opencode-update/service.js +150 -0
  18. package/dist/opencode-update/service.test.js +107 -0
  19. package/dist/permissions/auto-accept-manager.js +380 -0
  20. package/dist/permissions/auto-accept-manager.test.js +736 -0
  21. package/dist/permissions/auto-accept-store.js +118 -0
  22. package/dist/permissions/auto-accept-store.test.js +157 -0
  23. package/dist/permissions/opencode-replier.js +31 -0
  24. package/dist/permissions/opencode-yolo-metadata.js +81 -0
  25. package/dist/permissions/opencode-yolo-metadata.test.js +54 -0
  26. package/dist/server/__tests__/listener-retry.test.js +15 -0
  27. package/dist/server/__tests__/remote-proxy.test.js +151 -47
  28. package/dist/server/http-server.js +22 -9
  29. package/dist/server/remote-proxy.js +91 -34
  30. package/dist/server/routes/auth-pages/login.html +3 -3
  31. package/dist/server/routes/auth.js +1 -1
  32. package/dist/server/routes/auth.test.js +21 -0
  33. package/dist/server/routes/opencode-update.js +37 -0
  34. package/dist/server/routes/opencode-update.test.js +34 -0
  35. package/dist/server/routes/remote-servers.js +1 -1
  36. package/dist/server/routes/settings.js +48 -2
  37. package/dist/server/routes/settings.test.js +58 -0
  38. package/dist/server/routes/usage.js +18 -0
  39. package/dist/server/routes/usage.test.js +26 -0
  40. package/dist/server/routes/workspaces.js +34 -2
  41. package/dist/server/routes/workspaces.test.js +113 -0
  42. package/dist/server/routes/worktrees.js +19 -0
  43. package/dist/server/routes/yolo.js +13 -0
  44. package/dist/server/tls.js +2 -2
  45. package/dist/settings/binaries.js +4 -1
  46. package/dist/settings/binaries.test.js +19 -0
  47. package/dist/settings/public-config.js +14 -0
  48. package/dist/settings/public-config.test.js +56 -0
  49. package/dist/settings/service.js +17 -5
  50. package/dist/settings/service.test.js +51 -0
  51. package/dist/settings/yaml-doc-store.js +55 -4
  52. package/dist/settings/yaml-doc-store.test.js +78 -0
  53. package/dist/shutdown.js +83 -0
  54. package/dist/shutdown.test.js +148 -0
  55. package/dist/sidecars/manager.js +26 -3
  56. package/dist/sidecars/manager.test.js +42 -0
  57. package/dist/speech/service.js +121 -10
  58. package/dist/speech/service.test.js +247 -0
  59. package/dist/ui/remote-ui.js +2 -2
  60. package/dist/usage/providers/api-key.js +171 -0
  61. package/dist/usage/providers/google.js +171 -0
  62. package/dist/usage/providers/minimax.js +109 -0
  63. package/dist/usage/providers/oauth.js +76 -0
  64. package/dist/usage/providers/special.js +148 -0
  65. package/dist/usage/service.js +83 -0
  66. package/dist/usage/service.test.js +61 -0
  67. package/dist/usage/shared.js +130 -0
  68. package/dist/usage/shared.test.js +33 -0
  69. package/dist/usage/types.js +1 -0
  70. package/dist/workspaces/__tests__/spawn.test.js +64 -7
  71. package/dist/workspaces/__tests__/workspace-identity.test.js +163 -0
  72. package/dist/workspaces/binary-path.test.js +10 -0
  73. package/dist/workspaces/instance-client.js +42 -0
  74. package/dist/workspaces/instance-client.test.js +149 -0
  75. package/dist/workspaces/instance-events.js +2 -2
  76. package/dist/workspaces/launch-cleanup.test.js +29 -0
  77. package/dist/workspaces/loopback.js +8 -0
  78. package/dist/workspaces/manager.js +473 -128
  79. package/dist/workspaces/manager.test.js +335 -0
  80. package/dist/workspaces/process-identity.darwin.test.js +88 -0
  81. package/dist/workspaces/process-identity.js +449 -0
  82. package/dist/workspaces/process-identity.test.js +140 -0
  83. package/dist/workspaces/runtime.js +471 -138
  84. package/dist/workspaces/runtime.test.js +286 -0
  85. package/dist/workspaces/spawn.js +86 -15
  86. package/dist/workspaces/workspace-identity.js +27 -0
  87. package/package.json +2 -1
  88. package/public/assets/FilesTab-Cbs7b7y9.js +2 -0
  89. package/public/assets/{GitChangesTab-DyRStL3G.js → GitChangesTab-D3H4cqJJ.js} +2 -2
  90. package/public/assets/{SplitFilePanel-C4FztlTR.js → SplitFilePanel-C_Bcle0r.js} +1 -1
  91. package/public/assets/StatusTab-D1-tfkgN.js +1 -0
  92. package/public/assets/{align-justify-GNs_d9nT.js → align-justify-B5HUL_LR.js} +1 -1
  93. package/public/assets/{bundle-full-B0vc8NGv.js → bundle-full-CEFzES5w.js} +1 -1
  94. package/public/assets/{diff-viewer-BmSzmlPC.js → diff-viewer-BBC2_yI1.js} +1 -1
  95. package/public/assets/{git-diff-vendor-CSgooKT_.js → git-diff-vendor-CYS3ApzA.js} +1 -1
  96. package/public/assets/{index-ChDVvMF4.js → index-B81f0aWL.js} +1 -1
  97. package/public/assets/index-BHlYVddm.js +1 -0
  98. package/public/assets/index-Best16ZB.js +2 -0
  99. package/public/assets/index-Boq37ErX.js +1 -0
  100. package/public/assets/index-By9pgzQk.css +1 -0
  101. package/public/assets/index-C0caoeJg.js +1 -0
  102. package/public/assets/index-Dqg2UVvS.js +1 -0
  103. package/public/assets/index-it6EGJV6.js +1 -0
  104. package/public/assets/{index-Bv867yIC.js → index-lORR8OnW.js} +1 -1
  105. package/public/assets/index-ppe6yWaU.js +1 -0
  106. package/public/assets/index-wEqeBwqT.js +1 -0
  107. package/public/assets/index-yEcajWX_.js +1 -0
  108. package/public/assets/{loading-DRzViX8M.js → loading-CbUWFqQ_.js} +1 -1
  109. package/public/assets/main-DfSREDgt.js +69 -0
  110. package/public/assets/{markdown-BlxzERp2.js → markdown-CEtfpKK-.js} +60 -47
  111. package/public/assets/monaco-viewer-NKl8kwH2.js +26 -0
  112. package/public/assets/terminal-square-q-by1uT7.js +1 -0
  113. package/public/assets/tool-call-CZL2uqIM.js +59 -0
  114. package/public/assets/unified-picker-CvJXD-j8.js +1 -0
  115. package/public/assets/{wrap-text-CMFBVbBi.js → wrap-text-Bo7xr74P.js} +1 -1
  116. package/public/index.html +5 -5
  117. package/public/loading.html +5 -5
  118. package/public/sw.js +1 -1
  119. package/public/ui-version.json +1 -1
  120. package/public/assets/FilesTab-CFF9uJuc.js +0 -2
  121. package/public/assets/StatusTab-CcoPFya8.js +0 -1
  122. package/public/assets/index--bYE3fA1.js +0 -1
  123. package/public/assets/index-B-9c-wPM.css +0 -1
  124. package/public/assets/index-BDJqHo1E.js +0 -1
  125. package/public/assets/index-BEXDNmDA.js +0 -1
  126. package/public/assets/index-BWX6Cyx3.js +0 -2
  127. package/public/assets/index-CUB1cngT.js +0 -1
  128. package/public/assets/index-CyGPk9Qx.js +0 -1
  129. package/public/assets/index-D9T8sYiH.js +0 -1
  130. package/public/assets/index-DQ8RfkwK.js +0 -1
  131. package/public/assets/index-udaOwtFG.js +0 -1
  132. package/public/assets/main-DUP17Bqi.js +0 -68
  133. package/public/assets/monaco-viewer-BbohfXZk.js +0 -26
  134. package/public/assets/tool-call-B0Ri40qI.js +0 -59
  135. package/public/assets/unified-picker-CGg8mlSo.js +0 -1
package/README.md CHANGED
@@ -217,3 +217,15 @@ When running as a server CodeNomad can also be installed as a PWA from any suppo
217
217
 
218
218
  - **Config**: `~/.config/codenomad/config.json`
219
219
  - **Instance Data**: `~/.config/codenomad/instances` (chat history, etc.)
220
+
221
+ ### Provider Plan Usage
222
+
223
+ The Status panel automatically displays quota information for the provider used by the active session. CodeNomad reads existing OpenCode credentials and never returns provider secrets through its API.
224
+
225
+ Some optional usage integrations require credentials that OpenCode does not expose. They can be enabled without UI configuration through these environment variables:
226
+
227
+ - Google token refresh: `GOOGLE_OAUTH_CLIENT_ID` and `GOOGLE_OAUTH_CLIENT_SECRET`
228
+ - Antigravity token refresh: `ANTIGRAVITY_OAUTH_CLIENT_ID` and `ANTIGRAVITY_OAUTH_CLIENT_SECRET`
229
+ - Cursor: `CURSOR_ACCESS_TOKEN` or `CURSOR_TOKEN`, with optional `CURSOR_REFRESH_TOKEN`
230
+ - Ollama Cloud: `OLLAMA_CLOUD_COOKIE`
231
+ - OpenCode Go: `OPENCODE_GO_WORKSPACE_ID` and `OPENCODE_GO_AUTH_COOKIE`
@@ -0,0 +1,26 @@
1
+ # Third-Party Notices
2
+
3
+ The provider usage adapters are derived from OpenChamber:
4
+ https://github.com/openchamber/openchamber
5
+
6
+ MIT License
7
+
8
+ Copyright (c) 2025 Bohdan Triapitsyn
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
@@ -26,7 +26,7 @@ export class AuthManager {
26
26
  password: init.password,
27
27
  allowBootstrapWithoutPassword: init.generateToken,
28
28
  });
29
- this.tokenManager = init.generateToken ? new TokenManager(60000) : null;
29
+ this.tokenManager = init.generateToken ? new TokenManager(60_000) : null;
30
30
  }
31
31
  isAuthEnabled() {
32
32
  return this.authEnabled;
@@ -2,6 +2,7 @@ import { spawn, spawnSync } from "child_process";
2
2
  import { createWriteStream, existsSync, promises as fs } from "fs";
3
3
  import path from "path";
4
4
  import { randomBytes } from "crypto";
5
+ import { createInstanceClient } from "../workspaces/instance-client";
5
6
  const ROOT_DIR = ".codenomad/background_processes";
6
7
  const INDEX_FILE = "index.json";
7
8
  const OUTPUT_FILE = "output.txt";
@@ -511,38 +512,22 @@ export class BackgroundProcessManager {
511
512
  const notify = record.notify;
512
513
  if (!notify || !record.terminalReason)
513
514
  return;
514
- if (!this.deps.workspaceManager.get(workspaceId)) {
515
- throw new Error("Workspace not found");
516
- }
517
- const port = this.deps.workspaceManager.getInstancePort(workspaceId);
518
- if (!port) {
519
- throw new Error("Workspace instance is not ready");
520
- }
521
- const targetUrl = `http://127.0.0.1:${port}/session/${encodeURIComponent(notify.sessionID)}/prompt_async`;
522
- const headers = {
523
- "content-type": "application/json",
524
- };
525
- const authorization = this.deps.workspaceManager.getInstanceAuthorizationHeader(workspaceId);
526
- if (authorization) {
527
- headers.authorization = authorization;
528
- }
529
- const response = await fetch(targetUrl, {
530
- method: "POST",
531
- headers,
532
- body: JSON.stringify({
533
- parts: [
534
- {
535
- type: "text",
536
- text: this.buildSyntheticCompletionPrompt(record),
537
- synthetic: true,
538
- },
539
- ],
540
- }),
515
+ const client = createInstanceClient(this.deps.workspaceManager, workspaceId, {
516
+ directory: notify.directory,
541
517
  });
542
- if (!response.ok) {
543
- const message = await response.text().catch(() => "");
544
- throw new Error(message || `Prompt request failed with ${response.status}`);
518
+ if (!client) {
519
+ throw new Error("Workspace instance is not ready");
545
520
  }
521
+ await client.session.promptAsync({
522
+ sessionID: notify.sessionID,
523
+ parts: [
524
+ {
525
+ type: "text",
526
+ text: this.buildSyntheticCompletionPrompt(record),
527
+ synthetic: true,
528
+ },
529
+ ],
530
+ }, { throwOnError: true });
546
531
  }
547
532
  buildCompletionPrompt(record) {
548
533
  const ref = `Background process "${record.title}" (${record.id})`;
@@ -0,0 +1,123 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import { promises as fs } from "node:fs";
4
+ import path from "node:path";
5
+ import os from "node:os";
6
+ import { BackgroundProcessManager } from "./manager";
7
+ const WORKSPACE_ID = "ws-test";
8
+ const SESSION_ID = "sess-1";
9
+ const INSTANCE_PORT = 9999;
10
+ const AUTH_HEADER = "Basic test-auth";
11
+ const TERMINAL_TIMEOUT_MS = 3000;
12
+ /**
13
+ * Drives the real {@link BackgroundProcessManager} lifecycle (spawn a
14
+ * fast-exiting command with notify enabled) against a mocked transport, so the
15
+ * migrated `sendCompletionPrompt` path — factory + SDK client + `fetch` — is
16
+ * exercised end to end without touching production wiring.
17
+ *
18
+ * The workspace temp directory is intentionally left in place (under
19
+ * `os.tmpdir()`, OS-reaped): removing it from the test races the manager's
20
+ * asynchronous finalization writes, which intermittently fail with ENOENT.
21
+ */
22
+ async function runCompletionPrompt(fetchImpl) {
23
+ const requests = [];
24
+ const originalFetch = globalThis.fetch;
25
+ // Captured now but swapped in only inside the try below, so a failure during
26
+ // setup (mkdtemp, manager construction) can't leak the mocked fetch.
27
+ const fetchMock = (async (input, init) => {
28
+ const req = input instanceof Request ? input : new Request(String(input), init);
29
+ requests.push({
30
+ method: req.method,
31
+ url: req.url,
32
+ headers: req.headers,
33
+ body: await req.text(),
34
+ });
35
+ return fetchImpl(input instanceof Request ? input : req, init);
36
+ });
37
+ let warned = false;
38
+ const logger = {
39
+ warn: () => { warned = true; },
40
+ debug: () => { },
41
+ trace: () => { },
42
+ info: () => { },
43
+ error: () => { },
44
+ fatal: () => { },
45
+ isLevelEnabled: () => false,
46
+ level: "info",
47
+ child: () => logger,
48
+ };
49
+ const workspacePath = await fs.mkdtemp(path.join(os.tmpdir(), "bp-test-"));
50
+ // Distinct from the workspace root so the directory-override assertion is
51
+ // discriminating: if `sendCompletionPrompt` stops passing `notify.directory`,
52
+ // the factory would fall back to `workspacePath` and the header check fails.
53
+ const sessionDir = path.join(workspacePath, "session-worktree");
54
+ // Resolve once the manager publishes a terminal (non-running) status update.
55
+ let resolveTerminal = () => { };
56
+ const terminal = new Promise((resolve) => { resolveTerminal = resolve; });
57
+ const eventBus = {
58
+ on: () => { },
59
+ publish: (event) => {
60
+ if (event?.type === "instance.event") {
61
+ const type = event?.event?.type;
62
+ const status = event?.event?.properties?.process?.status;
63
+ if (type === "background.process.removed" || (status && status !== "running"))
64
+ resolveTerminal();
65
+ }
66
+ return true;
67
+ },
68
+ };
69
+ const workspaceManager = {
70
+ get: () => ({ path: workspacePath }),
71
+ getInstancePort: () => INSTANCE_PORT,
72
+ getInstanceAuthorizationHeader: () => AUTH_HEADER,
73
+ };
74
+ const manager = new BackgroundProcessManager({ workspaceManager, eventBus, logger });
75
+ try {
76
+ globalThis.fetch = fetchMock;
77
+ await manager.start(WORKSPACE_ID, "test-proc", "true", {
78
+ notify: true,
79
+ notification: { sessionID: SESSION_ID, directory: sessionDir },
80
+ });
81
+ // The terminal status update is published at the very end of finalize, so
82
+ // resolving on it is a deterministic completion signal. Fail loudly rather
83
+ // than racing a silent timeout that could mask a hang.
84
+ let timeoutHandle;
85
+ const reachedTerminal = await Promise.race([
86
+ terminal.then(() => true),
87
+ new Promise((resolve) => {
88
+ timeoutHandle = setTimeout(() => resolve(false), TERMINAL_TIMEOUT_MS);
89
+ }),
90
+ ]);
91
+ if (timeoutHandle)
92
+ clearTimeout(timeoutHandle);
93
+ if (!reachedTerminal) {
94
+ throw new Error("background process did not reach a terminal state in time");
95
+ }
96
+ }
97
+ finally {
98
+ globalThis.fetch = originalFetch;
99
+ }
100
+ return { requests, warned, directory: sessionDir };
101
+ }
102
+ describe("BackgroundProcessManager.sendCompletionPrompt", () => {
103
+ it("posts the synthetic completion prompt to the instance via the SDK route", async () => {
104
+ const { requests, directory } = await runCompletionPrompt(async () => new Response("{}", { status: 200, headers: { "content-type": "application/json" } }));
105
+ const promptCall = requests.find((r) => r.url.includes("/prompt_async"));
106
+ assert.ok(promptCall, "expected a prompt_async request");
107
+ assert.equal(promptCall.method, "POST");
108
+ assert.equal(promptCall.url, `http://127.0.0.1:${INSTANCE_PORT}/session/${SESSION_ID}/prompt_async`);
109
+ assert.equal(promptCall.headers.get("authorization"), AUTH_HEADER);
110
+ // The prompt is scoped to the session's directory (a POST keeps the
111
+ // directory as a header — the SDK only rewrites header→query for GET/HEAD).
112
+ assert.equal(promptCall.headers.get("x-opencode-directory"), encodeURIComponent(directory));
113
+ const body = JSON.parse(promptCall.body);
114
+ assert.equal(body.parts.length, 1);
115
+ assert.equal(body.parts[0].type, "text");
116
+ assert.equal(body.parts[0].synthetic, true);
117
+ assert.match(body.parts[0].text, /test-proc/);
118
+ });
119
+ it("swallows a failed prompt and logs it without aborting finalization", async () => {
120
+ const { warned } = await runCompletionPrompt(async () => new Response("boom", { status: 500 }));
121
+ assert.equal(warned, true);
122
+ });
123
+ });
@@ -19,8 +19,9 @@ const PreferencesSchema = z
19
19
  modelThinkingSelections: z.record(z.string(), z.string()).default({}),
20
20
  diffViewMode: z.enum(["split", "unified"]).default("split"),
21
21
  toolOutputExpansion: z.enum(["expanded", "collapsed"]).default("expanded"),
22
- diagnosticsExpansion: z.enum(["expanded", "collapsed"]).default("expanded"),
22
+ diagnosticsExpansion: z.enum(["hidden", "expanded", "collapsed"]).default("expanded"),
23
23
  showUsageMetrics: z.boolean().default(true),
24
+ usageMetricsExpansion: z.enum(["expanded", "collapsed"]).default("collapsed"),
24
25
  autoCleanupBlankSessions: z.boolean().default(true),
25
26
  listeningMode: z.enum(["local", "all"]).default("local"),
26
27
  logLevel: z.enum(["DEBUG", "INFO", "WARN", "ERROR"]).default("DEBUG"),
@@ -0,0 +1,13 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import { PreferencesSchema } from "./schema";
4
+ describe("chat visibility preferences", () => {
5
+ it("accepts hidden diagnostics and collapsed usage metrics", () => {
6
+ const preferences = PreferencesSchema.parse({
7
+ diagnosticsExpansion: "hidden",
8
+ usageMetricsExpansion: "collapsed",
9
+ });
10
+ assert.equal(preferences.diagnosticsExpansion, "hidden");
11
+ assert.equal(preferences.usageMetricsExpansion, "collapsed");
12
+ });
13
+ });
@@ -3,8 +3,19 @@ export class EventBus extends EventEmitter {
3
3
  constructor(logger) {
4
4
  super();
5
5
  this.logger = logger;
6
+ this.instanceStatuses = new Map();
6
7
  }
7
8
  publish(event) {
9
+ if (event.type === "instance.eventStatus") {
10
+ const terminal = event.status === "disconnected"
11
+ && (event.reason === "workspace stopped" || event.reason === "workspace error");
12
+ if (terminal) {
13
+ this.instanceStatuses.delete(event.instanceId);
14
+ }
15
+ else {
16
+ this.instanceStatuses.set(event.instanceId, event);
17
+ }
18
+ }
8
19
  if (event.type !== "instance.event" && event.type !== "instance.eventStatus") {
9
20
  this.logger?.debug({ type: event.type }, "Publishing workspace event");
10
21
  if (this.logger?.isLevelEnabled("trace")) {
@@ -27,6 +38,10 @@ export class EventBus extends EventEmitter {
27
38
  this.on("instance.dataChanged", handler);
28
39
  this.on("instance.event", handler);
29
40
  this.on("instance.eventStatus", handler);
41
+ this.on("yolo.stateChanged", handler);
42
+ this.on("yolo.autoAccepted", handler);
43
+ for (const status of this.instanceStatuses.values())
44
+ listener(status);
30
45
  return () => {
31
46
  this.off("workspace.created", handler);
32
47
  this.off("workspace.started", handler);
@@ -40,6 +55,8 @@ export class EventBus extends EventEmitter {
40
55
  this.off("instance.dataChanged", handler);
41
56
  this.off("instance.event", handler);
42
57
  this.off("instance.eventStatus", handler);
58
+ this.off("yolo.stateChanged", handler);
59
+ this.off("yolo.autoAccepted", handler);
43
60
  };
44
61
  }
45
62
  }
@@ -0,0 +1,37 @@
1
+ import assert from "node:assert/strict";
2
+ import { describe, it } from "node:test";
3
+ import { EventBus } from "./bus";
4
+ describe("event bus instance status replay", () => {
5
+ it("replays the latest instance status to a late subscriber", () => {
6
+ const bus = new EventBus();
7
+ bus.publish({ type: "instance.eventStatus", instanceId: "workspace-1", status: "connecting" });
8
+ bus.publish({ type: "instance.eventStatus", instanceId: "workspace-1", status: "connected" });
9
+ const received = [];
10
+ bus.onEvent((event) => received.push(event));
11
+ assert.deepEqual(received, [
12
+ { type: "instance.eventStatus", instanceId: "workspace-1", status: "connected" },
13
+ ]);
14
+ });
15
+ it("delivers terminal disconnects live without replaying stopped workspaces", () => {
16
+ const bus = new EventBus();
17
+ bus.publish({ type: "instance.eventStatus", instanceId: "workspace-1", status: "connected" });
18
+ const live = [];
19
+ bus.onEvent((event) => live.push(event));
20
+ live.length = 0;
21
+ bus.publish({
22
+ type: "instance.eventStatus",
23
+ instanceId: "workspace-1",
24
+ status: "disconnected",
25
+ reason: "workspace stopped",
26
+ });
27
+ assert.deepEqual(live, [{
28
+ type: "instance.eventStatus",
29
+ instanceId: "workspace-1",
30
+ status: "disconnected",
31
+ reason: "workspace stopped",
32
+ }]);
33
+ const replayed = [];
34
+ bus.onEvent((event) => replayed.push(event));
35
+ assert.deepEqual(replayed, []);
36
+ });
37
+ });
@@ -7,26 +7,38 @@ describe("workspace search cache", () => {
7
7
  });
8
8
  it("expires cached candidates after the TTL", () => {
9
9
  const workspacePath = "/tmp/workspace";
10
- const startTime = 1000;
11
- refreshWorkspaceCandidates(workspacePath, () => [createEntry("file-a")], startTime);
12
- const beforeExpiry = getWorkspaceCandidates(workspacePath, startTime + WORKSPACE_CANDIDATE_CACHE_TTL_MS - 1);
10
+ const startTime = 1_000;
11
+ refreshWorkspaceCandidates(workspacePath, "query-a", () => [createEntry("file-a")], startTime);
12
+ const beforeExpiry = getWorkspaceCandidates(workspacePath, "query-a", startTime + WORKSPACE_CANDIDATE_CACHE_TTL_MS - 1);
13
13
  assert.ok(beforeExpiry);
14
14
  assert.equal(beforeExpiry.length, 1);
15
15
  assert.equal(beforeExpiry[0].name, "file-a");
16
- const afterExpiry = getWorkspaceCandidates(workspacePath, startTime + WORKSPACE_CANDIDATE_CACHE_TTL_MS + 1);
16
+ const afterExpiry = getWorkspaceCandidates(workspacePath, "query-a", startTime + WORKSPACE_CANDIDATE_CACHE_TTL_MS + 1);
17
17
  assert.equal(afterExpiry, undefined);
18
18
  });
19
19
  it("replaces cached entries when manually refreshed", () => {
20
20
  const workspacePath = "/tmp/workspace";
21
- refreshWorkspaceCandidates(workspacePath, () => [createEntry("file-a")], 5000);
22
- const initial = getWorkspaceCandidates(workspacePath, 5001);
21
+ refreshWorkspaceCandidates(workspacePath, "query-a", () => [createEntry("file-a")], 5_000);
22
+ const initial = getWorkspaceCandidates(workspacePath, "query-a", 5_001);
23
23
  assert.ok(initial);
24
24
  assert.equal(initial[0].name, "file-a");
25
- refreshWorkspaceCandidates(workspacePath, () => [createEntry("file-b")], 6000);
26
- const refreshed = getWorkspaceCandidates(workspacePath, 6001);
25
+ refreshWorkspaceCandidates(workspacePath, "query-a", () => [createEntry("file-b")], 6_000);
26
+ const refreshed = getWorkspaceCandidates(workspacePath, "query-a", 6_001);
27
27
  assert.ok(refreshed);
28
28
  assert.equal(refreshed[0].name, "file-b");
29
29
  });
30
+ it("does not reuse candidates across query scopes", () => {
31
+ const workspacePath = "/tmp/workspace";
32
+ refreshWorkspaceCandidates(workspacePath, "query-a", () => [createEntry("file-a")], 5_000);
33
+ assert.equal(getWorkspaceCandidates(workspacePath, "query-a", 5_001)?.[0].name, "file-a");
34
+ assert.equal(getWorkspaceCandidates(workspacePath, "query-b", 5_001), undefined);
35
+ refreshWorkspaceCandidates(workspacePath, "query-b", () => [createEntry("file-b")], 5_000);
36
+ assert.equal(getWorkspaceCandidates(workspacePath, "query-a", 5_001), undefined);
37
+ assert.equal(getWorkspaceCandidates(workspacePath, "query-b", 5_001)?.[0].name, "file-b");
38
+ clearWorkspaceSearchCache(workspacePath);
39
+ assert.equal(getWorkspaceCandidates(workspacePath, "query-a", 5_001), undefined);
40
+ assert.equal(getWorkspaceCandidates(workspacePath, "query-b", 5_001), undefined);
41
+ });
30
42
  });
31
43
  function createEntry(name) {
32
44
  return {
@@ -0,0 +1,53 @@
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 { after, test } from "node:test";
6
+ import { searchWorkspaceFiles } from "../search";
7
+ import { getWorkspaceCandidates } from "../search-cache";
8
+ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-search-"));
9
+ after(() => fs.rmSync(workspace, { recursive: true, force: true }));
10
+ test("finds a matching file after more than 8000 non-matching entries", () => {
11
+ fs.mkdirSync(path.join(workspace, "a"));
12
+ fs.mkdirSync(path.join(workspace, "b"));
13
+ const [targetDirName, fillerDirName] = fs.readdirSync(workspace);
14
+ const fillerDir = path.join(workspace, fillerDirName);
15
+ const targetDir = path.join(workspace, targetDirName);
16
+ for (let index = 0; index < 8_001; index += 1) {
17
+ fs.writeFileSync(path.join(fillerDir, `filler-${index}.txt`), "");
18
+ }
19
+ fs.writeFileSync(path.join(targetDir, "unique-search-target.txt"), "");
20
+ const results = searchWorkspaceFiles(workspace, "unique-search-target", {
21
+ type: "file",
22
+ refresh: true,
23
+ });
24
+ assert.equal(results.some((entry) => entry.name === "unique-search-target.txt"), true);
25
+ searchWorkspaceFiles(workspace, "filler", { type: "file", refresh: true });
26
+ assert.equal(getWorkspaceCandidates(workspace, "file\0filler")?.length, 8_000);
27
+ });
28
+ test("does not revisit directory links", () => {
29
+ const cyclicWorkspace = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-search-cycle-"));
30
+ try {
31
+ fs.symlinkSync(cyclicWorkspace, path.join(cyclicWorkspace, "cycle"), process.platform === "win32" ? "junction" : "dir");
32
+ assert.deepEqual(searchWorkspaceFiles(cyclicWorkspace, "not-present", { refresh: true }), []);
33
+ }
34
+ finally {
35
+ fs.rmSync(cyclicWorkspace, { recursive: true, force: true });
36
+ }
37
+ });
38
+ test("indexes both real and linked directory paths", () => {
39
+ const linkedWorkspace = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-search-link-"));
40
+ try {
41
+ const realDirectory = path.join(linkedWorkspace, "b");
42
+ fs.mkdirSync(realDirectory);
43
+ fs.writeFileSync(path.join(realDirectory, "needle.txt"), "");
44
+ fs.symlinkSync(realDirectory, path.join(linkedWorkspace, "a"), process.platform === "win32" ? "junction" : "dir");
45
+ const linkedResults = searchWorkspaceFiles(linkedWorkspace, "a/needle", { type: "file", refresh: true });
46
+ const realResults = searchWorkspaceFiles(linkedWorkspace, "b/needle", { type: "file", refresh: true });
47
+ assert.equal(linkedResults.some((entry) => entry.path === "a/needle.txt"), true);
48
+ assert.equal(realResults.some((entry) => entry.path === "b/needle.txt"), true);
49
+ }
50
+ finally {
51
+ fs.rmSync(linkedWorkspace, { recursive: true, force: true });
52
+ }
53
+ });
@@ -1,10 +1,10 @@
1
1
  import path from "path";
2
- export const WORKSPACE_CANDIDATE_CACHE_TTL_MS = 30000;
2
+ export const WORKSPACE_CANDIDATE_CACHE_TTL_MS = 30_000;
3
3
  const workspaceCandidateCache = new Map();
4
- export function getWorkspaceCandidates(rootDir, now = Date.now()) {
4
+ export function getWorkspaceCandidates(rootDir, scope, now = Date.now()) {
5
5
  const key = normalizeKey(rootDir);
6
6
  const cached = workspaceCandidateCache.get(key);
7
- if (!cached) {
7
+ if (!cached || cached.scope !== scope) {
8
8
  return undefined;
9
9
  }
10
10
  if (cached.expiresAt <= now) {
@@ -13,15 +13,12 @@ export function getWorkspaceCandidates(rootDir, now = Date.now()) {
13
13
  }
14
14
  return cloneEntries(cached.candidates);
15
15
  }
16
- export function refreshWorkspaceCandidates(rootDir, builder, now = Date.now()) {
16
+ export function refreshWorkspaceCandidates(rootDir, scope, builder, now = Date.now()) {
17
17
  const key = normalizeKey(rootDir);
18
18
  const freshCandidates = builder();
19
- if (!freshCandidates || freshCandidates.length === 0) {
20
- workspaceCandidateCache.delete(key);
21
- return [];
22
- }
23
19
  const storedCandidates = cloneEntries(freshCandidates);
24
20
  workspaceCandidateCache.set(key, {
21
+ scope,
25
22
  expiresAt: now + WORKSPACE_CANDIDATE_CACHE_TTL_MS,
26
23
  candidates: storedCandidates,
27
24
  });
@@ -32,8 +29,7 @@ export function clearWorkspaceSearchCache(rootDir) {
32
29
  workspaceCandidateCache.clear();
33
30
  return;
34
31
  }
35
- const key = normalizeKey(rootDir);
36
- workspaceCandidateCache.delete(key);
32
+ workspaceCandidateCache.delete(normalizeKey(rootDir));
37
33
  }
38
34
  function cloneEntries(entries) {
39
35
  return entries.map((entry) => ({ ...entry }));
@@ -15,13 +15,14 @@ export function searchWorkspaceFiles(rootDir, query, options = {}) {
15
15
  const limit = normalizeLimit(options.limit);
16
16
  const typeFilter = options.type ?? "all";
17
17
  const refreshRequested = options.refresh === true;
18
+ const cacheScope = `${typeFilter}\0${trimmedQuery.toLowerCase()}`;
18
19
  let entries;
19
20
  try {
20
21
  if (!refreshRequested) {
21
- entries = getWorkspaceCandidates(normalizedRoot);
22
+ entries = getWorkspaceCandidates(normalizedRoot, cacheScope);
22
23
  }
23
24
  if (!entries) {
24
- entries = refreshWorkspaceCandidates(normalizedRoot, () => collectCandidates(normalizedRoot));
25
+ entries = refreshWorkspaceCandidates(normalizedRoot, cacheScope, () => collectCandidates(normalizedRoot, trimmedQuery, typeFilter));
25
26
  }
26
27
  }
27
28
  catch (error) {
@@ -29,7 +30,6 @@ export function searchWorkspaceFiles(rootDir, query, options = {}) {
29
30
  throw error;
30
31
  }
31
32
  if (!entries || entries.length === 0) {
32
- clearWorkspaceSearchCache(normalizedRoot);
33
33
  return [];
34
34
  }
35
35
  const candidates = buildCandidateEntries(entries, typeFilter);
@@ -45,14 +45,23 @@ export function searchWorkspaceFiles(rootDir, query, options = {}) {
45
45
  }
46
46
  return matches.map((match) => match.obj.entry);
47
47
  }
48
- function collectCandidates(rootDir) {
49
- const queue = [""];
48
+ function collectCandidates(rootDir, query, filter) {
49
+ const queue = [
50
+ { relativeDir: "", ancestors: new Set() },
51
+ ];
50
52
  const entries = [];
51
53
  while (queue.length > 0 && entries.length < MAX_CANDIDATES) {
52
- const relativeDir = queue.pop() || "";
54
+ const queuedDirectory = queue.pop();
55
+ const { relativeDir, ancestors } = queuedDirectory;
53
56
  const absoluteDir = relativeDir ? path.join(rootDir, relativeDir) : rootDir;
54
57
  let dirents;
58
+ let branchAncestors;
55
59
  try {
60
+ const realDir = normalizeDirectoryIdentity(fs.realpathSync.native(absoluteDir));
61
+ if (ancestors.has(realDir)) {
62
+ continue;
63
+ }
64
+ branchAncestors = new Set([...ancestors, realDir]);
56
65
  dirents = fs.readdirSync(absoluteDir, { withFileTypes: true });
57
66
  }
58
67
  catch {
@@ -75,9 +84,7 @@ function collectCandidates(rootDir) {
75
84
  }
76
85
  const isDirectory = stats.isDirectory();
77
86
  if (isDirectory && !IGNORED_DIRECTORIES.has(lowerName)) {
78
- if (entries.length < MAX_CANDIDATES) {
79
- queue.push(relativePath);
80
- }
87
+ queue.push({ relativeDir: relativePath, ancestors: branchAncestors });
81
88
  }
82
89
  const entryType = isDirectory ? "directory" : "file";
83
90
  const normalizedPath = normalizeRelativeEntryPath(relativePath);
@@ -89,6 +96,9 @@ function collectCandidates(rootDir) {
89
96
  size: entryType === "file" ? stats.size : undefined,
90
97
  modifiedAt: stats.mtime.toISOString(),
91
98
  };
99
+ if (!shouldInclude(entry.type, filter) || !fuzzysort.single(query, buildSearchKey(entry))) {
100
+ continue;
101
+ }
92
102
  entries.push(entry);
93
103
  if (entries.length >= MAX_CANDIDATES) {
94
104
  break;
@@ -133,3 +143,6 @@ function normalizeRelativeEntryPath(relativePath) {
133
143
  function buildSearchKey(entry) {
134
144
  return entry.path.toLowerCase();
135
145
  }
146
+ function normalizeDirectoryIdentity(directoryPath) {
147
+ return process.platform === "win32" ? directoryPath.toLowerCase() : directoryPath;
148
+ }