@openchamber/web 1.18.3 → 1.18.4

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 (60) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-DbUi6I9s.js → CodeMirrorCommentWidgets-4qZbrEXU.js} +1 -1
  2. package/dist/assets/{CommitSection-Jc2_hNPE.js → CommitSection-MJmntVPJ.js} +1 -1
  3. package/dist/assets/{DiagramEditor-PCrYHBko.js → DiagramEditor-jnG3Hbxg.js} +1 -1
  4. package/dist/assets/{DiagramView-CndEcZNu.js → DiagramView-CFXxgg_a.js} +1 -1
  5. package/dist/assets/{DiffView-DEGlNjMH.js → DiffView-DZIoOnV7.js} +1 -1
  6. package/dist/assets/{FilesView-CzUgIvUm.js → FilesView-BKL6YlKG.js} +1 -1
  7. package/dist/assets/{GitView-C-n17voy.js → GitView-DBFrDDBv.js} +1 -1
  8. package/dist/assets/{JsonTreeView-BYcgdTOQ.js → JsonTreeView-DLW2Wy1g.js} +1 -1
  9. package/dist/assets/MarkdownImageGallery-DKIylIK7.js +1 -0
  10. package/dist/assets/MarkdownRendererImpl-CLv8hxvv.js +12 -0
  11. package/dist/assets/{OnboardingScreen-BmN0lhk4.js → OnboardingScreen-D2Y6djMw.js} +1 -1
  12. package/dist/assets/{PatchDiff-Bn7bfgUv.js → PatchDiff-BuLPx7AN.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-D1fWvrUn.js → PierreDiffViewer-BHm4Yr0X.js} +1 -1
  14. package/dist/assets/{PlanView-CWM0iyFk.js → PlanView-ZYEJn8A_.js} +1 -1
  15. package/dist/assets/{SessionSwitcherDropdown-Cez-9xRh.js → SessionSwitcherDropdown-rro-SsaO.js} +1 -1
  16. package/dist/assets/{SettingsView-Bl1drwPw.js → SettingsView-5RmswFZe.js} +1 -1
  17. package/dist/assets/{SettingsWindow-DL5axjDZ.js → SettingsWindow-BZhAYFdS.js} +1 -1
  18. package/dist/assets/{ToolOutputDialog-BtIJkFno.js → ToolOutputDialog-Za6V4VMJ.js} +1 -1
  19. package/dist/assets/{ToolPartDiffPreview-i3PQo6_0.js → ToolPartDiffPreview-BL-9ixyC.js} +1 -1
  20. package/dist/assets/{VirtualizedFileDiff-DkcusvMa.js → VirtualizedFileDiff-CwGocYQd.js} +1 -1
  21. package/dist/assets/{WalkthroughView-Cc5Hd6P5.js → WalkthroughView-5DyvN03T.js} +1 -1
  22. package/dist/assets/{computeVirtualFileMetrics-xPena3W2.js → computeVirtualFileMetrics-Da00Jg7M.js} +1 -1
  23. package/dist/assets/{contextPanelEmbeddedChat-tQekJUAF.js → contextPanelEmbeddedChat-B-bSg3P5.js} +1 -1
  24. package/dist/assets/index-BzIpNlNE.css +1 -0
  25. package/dist/assets/{index-Crz1YOFl.js → index-C0yNhuZw.js} +1 -1
  26. package/dist/assets/{index-iFY_N5aO.js → index-DRpChWux.js} +1 -1
  27. package/dist/assets/{isDiffPlainText-Dudf-dWx.js → isDiffPlainText-D9YpoLrV.js} +1 -1
  28. package/dist/assets/{isFilePlainText-DS4QV1dd.js → isFilePlainText-gTibdNIe.js} +1 -1
  29. package/dist/assets/{main-C0DyIwTb.js → main-D7UcL3VQ.js} +2 -2
  30. package/dist/assets/{main-CAxX6DAN.js → main-DPMd2iKS.js} +4 -4
  31. package/dist/assets/markdownCore-DDrHVneM.js +2 -0
  32. package/dist/assets/{miniChat-CGfrxKpJ.js → miniChat-O_GVoEbc.js} +2 -2
  33. package/dist/assets/{mobile-DEmhwNcV.js → mobile-Br4TtAqc.js} +2 -2
  34. package/dist/assets/{patchFileDiff-C5D1OPCa.js → patchFileDiff-KNkxM1C1.js} +1 -1
  35. package/dist/assets/{renderElectronMiniChatApp-Dpbswpom.js → renderElectronMiniChatApp-CJpdxTT1.js} +2 -2
  36. package/dist/assets/{renderMobileApp-B5HA4qbi.js → renderMobileApp-toj9cXoh.js} +4 -4
  37. package/dist/assets/{runtimeEndpointReset-cbahJ3hD.js → runtimeEndpointReset-BVmispdD.js} +2 -2
  38. package/dist/assets/{scheduledTasksApi-BxgGWTL8.js → scheduledTasksApi-ByKya3Un.js} +1 -1
  39. package/dist/assets/{shikiHighlight-CmanopUB.js → shikiHighlight-C7LTbwFx.js} +1 -1
  40. package/dist/assets/{useAppFontEffects-sHmU5b8u.js → useAppFontEffects-BikB6enL.js} +131 -131
  41. package/dist/assets/{useInlineCommentController-gt56WkxJ.js → useInlineCommentController-CYPvYJDt.js} +1 -1
  42. package/dist/assets/{vendor-codemirror-language-data-Dihw9MtL.js → vendor-codemirror-language-data-CLHw8NWn.js} +2 -2
  43. package/dist/assets/{web-components-BL-Ur2Tb.js → web-components-GMc3oR3i.js} +1 -1
  44. package/dist/index.html +4 -4
  45. package/dist/mini-chat.html +3 -3
  46. package/dist/mobile.html +3 -3
  47. package/package.json +1 -1
  48. package/server/lib/dev-tunnel/client.js +20 -1
  49. package/server/lib/dev-tunnel/tunnel.test.js +9 -0
  50. package/server/lib/markdown-image-grants/DOCUMENTATION.md +36 -0
  51. package/server/lib/markdown-image-grants/routes.js +340 -0
  52. package/server/lib/markdown-image-grants/routes.test.js +221 -0
  53. package/server/lib/opencode/feature-routes-runtime.js +11 -0
  54. package/server/lib/opencode/server-startup-runtime.js +22 -1
  55. package/server/lib/opencode/server-startup-runtime.test.js +44 -0
  56. package/dist/assets/MarkdownImageGallery-DzHwkVIH.js +0 -1
  57. package/dist/assets/MarkdownRendererImpl-DUcIcWgs.js +0 -12
  58. package/dist/assets/index-CVNuER6G.css +0 -1
  59. package/dist/assets/markdownCore-DhfzuGXu.js +0 -2
  60. package/dist/assets/markdownImageAssets-BTNlRyjd.js +0 -1
