@neuralnomads/codenomad-dev 0.20.0-dev-20260918-a311de98 → 0.20.0-dev-20260919-c2b349f8

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 (143) hide show
  1. package/dist/api-types.js +1 -0
  2. package/dist/api-types.js.map +1 -1
  3. package/dist/opencode/automation/desktop-plugin.js.map +1 -1
  4. package/dist/opencode/automation/desktop-plugin.test.js +40 -0
  5. package/dist/opencode/automation/desktop-plugin.test.js.map +1 -1
  6. package/dist/opencode/desktop-plugin-installation.js +23 -9
  7. package/dist/opencode/desktop-plugin-installation.js.map +1 -1
  8. package/dist/opencode/desktop-plugin-lifecycle.test.js +2 -1
  9. package/dist/opencode/desktop-plugin-lifecycle.test.js.map +1 -1
  10. package/dist/opencode/desktop-plugin-paths.js +10 -4
  11. package/dist/opencode/desktop-plugin-paths.js.map +1 -1
  12. package/dist/opencode/desktop-plugin-paths.test.js +16 -10
  13. package/dist/opencode/desktop-plugin-paths.test.js.map +1 -1
  14. package/dist/opencode/desktop-plugin-presence.js +2 -1
  15. package/dist/opencode/desktop-plugin-presence.js.map +1 -1
  16. package/dist/opencode/session-pruning/desktop-plugin.js.map +1 -1
  17. package/dist/opencode-update/legacy-package.js +27 -0
  18. package/dist/opencode-update/legacy-package.js.map +1 -0
  19. package/dist/opencode-update/legacy-package.test.js +79 -0
  20. package/dist/opencode-update/legacy-package.test.js.map +1 -0
  21. package/dist/opencode-update/service.js +17 -7
  22. package/dist/opencode-update/service.js.map +1 -1
  23. package/dist/opencode-update/service.test.js +42 -24
  24. package/dist/opencode-update/service.test.js.map +1 -1
  25. package/dist/plugins/automation/plugin.mjs +2 -1
  26. package/dist/plugins/session-pruning/plugin.mjs +2 -1
  27. package/dist/server/__tests__/instance-proxy-legacy.test.js +2 -0
  28. package/dist/server/__tests__/instance-proxy-legacy.test.js.map +1 -1
  29. package/dist/server/__tests__/instance-proxy.test.js +13 -0
  30. package/dist/server/__tests__/instance-proxy.test.js.map +1 -1
  31. package/dist/server/__tests__/session-environment.test.js +189 -0
  32. package/dist/server/__tests__/session-environment.test.js.map +1 -0
  33. package/dist/server/http-server.js +34 -5
  34. package/dist/server/http-server.js.map +1 -1
  35. package/dist/workspaces/git-worktrees.js +13 -0
  36. package/dist/workspaces/git-worktrees.js.map +1 -1
  37. package/dist/workspaces/instance-event-queue.js +79 -0
  38. package/dist/workspaces/instance-event-queue.js.map +1 -0
  39. package/dist/workspaces/instance-event-routing.test.js +291 -0
  40. package/dist/workspaces/instance-event-routing.test.js.map +1 -0
  41. package/dist/workspaces/instance-events.js +132 -67
  42. package/dist/workspaces/instance-events.js.map +1 -1
  43. package/dist/workspaces/instance-events.test.js +17 -8
  44. package/dist/workspaces/instance-events.test.js.map +1 -1
  45. package/dist/workspaces/manager.js +23 -2
  46. package/dist/workspaces/manager.js.map +1 -1
  47. package/dist/workspaces/manager.test.js +30 -0
  48. package/dist/workspaces/manager.test.js.map +1 -1
  49. package/dist/workspaces/session-environment.js +49 -0
  50. package/dist/workspaces/session-environment.js.map +1 -0
  51. package/dist/workspaces/session-environment.test.js +45 -0
  52. package/dist/workspaces/session-environment.test.js.map +1 -0
  53. package/package.json +1 -1
  54. package/public/assets/App-NeYzGM-n.js +54 -0
  55. package/public/assets/App-NeYzGM-n.js.map +1 -0
  56. package/public/assets/{FilesTab-_xb_Aq0c.js → FilesTab-2niJoikP.js} +2 -2
  57. package/public/assets/{FilesTab-_xb_Aq0c.js.map → FilesTab-2niJoikP.js.map} +1 -1
  58. package/public/assets/{GitChangesTab-Cz0RckYn.js → GitChangesTab-0Gk9LJqf.js} +2 -2
  59. package/public/assets/{GitChangesTab-Cz0RckYn.js.map → GitChangesTab-0Gk9LJqf.js.map} +1 -1
  60. package/public/assets/{SplitFilePanel-DVkVS5C0.js → SplitFilePanel-Du8YxLSZ.js} +2 -2
  61. package/public/assets/{SplitFilePanel-DVkVS5C0.js.map → SplitFilePanel-Du8YxLSZ.js.map} +1 -1
  62. package/public/assets/StatusTab-BdjRXfMr.js +2 -0
  63. package/public/assets/StatusTab-BdjRXfMr.js.map +1 -0
  64. package/public/assets/{align-justify-Czy9hp3K.js → align-justify-D-DgUJlu.js} +2 -2
  65. package/public/assets/{align-justify-Czy9hp3K.js.map → align-justify-D-DgUJlu.js.map} +1 -1
  66. package/public/assets/{bundle-full-CMakdq_6.js → bundle-full-D08Vq90h.js} +2 -2
  67. package/public/assets/{bundle-full-CMakdq_6.js.map → bundle-full-D08Vq90h.js.map} +1 -1
  68. package/public/assets/{client-state-DGbupmmR.js → client-state-CVV6lrdS.js} +2 -2
  69. package/public/assets/{client-state-DGbupmmR.js.map → client-state-CVV6lrdS.js.map} +1 -1
  70. package/public/assets/{diff-viewer-CSOlh3i1.js → diff-viewer-BfjJu-1e.js} +2 -2
  71. package/public/assets/{diff-viewer-CSOlh3i1.js.map → diff-viewer-BfjJu-1e.js.map} +1 -1
  72. package/public/assets/index-90UrxIKO.js +2 -0
  73. package/public/assets/index-90UrxIKO.js.map +1 -0
  74. package/public/assets/index-BP_qlylD.js +2 -0
  75. package/public/assets/index-BP_qlylD.js.map +1 -0
  76. package/public/assets/{index-B0BLbbT3.js → index-BQKGBBLR.js} +2 -2
  77. package/public/assets/{index-B0BLbbT3.js.map → index-BQKGBBLR.js.map} +1 -1
  78. package/public/assets/index-BbBHd0cY.js +2 -0
  79. package/public/assets/index-BbBHd0cY.js.map +1 -0
  80. package/public/assets/index-Cpje-SXI.js +2 -0
  81. package/public/assets/index-Cpje-SXI.js.map +1 -0
  82. package/public/assets/index-D-VZJ2Z7.js +3 -0
  83. package/public/assets/index-D-VZJ2Z7.js.map +1 -0
  84. package/public/assets/index-D3LSE5oW.js +2 -0
  85. package/public/assets/index-D3LSE5oW.js.map +1 -0
  86. package/public/assets/index-DhA0LHT4.js +2 -0
  87. package/public/assets/index-DhA0LHT4.js.map +1 -0
  88. package/public/assets/index-DkaJwGk1.css +1 -0
  89. package/public/assets/{index-Cq5Hfa6i.js → index-DzdSV8oZ.js} +2 -2
  90. package/public/assets/{index-Cq5Hfa6i.js.map → index-DzdSV8oZ.js.map} +1 -1
  91. package/public/assets/index-JmxkH2Vl.js +2 -0
  92. package/public/assets/index-JmxkH2Vl.js.map +1 -0
  93. package/public/assets/index-WJeAfwc5.js +2 -0
  94. package/public/assets/index-WJeAfwc5.js.map +1 -0
  95. package/public/assets/index-hSNEnd1l.js +2 -0
  96. package/public/assets/index-hSNEnd1l.js.map +1 -0
  97. package/public/assets/{loading-B2-6L7aO.js → loading-BdKsKRIT.js} +2 -2
  98. package/public/assets/{loading-B2-6L7aO.js.map → loading-BdKsKRIT.js.map} +1 -1
  99. package/public/assets/main-Bcp7d5hF.js +42 -0
  100. package/public/assets/main-Bcp7d5hF.js.map +1 -0
  101. package/public/assets/{markdown-CH9bocix.js → markdown-Ck_cfSIT.js} +4 -4
  102. package/public/assets/{markdown-CH9bocix.js.map → markdown-Ck_cfSIT.js.map} +1 -1
  103. package/public/assets/{startup-state-settings-card-mmovljyz.js → startup-state-settings-card-BecUJM-2.js} +2 -2
  104. package/public/assets/{startup-state-settings-card-mmovljyz.js.map → startup-state-settings-card-BecUJM-2.js.map} +1 -1
  105. package/public/assets/{terminal-square-U8R46SS0.js → terminal-square-DKJZTU9_.js} +2 -2
  106. package/public/assets/{terminal-square-U8R46SS0.js.map → terminal-square-DKJZTU9_.js.map} +1 -1
  107. package/public/assets/{tool-call-AnfwOPww.js → tool-call-BSI5yjIz.js} +4 -4
  108. package/public/assets/{tool-call-AnfwOPww.js.map → tool-call-BSI5yjIz.js.map} +1 -1
  109. package/public/assets/{unified-picker-DtvQUEiv.js → unified-picker-isN1GYme.js} +2 -2
  110. package/public/assets/{unified-picker-DtvQUEiv.js.map → unified-picker-isN1GYme.js.map} +1 -1
  111. package/public/assets/{wrap-text-Bh1AU9Re.js → wrap-text-D19qzqdL.js} +2 -2
  112. package/public/assets/{wrap-text-Bh1AU9Re.js.map → wrap-text-D19qzqdL.js.map} +1 -1
  113. package/public/index.html +3 -3
  114. package/public/loading.html +3 -3
  115. package/public/sw.js +1 -1
  116. package/public/sw.js.map +1 -1
  117. package/public/assets/App-I9uNKt0K.js +0 -54
  118. package/public/assets/App-I9uNKt0K.js.map +0 -1
  119. package/public/assets/StatusTab-DU1H4ngp.js +0 -2
  120. package/public/assets/StatusTab-DU1H4ngp.js.map +0 -1
  121. package/public/assets/index-B52s_Dh2.js +0 -2
  122. package/public/assets/index-B52s_Dh2.js.map +0 -1
  123. package/public/assets/index-B8W9is7z.js +0 -2
  124. package/public/assets/index-B8W9is7z.js.map +0 -1
  125. package/public/assets/index-Bn8a8ymh.js +0 -2
  126. package/public/assets/index-Bn8a8ymh.js.map +0 -1
  127. package/public/assets/index-CWaDoBhJ.js +0 -2
  128. package/public/assets/index-CWaDoBhJ.js.map +0 -1
  129. package/public/assets/index-CXEtEGDL.css +0 -1
  130. package/public/assets/index-CbuT2QEY.js +0 -2
  131. package/public/assets/index-CbuT2QEY.js.map +0 -1
  132. package/public/assets/index-D03eJbIp.js +0 -2
  133. package/public/assets/index-D03eJbIp.js.map +0 -1
  134. package/public/assets/index-DDK0Fk7j.js +0 -2
  135. package/public/assets/index-DDK0Fk7j.js.map +0 -1
  136. package/public/assets/index-DftCJdT3.js +0 -2
  137. package/public/assets/index-DftCJdT3.js.map +0 -1
  138. package/public/assets/index-_N9V2vB3.js +0 -3
  139. package/public/assets/index-_N9V2vB3.js.map +0 -1
  140. package/public/assets/index-zo6cKyNQ.js +0 -2
  141. package/public/assets/index-zo6cKyNQ.js.map +0 -1
  142. package/public/assets/main-pZWMgVoG.js +0 -42
  143. package/public/assets/main-pZWMgVoG.js.map +0 -1
