@openchamber/web 1.14.0 → 1.15.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 (100) hide show
  1. package/bin/cli.test.js +8 -0
  2. package/bin/lib/DOCUMENTATION.md +3 -0
  3. package/bin/lib/cli-args.js +10 -0
  4. package/bin/lib/commands-connect-url.js +169 -22
  5. package/dist/assets/{DiagramView-CIaZCGUT.js → DiagramView-HR2xZxJ8.js} +1 -1
  6. package/dist/assets/MarkdownRendererImpl-sm01Q7R7.js +11 -0
  7. package/dist/assets/{MultiRunWindow-Bsbr3i8y.js → MultiRunWindow-DlFUaNQK.js} +1 -1
  8. package/dist/assets/OnboardingScreen-DVRz82mJ.js +1 -0
  9. package/dist/assets/{SessionSwitcherDropdown-CLm6tF5n.js → SessionSwitcherDropdown-DvoOalMY.js} +1 -1
  10. package/dist/assets/SettingsWindow-CkInZcj7.js +1 -0
  11. package/dist/assets/{TerminalView-DF7-jlam.js → TerminalView-D_9BAjtv.js} +3 -3
  12. package/dist/assets/es-cjUissX4.js +15 -0
  13. package/dist/assets/fr-DqbXnTdK.js +13 -0
  14. package/dist/assets/index-Dg0nmvQU.css +1 -0
  15. package/dist/assets/index-ltrmNGAf.js +2 -0
  16. package/dist/assets/ja-Cetyq6Eg.js +15 -0
  17. package/dist/assets/ko-DtunWisP.js +15 -0
  18. package/dist/assets/main-BC0m8s1v.js +236 -0
  19. package/dist/assets/main-DzNa8r0N.js +2 -0
  20. package/dist/assets/miniChat-BRYDE-Se.js +2 -0
  21. package/dist/assets/mobile-C3QJVA97.js +2 -0
  22. package/dist/assets/pl-DctGLgve.js +15 -0
  23. package/dist/assets/pt-BR-CXPhf78S.js +15 -0
  24. package/dist/assets/renderElectronMiniChatApp-CVFbDC5A.js +2 -0
  25. package/dist/assets/renderMobileApp-wkBjh5WR.js +16 -0
  26. package/dist/assets/runtimeEndpointReset-C42u8PvG.js +167 -0
  27. package/dist/assets/uk-Bdrc-kqF.js +15 -0
  28. package/dist/assets/{useAppFontEffects-DTO332li.js → useAppFontEffects-DzBg8hrC.js} +132 -116
  29. package/dist/assets/{vendor-.bun-C6iL44L9.js → vendor-.bun-BE757pvp.js} +1 -1
  30. package/dist/assets/zh-CN-CeCVKrHP.js +15 -0
  31. package/dist/assets/zh-TW-CoqiQING.js +15 -0
  32. package/dist/index.html +4 -4
  33. package/dist/mini-chat.html +4 -4
  34. package/dist/mobile.html +4 -4
  35. package/package.json +2 -2
  36. package/server/index.js +157 -6
  37. package/server/lib/client-auth/pairing.js +308 -0
  38. package/server/lib/client-auth/pairing.test.js +142 -0
  39. package/server/lib/client-auth/remote-clients.js +65 -3
  40. package/server/lib/notifications/apns-runtime.js +9 -16
  41. package/server/lib/opencode/bootstrap-runtime.js +10 -0
  42. package/server/lib/opencode/core-routes.js +247 -6
  43. package/server/lib/opencode/core-routes.test.js +248 -9
  44. package/server/lib/opencode/feature-routes-runtime.js +10 -0
  45. package/server/lib/opencode/models-metadata.js +61 -0
  46. package/server/lib/opencode/network-runtime.js +14 -1
  47. package/server/lib/opencode/network-runtime.test.js +29 -9
  48. package/server/lib/opencode/openchamber-routes.js +7 -40
  49. package/server/lib/opencode/proxy.js +47 -6
  50. package/server/lib/opencode/settings-helpers.js +16 -0
  51. package/server/lib/opencode/settings-helpers.test.js +11 -0
  52. package/server/lib/opencode/settings-normalization-runtime.js +2 -0
  53. package/server/lib/opencode/shutdown-runtime.js +2 -0
  54. package/server/lib/package-manager.js +18 -5
  55. package/server/lib/relay/DOCUMENTATION.md +78 -0
  56. package/server/lib/relay/cross-compat.test.js +135 -0
  57. package/server/lib/relay/e2ee.js +341 -0
  58. package/server/lib/relay/e2ee.test.js +124 -0
  59. package/server/lib/relay/host-client.js +389 -0
  60. package/server/lib/relay/host-client.test.js +280 -0
  61. package/server/lib/relay/identity.js +73 -0
  62. package/server/lib/relay/identity.test.js +78 -0
  63. package/server/lib/relay/service.js +247 -0
  64. package/server/lib/relay/signing-key.js +50 -0
  65. package/server/lib/relay/tunnel-codec.js +373 -0
  66. package/server/lib/relay/tunnel-codec.test.js +58 -0
  67. package/server/lib/relay/tunnel-host.js +462 -0
  68. package/server/lib/session-assist/DOCUMENTATION.md +66 -0
  69. package/server/lib/session-assist/runtime.js +394 -0
  70. package/server/lib/small-model/DOCUMENTATION.md +78 -0
  71. package/server/lib/small-model/call.js +380 -0
  72. package/server/lib/small-model/catalog.js +13 -0
  73. package/server/lib/small-model/index.js +167 -0
  74. package/server/lib/small-model/resolve.js +131 -0
  75. package/server/lib/small-model/resolve.test.js +197 -0
  76. package/server/lib/small-model/routes.js +44 -0
  77. package/server/lib/ui-auth/DOCUMENTATION.md +6 -0
  78. package/server/lib/ui-auth/ui-auth.js +10 -0
  79. package/server/opencode-proxy.test.js +38 -0
  80. package/dist/assets/MarkdownRendererImpl-DWgOeIpO.js +0 -7
  81. package/dist/assets/OnboardingScreen-3IAKkM5k.js +0 -1
  82. package/dist/assets/SettingsWindow-K-ErjehP.js +0 -1
  83. package/dist/assets/es-DQIFCjC2.js +0 -15
  84. package/dist/assets/fr-CJRav0LS.js +0 -13
  85. package/dist/assets/index-5eUDDB6w.js +0 -2
  86. package/dist/assets/index-CgpE7F8T.css +0 -1
  87. package/dist/assets/ja-CjAaqvHO.js +0 -15
  88. package/dist/assets/ko-BEbFxvrd.js +0 -15
  89. package/dist/assets/main-C2put7uQ.js +0 -2
  90. package/dist/assets/main-DuQEoz31.js +0 -214
  91. package/dist/assets/miniChat-o3AAQ-8r.js +0 -2
  92. package/dist/assets/mobile-X0421aWz.js +0 -2
  93. package/dist/assets/pl-D4kzai5T.js +0 -15
  94. package/dist/assets/pt-BR-9Sk3esQZ.js +0 -15
  95. package/dist/assets/renderElectronMiniChatApp-CdDj0ms1.js +0 -2
  96. package/dist/assets/renderMobileApp-cZ_HZKSe.js +0 -16
  97. package/dist/assets/runtimeEndpointReset-BYLVW9e7.js +0 -167
  98. package/dist/assets/uk-DW_dTfoO.js +0 -15
  99. package/dist/assets/zh-CN-r2_euV7U.js +0 -15
  100. package/dist/assets/zh-TW-BdPx3NWh.js +0 -15