@@ -0,0 +1,340 @@
1
+ import express from 'express';
2
+ import { constants as fsConstants } from 'node:fs';
3
+ import { mintOutsideFileGrant } from '../fs/routes.js';
4
+
5
+ const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
6
+ const MAX_IMAGE_SOURCES = 12;
7
+
8
+ const asString = (value) => typeof value === 'string' ? value.trim() : '';
9
+
10
+ const isWithin = (target, root, path) => {
11
+ const relative = path.relative(root, target);
12
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
13
+ };
14
+
15
+ const parseFileSource = (source) => {
16
+ if (/^file:\/\//i.test(source)) {
17
+ try {
18
+ const url = new URL(source);
19
+ if (url.protocol !== 'file:' || (url.host && url.host !== 'localhost')) return '';
20
+ const pathname = decodeURIComponent(url.pathname);
21
+ return /^\/[A-Za-z]:\//.test(pathname) ? pathname.slice(1) : pathname;
22
+ } catch {
23
+ return '';
24
+ }
25
+ }
26
+ const pathname = source.split(/[?#]/, 1)[0] || '';
27
+ try {
28
+ return decodeURIComponent(pathname);
29
+ } catch {
30
+ return pathname;
31
+ }
32
+ };
33
+
34
+ const hasImageSignature = (bytes) => {
35
+ if (bytes.length >= 8
36
+ && bytes[0] === 0x89 && bytes.subarray(1, 4).toString('ascii') === 'PNG'
37
+ && bytes[4] === 0x0d && bytes[5] === 0x0a && bytes[6] === 0x1a && bytes[7] === 0x0a) return true;
38
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return true;
39
+ const header = bytes.subarray(0, 12).toString('ascii');
40
+ return header.startsWith('GIF87a')
41
+ || header.startsWith('GIF89a')
42
+ || (header.startsWith('RIFF') && header.slice(8, 12) === 'WEBP');
43
+ };
44
+
45
+ const normalizeReferenceLabel = (value) => value.trim().replace(/\s+/g, ' ').toLowerCase();
46
+
47
+ const unescapeMarkdownDestination = (value) => value.replace(/\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~\\])/g, '$1');
48
+
49
+ const isEscapedAt = (value, index) => {
50
+ let slashes = 0;
51
+ for (let cursor = index - 1; cursor >= 0 && value[cursor] === '\\'; cursor -= 1) slashes += 1;
52
+ return slashes % 2 === 1;
53
+ };
54
+
55
+ const findClosingBracket = (value, start) => {
56
+ for (let cursor = start; cursor < value.length; cursor += 1) {
57
+ if (value[cursor] === ']' && !isEscapedAt(value, cursor)) return cursor;
58
+ }
59
+ return -1;
60
+ };
61
+
62
+ const findInlineImageEnd = (value, start) => {
63
+ let cursor = start;
64
+ while (/\s/.test(value[cursor] || '')) cursor += 1;
65
+ if (value[cursor] === ')') return cursor;
66
+
67
+ const opener = value[cursor];
68
+ const closer = opener === '"' ? '"' : opener === "'" ? "'" : opener === '(' ? ')' : '';
69
+ if (!closer) return -1;
70
+ cursor += 1;
71
+ for (; cursor < value.length; cursor += 1) {
72
+ if (value[cursor] !== closer || isEscapedAt(value, cursor)) continue;
73
+ cursor += 1;
74
+ while (/\s/.test(value[cursor] || '')) cursor += 1;
75
+ return value[cursor] === ')' ? cursor : -1;
76
+ }
77
+ return -1;
78
+ };
79
+
80
+ const parseInlineDestination = (value, start) => {
81
+ let cursor = start;
82
+ while (/\s/.test(value[cursor] || '')) cursor += 1;
83
+ if (value[cursor] === '<') {
84
+ const end = value.indexOf('>', cursor + 1);
85
+ if (end < 0) return null;
86
+ const imageEnd = findInlineImageEnd(value, end + 1);
87
+ return imageEnd < 0
88
+ ? null
89
+ : { source: unescapeMarkdownDestination(value.slice(cursor + 1, end)), end: imageEnd };
90
+ }
91
+
92
+ let source = '';
93
+ let depth = 0;
94
+ for (; cursor < value.length; cursor += 1) {
95
+ const char = value[cursor];
96
+ if (char === '\\' && cursor + 1 < value.length) {
97
+ source += char + value[cursor + 1];
98
+ cursor += 1;
99
+ continue;
100
+ }
101
+ if (char === '(') {
102
+ depth += 1;
103
+ source += char;
104
+ continue;
105
+ }
106
+ if (char === ')') {
107
+ if (depth === 0) return { source: unescapeMarkdownDestination(source), end: cursor };
108
+ depth -= 1;
109
+ source += char;
110
+ continue;
111
+ }
112
+ if (/\s/.test(char) && depth === 0) {
113
+ const imageEnd = findInlineImageEnd(value, cursor);
114
+ return imageEnd < 0 ? null : { source: unescapeMarkdownDestination(source), end: imageEnd };
115
+ }
116
+ source += char;
117
+ }
118
+ return null;
119
+ };
120
+
121
+ const parseDefinitionDestination = (value) => {
122
+ const trimmed = value.trimStart();
123
+ if (trimmed.startsWith('<')) {
124
+ const end = trimmed.indexOf('>', 1);
125
+ return end < 0 ? '' : unescapeMarkdownDestination(trimmed.slice(1, end));
126
+ }
127
+ const match = /^(?:\\.|\S)+/.exec(trimmed);
128
+ return match ? unescapeMarkdownDestination(match[0]) : '';
129
+ };
130
+
131
+ const collectMarkdownLinesOutsideCode = (message) => {
132
+ const lines = [];
133
+ for (const part of Array.isArray(message?.parts) ? message.parts : []) {
134
+ if (part?.type !== 'text' || typeof part.text !== 'string') continue;
135
+ let fence = null;
136
+ for (const line of part.text.split('\n')) {
137
+ const fenceMatch = /^\s{0,3}(`{3,}|~{3,})/.exec(line);
138
+ if (fenceMatch) {
139
+ const marker = fenceMatch[1];
140
+ if (!fence) {
141
+ fence = { char: marker[0], size: marker.length };
142
+ } else if (marker[0] === fence.char && marker.length >= fence.size) {
143
+ fence = null;
144
+ }
145
+ continue;
146
+ }
147
+ if (fence) continue;
148
+ lines.push(line.replace(/`+[^`]*`+/g, ''));
149
+ }
150
+ }
151
+ return lines;
152
+ };
153
+
154
+ const markdownImageSources = (message) => {
155
+ const sources = new Set();
156
+ const markdownLines = collectMarkdownLinesOutsideCode(message);
157
+ const definitions = new Map();
158
+ for (const line of markdownLines) {
159
+ const match = /^\s{0,3}\[([^\]]+)]\s*:\s*(.*)$/.exec(line);
160
+ if (!match) continue;
161
+ const source = parseDefinitionDestination(match[2]);
162
+ if (source) definitions.set(normalizeReferenceLabel(match[1]), source);
163
+ }
164
+
165
+ for (const line of markdownLines) {
166
+ for (let cursor = 0; cursor < line.length; cursor += 1) {
167
+ if (line[cursor] !== '!' || line[cursor + 1] !== '[' || isEscapedAt(line, cursor)) continue;
168
+ const altEnd = findClosingBracket(line, cursor + 2);
169
+ if (altEnd < 0) continue;
170
+ const alt = line.slice(cursor + 2, altEnd);
171
+ const next = line[altEnd + 1];
172
+ if (next === '(') {
173
+ const parsed = parseInlineDestination(line, altEnd + 2);
174
+ if (parsed?.source) sources.add(parsed.source);
175
+ cursor = parsed?.end ?? altEnd;
176
+ continue;
177
+ }
178
+ let label = alt;
179
+ if (next === '[') {
180
+ const labelEnd = findClosingBracket(line, altEnd + 2);
181
+ if (labelEnd < 0) continue;
182
+ label = line.slice(altEnd + 2, labelEnd) || alt;
183
+ cursor = labelEnd;
184
+ } else {
185
+ cursor = altEnd;
186
+ }
187
+ const source = definitions.get(normalizeReferenceLabel(label));
188
+ if (source) sources.add(source);
189
+ }
190
+ }
191
+ return sources;
192
+ };
193
+
194
+ const fetchMessage = async ({ sessionId, messageId, directory, buildOpenCodeUrl, getOpenCodeAuthHeaders }) => {
195
+ const url = new URL(buildOpenCodeUrl(
196
+ `/session/${encodeURIComponent(sessionId)}/message/${encodeURIComponent(messageId)}`,
197
+ '',
198
+ ));
199
+ url.searchParams.set('directory', directory);
200
+ const response = await fetch(url, {
201
+ headers: {
202
+ accept: 'application/json',
203
+ 'x-opencode-directory': directory,
204
+ ...getOpenCodeAuthHeaders(),
205
+ },
206
+ signal: AbortSignal.timeout(10_000),
207
+ });
208
+ if (response.status === 404) return null;
209
+ if (!response.ok) throw new Error(`OpenCode returned ${response.status}`);
210
+ const message = await response.json().catch(() => null);
211
+ return message?.info && Array.isArray(message.parts) ? message : null;
212
+ };
213
+
214
+ const inspectImage = async ({ source, directory, approvedTempRoot, fsPromises, path }) => {
215
+ const parsed = parseFileSource(source);
216
+ if (!parsed) return { status: 'error' };
217
+ const sourcePath = path.isAbsolute(parsed) ? parsed : path.resolve(directory, parsed);
218
+ const workspaceRoot = path.resolve(directory);
219
+ const outsideWorkspace = !isWithin(path.resolve(sourcePath), workspaceRoot, path);
220
+ const root = outsideWorkspace ? approvedTempRoot : workspaceRoot;
221
+
222
+ try {
223
+ // Resolve symlinks before comparing roots; lexical prefixes are not an authorization boundary.
224
+ const [canonicalRoot, canonicalPath] = await Promise.all([
225
+ fsPromises.realpath(root),
226
+ fsPromises.realpath(sourcePath),
227
+ ]);
228
+ if (!isWithin(canonicalPath, canonicalRoot, path)) return { status: 'error' };
229
+ const handle = await fsPromises.open(canonicalPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
230
+ try {
231
+ const stats = await handle.stat();
232
+ if (!stats.isFile() || stats.size > MAX_IMAGE_BYTES) return { status: 'error' };
233
+ const header = Buffer.alloc(12);
234
+ const { bytesRead } = await handle.read(header, 0, header.length, 0);
235
+ if (!hasImageSignature(header.subarray(0, bytesRead))) return { status: 'error' };
236
+ return {
237
+ status: 'ready',
238
+ path: outsideWorkspace ? canonicalPath : path.resolve(sourcePath),
239
+ outsideWorkspace,
240
+ };
241
+ } finally {
242
+ await handle.close();
243
+ }
244
+ } catch (error) {
245
+ if (error?.code === 'ENOENT') return { status: 'missing' };
246
+ if (error?.code === 'EACCES' || error?.code === 'EPERM' || error?.code === 'ELOOP') {
247
+ return { status: 'error' };
248
+ }
249
+ throw error;
250
+ }
251
+ };
252
+
253
+ export const registerMarkdownImageGrantRoutes = (app, dependencies) => {
254
+ const {
255
+ fsPromises,
256
+ path,
257
+ os,
258
+ crypto,
259
+ validateDirectoryPath,
260
+ buildOpenCodeUrl,
261
+ getOpenCodeAuthHeaders,
262
+ approvedTempRoot = path.join(os.tmpdir(), 'opencode'),
263
+ } = dependencies;
264
+
265
+ app.post(
266
+ '/api/openchamber/sessions/:sessionId/markdown-image-grants',
267
+ express.json({ limit: '32kb' }),
268
+ async (req, res) => {
269
+ const sessionId = asString(req.params.sessionId);
270
+ const messageId = asString(req.body?.messageId);
271
+ const sources = Array.isArray(req.body?.sources)
272
+ ? [...new Set(req.body.sources.map(asString).filter(Boolean))]
273
+ : [];
274
+ if (!sessionId || !messageId || sources.length === 0 || sources.length > MAX_IMAGE_SOURCES) {
275
+ return res.status(400).json({ error: 'sessionId, messageId, and 1-12 sources are required' });
276
+ }
277
+ const validatedDirectory = await validateDirectoryPath(asString(req.body?.directory));
278
+ if (!validatedDirectory.ok) {
279
+ return res.status(400).json({ error: validatedDirectory.error || 'Invalid directory' });
280
+ }
281
+
282
+ try {
283
+ const message = await fetchMessage({
284
+ sessionId,
285
+ messageId,
286
+ directory: validatedDirectory.directory,
287
+ buildOpenCodeUrl,
288
+ getOpenCodeAuthHeaders,
289
+ });
290
+ if (!message || message.info?.id !== messageId || message.info?.role !== 'assistant') {
291
+ return res.status(404).json({ error: 'Assistant message not found' });
292
+ }
293
+ // Assistant text is authoritative: a remote client cannot mint grants for unreferenced paths.
294
+ const referenced = markdownImageSources(message);
295
+ const results = [];
296
+ for (const source of sources) {
297
+ if (!referenced.has(source)) {
298
+ results.push({ source, status: 'error' });
299
+ continue;
300
+ }
301
+ try {
302
+ const inspected = await inspectImage({
303
+ source,
304
+ directory: validatedDirectory.directory,
305
+ approvedTempRoot,
306
+ fsPromises,
307
+ path,
308
+ });
309
+ if (inspected.status !== 'ready') {
310
+ results.push({ source, status: inspected.status });
311
+ continue;
312
+ }
313
+ // Reuse the existing path-bound raw-file grant instead of creating another asset lifecycle.
314
+ const grant = inspected.outsideWorkspace
315
+ ? await mintOutsideFileGrant(inspected.path, {
316
+ scopes: ['raw'],
317
+ fsPromises,
318
+ path,
319
+ crypto,
320
+ })
321
+ : null;
322
+ results.push({
323
+ source,
324
+ status: 'ready',
325
+ path: inspected.path,
326
+ outsideFileGrant: grant?.outsideFileGrant,
327
+ expiresAt: grant?.expiresAt,
328
+ });
329
+ } catch {
330
+ results.push({ source, status: 'error' });
331
+ }
332
+ }
333
+ return res.json({ results });
334
+ } catch (error) {
335
+ console.warn('[MarkdownImageGrants] failed to prepare images:', error?.message || error);
336
+ return res.status(503).json({ error: 'Failed to prepare session images' });
337
+ }
338
+ },
339
+ );
340
+ };
@@ -0,0 +1,221 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import express from 'express';
3
+ import request from 'supertest';
4
+ import crypto from 'node:crypto';
5
+ import fs from 'node:fs/promises';
6
+ import os from 'node:os';
7
+ import path from 'node:path';
8
+ import { registerMarkdownImageGrantRoutes } from './routes.js';
9
+
10
+ const PNG = Buffer.from(
11
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg==',
12
+ 'base64',
13
+ );
14
+ const roots = [];
15
+
16
+ afterEach(async () => {
17
+ vi.unstubAllGlobals();
18
+ await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true })));
19
+ });
20
+
21
+ const createFixture = async ({ sources, markdown } = {}) => {
22
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'openchamber-session-assets-'));
23
+ roots.push(root);
24
+ const approvedTempRoot = path.join(root, 'opencode');
25
+ const directory = path.join(root, 'workspace');
26
+ await Promise.all([
27
+ fs.mkdir(approvedTempRoot, { recursive: true }),
28
+ fs.mkdir(directory, { recursive: true }),
29
+ ]);
30
+ const defaultPath = path.join(approvedTempRoot, 'image.png');
31
+ await fs.writeFile(defaultPath, PNG);
32
+ const requestedSources = sources ?? [new URL(`file://${defaultPath}`).toString()];
33
+ const text = markdown ?? requestedSources.map((source) => `![image](${source})`).join('\n');
34
+ const fetchMock = vi.fn(async () => new Response(JSON.stringify({
35
+ info: { id: 'msg_1', role: 'assistant' },
36
+ parts: [{ type: 'text', text }],
37
+ }), { status: 200, headers: { 'content-type': 'application/json' } }));
38
+ vi.stubGlobal('fetch', fetchMock);
39
+
40
+ let fullReadCount = 0;
41
+ const app = express();
42
+ registerMarkdownImageGrantRoutes(app, {
43
+ fsPromises: {
44
+ ...fs,
45
+ readFile: async (...args) => {
46
+ fullReadCount += 1;
47
+ return fs.readFile(...args);
48
+ },
49
+ },
50
+ path,
51
+ os,
52
+ crypto,
53
+ approvedTempRoot,
54
+ validateDirectoryPath: async (candidate) => candidate === directory
55
+ ? { ok: true, directory }
56
+ : { ok: false, error: 'Invalid directory' },
57
+ buildOpenCodeUrl: (route) => `http://opencode.test${route}`,
58
+ getOpenCodeAuthHeaders: () => ({ authorization: 'Basic test' }),
59
+ });
60
+ return {
61
+ app,
62
+ approvedTempRoot,
63
+ directory,
64
+ fetchMock,
65
+ fullReadCount: () => fullReadCount,
66
+ root,
67
+ sources: requestedSources,
68
+ };
69
+ };
70
+
71
+ const prepare = (app, directory, sources) => request(app)
72
+ .post('/api/openchamber/sessions/ses_1/markdown-image-grants')
73
+ .send({ directory, messageId: 'msg_1', sources })
74
+ .expect(200);
75
+
76
+ describe('session image assets', () => {
77
+ it('prepares workspace and OpenCode temporary images with one message fetch', async () => {
78
+ const fixture = await createFixture({ sources: ['workspace.png'] });
79
+ await fs.writeFile(path.join(fixture.directory, 'workspace.png'), PNG);
80
+ const temporaryPath = path.join(fixture.approvedTempRoot, 'temporary.png');
81
+ await fs.writeFile(temporaryPath, PNG);
82
+ const temporarySource = new URL(`file://${temporaryPath}`).toString();
83
+ fixture.fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({
84
+ info: { id: 'msg_1', role: 'assistant' },
85
+ parts: [{ type: 'text', text: `![workspace](workspace.png)\n![temporary](${temporarySource})` }],
86
+ }), { status: 200, headers: { 'content-type': 'application/json' } }));
87
+
88
+ const response = await prepare(fixture.app, fixture.directory, ['workspace.png', temporarySource]);
89
+
90
+ expect(fixture.fetchMock).toHaveBeenCalledTimes(1);
91
+ expect(fixture.fullReadCount()).toBe(0);
92
+ expect(response.body.results).toHaveLength(2);
93
+ const canonicalTemporaryPath = await fs.realpath(temporaryPath);
94
+ expect(response.body.results[0]).toEqual({
95
+ source: 'workspace.png',
96
+ status: 'ready',
97
+ path: path.join(fixture.directory, 'workspace.png'),
98
+ });
99
+ expect(response.body.results[1]).toEqual(expect.objectContaining({
100
+ source: temporarySource,
101
+ status: 'ready',
102
+ path: canonicalTemporaryPath,
103
+ outsideFileGrant: expect.any(String),
104
+ expiresAt: expect.any(Number),
105
+ }));
106
+ });
107
+
108
+ it('returns partial results without letting one missing image block valid images', async () => {
109
+ const fixture = await createFixture({ sources: ['present.png', 'deleted.png'] });
110
+ await fs.writeFile(path.join(fixture.directory, 'present.png'), PNG);
111
+
112
+ const response = await prepare(fixture.app, fixture.directory, fixture.sources);
113
+
114
+ expect(response.body.results).toEqual([
115
+ expect.objectContaining({ source: 'present.png', status: 'ready' }),
116
+ { source: 'deleted.png', status: 'missing' },
117
+ ]);
118
+ });
119
+
120
+ it('resolves encoded workspace paths without treating query or fragment text as a filename', async () => {
121
+ const source = 'screen%20shot.png?version=1#preview';
122
+ const fixture = await createFixture({ sources: [source] });
123
+ await fs.writeFile(path.join(fixture.directory, 'screen shot.png'), PNG);
124
+
125
+ const response = await prepare(fixture.app, fixture.directory, fixture.sources);
126
+
127
+ expect(response.body.results).toEqual([
128
+ expect.objectContaining({ source, status: 'ready' }),
129
+ ]);
130
+ });
131
+
132
+ it('authorizes reference-style image syntax using its resolved destination', async () => {
133
+ const source = 'reference.png';
134
+ const fixture = await createFixture({
135
+ sources: [source],
136
+ markdown: '![screenshot][result]\n\n[result]: reference.png',
137
+ });
138
+ await fs.writeFile(path.join(fixture.directory, source), PNG);
139
+
140
+ const response = await prepare(fixture.app, fixture.directory, fixture.sources);
141
+
142
+ expect(response.body.results).toEqual([
143
+ expect.objectContaining({ source, status: 'ready' }),
144
+ ]);
145
+ });
146
+
147
+ it('authorizes inline image destinations containing balanced parentheses', async () => {
148
+ const source = 'screen(1).png';
149
+ const fixture = await createFixture({
150
+ sources: [source],
151
+ markdown: `![screenshot](${source})`,
152
+ });
153
+ await fs.writeFile(path.join(fixture.directory, source), PNG);
154
+
155
+ const response = await prepare(fixture.app, fixture.directory, fixture.sources);
156
+
157
+ expect(response.body.results).toEqual([
158
+ expect.objectContaining({ source, status: 'ready' }),
159
+ ]);
160
+ });
161
+
162
+ it('requires inline image destinations with titles to close', async () => {
163
+ const sources = ['valid.png', 'malformed.png'];
164
+ const fixture = await createFixture({
165
+ sources,
166
+ markdown: '![valid](valid.png "preview")\n![malformed](malformed.png "preview"',
167
+ });
168
+ await Promise.all(sources.map((source) => fs.writeFile(path.join(fixture.directory, source), PNG)));
169
+
170
+ const response = await prepare(fixture.app, fixture.directory, sources);
171
+
172
+ expect(response.body.results).toEqual([
173
+ expect.objectContaining({ source: 'valid.png', status: 'ready' }),
174
+ { source: 'malformed.png', status: 'error' },
175
+ ]);
176
+ });
177
+
178
+ it('rejects a source that the message does not reference', async () => {
179
+ const fixture = await createFixture({ markdown: 'No image here.' });
180
+ const response = await prepare(fixture.app, fixture.directory, fixture.sources);
181
+ expect(response.body.results).toEqual([{ source: fixture.sources[0], status: 'error' }]);
182
+ });
183
+
184
+ it('does not authorize image syntax inside fenced or inline code', async () => {
185
+ const fixture = await createFixture({
186
+ markdown: '```md\n![fenced](FENCED)\n```\n`![inline](INLINE)`',
187
+ });
188
+ const sources = ['FENCED', 'INLINE'];
189
+
190
+ const response = await prepare(fixture.app, fixture.directory, sources);
191
+
192
+ expect(response.body.results).toEqual(sources.map((source) => ({ source, status: 'error' })));
193
+ });
194
+
195
+ it('rejects paths outside the workspace and approved temporary root', async () => {
196
+ const fixture = await createFixture();
197
+ const outsidePath = path.join(fixture.root, 'outside.png');
198
+ await fs.writeFile(outsidePath, PNG);
199
+ const source = new URL(`file://${outsidePath}`).toString();
200
+ fixture.fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({
201
+ info: { id: 'msg_1', role: 'assistant' },
202
+ parts: [{ type: 'text', text: `![outside](${source})` }],
203
+ }), { status: 200, headers: { 'content-type': 'application/json' } }));
204
+
205
+ const response = await prepare(fixture.app, fixture.directory, [source]);
206
+ expect(response.body.results).toEqual([{ source, status: 'error' }]);
207
+ });
208
+
209
+ it('rejects non-image bytes and symlink escapes per source', async () => {
210
+ const fixture = await createFixture({ sources: ['invalid.png', 'linked.png'] });
211
+ await fs.writeFile(path.join(fixture.directory, 'invalid.png'), 'not an image');
212
+ await fs.writeFile(path.join(fixture.root, 'outside.png'), PNG);
213
+ await fs.symlink(path.join(fixture.root, 'outside.png'), path.join(fixture.directory, 'linked.png'));
214
+
215
+ const response = await prepare(fixture.app, fixture.directory, fixture.sources);
216
+ expect(response.body.results).toEqual([
217
+ { source: 'invalid.png', status: 'error' },
218
+ { source: 'linked.png', status: 'error' },
219
+ ]);
220
+ });
221
+ });
@@ -15,6 +15,7 @@ import { registerProjectIconRoutes } from './project-icon-routes.js';
15
15
  import { registerScheduledTaskRoutes } from '../scheduled-tasks/routes.js';