@@ -1,5 +1,6 @@
1
1
  import { isSessionNotFoundError } from "@opencode/client";
2
2
  import { readLocationRef } from "../opencode/compatibility/location";
3
+ import { InstanceEventQueue } from "./instance-event-queue";
3
4
  const RECONNECT_DELAY_MS = 1000;
4
5
  const LOCATION_OWNER_CACHE_MS = 2000;
5
6
  const SESSION_LOCATION_CACHE_MS = 2000;
@@ -32,10 +33,14 @@ export class InstanceEventBridge {
32
33
  this.status = "connecting";
33
34
  this.generation = 0;
34
35
  this.locationOwners = new Map();
36
+ this.ownershipRevision = 0;
37
+ this.lastSlowWarning = -Infinity;
38
+ this.workspaceEpochs = new Map();
35
39
  this.sessionLocations = new Map();
36
40
  this.ptyLocations = new Map();
37
41
  this.shellLocations = new Map();
38
42
  this.onWorkspaceStarted = (event) => {
43
+ this.advanceWorkspace(event.workspace.id);
39
44
  this.clearLocationCaches();
40
45
  if (!this.task)
41
46
  this.task = this.run();
@@ -43,17 +48,21 @@ export class InstanceEventBridge {
43
48
  this.publishStatus(event.workspace.id, this.status);
44
49
  };
45
50
  this.onWorkspaceStopped = (event) => {
51
+ this.advanceWorkspace(event.workspaceId);
46
52
  this.clearLocationCaches();
47
53
  this.publishStatus(event.workspaceId, "disconnected", "workspace stopped");
48
54
  };
49
55
  this.onWorkspaceError = (event) => {
56
+ this.advanceWorkspace(event.workspace.id);
50
57
  this.clearLocationCaches();
51
58
  this.publishStatus(event.workspace.id, "disconnected", "workspace error");
52
59
  };
60
+ this.onWorktreesChanged = () => this.invalidateOwners();
53
61
  const bus = this.options.eventBus;
54
62
  bus.on("workspace.started", this.onWorkspaceStarted);
55
63
  bus.on("workspace.stopped", this.onWorkspaceStopped);
56
64
  bus.on("workspace.error", this.onWorkspaceError);
65
+ bus.on("workspace.worktreesChanged", this.onWorktreesChanged);
57
66
  }
58
67
  shutdown() {
59
68
  this.controller.abort();
@@ -61,6 +70,7 @@ export class InstanceEventBridge {
61
70
  bus.off("workspace.started", this.onWorkspaceStarted);
62
71
  bus.off("workspace.stopped", this.onWorkspaceStopped);
63
72
  bus.off("workspace.error", this.onWorkspaceError);
73
+ bus.off("workspace.worktreesChanged", this.onWorktreesChanged);
64
74
  for (const workspace of this.options.workspaceManager.list()) {
65
75
  this.publishStatus(workspace.id, "disconnected");
66
76
  }
@@ -70,12 +80,18 @@ export class InstanceEventBridge {
70
80
  this.generation += 1;
71
81
  this.clearLocationCaches();
72
82
  this.updateStatus("connecting");
83
+ const attempt = new AbortController();
84
+ let failure;
85
+ const queue = new InstanceEventQueue(error => { failure = error; attempt.abort(); });
86
+ const abort = () => { attempt.abort(); queue.close(); };
87
+ this.controller.signal.addEventListener("abort", abort, { once: true });
88
+ const current = () => !attempt.signal.aborted && !this.controller.signal.aborted;
73
89
  try {
74
- const events = await this.options.workspaceManager.subscribeToSharedService(this.controller.signal);
90
+ const events = await this.options.workspaceManager.subscribeToSharedService(attempt.signal);
75
91
  let confirmed = false;
76
92
  for await (const event of events) {
77
- if (this.controller.signal.aborted)
78
- return;
93
+ if (!current())
94
+ break;
79
95
  if (!confirmed) {
80
96
  if (event.type !== "server.connected") {
81
97
  throw new Error(`Shared OpenCode event stream started with ${event.type}, expected server.connected`);
@@ -83,25 +99,43 @@ export class InstanceEventBridge {
83
99
  confirmed = true;
84
100
  this.updateStatus("connected");
85
101
  }
86
- await this.publishEvent(event);
102
+ if (event.type === "worktree.updated") {
103
+ this.options.workspaceManager.invalidateWorktrees();
104
+ this.invalidateOwners();
105
+ }
106
+ const receivedAt = Date.now();
107
+ const bytes = Buffer.byteLength(JSON.stringify(event));
108
+ const key = this.eventKey(event);
109
+ const recipients = this.options.workspaceManager.list().map(workspace => ({
110
+ id: workspace.id, epoch: this.workspaceEpochs.get(workspace.id) ?? 0,
111
+ }));
112
+ queue.enqueue(`resolve:${key}`, bytes, () => this.publishEvent(event, {
113
+ current, signal: attempt.signal, queue, key, bytes, recipients, receivedAt,
114
+ }));
87
115
  }
88
116
  if (!this.controller.signal.aborted)
89
- throw new Error("Shared OpenCode event stream ended");
117
+ throw failure ?? new Error("Shared OpenCode event stream ended");
90
118
  }
91
119
  catch (error) {
120
+ attempt.abort();
121
+ queue.close();
92
122
  if (this.controller.signal.aborted)
93
123
  return;
94
- this.options.logger.warn({ err: error }, "Shared OpenCode event stream disconnected");
95
- this.updateStatus("error", error instanceof Error ? error.message : String(error));
124
+ const reason = failure ?? error;
125
+ this.options.logger.warn({ err: reason }, "Shared OpenCode event stream disconnected");
126
+ this.updateStatus("error", reason instanceof Error ? reason.message : String(reason));
96
127
  await this.delay(RECONNECT_DELAY_MS);
97
128
  }
129
+ finally {
130
+ attempt.abort();
131
+ queue.close();
132
+ this.controller.signal.removeEventListener("abort", abort);
133
+ }
98
134
  }
99
135
  }
100
- async publishEvent(event) {
101
- if (event.type === "worktree.updated") {
102
- this.options.workspaceManager.invalidateWorktrees();
103
- this.locationOwners.clear();
104
- }
136
+ async publishEvent(event, route) {
137
+ if (!route.current())
138
+ return;
105
139
  const sessionId = this.sessionId(event);
106
140
  const ptyId = this.ptyId(event);
107
141
  const shellId = this.shellId(event);
@@ -114,16 +148,18 @@ export class InstanceEventBridge {
114
148
  ?? this.ptyInfoLocation(event)
115
149
  ?? (shellId ? this.shellLocations.get(shellId) : undefined)
116
150
  ?? this.shellInfoLocation(event)
117
- ?? (sessionId ? await this.resolveSessionLocation(sessionId) : undefined);
151
+ ?? (sessionId ? await this.resolveSessionLocation(sessionId, route.signal) : undefined);
152
+ if (!route.current())
153
+ return;
118
154
  if (!location) {
119
155
  if (GLOBAL_EVENT_TYPES.has(event.type)) {
120
- this.broadcastEvent(event);
156
+ this.deliverEvent(event, undefined, route);
121
157
  return;
122
158
  }
123
159
  if (event.type === "session.deleted" && sessionId) {
124
160
  // Deletion can make session.get return 404 before the event arrives. Session IDs are
125
161
  // service-global, so notifying every logical workspace cannot delete another session.
126
- this.broadcastEvent(event);
162
+ this.deliverEvent(event, undefined, route);
127
163
  this.sessionLocations.delete(sessionId);
128
164
  }
129
165
  return;
@@ -140,19 +176,7 @@ export class InstanceEventBridge {
140
176
  this.ptyLocations.set(ptyId, location);
141
177
  if (shellId)
142
178
  this.shellLocations.set(shellId, location);
143
- const instanceIds = await this.resolveLocationOwners(location);
144
- if (instanceIds.length === 0) {
145
- if (event.type === "session.deleted" && sessionId)
146
- this.sessionLocations.delete(sessionId);
147
- if (event.type === "pty.deleted" && ptyId)
148
- this.ptyLocations.delete(ptyId);
149
- if (event.type === "shell.deleted" && shellId)
150
- this.shellLocations.delete(shellId);
151
- return;
152
- }
153
- for (const instanceId of instanceIds) {
154
- this.options.eventBus.publish({ type: "instance.event", instanceId, event });
155
- }
179
+ this.deliverEvent(event, location, route);
156
180
  if (event.type === "session.deleted" && sessionId)
157
181
  this.sessionLocations.delete(sessionId);
158
182
  if (event.type === "pty.deleted" && ptyId)
@@ -160,6 +184,54 @@ export class InstanceEventBridge {
160
184
  if (event.type === "shell.deleted" && shellId)
161
185
  this.shellLocations.delete(shellId);
162
186
  }
187
+ eventKey(event) {
188
+ const session = this.sessionId(event);
189
+ if (session)
190
+ return `session:${session}`;
191
+ const pty = this.ptyId(event);
192
+ if (pty)
193
+ return `pty:${pty}`;
194
+ const shell = this.shellId(event);
195
+ if (shell)
196
+ return `shell:${shell}`;
197
+ const location = event.location ? readLocationRef(event.location) : undefined;
198
+ return `location:${JSON.stringify([location?.directory, location?.workspaceID])}`;
199
+ }
200
+ deliverEvent(event, location, route) {
201
+ const resolvedAt = Date.now();
202
+ for (const { id: instanceId, epoch } of route.recipients) {
203
+ const current = () => route.current() && (this.workspaceEpochs.get(instanceId) ?? 0) === epoch;
204
+ route.queue.enqueue(`deliver:${JSON.stringify([instanceId, route.key])}`, route.bytes, async () => {
205
+ if (!current())
206
+ return;
207
+ const lookupStarted = Date.now();
208
+ let allowed = !location;
209
+ let revision;
210
+ do {
211
+ revision = this.ownershipRevision;
212
+ if (location)
213
+ allowed = await this.resolveLocationOwner(instanceId, location, current);
214
+ if (!current())
215
+ return;
216
+ } while (revision !== this.ownershipRevision);
217
+ // Stopped recipients and work from an earlier connection never publish.
218
+ if (!this.options.workspaceManager.list().some(workspace => workspace.id === instanceId))
219
+ return;
220
+ const now = Date.now();
221
+ const upstreamAgeMs = "created" in event && typeof event.created === "number" ? route.receivedAt - event.created : undefined;
222
+ if ((now - route.receivedAt >= 1000 || (upstreamAgeMs ?? 0) >= 1000) && now - this.lastSlowWarning >= 10_000) {
223
+ this.lastSlowWarning = now;
224
+ this.options.logger.warn({ instanceId, eventType: event.type, pending: route.queue.pending,
225
+ routingMs: now - route.receivedAt, ownershipMs: now - lookupStarted,
226
+ locationMs: resolvedAt - route.receivedAt, recipientQueueMs: lookupStarted - resolvedAt,
227
+ upstreamAgeMs,
228
+ }, "Slow instance event routing");
229
+ }
230
+ if (allowed)
231
+ this.options.eventBus.publish({ type: "instance.event", instanceId, event });
232
+ });
233
+ }
234
+ }
163
235
  sessionId(event) {
164
236
  const data = event.data;
165
237
  const sessionId = data.sessionID ?? (event.type === "form.created" ? data.form?.sessionID : undefined);
@@ -191,24 +263,20 @@ export class InstanceEventBridge {
191
263
  const cwd = event.data.info?.cwd;
192
264
  return typeof cwd === "string" && cwd ? { directory: cwd } : undefined;
193
265
  }
194
- broadcastEvent(event) {
195
- for (const workspace of this.options.workspaceManager.list()) {
196
- this.options.eventBus.publish({ type: "instance.event", instanceId: workspace.id, event });
197
- }
198
- }
199
- resolveSessionLocation(sessionId) {
266
+ resolveSessionLocation(sessionId, signal) {
200
267
  const now = Date.now();
201
268
  const cached = this.sessionLocations.get(sessionId);
202
269
  if (cached && cached.expiresAt > now)
203
270
  return cached.location;
204
271
  const resolve = () => this.options.workspaceManager.getSharedServiceClient()
205
- .then((client) => client.session.get({ sessionID: sessionId }))
272
+ .then((client) => client.session.get({ sessionID: sessionId }, { signal }))
206
273
  .then((session) => readLocationRef(session.location));
207
274
  const location = resolve().catch((error) => {
208
- if (isSessionNotFoundError(error))
275
+ if (signal.aborted || isSessionNotFoundError(error))
209
276
  return undefined;
210
277
  return resolve().catch((retryError) => {
211
- this.options.logger.warn({ err: retryError, sessionId }, "Failed to resolve instance event session location");
278
+ if (!signal.aborted)
279
+ this.options.logger.warn({ err: retryError, sessionId }, "Failed to resolve instance event session location");
212
280
  return undefined;
213
281
  });
214
282
  });
@@ -218,41 +286,36 @@ export class InstanceEventBridge {
218
286
  void location.then(settle, settle);
219
287
  return location;
220
288
  }
221
- resolveLocationOwners(location) {
289
+ resolveLocationOwner(instanceId, location, current) {
222
290
  const now = Date.now();
223
- const key = JSON.stringify([location.directory, location.workspaceID]);
291
+ const key = JSON.stringify([instanceId, location.directory, location.workspaceID]);
224
292
  const cached = this.locationOwners.get(key);
225
293
  if (cached && cached.expiresAt > now)
226
- return cached.owners;
227
- const workspaces = this.options.workspaceManager.list();
228
- const owns = (id) => location.workspaceID === undefined
229
- ? this.options.workspaceManager.ownsDirectory(id, location.directory)
230
- : this.options.workspaceManager.ownsLocation(id, location);
231
- const owners = Promise.allSettled(workspaces.map((workspace) => (owns(workspace.id))))
232
- .then(async (ownership) => {
233
- if (ownership.some((result) => result.status === "rejected")) {
234
- ownership = await Promise.allSettled(ownership.map((result, index) => (result.status === "fulfilled"
235
- ? Promise.resolve(result.value)
236
- : owns(workspaces[index].id))));
237
- }
238
- const failed = ownership.find((result) => result.status === "rejected");
239
- if (failed) {
240
- this.options.logger.warn({ err: failed.reason, location }, "Failed to resolve instance event location owner");
241
- }
242
- const currentIds = new Set(this.options.workspaceManager.list().map((workspace) => workspace.id));
243
- return ownership.flatMap((result, index) => {
244
- const id = workspaces[index].id;
245
- return result.status === "fulfilled" && result.value && currentIds.has(id) ? [id] : [];
246
- });
294
+ return cached.owns;
295
+ const resolve = () => location.workspaceID === undefined
296
+ ? this.options.workspaceManager.ownsDirectory(instanceId, location.directory)
297
+ : this.options.workspaceManager.ownsLocation(instanceId, location);
298
+ const owns = Promise.resolve().then(resolve).catch(() => current() ? resolve() : false)
299
+ .catch(error => {
300
+ if (current())
301
+ this.options.logger.warn({ err: error, instanceId, location }, "Failed to resolve instance event location owner");
302
+ return false;
247
303
  });
248
- const entry = { expiresAt: Number.POSITIVE_INFINITY, owners };
304
+ const entry = { expiresAt: Number.POSITIVE_INFINITY, owns };
249
305
  this.locationOwners.set(key, entry);
250
306
  const settle = () => { entry.expiresAt = Date.now() + LOCATION_OWNER_CACHE_MS; };
251
- void owners.then(settle, settle);
252
- return owners;
307
+ void owns.then(settle, settle);
308
+ return owns;
253
309
  }
254
- clearLocationCaches() {
310
+ invalidateOwners() {
311
+ this.ownershipRevision++;
255
312
  this.locationOwners.clear();
313
+ }
314
+ advanceWorkspace(id) {
315
+ this.workspaceEpochs.set(id, (this.workspaceEpochs.get(id) ?? 0) + 1);
316
+ }
317
+ clearLocationCaches() {
318
+ this.invalidateOwners();
256
319
  this.sessionLocations.clear();
257
320
  this.ptyLocations.clear();
258
321
  this.shellLocations.clear();
@@ -269,11 +332,13 @@ export class InstanceEventBridge {
269
332
  }
270
333
  delay(duration) {
271
334
  return new Promise((resolve) => {
272
- const timeout = setTimeout(resolve, duration);
273
- this.controller.signal.addEventListener("abort", () => {
335
+ const done = () => {
274
336
  clearTimeout(timeout);
337
+ this.controller.signal.removeEventListener("abort", done);
275
338
  resolve();
276
- }, { once: true });
339
+ };
340
+ const timeout = setTimeout(done, duration);
341
+ this.controller.signal.addEventListener("abort", done, { once: true });
277
342
  });
278
343
  }
279
344
  }
@@ -1 +1 @@
1
- {"version":3,"file":"instance-events.js","sourceRoot":"","sources":["../../src/workspaces/instance-events.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAwC,MAAM,kBAAkB,CAAA;AAC/F,OAAO,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAA;AAMpE,MAAM,kBAAkB,GAAG,IAAI,CAAA;AAC/B,MAAM,uBAAuB,GAAG,IAAI,CAAA;AACpC,MAAM,yBAAyB,GAAG,IAAI,CAAA;AACtC,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACjC,iBAAiB;IACjB,eAAe;IACf,iBAAiB;IACjB,gBAAgB;IAChB,qBAAqB;IACrB,oBAAoB;IACpB,qBAAqB;IACrB,+BAA+B;IAC/B,sBAAsB;IACtB,uBAAuB;IACvB,oBAAoB;IACpB,sBAAsB;IACtB,eAAe;IACf,gBAAgB;IAChB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C,OAAO,EAAE,EAAE;YACnC,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAA;YAC7C,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,GAAG,EAAE;gBACpD,YAAY,CAAC,OAAO,CAAC,CAAA;gBACrB,OAAO,EAAE,CAAA;YACX,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAA;QACpB,CAAC,CAAC,CAAA;IACJ,CAAC;CACF","sourcesContent":["import { isSessionNotFoundError, type LocationRef, type OpenCodeEvent } from \"@opencode/client\"\nimport { readLocationRef } from \"../opencode/compatibility/location\"\nimport { EventBus } from \"../events/bus\"\nimport { Logger } from \"../logger\"\nimport { WorkspaceManager } from \"./manager\"\nimport { InstanceStreamStatus } from \"../api-types\"\n\nconst RECONNECT_DELAY_MS = 1000\nconst LOCATION_OWNER_CACHE_MS = 2000\nconst SESSION_LOCATION_CACHE_MS = 2000\nconst GLOBAL_EVENT_TYPES = new Set([\n \"catalog.updated\",\n \"agent.updated\",\n \"command.updated\",\n \"config.updated\",\n \"credential.switched\",\n \"credential.updated\",\n \"integration.updated\",\n \"installation.update-available\",\n \"installation.updated\",\n \"mcp.resources.changed\",\n \"mcp.status.changed\",\n \"models-dev.refreshed\",\n \"model.updated\",\n \"plugin.updated\",\n \"provider.updated\",\n \"reference.updated\",\n \"server.connected\",\n \"skill.updated\",\n \"websearch.updated\",\n \"worktree.updated\",\n])\n\ninterface InstanceEventBridgeOptions {\n workspaceManager: WorkspaceManager\n eventBus: EventBus\n logger: Logger\n}\n\nexport class InstanceEventBridge {\n private readonly controller = new AbortController()\n private status: InstanceStreamStatus = \"connecting\"\n private generation = 0\n private task?: Promise<void>\n private readonly locationOwners = new Map<string, { expiresAt: number; owners: Promise<string[]> }>()\n private readonly sessionLocations = new Map<string, { expiresAt: number; location: Promise<LocationRef | undefined> }>()\n private readonly ptyLocations = new Map<string, LocationRef>()\n private readonly shellLocations = new Map<string, LocationRef>()\n private readonly onWorkspaceStarted = (event: { workspace: { id: string } }) => {\n this.clearLocationCaches()\n if (!this.task) this.task = this.run()\n else this.publishStatus(event.workspace.id, this.status)\n }\n private readonly onWorkspaceStopped = (event: { workspaceId: string }) => {\n this.clearLocationCaches()\n this.publishStatus(event.workspaceId, \"disconnected\", \"workspace stopped\")\n }\n private readonly onWorkspaceError = (event: { workspace: { id: string } }) => {\n this.clearLocationCaches()\n this.publishStatus(event.workspace.id, \"disconnected\", \"workspace error\")\n }\n\n constructor(private readonly options: InstanceEventBridgeOptions) {\n const bus = this.options.eventBus\n bus.on(\"workspace.started\", this.onWorkspaceStarted)\n bus.on(\"workspace.stopped\", this.onWorkspaceStopped)\n bus.on(\"workspace.error\", this.onWorkspaceError)\n }\n\n shutdown() {\n this.controller.abort()\n const bus = this.options.eventBus\n bus.off(\"workspace.started\", this.onWorkspaceStarted)\n bus.off(\"workspace.stopped\", this.onWorkspaceStopped)\n bus.off(\"workspace.error\", this.onWorkspaceError)\n for (const workspace of this.options.workspaceManager.list()) {\n this.publishStatus(workspace.id, \"disconnected\")\n }\n }\n\n private async run() {\n while (!this.controller.signal.aborted) {\n this.generation += 1\n this.clearLocationCaches()\n this.updateStatus(\"connecting\")\n try {\n const events = await this.options.workspaceManager.subscribeToSharedService(this.controller.signal)\n let confirmed = false\n for await (const event of events) {\n if (this.controller.signal.aborted) return\n if (!confirmed) {\n if (event.type !== \"server.connected\") {\n throw new Error(`Shared OpenCode event stream started with ${event.type}, expected server.connected`)\n }\n confirmed = true\n this.updateStatus(\"connected\")\n }\n await this.publishEvent(event)\n }\n if (!this.controller.signal.aborted) throw new Error(\"Shared OpenCode event stream ended\")\n } catch (error) {\n if (this.controller.signal.aborted) return\n this.options.logger.warn({ err: error }, \"Shared OpenCode event stream disconnected\")\n this.updateStatus(\"error\", error instanceof Error ? error.message : String(error))\n await this.delay(RECONNECT_DELAY_MS)\n }\n }\n }\n\n private async publishEvent(event: OpenCodeEvent) {\n if (event.type === \"worktree.updated\") {\n this.options.workspaceManager.invalidateWorktrees()\n this.locationOwners.clear()\n }\n const sessionId = this.sessionId(event)\n const ptyId = this.ptyId(event)\n const shellId = this.shellId(event)\n if (event.type === \"session.moved\" && sessionId) this.sessionLocations.delete(sessionId)\n\n // A scoped event is native location authority, not merely a cwd hint. Keep\n // that full pair for subsequent locationless PTY/Shell/session events.\n const location = event.location ? readLocationRef(event.location)\n : (ptyId ? this.ptyLocations.get(ptyId) : undefined)\n ?? this.ptyInfoLocation(event)\n ?? (shellId ? this.shellLocations.get(shellId) : undefined)\n ?? this.shellInfoLocation(event)\n ?? (sessionId ? await this.resolveSessionLocation(sessionId) : undefined)\n if (!location) {\n if (GLOBAL_EVENT_TYPES.has(event.type)) {\n this.broadcastEvent(event)\n return\n }\n if (event.type === \"session.deleted\" && sessionId) {\n // Deletion can make session.get return 404 before the event arrives. Session IDs are\n // service-global, so notifying every logical workspace cannot delete another session.\n this.broadcastEvent(event)\n this.sessionLocations.delete(sessionId)\n }\n return\n }\n // The moved envelope can refer to the old location. The next locationless\n // event must resolve the native session rather than cache that old owner.\n if (sessionId && event.type !== \"session.moved\") {\n this.sessionLocations.set(sessionId, {\n expiresAt: Date.now() + SESSION_LOCATION_CACHE_MS,\n location: Promise.resolve(location),\n })\n }\n if (ptyId) this.ptyLocations.set(ptyId, location)\n if (shellId) this.shellLocations.set(shellId, location)\n\n const instanceIds = await this.resolveLocationOwners(location)\n if (instanceIds.length === 0) {\n if (event.type === \"session.deleted\" && sessionId) this.sessionLocations.delete(sessionId)\n if (event.type === \"pty.deleted\" && ptyId) this.ptyLocations.delete(ptyId)\n if (event.type === \"shell.deleted\" && shellId) this.shellLocations.delete(shellId)\n return\n }\n\n for (const instanceId of instanceIds) {\n this.options.eventBus.publish({ type: \"instance.event\", instanceId, event })\n }\n if (event.type === \"session.deleted\" && sessionId) this.sessionLocations.delete(sessionId)\n if (event.type === \"pty.deleted\" && ptyId) this.ptyLocations.delete(ptyId)\n if (event.type === \"shell.deleted\" && shellId) this.shellLocations.delete(shellId)\n }\n\n private sessionId(event: OpenCodeEvent): string | undefined {\n const data = event.data as { sessionID?: unknown; form?: { sessionID?: unknown } }\n const sessionId = data.sessionID ?? (event.type === \"form.created\" ? data.form?.sessionID : undefined)\n return typeof sessionId === \"string\" && sessionId && sessionId !== \"global\" ? sessionId : undefined\n }\n\n private ptyId(event: OpenCodeEvent): string | undefined {\n if (!event.type.startsWith(\"pty.\")) return undefined\n const data = event.data as { id?: unknown; info?: { id?: unknown } }\n const id = data.id ?? data.info?.id\n return typeof id === \"string\" && id ? id : undefined\n }\n\n private ptyInfoLocation(event: OpenCodeEvent): LocationRef | undefined {\n if (event.type !== \"pty.created\" && event.type !== \"pty.updated\") return undefined\n const cwd = (event.data as { info?: { cwd?: unknown } }).info?.cwd\n return typeof cwd === \"string\" && cwd ? { directory: cwd } : undefined\n }\n\n private shellId(event: OpenCodeEvent): string | undefined {\n if (!event.type.startsWith(\"shell.\")) return undefined\n const data = event.data as { id?: unknown; info?: { id?: unknown } }\n const id = data.id ?? data.info?.id\n return typeof id === \"string\" && id ? id : undefined\n }\n\n private shellInfoLocation(event: OpenCodeEvent): LocationRef | undefined {\n if (event.type !== \"shell.created\") return undefined\n const cwd = (event.data as { info?: { cwd?: unknown } }).info?.cwd\n return typeof cwd === \"string\" && cwd ? { directory: cwd } : undefined\n }\n\n private broadcastEvent(event: OpenCodeEvent): void {\n for (const workspace of this.options.workspaceManager.list()) {\n this.options.eventBus.publish({ type: \"instance.event\", instanceId: workspace.id, event })\n }\n }\n\n private resolveSessionLocation(sessionId: string): Promise<LocationRef | undefined> {\n const now = Date.now()\n const cached = this.sessionLocations.get(sessionId)\n if (cached && cached.expiresAt > now) return cached.location\n\n const resolve = () => this.options.workspaceManager.getSharedServiceClient()\n .then((client) => client.session.get({ sessionID: sessionId }))\n .then((session) => readLocationRef(session.location))\n const location = resolve().catch((error) => {\n if (isSessionNotFoundError(error)) return undefined\n return resolve().catch((retryError) => {\n this.options.logger.warn({ err: retryError, sessionId }, \"Failed to resolve instance event session location\")\n return undefined\n })\n })\n const entry = { expiresAt: Number.POSITIVE_INFINITY, location }\n this.sessionLocations.set(sessionId, entry)\n const settle = () => { entry.expiresAt = Date.now() + SESSION_LOCATION_CACHE_MS }\n void location.then(settle, settle)\n return location\n }\n\n private resolveLocationOwners(location: LocationRef): Promise<string[]> {\n const now = Date.now()\n const key = JSON.stringify([location.directory, location.workspaceID])\n const cached = this.locationOwners.get(key)\n if (cached && cached.expiresAt > now) return cached.owners\n\n const workspaces = this.options.workspaceManager.list()\n const owns = (id: string) => location.workspaceID === undefined\n ? this.options.workspaceManager.ownsDirectory(id, location.directory)\n : this.options.workspaceManager.ownsLocation(id, location)\n const owners = Promise.allSettled(workspaces.map((workspace) => (\n owns(workspace.id)\n )))\n .then(async (ownership) => {\n if (ownership.some((result) => result.status === \"rejected\")) {\n ownership = await Promise.allSettled(ownership.map((result, index) => (\n result.status === \"fulfilled\"\n ? Promise.resolve(result.value)\n : owns(workspaces[index].id)\n )))\n }\n const failed = ownership.find((result) => result.status === \"rejected\")\n if (failed) {\n this.options.logger.warn({ err: failed.reason, location }, \"Failed to resolve instance event location owner\")\n }\n const currentIds = new Set(this.options.workspaceManager.list().map((workspace) => workspace.id))\n return ownership.flatMap((result, index) => {\n const id = workspaces[index].id\n return result.status === \"fulfilled\" && result.value && currentIds.has(id) ? [id] : []\n })\n })\n const entry = { expiresAt: Number.POSITIVE_INFINITY, owners }\n this.locationOwners.set(key, entry)\n const settle = () => { entry.expiresAt = Date.now() + LOCATION_OWNER_CACHE_MS }\n void owners.then(settle, settle)\n return owners\n }\n\n private clearLocationCaches(): void {\n this.locationOwners.clear()\n this.sessionLocations.clear()\n this.ptyLocations.clear()\n this.shellLocations.clear()\n }\n\n private updateStatus(status: InstanceStreamStatus, reason?: string) {\n this.status = status\n for (const workspace of this.options.workspaceManager.list()) {\n this.publishStatus(workspace.id, status, reason)\n }\n }\n\n private publishStatus(instanceId: string, status: InstanceStreamStatus, reason?: string) {\n this.options.logger.debug({ instanceId, status, reason }, \"Instance event status updated\")\n this.options.eventBus.publish({ type: \"instance.eventStatus\", instanceId, status, generation: this.generation, reason })\n }\n\n private delay(duration: number) {\n return new Promise<void>((resolve) => {\n const timeout = setTimeout(resolve, duration)\n this.controller.signal.addEventListener(\"abort\", () => {\n clearTimeout(timeout)\n resolve()\n }, { once: true })\n })\n }\n}\n"]}
1
+ {"version":3,"file":"instance-events.js","sourceRoot":"","sources":["../../src/workspaces/instance-events.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAwC,MAAM,kBAAkB,CAAA;AAC/F,OAAO,EAAE,eAAe,EAAE,MAAM,oCAAoC,CAAA;AAKpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAA;AAE3D,MAAM,kBAAkB,GAAG,IAAI,CAAA;AAC/B,MAAM,uBAAuB,GAAG,IAAI,CAAA;AACpC,MAAM,yBAAyB,GAAG,IAAI,CAAA;AACtC,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC;IACjC,iBAAiB;IACjB,eAAe;IACf,iBAAiB;IACjB,gBAAgB;IAChB,qBAAqB;IACrB,oBAAoB;IACpB,qBAAqB;IACrB,+BAA+B;IAC/B,sBAAsB;IACtB,uBAAuB;IACvB,oBAAoB;IACpB,sBAAsB;IACtB,eAAe;IACf,gBAAgB;IAChB,kBAAkB;IAClB,mBAAmB;IACnB,kBAAkB;IAClB,eAAe;IACf,mBAAmB;IACnB,kBAAkB;CACnB,CAAC,CAAA;AAkBF,MAAM,OAAO,mBAAmB;IA8B9B,YAA6B,OAAmC;QAAnC,YAAO,GAAP,OAAO,CAA4B;QA7B/C,eAAU,GAAG,IAAI,eAAe,EAAE,CAAA;QAC3C,WAAM,GAAyB,YAAY,CAAA;QAC3C,eAAU,GAAG,CAAC,CAAA;QAEL,mBAAc,GAAG,IAAI,GAAG,EAAyD,CAAA;QAC1F,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oundError, type LocationRef, type OpenCodeEvent } from \"@opencode/client\"\nimport { readLocationRef } from \"../opencode/compatibility/location\"\nimport { EventBus } from \"../events/bus\"\nimport { Logger } from \"../logger\"\nimport { WorkspaceManager } from \"./manager\"\nimport { InstanceStreamStatus } from \"../api-types\"\nimport { InstanceEventQueue } from \"./instance-event-queue\"\n\nconst RECONNECT_DELAY_MS = 1000\nconst LOCATION_OWNER_CACHE_MS = 2000\nconst SESSION_LOCATION_CACHE_MS = 2000\nconst GLOBAL_EVENT_TYPES = new Set([\n \"catalog.updated\",\n \"agent.updated\",\n \"command.updated\",\n \"config.updated\",\n \"credential.switched\",\n \"credential.updated\",\n \"integration.updated\",\n \"installation.update-available\",\n \"installation.updated\",\n \"mcp.resources.changed\",\n \"mcp.status.changed\",\n \"models-dev.refreshed\",\n \"model.updated\",\n \"plugin.updated\",\n \"provider.updated\",\n \"reference.updated\",\n \"server.connected\",\n \"skill.updated\",\n \"websearch.updated\",\n \"worktree.updated\",\n])\n\ninterface InstanceEventBridgeOptions {\n workspaceManager: WorkspaceManager\n eventBus: EventBus\n logger: Logger\n}\n\ninterface EventRoute {\n current: () => boolean\n signal: AbortSignal\n queue: InstanceEventQueue\n key: string\n bytes: number\n recipients: Array<{ id: string; epoch: number }>\n receivedAt: number\n}\n\nexport class InstanceEventBridge {\n private readonly controller = new AbortController()\n private status: InstanceStreamStatus = \"connecting\"\n private generation = 0\n private task?: Promise<void>\n private readonly locationOwners = new Map<string, { expiresAt: number; owns: Promise<boolean> }>()\n private ownershipRevision = 0\n private lastSlowWarning = -Infinity\n private readonly workspaceEpochs = new Map<string, number>()\n private readonly sessionLocations = new Map<string, { expiresAt: number; location: Promise<LocationRef | undefined> }>()\n private readonly ptyLocations = new Map<string, LocationRef>()\n private readonly shellLocations = new Map<string, LocationRef>()\n private readonly onWorkspaceStarted = (event: { workspace: { id: string } }) => {\n this.advanceWorkspace(event.workspace.id)\n this.clearLocationCaches()\n if (!this.task) this.task = this.run()\n else this.publishStatus(event.workspace.id, this.status)\n }\n private readonly onWorkspaceStopped = (event: { workspaceId: string }) => {\n this.advanceWorkspace(event.workspaceId)\n this.clearLocationCaches()\n this.publishStatus(event.workspaceId, \"disconnected\", \"workspace stopped\")\n }\n private readonly onWorkspaceError = (event: { workspace: { id: string } }) => {\n this.advanceWorkspace(event.workspace.id)\n this.clearLocationCaches()\n this.publishStatus(event.workspace.id, \"disconnected\", \"workspace error\")\n }\n private readonly onWorktreesChanged = () => this.invalidateOwners()\n\n constructor(private readonly options: InstanceEventBridgeOptions) {\n const bus = this.options.eventBus\n bus.on(\"workspace.started\", this.onWorkspaceStarted)\n bus.on(\"workspace.stopped\", this.onWorkspaceStopped)\n bus.on(\"workspace.error\", this.onWorkspaceError)\n bus.on(\"workspace.worktreesChanged\", this.onWorktreesChanged)\n }\n\n shutdown() {\n this.controller.abort()\n const bus = this.options.eventBus\n bus.off(\"workspace.started\", this.onWorkspaceStarted)\n bus.off(\"workspace.stopped\", this.onWorkspaceStopped)\n bus.off(\"workspace.error\", this.onWorkspaceError)\n bus.off(\"workspace.worktreesChanged\", this.onWorktreesChanged)\n for (const workspace of this.options.workspaceManager.list()) {\n this.publishStatus(workspace.id, \"disconnected\")\n }\n }\n\n private async run() {\n while (!this.controller.signal.aborted) {\n this.generation += 1\n this.clearLocationCaches()\n this.updateStatus(\"connecting\")\n const attempt = new AbortController()\n let failure: Error | undefined\n const queue = new InstanceEventQueue(error => { failure = error; attempt.abort() })\n const abort = () => { attempt.abort(); queue.close() }\n this.controller.signal.addEventListener(\"abort\", abort, { once: true })\n const current = () => !attempt.signal.aborted && !this.controller.signal.aborted\n try {\n const events = await this.options.workspaceManager.subscribeToSharedService(attempt.signal)\n let confirmed = false\n for await (const event of events) {\n if (!current()) break\n if (!confirmed) {\n if (event.type !== \"server.connected\") {\n throw new Error(`Shared OpenCode event stream started with ${event.type}, expected server.connected`)\n }\n confirmed = true\n this.updateStatus(\"connected\")\n }\n if (event.type === \"worktree.updated\") {\n this.options.workspaceManager.invalidateWorktrees()\n this.invalidateOwners()\n }\n const receivedAt = Date.now()\n const bytes = Buffer.byteLength(JSON.stringify(event))\n const key = this.eventKey(event)\n const recipients = this.options.workspaceManager.list().map(workspace => ({\n id: workspace.id, epoch: this.workspaceEpochs.get(workspace.id) ?? 0,\n }))\n queue.enqueue(`resolve:${key}`, bytes, () => this.publishEvent(event, {\n current, signal: attempt.signal, queue, key, bytes, recipients, receivedAt,\n }))\n }\n if (!this.controller.signal.aborted) throw failure ?? new Error(\"Shared OpenCode event stream ended\")\n } catch (error) {\n attempt.abort()\n queue.close()\n if (this.controller.signal.aborted) return\n const reason = failure ?? error\n this.options.logger.warn({ err: reason }, \"Shared OpenCode event stream disconnected\")\n this.updateStatus(\"error\", reason instanceof Error ? reason.message : String(reason))\n await this.delay(RECONNECT_DELAY_MS)\n } finally {\n attempt.abort()\n queue.close()\n this.controller.signal.removeEventListener(\"abort\", abort)\n }\n }\n }\n\n private async publishEvent(event: OpenCodeEvent, route: EventRoute) {\n if (!route.current()) return\n const sessionId = this.sessionId(event)\n const ptyId = this.ptyId(event)\n const shellId = this.shellId(event)\n if (event.type === \"session.moved\" && sessionId) this.sessionLocations.delete(sessionId)\n\n // A scoped event is native location authority, not merely a cwd hint. Keep\n // that full pair for subsequent locationless PTY/Shell/session events.\n const location = event.location ? readLocationRef(event.location)\n : (ptyId ? this.ptyLocations.get(ptyId) : undefined)\n ?? this.ptyInfoLocation(event)\n ?? (shellId ? this.shellLocations.get(shellId) : undefined)\n ?? this.shellInfoLocation(event)\n ?? (sessionId ? await this.resolveSessionLocation(sessionId, route.signal) : undefined)\n if (!route.current()) return\n if (!location) {\n if (GLOBAL_EVENT_TYPES.has(event.type)) {\n this.deliverEvent(event, undefined, route)\n return\n }\n if (event.type === \"session.deleted\" && sessionId) {\n // Deletion can make session.get return 404 before the event arrives. Session IDs are\n // service-global, so notifying every logical workspace cannot delete another session.\n this.deliverEvent(event, undefined, route)\n this.sessionLocations.delete(sessionId)\n }\n return\n }\n // The moved envelope can refer to the old location. The next locationless\n // event must resolve the native session rather than cache that old owner.\n if (sessionId && event.type !== \"session.moved\") {\n this.sessionLocations.set(sessionId, {\n expiresAt: Date.now() + SESSION_LOCATION_CACHE_MS,\n location: Promise.resolve(location),\n })\n }\n if (ptyId) this.ptyLocations.set(ptyId, location)\n if (shellId) this.shellLocations.set(shellId, location)\n\n this.deliverEvent(event, location, route)\n if (event.type === \"session.deleted\" && sessionId) this.sessionLocations.delete(sessionId)\n if (event.type === \"pty.deleted\" && ptyId) this.ptyLocations.delete(ptyId)\n if (event.type === \"shell.deleted\" && shellId) this.shellLocations.delete(shellId)\n }\n\n private eventKey(event: OpenCodeEvent): string {\n const session = this.sessionId(event)\n if (session) return `session:${session}`\n const pty = this.ptyId(event)\n if (pty) return `pty:${pty}`\n const shell = this.shellId(event)\n if (shell) return `shell:${shell}`\n const location = event.location ? readLocationRef(event.location) : undefined\n return `location:${JSON.stringify([location?.directory, location?.workspaceID])}`\n }\n\n private deliverEvent(event: OpenCodeEvent, location: LocationRef | undefined, route: EventRoute): void {\n const resolvedAt = Date.now()\n for (const { id: instanceId, epoch } of route.recipients) {\n const current = () => route.current() && (this.workspaceEpochs.get(instanceId) ?? 0) === epoch\n route.queue.enqueue(`deliver:${JSON.stringify([instanceId, route.key])}`, route.bytes, async () => {\n if (!current()) return\n const lookupStarted = Date.now()\n let allowed = !location\n let revision: number\n do {\n revision = this.ownershipRevision\n if (location) allowed = await this.resolveLocationOwner(instanceId, location, current)\n if (!current()) return\n } while (revision !== this.ownershipRevision)\n // Stopped recipients and work from an earlier connection never publish.\n if (!this.options.workspaceManager.list().some(workspace => workspace.id === instanceId)) return\n const now = Date.now()\n const upstreamAgeMs = \"created\" in event && typeof event.created === \"number\" ? route.receivedAt - event.created : undefined\n if ((now - route.receivedAt >= 1000 || (upstreamAgeMs ?? 0) >= 1000) && now - this.lastSlowWarning >= 10_000) {\n this.lastSlowWarning = now\n this.options.logger.warn({ instanceId, eventType: event.type, pending: route.queue.pending,\n routingMs: now - route.receivedAt, ownershipMs: now - lookupStarted,\n locationMs: resolvedAt - route.receivedAt, recipientQueueMs: lookupStarted - resolvedAt,\n upstreamAgeMs,\n }, \"Slow instance event routing\")\n }\n if (allowed) this.options.eventBus.publish({ type: \"instance.event\", instanceId, event })\n })\n }\n }\n\n private sessionId(event: OpenCodeEvent): string | undefined {\n const data = event.data as { sessionID?: unknown; form?: { sessionID?: unknown } }\n const sessionId = data.sessionID ?? (event.type === \"form.created\" ? data.form?.sessionID : undefined)\n return typeof sessionId === \"string\" && sessionId && sessionId !== \"global\" ? sessionId : undefined\n }\n\n private ptyId(event: OpenCodeEvent): string | undefined {\n if (!event.type.startsWith(\"pty.\")) return undefined\n const data = event.data as { id?: unknown; info?: { id?: unknown } }\n const id = data.id ?? data.info?.id\n return typeof id === \"string\" && id ? id : undefined\n }\n\n private ptyInfoLocation(event: OpenCodeEvent): LocationRef | undefined {\n if (event.type !== \"pty.created\" && event.type !== \"pty.updated\") return undefined\n const cwd = (event.data as { info?: { cwd?: unknown } }).info?.cwd\n return typeof cwd === \"string\" && cwd ? { directory: cwd } : undefined\n }\n\n private shellId(event: OpenCodeEvent): string | undefined {\n if (!event.type.startsWith(\"shell.\")) return undefined\n const data = event.data as { id?: unknown; info?: { id?: unknown } }\n const id = data.id ?? data.info?.id\n return typeof id === \"string\" && id ? id : undefined\n }\n\n private shellInfoLocation(event: OpenCodeEvent): LocationRef | undefined {\n if (event.type !== \"shell.created\") return undefined\n const cwd = (event.data as { info?: { cwd?: unknown } }).info?.cwd\n return typeof cwd === \"string\" && cwd ? { directory: cwd } : undefined\n }\n\n private resolveSessionLocation(sessionId: string, signal: AbortSignal): Promise<LocationRef | undefined> {\n const now = Date.now()\n const cached = this.sessionLocations.get(sessionId)\n if (cached && cached.expiresAt > now) return cached.location\n\n const resolve = () => this.options.workspaceManager.getSharedServiceClient()\n .then((client) => client.session.get({ sessionID: sessionId }, { signal }))\n .then((session) => readLocationRef(session.location))\n const location = resolve().catch((error) => {\n if (signal.aborted || isSessionNotFoundError(error)) return undefined\n return resolve().catch((retryError) => {\n if (!signal.aborted) this.options.logger.warn({ err: retryError, sessionId }, \"Failed to resolve instance event session location\")\n return undefined\n })\n })\n const entry = { expiresAt: Number.POSITIVE_INFINITY, location }\n this.sessionLocations.set(sessionId, entry)\n const settle = () => { entry.expiresAt = Date.now() + SESSION_LOCATION_CACHE_MS }\n void location.then(settle, settle)\n return location\n }\n\n private resolveLocationOwner(instanceId: string, location: LocationRef, current: () => boolean): Promise<boolean> {\n const now = Date.now()\n const key = JSON.stringify([instanceId, location.directory, location.workspaceID])\n const cached = this.locationOwners.get(key)\n if (cached && cached.expiresAt > now) return cached.owns\n\n const resolve = () => location.workspaceID === undefined\n ? this.options.workspaceManager.ownsDirectory(instanceId, location.directory)\n : this.options.workspaceManager.ownsLocation(instanceId, location)\n const owns = Promise.resolve().then(resolve).catch(() => current() ? resolve() : false)\n .catch(error => {\n if (current()) this.options.logger.warn({ err: error, instanceId, location }, \"Failed to resolve instance event location owner\")\n return false\n })\n const entry = { expiresAt: Number.POSITIVE_INFINITY, owns }\n this.locationOwners.set(key, entry)\n const settle = () => { entry.expiresAt = Date.now() + LOCATION_OWNER_CACHE_MS }\n void owns.then(settle, settle)\n return owns\n }\n\n private invalidateOwners(): void {\n this.ownershipRevision++\n this.locationOwners.clear()\n }\n\n private advanceWorkspace(id: string): void {\n this.workspaceEpochs.set(id, (this.workspaceEpochs.get(id) ?? 0) + 1)\n }\n\n private clearLocationCaches(): void {\n this.invalidateOwners()\n this.sessionLocations.clear()\n this.ptyLocations.clear()\n this.shellLocations.clear()\n }\n\n private updateStatus(status: InstanceStreamStatus, reason?: string) {\n this.status = status\n for (const workspace of this.options.workspaceManager.list()) {\n this.publishStatus(workspace.id, status, reason)\n }\n }\n\n private publishStatus(instanceId: string, status: InstanceStreamStatus, reason?: string) {\n this.options.logger.debug({ instanceId, status, reason }, \"Instance event status updated\")\n this.options.eventBus.publish({ type: \"instance.eventStatus\", instanceId, status, generation: this.generation, reason })\n }\n\n private delay(duration: number) {\n return new Promise<void>((resolve) => {\n const done = () => {\n clearTimeout(timeout)\n this.controller.signal.removeEventListener(\"abort\", done)\n resolve()\n }\n const timeout = setTimeout(done, duration)\n this.controller.signal.addEventListener(\"abort\", done, { once: true })\n })\n }\n}\n"]}
@@ -80,13 +80,15 @@ describe("InstanceEventBridge", () => {
80
80
  manager.ownsLocation = async (...args) => { checks++; return owns(...args); };
81
81
  const bus = new EventBus();
82
82
  const received = [];
83
- bus.on("instance.event", event => { if (event.event.type !== "server.connected")
84
- received.push(event.instanceId); });
83
+ bus.on("instance.event", event => {
84
+ if (event.event.type === "session.text.delta")
85
+ received.push(`${event.instanceId}:${event.event.data.delta}`);
86
+ });
85
87
  const bridge = new InstanceEventBridge({ workspaceManager: manager, eventBus: bus, logger });
86
88
  try {
87
89
  bus.publish({ type: "workspace.started", workspace: manager.list()[0] });
88
90
  await waitFor(() => received.length === events.length);
89
- assert.deepEqual(received, ["a", "b", "a", "b", "b", "b"]);
91
+ assert.deepEqual([...received].sort(), ["a:one", "b:two", "a:cached one", "b:cached two", "b:resolved two", "b:cached resolved two"].sort());
90
92
  assert.equal(checks, 4, "one lookup per full location and logical workspace");
91
93
  assert.equal(sessionGets(), 1);
92
94
  }
@@ -234,6 +236,7 @@ describe("InstanceEventBridge", () => {
234
236
  }
235
237
  });
236
238
  it("clears routing caches before reconnecting", async () => {
239
+ const firstDelivered = deferred();
237
240
  let subscriptions = 0;
238
241
  let ownershipChecks = 0;
239
242
  const event = { type: "permission.asked", location: { directory: "/repo-a" }, data: { id: "p1" } };
@@ -246,6 +249,8 @@ describe("InstanceEventBridge", () => {
246
249
  return (async function* () {
247
250
  yield serverConnected();
248
251
  yield event;
252
+ if (current === 1)
253
+ await firstDelivered.promise;
249
254
  if (current > 1)
250
255
  await new Promise((resolve) => signal?.addEventListener("abort", () => resolve(), { once: true }));
251
256
  })();
@@ -254,8 +259,10 @@ describe("InstanceEventBridge", () => {
254
259
  const bus = new EventBus();
255
260
  const received = [];
256
261
  bus.on("instance.event", (value) => {
257
- if (value.event.type !== "server.connected")
262
+ if (value.event.type !== "server.connected") {
258
263
  received.push(value);
264
+ firstDelivered.resolve();
265
+ }
259
266
  });
260
267
  const bridge = new InstanceEventBridge({ workspaceManager: manager, eventBus: bus, logger });
261
268
  try {
@@ -400,7 +407,7 @@ describe("InstanceEventBridge", () => {
400
407
  try {
401
408
  bus.publish({ type: "workspace.started", workspace: manager.list()[0] });
402
409
  await waitFor(() => received.length === 2);
403
- assert.deepEqual(received, ["failed", "owner"]);
410
+ assert.deepEqual(received, ["owner", "failed"], "the successful recipient must not wait for another recipient's retry");
404
411
  assert.equal(failedOwnerChecks, 2);
405
412
  }
406
413
  finally {
@@ -414,8 +421,8 @@ describe("InstanceEventBridge", () => {
414
421
  const manager = {
415
422
  list: () => workspaces,
416
423
  ownsDirectory: async (workspaceId) => {
417
- if (workspaceId === "owner")
418
- return true;
424
+ if (workspaceId !== "owner")
425
+ return false;
419
426
  if (++checks === 1)
420
427
  throw new Error("temporary lookup failure");
421
428
  return retry.promise;
@@ -423,6 +430,7 @@ describe("InstanceEventBridge", () => {
423
430
  subscribeToSharedService: async (signal) => (async function* () {
424
431
  yield serverConnected();
425
432
  yield { type: "permission.asked", location: { directory: "/repo" }, data: { id: "p1" } };
433
+ await retry.promise;
426
434
  yield { id: "model-update", created: 1, type: "model.updated", data: {} };
427
435
  await new Promise((resolve) => signal?.addEventListener("abort", () => resolve(), { once: true }));
428
436
  })(),
@@ -438,7 +446,8 @@ describe("InstanceEventBridge", () => {
438
446
  bus.publish({ type: "workspace.started", workspace: workspaces[0] });
439
447
  await waitFor(() => checks === 2);
440
448
  workspaces = [workspaces[1]];
441
- retry.resolve(false);
449
+ bus.publish({ type: "workspace.stopped", workspaceId: "owner" });
450
+ retry.resolve(true);
442
451
  await waitFor(() => received.length === 1);
443
452
  assert.equal(received[0].event.type, "model.updated");
444
453
  assert.equal(received[0].instanceId, "flaky");