@@ -1,9 +1,13 @@
1
- import { describe, it, expect, vi } from 'vitest';
1
+ import { describe, it, expect, vi, afterEach } from 'vitest';
2
2
  import express from 'express';
3
3
  import request from 'supertest';
4
4
  import { registerAuthAndAccessRoutes, registerCommonRequestMiddleware, registerServerStatusRoutes } from './core-routes.js';
5
5
 
6
6
  describe('core-routes', () => {
7
+ afterEach(() => {
8
+ vi.useRealTimers();
9
+ });
10
+
7
11
  it('should call gracefulShutdown with exitProcess: true on /api/system/shutdown', async () => {
8
12
  const app = express();
9
13
  let shutdownOpts = null;
@@ -225,6 +229,206 @@ describe('core-routes', () => {
225
229
  }
226
230
  });
227
231
 
232
+ const createPairingRouteApp = (overrides = {}) => {
233
+ const app = express();
234
+ const dependencies = {
235
+ express,
236
+ tunnelAuthController: {
237
+ classifyRequestScope: () => 'local',
238
+ requireTunnelSession: vi.fn(),
239
+ getTunnelSessionFromRequest: vi.fn(),
240
+ clearTunnelSessionCookie: vi.fn(),
241
+ exchangeBootstrapToken: vi.fn(),
242
+ },
243
+ uiAuthController: {
244
+ resolveAuthContext: vi.fn(async () => ({ type: 'session', token: 'session-token' })),
245
+ requireAuth: vi.fn((_req, _res, next) => next()),
246
+ requireSessionAuth: vi.fn((_req, _res, next) => next()),
247
+ handleSessionStatus: vi.fn(),
248
+ handleSessionCreate: vi.fn(),
249
+ handleUrlAuthToken: vi.fn(),
250
+ handlePasskeyStatus: vi.fn(),
251
+ handlePasskeyAuthenticationOptions: vi.fn(),
252
+ handlePasskeyAuthenticationVerify: vi.fn(),
253
+ handlePasskeyRegistrationOptions: vi.fn(),
254
+ handlePasskeyRegistrationVerify: vi.fn(),
255
+ handlePasskeyList: vi.fn(),
256
+ handlePasskeyRevoke: vi.fn(),
257
+ handleResetAuth: vi.fn(),
258
+ },
259
+ remoteClientAuthRuntime: {
260
+ listClients: vi.fn(async () => []),
261
+ createClient: vi.fn(),
262
+ revokeClient: vi.fn(),
263
+ purgeRevokedClients: vi.fn(),
264
+ },
265
+ clientPairingRuntime: {
266
+ createPairingSession: vi.fn(async () => ({ pairing: { id: 'pair_1', secret: 'secret', expiresAt: '2099-01-01T00:00:00.000Z', fingerprint: 'ABCD-1234' } })),
267
+ cancelPairingSession: vi.fn(async () => ({ cancelled: true })),
268
+ redeemPairingSession: vi.fn(async () => ({
269
+ pairing: { fingerprint: 'ABCD-1234' },
270
+ client: { id: 'client-1', label: 'Phone', authMethod: 'pairing' },
271
+ token: 'oc_client_token',
272
+ })),
273
+ },
274
+ readSettingsFromDiskMigrated: vi.fn(async () => ({})),
275
+ normalizeTunnelSessionTtlMs: vi.fn(),
276
+ ...overrides,
277
+ };
278
+ registerAuthAndAccessRoutes(app, dependencies);
279
+ return { app, dependencies };
280
+ };
281
+
282
+ it('creates pairing sessions behind owner auth and returns no-store payload data', async () => {
283
+ const { app, dependencies } = createPairingRouteApp();
284
+
285
+ const response = await request(app)
286
+ .post('/api/client-auth/pairing/sessions')
287
+ .set('Host', 'runtime.example')
288
+ .send({ label: 'Pair phone', allowedClientKinds: ['mobile'] })
289
+ .expect(201);
290
+
291
+ expect(response.headers['cache-control']).toBe('no-store');
292
+ expect(response.body.pairing).toMatchObject({ id: 'pair_1', secret: 'secret' });
293
+ expect(response.body.server.candidates).toEqual([{ type: 'lan', url: 'http://runtime.example', priority: 10 }]);
294
+ expect(dependencies.clientPairingRuntime.createPairingSession).toHaveBeenCalledWith({
295
+ label: 'Pair phone',
296
+ allowedClientKinds: ['mobile'],
297
+ createdByClientId: null,
298
+ usesRelay: false,
299
+ });
300
+ });
301
+
302
+ it('advertises the caller-supplied serverUrl as the direct candidate over the request origin', async () => {
303
+ const { app } = createPairingRouteApp();
304
+
305
+ const response = await request(app)
306
+ .post('/api/client-auth/pairing/sessions')
307
+ .set('Host', 'runtime.example')
308
+ .send({ label: 'Pair phone', serverUrl: 'http://192.168.1.20:2606' })
309
+ .expect(201);
310
+
311
+ expect(response.body.server.candidates).toEqual([
312
+ { type: 'lan', url: 'http://192.168.1.20:2606', priority: 10 },
313
+ ]);
314
+ });
315
+
316
+ it('folds in a relay candidate when the host relay is enabled', async () => {
317
+ const relayCandidate = {
318
+ type: 'relay',
319
+ relayUrl: 'wss://relay.example/ws',
320
+ serverId: 'srv_1',
321
+ hostEncPubJwk: { kty: 'EC', crv: 'P-256', x: 'aaa', y: 'bbb' },
322
+ priority: 30,
323
+ };
324
+ const { app } = createPairingRouteApp({ getRelayPairingCandidate: vi.fn(async () => relayCandidate) });
325
+
326
+ const response = await request(app)
327
+ .post('/api/client-auth/pairing/sessions')
328
+ .set('Host', 'runtime.example')
329
+ .send({ label: 'Pair phone' })
330
+ .expect(201);
331
+
332
+ expect(response.body.server.candidates).toEqual([
333
+ { type: 'lan', url: 'http://runtime.example', priority: 10 },
334
+ relayCandidate,
335
+ ]);
336
+ });
337
+
338
+ it('still returns the direct candidate when the relay candidate lookup throws', async () => {
339
+ const { app } = createPairingRouteApp({
340
+ getRelayPairingCandidate: vi.fn(async () => { throw new Error('relay status read failed'); }),
341
+ });
342
+
343
+ const response = await request(app)
344
+ .post('/api/client-auth/pairing/sessions')
345
+ .set('Host', 'runtime.example')
346
+ .send({ label: 'Pair phone' })
347
+ .expect(201);
348
+
349
+ expect(response.body.server.candidates).toEqual([{ type: 'lan', url: 'http://runtime.example', priority: 10 }]);
350
+ });
351
+
352
+ it('requires owner auth before creating or cancelling pairing sessions', async () => {
353
+ const { app, dependencies } = createPairingRouteApp({
354
+ uiAuthController: {
355
+ resolveAuthContext: vi.fn(async () => null),
356
+ requireAuth: vi.fn((_req, res) => res.status(401).json({ error: 'Unauthorized' })),
357
+ requireSessionAuth: vi.fn((_req, res) => res.status(401).json({ error: 'Unauthorized' })),
358
+ },
359
+ });
360
+
361
+ await request(app).post('/api/client-auth/pairing/sessions').send({}).expect(401);
362
+ await request(app).delete('/api/client-auth/pairing/sessions/pair_1').expect(401);
363
+ expect(dependencies.clientPairingRuntime.createPairingSession).not.toHaveBeenCalled();
364
+ expect(dependencies.clientPairingRuntime.cancelPairingSession).not.toHaveBeenCalled();
365
+ });
366
+
367
+ it('redeems pairing sessions with no-store response and generic errors', async () => {
368
+ const { app, dependencies } = createPairingRouteApp();
369
+
370
+ const response = await request(app)
371
+ .post('/api/client-auth/pairing/redeem')
372
+ .set('Host', 'runtime.example')
373
+ .send({ pairingId: 'pair_1', secret: 'secret', clientKind: 'mobile', deviceName: 'Phone' })
374
+ .expect(200);
375
+
376
+ expect(response.headers['cache-control']).toBe('no-store');
377
+ expect(response.body).toMatchObject({
378
+ ok: true,
379
+ server: { label: 'OpenChamber', url: 'http://runtime.example', fingerprint: 'ABCD-1234' },
380
+ client: { id: 'client-1', authMethod: 'pairing' },
381
+ clientToken: 'oc_client_token',
382
+ });
383
+ expect(dependencies.clientPairingRuntime.redeemPairingSession).toHaveBeenCalledWith(expect.objectContaining({
384
+ pairingId: 'pair_1',
385
+ secret: 'secret',
386
+ clientKind: 'mobile',
387
+ deviceName: 'Phone',
388
+ }));
389
+
390
+ dependencies.clientPairingRuntime.redeemPairingSession.mockRejectedValueOnce(new Error('Invalid or expired pairing session'));
391
+ await request(app)
392
+ .post('/api/client-auth/pairing/redeem')
393
+ .send({ pairingId: 'pair_2', secret: 'wrong' })
394
+ .expect(400, { error: 'Invalid or expired pairing session' });
395
+ });
396
+
397
+ it('rate limits pairing redeem attempts by socket address and pairingId, then resets after the window', async () => {
398
+ vi.useFakeTimers();
399
+ vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
400
+ const { app, dependencies } = createPairingRouteApp();
401
+ app.set('trust proxy', true);
402
+ dependencies.clientPairingRuntime.redeemPairingSession.mockRejectedValue(new Error('Invalid or expired pairing session'));
403
+
404
+ // The X-Forwarded-For headers below are deliberate spoof attempts: the rate
405
+ // limiter buckets by socket address (not forwarded headers), so rotating the
406
+ // header must NOT reset the counter or evade the lockout.
407
+ for (let index = 0; index < 10; index += 1) {
408
+ await request(app)
409
+ .post('/api/client-auth/pairing/redeem')
410
+ .set('X-Forwarded-For', `203.0.113.${index}`)
411
+ .send({ pairingId: 'pair_rate', secret: `wrong-${index}` })
412
+ .expect(400, { error: 'Invalid or expired pairing session' });
413
+ }
414
+
415
+ const locked = await request(app)
416
+ .post('/api/client-auth/pairing/redeem')
417
+ .set('X-Forwarded-For', '203.0.113.10')
418
+ .send({ pairingId: 'pair_rate', secret: 'wrong-locked' })
419
+ .expect(429, { error: 'Invalid or expired pairing session' });
420
+ expect(locked.headers['retry-after']).toBe('300');
421
+ expect(dependencies.clientPairingRuntime.redeemPairingSession).toHaveBeenCalledTimes(10);
422
+
423
+ vi.setSystemTime(new Date('2026-01-01T00:05:01Z'));
424
+ await request(app)
425
+ .post('/api/client-auth/pairing/redeem')
426
+ .set('X-Forwarded-For', '203.0.113.10')
427
+ .send({ pairingId: 'pair_rate', secret: 'wrong-after-reset' })
428
+ .expect(400, { error: 'Invalid or expired pairing session' });
429
+ expect(dependencies.clientPairingRuntime.redeemPairingSession).toHaveBeenCalledTimes(11);
430
+ });
431
+
228
432
  it('should let preview proxy credentials reach preview proxy validation', async () => {
229
433
  const app = express();
230
434
  const requireAuth = vi.fn((_req, res) => res.status(401).type('text/plain').send('Authentication required'));
@@ -364,11 +568,9 @@ describe('client auth routes', () => {
364
568
 
365
569
  const listedAfterPurge = await request(app).get('/api/client-auth/clients');
366
570
  expect(listedAfterPurge.body.clients).toHaveLength(0);
367
- expect(dependencies.testHooks.requireSessionAuth).toHaveBeenCalled();
368
- expect(dependencies.testHooks.requireAuth).not.toHaveBeenCalled();
369
571
  });
370
572
 
371
- it('allows client credentials to list and revoke only the authenticated client', async () => {
573
+ it('scopes non-desktop client credentials to list and revoke only themselves', async () => {
372
574
  const app = express();
373
575
  let authContext = { type: 'session' };
374
576
  const dependencies = createDependencies({
@@ -383,20 +585,57 @@ describe('client auth routes', () => {
383
585
  .post('/api/client-auth/clients')
384
586
  .send({ label: 'Other device' });
385
587
 
386
- authContext = { type: 'client', clientId: current.body.client.id, client: current.body.client };
588
+ // A regular (non-desktop-local) client token only sees and manages itself.
589
+ authContext = { type: 'client', clientId: other.body.client.id, client: other.body.client };
387
590
 
388
591
  const listed = await request(app).get('/api/client-auth/clients');
389
592
  expect(listed.status).toBe(200);
390
- expect(listed.body.clients).toEqual([current.body.client]);
593
+ expect(listed.body.clients).toEqual([other.body.client]);
391
594
 
392
- const denied = await request(app).delete(`/api/client-auth/clients/${other.body.client.id}`);
595
+ const denied = await request(app).delete(`/api/client-auth/clients/${current.body.client.id}`);
393
596
  expect(denied.status).toBe(403);
394
597
  expect(denied.body.revoked).toBe(false);
395
598
 
396
- const revoked = await request(app).delete(`/api/client-auth/clients/${current.body.client.id}`);
599
+ const deniedPurge = await request(app).delete('/api/client-auth/clients');
600
+ expect(deniedPurge.status).toBe(403);
601
+
602
+ const revoked = await request(app).delete(`/api/client-auth/clients/${other.body.client.id}`);
603
+ expect(revoked.status).toBe(200);
604
+ expect(revoked.body.revoked).toBe(true);
605
+ expect(revoked.body.client.id).toBe(other.body.client.id);
606
+ });
607
+
608
+ it('lets the local desktop client list and revoke every device', async () => {
609
+ const app = express();
610
+ let authContext = { type: 'session' };
611
+ const dependencies = createDependencies({
612
+ resolveAuthContext: async () => authContext,
613
+ });
614
+ registerAuthAndAccessRoutes(app, dependencies);
615
+
616
+ const desktop = await request(app)
617
+ .post('/api/client-auth/clients')
618
+ .send({ label: 'OpenChamber Desktop', clientKind: 'desktop-local' });
619
+ const other = await request(app)
620
+ .post('/api/client-auth/clients')
621
+ .send({ label: 'Other device' });
622
+
623
+ // The trusted desktop shell client manages all devices like a UI session.
624
+ authContext = { type: 'client', clientId: desktop.body.client.id, client: desktop.body.client };
625
+
626
+ const listed = await request(app).get('/api/client-auth/clients');
627
+ expect(listed.status).toBe(200);
628
+ const listedIds = listed.body.clients.map((client) => client.id).sort();
629
+ expect(listedIds).toEqual([desktop.body.client.id, other.body.client.id].sort());
630
+
631
+ const revoked = await request(app).delete(`/api/client-auth/clients/${other.body.client.id}`);
397
632
  expect(revoked.status).toBe(200);
398
633
  expect(revoked.body.revoked).toBe(true);
399
- expect(revoked.body.client.id).toBe(current.body.client.id);
634
+ expect(revoked.body.client.id).toBe(other.body.client.id);
635
+
636
+ const purged = await request(app).delete('/api/client-auth/clients');
637
+ expect(purged.status).toBe(200);
638
+ expect(purged.body.purged).toBe(1);
400
639
  });
401
640
 
402
641
  it('allows only the local desktop client token to create remote client tokens', async () => {
@@ -1,5 +1,6 @@
1
1
  import { registerFsRoutes } from '../fs/routes.js';
2
2
  import { registerQuotaRoutes } from '../quota/routes.js';
3
+ import { registerSmallModelRoutes } from '../small-model/routes.js';
3
4
  import { registerGitHubRoutes } from '../github/routes.js';
4
5
  import { registerGitRoutes } from '../git/routes.js';
5
6
  import { registerMagicPromptRoutes } from '../magic-prompts/routes.js';
@@ -54,6 +55,14 @@ export const createFeatureRoutesRuntime = (dependencies) => {
54
55
  return quotaProviders;
55
56
  };
56
57
 
58
+ let smallModelService = null;
59
+ const getSmallModelService = async () => {
60
+ if (!smallModelService) {
61
+ smallModelService = await import('../small-model/index.js');
62
+ }
63
+ return smallModelService;
64
+ };
65
+
57
66
  const registerRoutes = async (app, routeDependencies) => {
58
67
  const {
59
68
  crypto,
@@ -226,6 +235,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
226
235
  });
227
236
 
228
237
  registerQuotaRoutes(app, { getQuotaProviders });
238
+ registerSmallModelRoutes(app, { getSmallModelService });
229
239
  registerGitHubRoutes(app);
230
240
  registerGitRoutes(app);
231
241
  registerMagicPromptRoutes(app, {
@@ -0,0 +1,61 @@
1
+ const MODELS_DEV_API_URL = 'https://models.dev/api.json';
2
+ const DEFAULT_TTL_MS = 10 * 60 * 1000;
3
+ const DEFAULT_TIMEOUT_MS = 8000;
4
+
5
+ // Shared in-process cache of the models.dev catalog. Used by the
6
+ // /api/openchamber/models-metadata route and the small-model resolver so the
7
+ // server fetches the catalog once, not per consumer.
8
+ let cachedMetadata = null;
9
+ let cachedAt = 0;
10
+ let inflight = null;
11
+
12
+ const fetchCatalog = async (url, timeoutMs) => {
13
+ const response = await fetch(url, {
14
+ headers: { Accept: 'application/json' },
15
+ signal: AbortSignal.timeout(timeoutMs),
16
+ });
17
+ if (!response.ok) {
18
+ throw new Error(`models.dev responded with status ${response.status}`);
19
+ }
20
+ const metadata = await response.json();
21
+ if (!metadata || typeof metadata !== 'object') {
22
+ throw new Error('models.dev returned an unexpected payload');
23
+ }
24
+ return metadata;
25
+ };
26
+
27
+ /**
28
+ * Returns the models.dev catalog, serving the in-memory copy while fresh.
29
+ * On fetch failure a stale cached copy is returned when available; otherwise
30
+ * the error propagates.
31
+ */
32
+ export async function getModelsMetadata({
33
+ url = MODELS_DEV_API_URL,
34
+ ttlMs = DEFAULT_TTL_MS,
35
+ timeoutMs = DEFAULT_TIMEOUT_MS,
36
+ } = {}) {
37
+ const now = Date.now();
38
+ if (cachedMetadata && now - cachedAt < ttlMs) {
39
+ return { metadata: cachedMetadata, fromCache: true };
40
+ }
41
+
42
+ if (!inflight) {
43
+ inflight = fetchCatalog(url, timeoutMs).finally(() => {
44
+ inflight = null;
45
+ });
46
+ }
47
+
48
+ try {
49
+ const metadata = await inflight;
50
+ cachedMetadata = metadata;
51
+ cachedAt = Date.now();
52
+ return { metadata, fromCache: false };
53
+ } catch (error) {
54
+ if (cachedMetadata) {
55
+ return { metadata: cachedMetadata, fromCache: true, stale: true };
56
+ }
57
+ throw error;
58
+ }
59
+ }
60
+
61
+ export { MODELS_DEV_API_URL };
@@ -2,8 +2,21 @@ export const createOpenCodeNetworkRuntime = (deps) => {
2
2
  const {
3
3
  state,
4
4
  getOpenCodeAuthHeaders,
5
+ configuredOpenCodeHostname = '127.0.0.1',
5
6
  } = deps;
6
7
 
8
+ const resolveConnectHostname = () => {
9
+ const raw = typeof configuredOpenCodeHostname === 'string' ? configuredOpenCodeHostname.trim() : '';
10
+ const hostname = raw || '127.0.0.1';
11
+ if (hostname === '0.0.0.0' || hostname === '::' || hostname === '[::]') {
12
+ return '127.0.0.1';
13
+ }
14
+ if (hostname.startsWith('[') && hostname.endsWith(']')) {
15
+ return hostname;
16
+ }
17
+ return hostname.includes(':') ? `[${hostname}]` : hostname;
18
+ };
19
+
7
20
  const normalizeApiPrefix = (prefix) => {
8
21
  if (!prefix) {
9
22
  return '';
@@ -77,7 +90,7 @@ export const createOpenCodeNetworkRuntime = (deps) => {
77
90
  const normalizedPath = path.startsWith('/') ? path : `/${path}`;
78
91
  const prefix = normalizeApiPrefix(prefixOverride !== undefined ? prefixOverride : '');
79
92
  const fullPath = `${prefix}${normalizedPath}`;
80
- const base = state.openCodeBaseUrl ?? `http://localhost:${state.openCodePort}`;
93
+ const base = state.openCodeBaseUrl ?? `http://${resolveConnectHostname()}:${state.openCodePort}`;
81
94
  return `${base}${fullPath}`;
82
95
  };
83
96
 
@@ -2,36 +2,56 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
2
2
 
3
3
  import { createOpenCodeNetworkRuntime } from './network-runtime.js';
4
4
 
5
- const createRuntime = () => createOpenCodeNetworkRuntime({
5
+ const originalFetch = globalThis.fetch;
6
+
7
+ const createRuntime = (overrides = {}) => createOpenCodeNetworkRuntime({
6
8
  state: {
7
9
  openCodePort: 4096,
8
10
  openCodeBaseUrl: null,
9
11
  openCodeApiPrefix: '',
10
12
  openCodeApiPrefixDetected: false,
11
13
  openCodeApiDetectionTimer: null,
14
+ ...overrides.state,
12
15
  },
13
16
  getOpenCodeAuthHeaders: () => ({}),
17
+ configuredOpenCodeHostname: overrides.configuredOpenCodeHostname,
14
18
  });
15
19
 
16
20
  describe('OpenCode network runtime', () => {
17
21
  afterEach(() => {
18
22
  vi.useRealTimers();
19
- vi.unstubAllGlobals();
23
+ globalThis.fetch = originalFetch;
20
24
  });
21
25
 
22
- it('clears the probe abort timer when readiness fetch rejects', async () => {
23
- vi.useFakeTimers();
24
- vi.setSystemTime(0);
25
- vi.stubGlobal('fetch', vi.fn(async () => {
26
+ it('returns false when readiness fetch rejects', async () => {
27
+ globalThis.fetch = vi.fn(async () => {
26
28
  throw new Error('offline');
27
- }));
29
+ });
28
30
 
29
31
  const runtime = createRuntime();
30
32
  const readyPromise = runtime.waitForReady('http://127.0.0.1:4096', 1);
31
33
 
32
- await vi.advanceTimersByTimeAsync(100);
33
34
  await expect(readyPromise).resolves.toBe(false);
35
+ });
36
+
37
+ it('builds managed OpenCode URLs against IPv4 loopback by default', () => {
38
+ const runtime = createRuntime();
39
+
40
+ expect(runtime.buildOpenCodeUrl('/provider')).toBe('http://127.0.0.1:4096/provider');
41
+ });
42
+
43
+ it('keeps external OpenCode base URLs authoritative', () => {
44
+ const runtime = createRuntime({
45
+ state: { openCodeBaseUrl: 'http://remote.example:4096' },
46
+ });
47
+
48
+ expect(runtime.buildOpenCodeUrl('/provider')).toBe('http://remote.example:4096/provider');
49
+ });
34
50
 
35
- expect(vi.getTimerCount()).toBe(0);
51
+ it('normalizes wildcard and IPv6 OpenCode bind hosts for local connects', () => {
52
+ expect(createRuntime({ configuredOpenCodeHostname: '0.0.0.0' }).buildOpenCodeUrl('/provider'))
53
+ .toBe('http://127.0.0.1:4096/provider');
54
+ expect(createRuntime({ configuredOpenCodeHostname: '::1' }).buildOpenCodeUrl('/provider'))
55
+ .toBe('http://[::1]:4096/provider');
36
56
  });
37
57
  });
@@ -13,9 +13,6 @@ export const registerOpenChamberRoutes = (app, dependencies) => {
13
13
  getCachedZenModels,
14
14
  } = dependencies;
15
15
 
16
- let cachedModelsMetadata = null;
17
- let cachedModelsMetadataTimestamp = 0;
18
-
19
16
  app.get('/api/openchamber/update-check', async (req, res) => {
20
17
  try {
21
18
  const { checkForUpdates } = await import('../package-manager.js');
@@ -254,48 +251,18 @@ export const registerOpenChamberRoutes = (app, dependencies) => {
254
251
  });
255
252
 
256
253
  app.get('/api/openchamber/models-metadata', async (_req, res) => {
257
- const now = Date.now();
258
-
259
- if (cachedModelsMetadata && now - cachedModelsMetadataTimestamp < modelsMetadataCacheTtl) {
260
- res.setHeader('Cache-Control', 'public, max-age=60');
261
- return res.json(cachedModelsMetadata);
262
- }
263
-
264
- const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
265
- const timeout = controller ? setTimeout(() => controller.abort(), 8000) : null;
266
-
267
254
  try {
268
- const response = await fetch(modelsDevApiUrl, {
269
- signal: controller?.signal,
270
- headers: {
271
- Accept: 'application/json'
272
- }
255
+ const { getModelsMetadata } = await import('./models-metadata.js');
256
+ const { metadata, fromCache, stale } = await getModelsMetadata({
257
+ url: modelsDevApiUrl,
258
+ ttlMs: modelsMetadataCacheTtl,
273
259
  });
274
-
275
- if (!response.ok) {
276
- throw new Error(`models.dev responded with status ${response.status}`);
277
- }
278
-
279
- const metadata = await response.json();
280
- cachedModelsMetadata = metadata;
281
- cachedModelsMetadataTimestamp = Date.now();
282
-
283
- res.setHeader('Cache-Control', 'public, max-age=300');
260
+ res.setHeader('Cache-Control', fromCache && !stale ? 'public, max-age=60' : 'public, max-age=300');
284
261
  res.json(metadata);
285
262
  } catch (error) {
286
263
  console.warn('Failed to fetch models.dev metadata via server:', error);
287
-
288
- if (cachedModelsMetadata) {
289
- res.setHeader('Cache-Control', 'public, max-age=60');
290
- res.json(cachedModelsMetadata);
291
- } else {
292
- const statusCode = error?.name === 'AbortError' ? 504 : 502;
293
- res.status(statusCode).json({ error: 'Failed to retrieve model metadata' });
294
- }
295
- } finally {
296
- if (timeout) {
297
- clearTimeout(timeout);
298
- }
264
+ const statusCode = error?.name === 'TimeoutError' || error?.name === 'AbortError' ? 504 : 502;
265
+ res.status(statusCode).json({ error: 'Failed to retrieve model metadata' });
299
266
  }
300
267
  });
301
268
 
@@ -181,6 +181,7 @@ export const registerOpenCodeProxy = (app, deps) => {
181
181
  os,
182
182
  path,
183
183
  OPEN_CODE_READY_GRACE_MS,
184
+ LONG_REQUEST_TIMEOUT_MS,
184
185
  getRuntime,
185
186
  getOpenCodeAuthHeaders,
186
187
  buildOpenCodeUrl,
@@ -291,11 +292,46 @@ export const registerOpenCodeProxy = (app, deps) => {
291
292
  return externalBase;
292
293
  }
293
294
 
294
- if (runtimeState.openCodePort) {
295
- return `http://localhost:${runtimeState.openCodePort}`;
295
+ return FALLBACK_PROXY_TARGET;
296
+ };
297
+
298
+ const normalizeProxyTimeout = (value) => {
299
+ return Number.isFinite(value) && value > 0 ? value : 4 * 60 * 1000;
300
+ };
301
+
302
+ const PROXY_REQUEST_TIMEOUT_MS = normalizeProxyTimeout(LONG_REQUEST_TIMEOUT_MS);
303
+ const PROXY_TIMEOUT_MARKER = Symbol('openchamberProxyTimedOut');
304
+
305
+ const isProxyTimeoutError = (error) => {
306
+ const code = typeof error?.code === 'string' ? error.code : '';
307
+ const message = typeof error?.message === 'string' ? error.message.toLowerCase() : '';
308
+ return code === 'ETIMEDOUT'
309
+ || code === 'ESOCKETTIMEDOUT'
310
+ || message.includes('timeout')
311
+ || message.includes('timed out');
312
+ };
313
+
314
+ const sendProxyErrorResponse = (res, statusCode) => {
315
+ if (!res || res.headersSent || res.writableEnded || typeof res.status !== 'function') {
316
+ return false;
296
317
  }
318
+ res.status(statusCode).json({ error: statusCode === 504 ? 'OpenCode upstream timed out' : 'OpenCode service unavailable' });
319
+ return true;
320
+ };
297
321
 
298
- return FALLBACK_PROXY_TARGET;
322
+ const applyProxyResponseDeadline = (req, res, next) => {
323
+ const timeout = setTimeout(() => {
324
+ req[PROXY_TIMEOUT_MARKER] = true;
325
+ if (sendProxyErrorResponse(res, 504)) {
326
+ res.once('finish', () => req.destroy?.());
327
+ }
328
+ }, PROXY_REQUEST_TIMEOUT_MS);
329
+ timeout.unref?.();
330
+
331
+ const clear = () => clearTimeout(timeout);
332
+ res.once('finish', clear);
333
+ res.once('close', clear);
334
+ next();
299
335
  };
300
336
 
301
337
  const forwardSseRequest = async (req, res) => {
@@ -665,6 +701,8 @@ export const registerOpenCodeProxy = (app, deps) => {
665
701
  target: resolveProxyTarget(),
666
702
  changeOrigin: true,
667
703
  pathRewrite: { '^/api': '' },
704
+ timeout: PROXY_REQUEST_TIMEOUT_MS,
705
+ proxyTimeout: PROXY_REQUEST_TIMEOUT_MS,
668
706
  // Dynamic target — port can change after restart
669
707
  router: () => resolveProxyTarget(),
670
708
  on: {
@@ -700,11 +738,13 @@ export const registerOpenCodeProxy = (app, deps) => {
700
738
  }
701
739
  }
702
740
  },
703
- error: (err, _req, res) => {
741
+ error: (err, req, res) => {
704
742
  console.error('[proxy] OpenCode proxy error:', err.message);
705
- if (res && !res.headersSent && typeof res.status === 'function') {
706
- res.status(503).json({ error: 'OpenCode service unavailable' });
743
+ if (req?.[PROXY_TIMEOUT_MARKER]) {
744
+ return;
707
745
  }
746
+ const statusCode = isProxyTimeoutError(err) ? 504 : 503;
747
+ sendProxyErrorResponse(res, statusCode);
708
748
  },
709
749
  },
710
750
  });
@@ -724,5 +764,6 @@ export const registerOpenCodeProxy = (app, deps) => {
724
764
  next();
725
765
  });
726
766
 
767
+ app.use('/api', applyProxyResponseDeadline);
727
768
  app.use('/api', apiProxy);
728
769
  };
@@ -181,6 +181,9 @@ export const createSettingsHelpers = (dependencies) => {
181
181
  if (typeof candidate.desktopKeepAwakeEnabled === 'boolean') {
182
182
  result.desktopKeepAwakeEnabled = candidate.desktopKeepAwakeEnabled;
183
183
  }
184
+ if (typeof candidate.desktopMinimizeToTrayEnabled === 'boolean') {
185
+ result.desktopMinimizeToTrayEnabled = candidate.desktopMinimizeToTrayEnabled;
186
+ }
184
187
  if (typeof candidate.desktopUiPassword === 'string') {
185
188
  result.desktopUiPassword = candidate.desktopUiPassword.trim();
186
189
  }
@@ -245,6 +248,12 @@ export const createSettingsHelpers = (dependencies) => {
245
248
  if (typeof candidate.showReasoningTraces === 'boolean') {
246
249
  result.showReasoningTraces = candidate.showReasoningTraces;
247
250
  }
251
+ if (typeof candidate.sessionRecapEnabled === 'boolean') {
252
+ result.sessionRecapEnabled = candidate.sessionRecapEnabled;
253
+ }
254
+ if (typeof candidate.sessionSuggestionEnabled === 'boolean') {
255
+ result.sessionSuggestionEnabled = candidate.sessionSuggestionEnabled;
256
+ }
248
257
  if (typeof candidate.collapsibleThinkingBlocks === 'boolean') {
249
258
  result.collapsibleThinkingBlocks = candidate.collapsibleThinkingBlocks;
250
259
  }
@@ -374,6 +383,13 @@ export const createSettingsHelpers = (dependencies) => {
374
383
  const trimmed = candidate.defaultAgent.trim();
375
384
  result.defaultAgent = trimmed.length > 0 ? trimmed : undefined;
376
385
  }
386
+ if (typeof candidate.smallModelUseDefault === 'boolean') {
387
+ result.smallModelUseDefault = candidate.smallModelUseDefault;
388
+ }
389
+ if (typeof candidate.smallModelOverride === 'string') {
390
+ const trimmed = candidate.smallModelOverride.trim();
391
+ result.smallModelOverride = trimmed.length > 0 ? trimmed : undefined;
392
+ }
377
393
  if (typeof candidate.defaultGitIdentityId === 'string') {
378
394
  const trimmed = candidate.defaultGitIdentityId.trim();
379
395
  result.defaultGitIdentityId = trimmed.length > 0 ? trimmed : undefined;