16
16
  import { registerOpenChamberSessionRoutes } from '../openchamber-sessions/routes.js';
17
17
  import { registerOpenChamberControlRoutes } from '../openchamber-control/routes.js';
18
+ import { registerMarkdownImageGrantRoutes } from '../markdown-image-grants/routes.js';
18
19
  import { registerSkillRoutes } from './skill-routes.js';
19
20
  import { registerPluginRoutes } from './plugin-routes.js';
20
21
  import { getNpmInfo, clearCache as clearNpmCache } from './npm-registry.js';
@@ -190,6 +191,16 @@ export const createFeatureRoutesRuntime = (dependencies) => {
190
191
 
191
192
  registerOpenChamberControlRoutes(app, { controlService: openChamberControlService });
192
193
 
194
+ registerMarkdownImageGrantRoutes(app, {
195
+ fsPromises,
196
+ path,
197
+ os,
198
+ crypto,
199
+ validateDirectoryPath,
200
+ buildOpenCodeUrl,
201
+ getOpenCodeAuthHeaders,
202
+ });
203
+
193
204
  registerConfigEntityRoutes(app, {
194
205
  resolveProjectDirectory,
195
206
  resolveOptionalProjectDirectory,
@@ -1,3 +1,7 @@
1
+ /** One stray uncaught exception is survivable; a storm means the process is broken. */
2
+ const UNCAUGHT_STORM_LIMIT = 10;
3
+ const UNCAUGHT_STORM_WINDOW_MS = 60_000;
4
+
1
5
  export const createServerStartupRuntime = (dependencies) => {
2
6
  const {
3
7
  process,
@@ -148,9 +152,26 @@ export const createServerStartupRuntime = (dependencies) => {
148
152
  console.error('Unhandled Rejection at:', promise, 'reason:', reason);
149
153
  });
150
154
 
155
+ // A single stray exception — a socket teardown race, a Node-internal bug
156
+ // like `setTypeOfService EINVAL` — must not take the server down. Nothing
157
+ // restarts this process (it is embedded in the desktop app or run by hand
158
+ // in a terminal), so shutting down turns every such stray into "the
159
+ // instance is unreachable until I restart it". Mirror the
160
+ // unhandledRejection policy above: log and keep serving. A sustained storm
161
+ // of exceptions is a different situation — the process is genuinely
162
+ // broken — so that still shuts down rather than limping along half-alive.
163
+ const exceptionTimes = [];
151
164
  process.on('uncaughtException', (error) => {
152
165
  console.error('Uncaught Exception:', error);
153
- gracefulShutdown();
166
+ const now = Date.now();
167
+ exceptionTimes.push(now);
168
+ while (exceptionTimes.length > 0 && now - exceptionTimes[0] > UNCAUGHT_STORM_WINDOW_MS) {
169
+ exceptionTimes.shift();
170
+ }
171
+ if (exceptionTimes.length > UNCAUGHT_STORM_LIMIT) {
172
+ console.error(`More than ${UNCAUGHT_STORM_LIMIT} uncaught exceptions within a minute; shutting down.`);
173
+ gracefulShutdown();
174
+ }
154
175
  });
155
176
  };
156
177
 
@@ -0,0 +1,44 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+ import { EventEmitter } from 'node:events';
3
+ import { createServerStartupRuntime } from './server-startup-runtime.js';
4
+
5
+ /**
6
+ * The desktop app embeds this server and nothing restarts it, so shutting down
7
+ * on a single uncaught exception turned every stray socket error into "the
8
+ * instance is unreachable until restarted". Only a sustained storm shuts down.
9
+ */
10
+ describe('uncaught exception policy', () => {
11
+ const setup = () => {
12
+ const fakeProcess = new EventEmitter();
13
+ let shutdowns = 0;
14
+ const runtime = createServerStartupRuntime({
15
+ process: fakeProcess,
16
+ gracefulShutdown: () => { shutdowns += 1; },
17
+ getSignalsAttached: () => true,
18
+ setSignalsAttached: () => {},
19
+ syncToHmrState: () => {},
20
+ });
21
+ runtime.attachProcessHandlers({ attachSignals: false });
22
+ return { fakeProcess, shutdowns: () => shutdowns };
23
+ };
24
+
25
+ test('a single uncaught exception keeps the server running', () => {
26
+ const { fakeProcess, shutdowns } = setup();
27
+ fakeProcess.emit('uncaughtException', new Error('setTypeOfService EINVAL'));
28
+ expect(shutdowns()).toBe(0);
29
+ });
30
+
31
+ test('a storm of uncaught exceptions still shuts down', () => {
32
+ const { fakeProcess, shutdowns } = setup();
33
+ for (let i = 0; i < 11; i += 1) {
34
+ fakeProcess.emit('uncaughtException', new Error(`stray ${i}`));
35
+ }
36
+ expect(shutdowns()).toBeGreaterThan(0);
37
+ });
38
+
39
+ test('an unhandled rejection is logged without shutting down', () => {
40
+ const { fakeProcess, shutdowns } = setup();
41
+ fakeProcess.emit('unhandledRejection', new Error('late failure'), Promise.resolve());
42
+ expect(shutdowns()).toBe(0);
43
+ });
44
+ });