@openchamber/web 1.21.1 → 1.22.1

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 (175) hide show
  1. package/dist/assets/{CodeMirrorCommentWidgets-BGj8TJxW.js → CodeMirrorCommentWidgets-BO_2OW4E.js} +1 -1
  2. package/dist/assets/DiffView-CNnDxRmO.js +4 -0
  3. package/dist/assets/DirtyBranchSwitchDialog-jADfXQnR.js +1 -0
  4. package/dist/assets/FilesView-8wdiG2mj.js +17 -0
  5. package/dist/assets/GitView-Cv2xH-S6.js +6 -0
  6. package/dist/assets/{JsonTreeView-CggOsLot.js → JsonTreeView-DUiIpERC.js} +1 -1
  7. package/dist/assets/LinearIssuesView-CoZ7pQN5.js +1 -0
  8. package/dist/assets/MarkdownImageGallery-DffjmciG.js +1 -0
  9. package/dist/assets/MarkdownRendererImpl-DxqdYDAx.js +12 -0
  10. package/dist/assets/OnboardingScreen-CTZe6HZn.js +1 -0
  11. package/dist/assets/{PatchDiff-DJYMUiXA.js → PatchDiff-BymkP9JA.js} +1 -1
  12. package/dist/assets/{PierreDiffViewer-CY2bx_SB.js → PierreDiffViewer-BvwtCxW4.js} +3 -3
  13. package/dist/assets/{PlanView-PkiOY_9H.js → PlanView-C1qvAm7m.js} +3 -3
  14. package/dist/assets/SettingsView-xGONHFGS.js +28 -0
  15. package/dist/assets/{SettingsWindow-oyOm2fHR.js → SettingsWindow-COzgfFxM.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-lKyeQTPL.js → ToolOutputDialog-Dlhh_-oe.js} +6 -6
  17. package/dist/assets/ToolPartDiffPreview-b9joNtXH.js +8 -0
  18. package/dist/assets/{VirtualizedFileDiff-BP7ebDFF.js → VirtualizedFileDiff-vqW3KKo5.js} +1 -1
  19. package/dist/assets/WalkthroughView-D-HFgdmM.js +4 -0
  20. package/dist/assets/{computeVirtualFileMetrics-CZ0xPeaT.js → computeVirtualFileMetrics-DUnyszhW.js} +1 -1
  21. package/dist/assets/{contextPanelEmbeddedChat-C9abMBTb.js → contextPanelEmbeddedChat-CV-DwAiX.js} +1 -1
  22. package/dist/assets/{de-CEoCz3j6.js → de-Cv_4FoXm.js} +6 -5
  23. package/dist/assets/es-BIWNEbnS.js +16 -0
  24. package/dist/assets/{fr-CS7Csln9.js → fr-SD3OfMHJ.js} +6 -5
  25. package/dist/assets/index-CHUT_bDS.css +1 -0
  26. package/dist/assets/index-DDInLQDd.js +40 -0
  27. package/dist/assets/{index-CaPAjwXQ.js → index-DLiD86ge.js} +1 -1
  28. package/dist/assets/{isDiffPlainText-ZBvDxhVB.js → isDiffPlainText-TNageFjy.js} +1 -1
  29. package/dist/assets/{isFilePlainText-DiLRrkJr.js → isFilePlainText-JPmZOYSp.js} +1 -1
  30. package/dist/assets/{ja-vnwqLcx6.js → ja-D7I9HofF.js} +7 -6
  31. package/dist/assets/{ko-CXuSfZv5.js → ko-BsVJM_PQ.js} +7 -6
  32. package/dist/assets/{main-D5RWr6sJ.js → main-DCB4JgVe.js} +2 -2
  33. package/dist/assets/main-De8Z5w49.js +928 -0
  34. package/dist/assets/markdownCore-BoQVG5-a.js +3 -0
  35. package/dist/assets/{miniChat-CqR3icsk.js → miniChat-BtV7N5OF.js} +2 -2
  36. package/dist/assets/{mobile-RN_UTTlB.js → mobile-DZV_sfX7.js} +2 -2
  37. package/dist/assets/{patchFileDiff-CjRR5ESs.js → patchFileDiff-Chmiz6hq.js} +4 -4
  38. package/dist/assets/{pl-BJxry0Mi.js → pl-XR9Bs8Be.js} +6 -5
  39. package/dist/assets/pt-BR-Due4be8g.js +16 -0
  40. package/dist/assets/{renderElectronMiniChatApp-1wC94fQK.js → renderElectronMiniChatApp-8tXADjfl.js} +2 -2
  41. package/dist/assets/renderMobileApp-Cji7Hma5.js +25 -0
  42. package/dist/assets/runtimeEndpointReset-gWt3Lb5D.js +16 -0
  43. package/dist/assets/scheduledTasksApi-9e-UX6im.js +1 -0
  44. package/dist/assets/{shikiHighlight-fGmFkxAM.js → shikiHighlight-CRpCl7UT.js} +1 -1
  45. package/dist/assets/tr-DBJcAv4y.js +7 -0
  46. package/dist/assets/uk-COYh2BaN.js +16 -0
  47. package/dist/assets/{useAppFontEffects-KP8_yiGW.js → useAppFontEffects-CCgvcQ6u.js} +178 -170
  48. package/dist/assets/useInlineCommentController-BkfXnjNZ.js +2 -0
  49. package/dist/assets/useRootScrollLock-KzOUytpn.js +1 -0
  50. package/dist/assets/{vendor-codemirror-language-data-DrTPkHl4.js → vendor-codemirror-language-data-BxpoC5Fp.js} +2 -2
  51. package/dist/assets/vendor-zod-DVWEh-IS.js +39 -0
  52. package/dist/assets/{web-components-DOXvU-tB.js → web-components-B6QgbmTo.js} +4 -4
  53. package/dist/assets/zh-CN-Cjk6lzhc.js +16 -0
  54. package/dist/assets/{zh-TW-Dv8yyhN1.js → zh-TW-Dk0dOg03.js} +6 -5
  55. package/dist/index.html +5 -5
  56. package/dist/mini-chat.html +4 -4
  57. package/dist/mobile.html +4 -4
  58. package/package.json +2 -2
  59. package/server/index.js +35 -4
  60. package/server/lib/agent-tool/runtime.js +2 -19
  61. package/server/lib/dev-tunnel/DOCUMENTATION.md +13 -4
  62. package/server/lib/dev-tunnel/runtime.js +4 -4
  63. package/server/lib/dev-tunnel/tunnel.test.js +20 -0
  64. package/server/lib/dictation/DOCUMENTATION.md +19 -6
  65. package/server/lib/dictation/local/model-catalog.js +220 -0
  66. package/server/lib/dictation/local/model-catalog.test.js +42 -0
  67. package/server/lib/dictation/local/sherpa-tts.js +41 -20
  68. package/server/lib/dictation/local/worker-process.js +2 -0
  69. package/server/lib/dictation/runtime.js +4 -0
  70. package/server/lib/dictation/service.js +27 -4
  71. package/server/lib/fs/DOCUMENTATION.md +4 -0
  72. package/server/lib/fs/routes.js +129 -0
  73. package/server/lib/fs/routes.test.js +219 -0
  74. package/server/lib/git/DOCUMENTATION.md +3 -1
  75. package/server/lib/git/routes.js +16 -0
  76. package/server/lib/git/service.js +97 -17
  77. package/server/lib/git/service.test.js +153 -0
  78. package/server/lib/linear/DOCUMENTATION.md +97 -0
  79. package/server/lib/linear/OAUTH-BROKER-HANDOFF.md +91 -0
  80. package/server/lib/linear/auth.js +436 -0
  81. package/server/lib/linear/auth.test.js +242 -0
  82. package/server/lib/linear/client.js +191 -0
  83. package/server/lib/linear/index.js +61 -0
  84. package/server/lib/linear/issues.js +499 -0
  85. package/server/lib/linear/issues.test.js +512 -0
  86. package/server/lib/linear/mapping.js +188 -0
  87. package/server/lib/linear/mapping.test.js +147 -0
  88. package/server/lib/linear/oauth.js +345 -0
  89. package/server/lib/linear/oauth.test.js +166 -0
  90. package/server/lib/linear/parse.js +23 -0
  91. package/server/lib/linear/routes.js +432 -0
  92. package/server/lib/linear/routes.test.js +661 -0
  93. package/server/lib/linear/status-runtime.js +64 -0
  94. package/server/lib/linear/status-runtime.test.js +167 -0
  95. package/server/lib/linear/status.js +280 -0
  96. package/server/lib/linear/status.test.js +271 -0
  97. package/server/lib/linear/teams.js +72 -0
  98. package/server/lib/linear/teams.test.js +94 -0
  99. package/server/lib/mcp-reconnect/DOCUMENTATION.md +55 -0
  100. package/server/lib/mcp-reconnect/runtime.js +122 -0
  101. package/server/lib/mcp-reconnect/runtime.test.js +140 -0
  102. package/server/lib/message-queue/DOCUMENTATION.md +148 -0
  103. package/server/lib/message-queue/runtime.js +818 -0
  104. package/server/lib/message-queue/runtime.test.js +426 -0
  105. package/server/lib/openchamber-sessions/routes.js +102 -0
  106. package/server/lib/openchamber-sessions/routes.test.js +88 -0
  107. package/server/lib/opencode/DOCUMENTATION.md +5 -1
  108. package/server/lib/opencode/core-routes.js +1 -0
  109. package/server/lib/opencode/feature-routes-runtime.js +5 -0
  110. package/server/lib/opencode/managed-plugin-config.js +35 -0
  111. package/server/lib/opencode/settings-runtime.js +2 -2
  112. package/server/lib/opencode/settings-runtime.test.js +29 -0
  113. package/server/lib/opencode/shutdown-runtime.js +2 -0
  114. package/server/lib/opencode/static-routes-runtime.js +3 -3
  115. package/server/lib/projects/project-config.js +33 -5
  116. package/server/lib/projects/project-config.test.js +85 -0
  117. package/server/lib/quota/DOCUMENTATION.md +2 -1
  118. package/server/lib/quota/credentials/providers.js +4 -0
  119. package/server/lib/quota/credentials/store.js +1 -1
  120. package/server/lib/quota/credentials/store.test.js +4 -4
  121. package/server/lib/quota/providers/exe-dev.js +75 -0
  122. package/server/lib/quota/providers/exe-dev.test.js +47 -0
  123. package/server/lib/quota/providers/index.js +7 -0
  124. package/server/lib/quota/providers/opencode-go.js +1 -0
  125. package/server/lib/quota/providers/opencode-go.test.js +5 -1
  126. package/server/lib/quota/routes.js +2 -0
  127. package/server/lib/relay/DOCUMENTATION.md +1 -1
  128. package/server/lib/relay/tunnel-host.js +3 -1
  129. package/server/lib/relay/tunnel-host.test.js +9 -1
  130. package/server/lib/scheduled-tasks/DOCUMENTATION.md +7 -0
  131. package/server/lib/security/request-security.js +21 -6
  132. package/server/lib/security/request-security.test.js +42 -8
  133. package/server/lib/session-assist/runtime.js +1 -0
  134. package/server/lib/session-goal/create.js +3 -1
  135. package/server/lib/session-goal/runtime.js +1 -0
  136. package/server/lib/small-model/DOCUMENTATION.md +4 -0
  137. package/server/lib/small-model/call.js +8 -2
  138. package/server/lib/small-model/call.test.js +23 -0
  139. package/server/lib/small-model/index.js +2 -1
  140. package/server/lib/small-model/routes.js +2 -1
  141. package/server/lib/system-prompt/runtime.js +2 -21
  142. package/server/lib/terminal/runtime.js +30 -7
  143. package/server/lib/tts/DOCUMENTATION.md +1 -0
  144. package/server/lib/tts/language-detect.js +210 -0
  145. package/server/lib/tts/language-detect.test.js +76 -0
  146. package/server/lib/tts/routes.js +23 -1
  147. package/server/lib/tts/routes.test.js +26 -0
  148. package/server/lib/ui-auth/ui-auth.js +4 -1
  149. package/server/lib/ui-auth/ui-auth.test.js +16 -0
  150. package/server/lib/walkthrough/index.js +1 -0
  151. package/dist/assets/CommitSection-DwGiXyjf.js +0 -1
  152. package/dist/assets/DiffView-Db6bjVv1.js +0 -4
  153. package/dist/assets/FilesView-DQOa7Lgz.js +0 -17
  154. package/dist/assets/GitView-CHzJxTi0.js +0 -6
  155. package/dist/assets/MarkdownImageGallery-DoZpaHev.js +0 -1
  156. package/dist/assets/MarkdownRendererImpl-B5Y5xCOz.js +0 -12
  157. package/dist/assets/OnboardingScreen-C98d69Fp.js +0 -1
  158. package/dist/assets/SettingsView-D-K3ELCM.js +0 -28
  159. package/dist/assets/ToolPartDiffPreview-C7kBQNAA.js +0 -8
  160. package/dist/assets/WalkthroughView-MuJodAHD.js +0 -4
  161. package/dist/assets/es-DwyXCqaL.js +0 -15
  162. package/dist/assets/index-CUKcHnUA.css +0 -1
  163. package/dist/assets/index-DIvDEKE-.js +0 -7
  164. package/dist/assets/main-DLlfDjQ_.js +0 -926
  165. package/dist/assets/markdownCore-CcTcLsQF.js +0 -3
  166. package/dist/assets/pt-BR-DxLmkhdv.js +0 -15
  167. package/dist/assets/renderMobileApp-ltva2Plg.js +0 -25
  168. package/dist/assets/runtimeEndpointReset-D6SmNZaP.js +0 -15
  169. package/dist/assets/scheduledTasksApi-mjMDet_H.js +0 -1
  170. package/dist/assets/tr-5Mk_hQ2Q.js +0 -6
  171. package/dist/assets/uk-ClgQjmlw.js +0 -15
  172. package/dist/assets/useInlineCommentController-HIjtuhxD.js +0 -2
  173. package/dist/assets/useRootScrollLock-BSiQ5F75.js +0 -1
  174. package/dist/assets/vendor-zod-BLfBSgBh.js +0 -39
  175. package/dist/assets/zh-CN-Ba6y8H-i.js +0 -15
@@ -0,0 +1,271 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
5
+ import { setLinearAuth, clearLinearAuth, setLinearSessionCommentsEnabled } from './auth.js';
6
+ import {
7
+ buildLinearSessionOpenUrl,
8
+ buildLinearSessionStatusComment,
9
+ isPublicSessionOrigin,
10
+ postLinearSessionStatus,
11
+ pruneSessionStatusRecords,
12
+ readSessionOrigin,
13
+ } from './status.js';
14
+
15
+ const makeTempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-linear-status-'));
16
+
17
+ const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), {
18
+ status,
19
+ headers: { 'Content-Type': 'application/json' },
20
+ });
21
+
22
+ const issueNode = {
23
+ id: 'issue-uuid-1',
24
+ identifier: 'ENG-12',
25
+ title: 'Broken login',
26
+ url: 'https://linear.app/openchamber/issue/ENG-12',
27
+ state: { name: 'In Progress', type: 'started' },
28
+ assignee: null,
29
+ team: { id: 'team-eng', key: 'ENG', name: 'Engineering' },
30
+ description: null,
31
+ comments: { nodes: [] },
32
+ };
33
+
34
+ function stubLinearGraphql({ commentId = 'comment-1' } = {}) {
35
+ return vi.fn(async (_url, options) => {
36
+ const body = JSON.parse(options.body);
37
+ if (body.query.includes('query GetLinearIssue')) {
38
+ return jsonResponse({ data: { issue: issueNode } });
39
+ }
40
+ if (body.query.includes('mutation CommentCreate')) {
41
+ expect(body.variables.input.issueId).toBe('issue-uuid-1');
42
+ expect(body.variables.input.body).toContain('/?session=ses_1');
43
+ return jsonResponse({
44
+ data: {
45
+ commentCreate: {
46
+ success: true,
47
+ comment: { id: commentId },
48
+ },
49
+ },
50
+ });
51
+ }
52
+ throw new Error(`unexpected query: ${body.query}`);
53
+ });
54
+ }
55
+
56
+ describe('Linear session status comments', () => {
57
+ let dataDir;
58
+ let previousDataDir;
59
+ let previousPort;
60
+
61
+ beforeEach(() => {
62
+ previousDataDir = process.env.OPENCHAMBER_DATA_DIR;
63
+ previousPort = process.env.OPENCHAMBER_PORT;
64
+ dataDir = makeTempDir();
65
+ process.env.OPENCHAMBER_DATA_DIR = dataDir;
66
+ process.env.OPENCHAMBER_PORT = '3001';
67
+ setLinearAuth({
68
+ accessToken: 'access-1',
69
+ refreshToken: 'refresh-1',
70
+ tokenType: 'Bearer',
71
+ expiresAt: Date.now() + 86_400_000,
72
+ scope: 'read,write,comments:create',
73
+ });
74
+ setLinearSessionCommentsEnabled(true);
75
+ });
76
+
77
+ afterEach(() => {
78
+ vi.unstubAllGlobals();
79
+ clearLinearAuth();
80
+ if (previousDataDir === undefined) {
81
+ delete process.env.OPENCHAMBER_DATA_DIR;
82
+ } else {
83
+ process.env.OPENCHAMBER_DATA_DIR = previousDataDir;
84
+ }
85
+ if (previousPort === undefined) {
86
+ delete process.env.OPENCHAMBER_PORT;
87
+ } else {
88
+ process.env.OPENCHAMBER_PORT = previousPort;
89
+ }
90
+ fs.rmSync(dataDir, { recursive: true, force: true });
91
+ });
92
+
93
+ it('reads http(s) origins and rejects other URLs', () => {
94
+ expect(readSessionOrigin('https://app.example.com')).toBe('https://app.example.com');
95
+ expect(readSessionOrigin('http://127.0.0.1:3001/')).toBe('http://127.0.0.1:3001');
96
+ expect(readSessionOrigin('javascript:alert(1)')).toBe('');
97
+ expect(readSessionOrigin('https://app.example.com/secret')).toBe('');
98
+ expect(readSessionOrigin('openchamber:')).toBe('');
99
+ expect(buildLinearSessionOpenUrl('ses_1', 'https://app.example.com'))
100
+ .toBe('https://app.example.com/?session=ses_1');
101
+ expect(buildLinearSessionOpenUrl('ses_1', '')).toBe('');
102
+ });
103
+
104
+ it('treats only externally reachable origins as public', () => {
105
+ expect(isPublicSessionOrigin('https://chamber.example.com')).toBe(true);
106
+ expect(isPublicSessionOrigin('http://chamber.example.com:8080')).toBe(true);
107
+ expect(isPublicSessionOrigin('https://203.0.113.10')).toBe(true);
108
+
109
+ expect(isPublicSessionOrigin('http://localhost:3001')).toBe(false);
110
+ expect(isPublicSessionOrigin('http://127.0.0.1:3001')).toBe(false);
111
+ expect(isPublicSessionOrigin('http://[::1]:3001')).toBe(false);
112
+ expect(isPublicSessionOrigin('http://192.168.1.20:3001')).toBe(false);
113
+ expect(isPublicSessionOrigin('http://10.0.0.5:3001')).toBe(false);
114
+ expect(isPublicSessionOrigin('http://172.20.1.4:3001')).toBe(false);
115
+ expect(isPublicSessionOrigin('http://169.254.10.1:3001')).toBe(false);
116
+ expect(isPublicSessionOrigin('http://100.101.102.103:3001')).toBe(false);
117
+ expect(isPublicSessionOrigin('http://macbook.local:3001')).toBe(false);
118
+ expect(isPublicSessionOrigin('http://macbook:3001')).toBe(false);
119
+ expect(isPublicSessionOrigin('http://[fd00::1]:3001')).toBe(false);
120
+ expect(isPublicSessionOrigin('openchamber:')).toBe(false);
121
+ expect(isPublicSessionOrigin('')).toBe(false);
122
+ });
123
+
124
+ it('posts nothing while session comments are turned off', async () => {
125
+ setLinearSessionCommentsEnabled(false);
126
+ const graphql = vi.fn();
127
+ vi.stubGlobal('fetch', graphql);
128
+ await expect(postLinearSessionStatus({
129
+ kind: 'started',
130
+ sessionId: 'ses_1',
131
+ issueIdentifier: 'ENG-12',
132
+ sessionOrigin: 'https://app.example.com',
133
+ })).resolves.toEqual({ connected: true, posted: false, skipped: 'disabled' });
134
+ expect(graphql).not.toHaveBeenCalled();
135
+ });
136
+
137
+ it('posts nothing when the session origin only the author can reach', async () => {
138
+ const graphql = vi.fn();
139
+ vi.stubGlobal('fetch', graphql);
140
+ await expect(postLinearSessionStatus({
141
+ kind: 'started',
142
+ sessionId: 'ses_1',
143
+ issueIdentifier: 'ENG-12',
144
+ sessionOrigin: 'http://127.0.0.1:3001',
145
+ })).resolves.toEqual({ connected: true, posted: false, skipped: 'origin-not-public' });
146
+ await expect(postLinearSessionStatus({
147
+ kind: 'started',
148
+ sessionId: 'ses_2',
149
+ issueIdentifier: 'ENG-12',
150
+ })).resolves.toEqual({ connected: true, posted: false, skipped: 'origin-not-public' });
151
+ expect(graphql).not.toHaveBeenCalled();
152
+ });
153
+
154
+ it('keeps the newest dedupe records and drops the oldest', () => {
155
+ const records = {};
156
+ for (let index = 0; index < 5; index += 1) {
157
+ records[`ses_${index}`] = { issueIdentifier: 'ENG-12', started: true };
158
+ }
159
+ expect(Object.keys(pruneSessionStatusRecords(records, 3))).toEqual(['ses_2', 'ses_3', 'ses_4']);
160
+ expect(Object.keys(pruneSessionStatusRecords(records, 10))).toHaveLength(5);
161
+ });
162
+
163
+ it('makes the whole status line one link and carries no title', () => {
164
+ expect(buildLinearSessionStatusComment({
165
+ kind: 'started',
166
+ sessionUrl: 'https://app.example.com/?session=ses_1',
167
+ })).toBe('[OpenChamber session started](https://app.example.com/?session=ses_1)');
168
+ expect(buildLinearSessionStatusComment({
169
+ kind: 'completed',
170
+ sessionUrl: 'https://app.example.com/?session=ses_1',
171
+ })).toBe('[OpenChamber session completed](https://app.example.com/?session=ses_1)');
172
+ expect(buildLinearSessionStatusComment({
173
+ kind: 'failure',
174
+ sessionUrl: 'https://app.example.com/?session=ses_1',
175
+ })).toBe('[OpenChamber session failed](https://app.example.com/?session=ses_1)');
176
+ });
177
+
178
+ it('cannot be broken by brackets in the issue title', async () => {
179
+ const graphql = stubLinearGraphql();
180
+ vi.stubGlobal('fetch', graphql);
181
+ await postLinearSessionStatus({
182
+ kind: 'started',
183
+ sessionId: 'ses_1',
184
+ issueIdentifier: 'ENG-12',
185
+ sessionOrigin: 'https://app.example.com',
186
+ });
187
+ const commentCalls = graphql.mock.calls.filter(([, options]) => {
188
+ return JSON.parse(options.body).query.includes('mutation CommentCreate');
189
+ });
190
+ const body = JSON.parse(commentCalls[0][1].body).variables.input.body;
191
+ // One balanced pair of brackets, so a title like "[Bug] …" can never leak in
192
+ // and split the link across the renderer.
193
+ expect(body.match(/\[/g)).toHaveLength(1);
194
+ expect(body.match(/\]/g)).toHaveLength(1);
195
+ });
196
+
197
+ it('returns disconnected without calling Linear when there is no auth', async () => {
198
+ clearLinearAuth();
199
+ const graphql = vi.fn();
200
+ vi.stubGlobal('fetch', graphql);
201
+ await expect(postLinearSessionStatus({
202
+ kind: 'started',
203
+ sessionId: 'ses_1',
204
+ issueIdentifier: 'ENG-12',
205
+ })).resolves.toEqual({ connected: false });
206
+ expect(graphql).not.toHaveBeenCalled();
207
+ });
208
+
209
+ it('posts a started comment once and skips repeats', async () => {
210
+ const graphql = stubLinearGraphql();
211
+ vi.stubGlobal('fetch', graphql);
212
+
213
+ const first = await postLinearSessionStatus({
214
+ kind: 'started',
215
+ sessionId: 'ses_1',
216
+ issueIdentifier: 'ENG-12',
217
+ sessionOrigin: 'https://app.example.com',
218
+ });
219
+ expect(first).toEqual({ connected: true, posted: true, commentId: 'comment-1' });
220
+
221
+ const second = await postLinearSessionStatus({
222
+ kind: 'started',
223
+ sessionId: 'ses_1',
224
+ issueIdentifier: 'ENG-12',
225
+ sessionOrigin: 'https://app.example.com',
226
+ });
227
+ expect(second).toEqual({ connected: true, posted: false, skipped: 'already-posted' });
228
+
229
+ const commentCalls = graphql.mock.calls.filter(([, options]) => {
230
+ return JSON.parse(options.body).query.includes('mutation CommentCreate');
231
+ });
232
+ expect(commentCalls).toHaveLength(1);
233
+ const body = JSON.parse(commentCalls[0][1].body).variables.input.body;
234
+ expect(body).toBe('[OpenChamber session started](https://app.example.com/?session=ses_1)');
235
+ expect(JSON.stringify(first)).not.toContain('access-1');
236
+ });
237
+
238
+ it('skips completed until started has been posted', async () => {
239
+ const graphql = stubLinearGraphql();
240
+ vi.stubGlobal('fetch', graphql);
241
+ await expect(postLinearSessionStatus({
242
+ kind: 'completed',
243
+ sessionId: 'ses_1',
244
+ })).resolves.toEqual({ connected: true, posted: false, skipped: 'not-started' });
245
+ expect(graphql).not.toHaveBeenCalled();
246
+ });
247
+
248
+ it('posts completed once after started, reusing the stored open URL', async () => {
249
+ vi.stubGlobal('fetch', stubLinearGraphql({ commentId: 'comment-started' }));
250
+ await postLinearSessionStatus({
251
+ kind: 'started',
252
+ sessionId: 'ses_1',
253
+ issueIdentifier: 'ENG-12',
254
+ sessionOrigin: 'https://app.example.com',
255
+ });
256
+
257
+ const graphql = stubLinearGraphql({ commentId: 'comment-done' });
258
+ vi.stubGlobal('fetch', graphql);
259
+ const first = await postLinearSessionStatus({ kind: 'completed', sessionId: 'ses_1' });
260
+ expect(first).toEqual({ connected: true, posted: true, commentId: 'comment-done' });
261
+ const second = await postLinearSessionStatus({ kind: 'completed', sessionId: 'ses_1' });
262
+ expect(second).toEqual({ connected: true, posted: false, skipped: 'already-posted' });
263
+
264
+ const commentCalls = graphql.mock.calls.filter(([, options]) => {
265
+ return JSON.parse(options.body).query.includes('mutation CommentCreate');
266
+ });
267
+ expect(commentCalls).toHaveLength(1);
268
+ const body = JSON.parse(commentCalls[0][1].body).variables.input.body;
269
+ expect(body).toBe('[OpenChamber session completed](https://app.example.com/?session=ses_1)');
270
+ });
271
+ });
@@ -0,0 +1,72 @@
1
+ import { clearLinearAuth, getLinearAuth } from './auth.js';
2
+ import { fetchLinearGraphql, getValidLinearAccessToken } from './client.js';
3
+ import { isPlainObject, readTrimmedString } from './parse.js';
4
+
5
+ const TEAMS_QUERY = `
6
+ query ListLinearTeams($first: Int!, $after: String) {
7
+ teams(first: $first, after: $after) {
8
+ nodes { id key name }
9
+ pageInfo { hasNextPage endCursor }
10
+ }
11
+ }
12
+ `;
13
+ const PAGE_SIZE = 50;
14
+ const MAX_PAGES = 20;
15
+
16
+ function readTeam(node) {
17
+ if (!isPlainObject(node)) {
18
+ return null;
19
+ }
20
+ const id = readTrimmedString(node.id);
21
+ const key = readTrimmedString(node.key);
22
+ const name = readTrimmedString(node.name);
23
+ if (!id || !key || !name) {
24
+ return null;
25
+ }
26
+ return { id, key, name };
27
+ }
28
+
29
+ export async function listLinearTeams() {
30
+ try {
31
+ const token = await getValidLinearAccessToken();
32
+ if (!token) {
33
+ return { connected: false };
34
+ }
35
+
36
+ const teams = [];
37
+ let after = null;
38
+ for (let page = 0; page < MAX_PAGES; page += 1) {
39
+ const variables = { first: PAGE_SIZE };
40
+ if (after) {
41
+ variables.after = after;
42
+ }
43
+ const data = await fetchLinearGraphql(token, TEAMS_QUERY, variables);
44
+ const connection = isPlainObject(data.teams) ? data.teams : null;
45
+ const nodes = isPlainObject(connection) && Array.isArray(connection.nodes)
46
+ ? connection.nodes
47
+ : [];
48
+ for (const node of nodes) {
49
+ const team = readTeam(node);
50
+ if (team) {
51
+ teams.push(team);
52
+ }
53
+ }
54
+ const pageInfo = isPlainObject(connection) ? connection.pageInfo : null;
55
+ if (!isPlainObject(pageInfo) || pageInfo.hasNextPage !== true) {
56
+ break;
57
+ }
58
+ after = readTrimmedString(pageInfo.endCursor);
59
+ if (!after) {
60
+ break;
61
+ }
62
+ }
63
+
64
+ return { connected: true, teams };
65
+ } catch (error) {
66
+ if (error?.status === 401) {
67
+ clearLinearAuth(getLinearAuth()?.workspaceId);
68
+ return { connected: false };
69
+ }
70
+ throw error;
71
+ }
72
+ }
@@ -0,0 +1,94 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+ import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
5
+ import { clearLinearAuth, setLinearAuth } from './auth.js';
6
+ import { listLinearTeams } from './teams.js';
7
+
8
+ const makeTempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-linear-teams-'));
9
+
10
+ const jsonResponse = (payload, status = 200) => new Response(JSON.stringify(payload), {
11
+ status,
12
+ headers: { 'Content-Type': 'application/json' },
13
+ });
14
+
15
+ describe('Linear teams list', () => {
16
+ let dataDir;
17
+ let previousDataDir;
18
+
19
+ beforeEach(() => {
20
+ previousDataDir = process.env.OPENCHAMBER_DATA_DIR;
21
+ dataDir = makeTempDir();
22
+ process.env.OPENCHAMBER_DATA_DIR = dataDir;
23
+ setLinearAuth({
24
+ accessToken: 'access-1',
25
+ refreshToken: 'refresh-1',
26
+ tokenType: 'Bearer',
27
+ expiresAt: Date.now() + 86_400_000,
28
+ scope: 'read,write,comments:create',
29
+ });
30
+ });
31
+
32
+ afterEach(() => {
33
+ vi.unstubAllGlobals();
34
+ clearLinearAuth();
35
+ if (previousDataDir === undefined) {
36
+ delete process.env.OPENCHAMBER_DATA_DIR;
37
+ } else {
38
+ process.env.OPENCHAMBER_DATA_DIR = previousDataDir;
39
+ }
40
+ fs.rmSync(dataDir, { recursive: true, force: true });
41
+ });
42
+
43
+ it('returns disconnected without calling Linear when there is no auth', async () => {
44
+ clearLinearAuth();
45
+ const graphql = vi.fn();
46
+ vi.stubGlobal('fetch', graphql);
47
+ await expect(listLinearTeams()).resolves.toEqual({ connected: false });
48
+ expect(graphql).not.toHaveBeenCalled();
49
+ });
50
+
51
+ it('lists teams across pages and never returns the token', async () => {
52
+ const graphql = vi.fn(async (_url, options) => {
53
+ const body = JSON.parse(options.body);
54
+ expect(body.query).toContain('query ListLinearTeams');
55
+ expect(options.headers.Authorization).toBe('Bearer access-1');
56
+ if (!body.variables.after) {
57
+ return jsonResponse({
58
+ data: {
59
+ teams: {
60
+ nodes: [{ id: 'team-eng', key: 'ENG', name: 'Engineering' }],
61
+ pageInfo: { hasNextPage: true, endCursor: 'cursor-2' },
62
+ },
63
+ },
64
+ });
65
+ }
66
+ expect(body.variables.after).toBe('cursor-2');
67
+ return jsonResponse({
68
+ data: {
69
+ teams: {
70
+ nodes: [{ id: 'team-des', key: 'DES', name: 'Design' }],
71
+ pageInfo: { hasNextPage: false, endCursor: null },
72
+ },
73
+ },
74
+ });
75
+ });
76
+ vi.stubGlobal('fetch', graphql);
77
+
78
+ const result = await listLinearTeams();
79
+ expect(result).toEqual({
80
+ connected: true,
81
+ teams: [
82
+ { id: 'team-eng', key: 'ENG', name: 'Engineering' },
83
+ { id: 'team-des', key: 'DES', name: 'Design' },
84
+ ],
85
+ });
86
+ expect(JSON.stringify(result)).not.toContain('access-1');
87
+ expect(graphql).toHaveBeenCalledTimes(2);
88
+ });
89
+
90
+ it('clears auth and reports disconnected after a GraphQL 401', async () => {
91
+ vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ errors: [{ message: 'Unauthorized' }] }, 401)));
92
+ await expect(listLinearTeams()).resolves.toEqual({ connected: false });
93
+ });
94
+ });
@@ -0,0 +1,55 @@
1
+ # Managed MCP Reconnect
2
+
3
+ ## Purpose
4
+
5
+ OpenCode connects each configured MCP server once, when a project directory is
6
+ first used. A server that does not come up then is marked `failed` and never
7
+ retried; a server whose live connection later drops is marked `failed` too and
8
+ stays that way until OpenCode restarts. This module injects a small plugin into
9
+ the OpenCode process OpenChamber launches that reconnects those servers, so a
10
+ server that was slow to start or crashed mid-session comes back on its own.
11
+
12
+ ## Runtime flow
13
+
14
+ 1. `prepareManagedOpenCodeEnv(configContent)` materializes the plugin under
15
+ `<openchamber-data-dir>/mcp-reconnect/` and appends its `file://` URL to
16
+ `OPENCODE_CONFIG_CONTENT` through the shared merge in
17
+ `packages/web/server/lib/opencode/managed-plugin-config.js`.
18
+ 2. It is always on for managed OpenCode. There is no setting, because it only
19
+ acts on servers OpenCode has already given up on.
20
+ 3. OpenCode loads the plugin once per project directory with an SDK client
21
+ scoped to that directory, so each directory reconnects its own servers.
22
+ 4. The plugin reads MCP status one second after load, calls connect for every
23
+ server in the `failed` state, then re-reads status after a per-server delay
24
+ that doubles from one second to a cap of thirty. A server seen in any other
25
+ state resets its counter. While nothing is failed it checks every thirty
26
+ seconds.
27
+ 5. A dropped connection publishes `mcp.tools.changed`, which the plugin uses to
28
+ check right away instead of waiting out the idle interval.
29
+ 6. OpenCode calls the plugin's `dispose` hook when it tears the directory down,
30
+ which stops the loop.
31
+
32
+ ## Invariants
33
+
34
+ - Only `failed` is retried. `disabled` is the user's choice, and `needs_auth`
35
+ or `needs_client_registration` need the user to act; retrying those would
36
+ either re-enable a server the user turned off or loop on a login prompt.
37
+ - The plugin logs nothing and swallows every error. OpenCode already logs each
38
+ failed attempt, and a status call failing during an OpenCode restart is not
39
+ news.
40
+ - One check runs at a time; a wake-up arriving during a check is honored once
41
+ it finishes rather than starting a second loop.
42
+
43
+ ## What the UI sees
44
+
45
+ OpenCode publishes no event when a reconnect succeeds. The chat picks the
46
+ server up on the next prompt because tools are resolved from live state, but
47
+ the MCP page reads status on bootstrap and refresh, so it can show `failed` for
48
+ a while after the server is back.
49
+
50
+ ## Runtime parity
51
+
52
+ - Web and Desktop managed OpenCode: injected automatically.
53
+ - External OpenCode (`OPENCODE_HOST` or skip-start) and VS Code's separate
54
+ OpenCode lifecycle: not injected, because OpenChamber does not control that
55
+ process environment.
@@ -0,0 +1,122 @@
1
+ import { pathToFileURL } from 'node:url';
2
+ import { appendManagedPlugin } from '../opencode/managed-plugin-config.js';
3
+
4
+ /**
5
+ * OpenCode marks an MCP server `failed` when it does not come up at startup or
6
+ * when a live connection drops, and never tries again. This plugin runs inside
7
+ * the managed OpenCode process and reconnects those servers with a per-server
8
+ * exponential backoff, so a server that was merely slow to start, or a local
9
+ * one that crashed, comes back without an OpenCode restart.
10
+ *
11
+ * Only `failed` is retried. `needs_auth`, `needs_client_registration`, and
12
+ * `disabled` are user decisions or need user action, and retrying them would
13
+ * either loop on a login prompt or re-enable a server the user turned off.
14
+ *
15
+ * The plugin talks to OpenCode through the SDK client OpenCode hands it, which
16
+ * is scoped to one project directory, so each open directory reconnects its
17
+ * own servers. Nothing is logged: OpenCode already reports each failed attempt.
18
+ */
19
+ const createPluginSource = () => String.raw`
20
+ const INITIAL_RETRY_MS = 1000
21
+ const MAX_RETRY_MS = 30000
22
+ const IDLE_CHECK_MS = 30000
23
+
24
+ export const OpenChamberMcpReconnectPlugin = async ({ client }) => {
25
+ let disposed = false
26
+ let running = false
27
+ let wakeRequested = false
28
+ let timer
29
+ // Consecutive failed attempts per server, cleared once it is seen healthy.
30
+ const attempts = new Map()
31
+ const dueAt = new Map()
32
+
33
+ const schedule = (delayMs) => {
34
+ if (disposed) return
35
+ clearTimeout(timer)
36
+ timer = setTimeout(tick, delayMs)
37
+ }
38
+
39
+ const tick = async () => {
40
+ if (running) {
41
+ wakeRequested = true
42
+ return
43
+ }
44
+ running = true
45
+ let delay = IDLE_CHECK_MS
46
+ try {
47
+ const statuses = (await client.mcp.status())?.data ?? {}
48
+ const now = Date.now()
49
+ const due = []
50
+ for (const [name, entry] of Object.entries(statuses)) {
51
+ if (entry?.status !== "failed") {
52
+ attempts.delete(name)
53
+ dueAt.delete(name)
54
+ continue
55
+ }
56
+ const at = dueAt.get(name) ?? now
57
+ if (at > now) {
58
+ delay = Math.min(delay, at - now)
59
+ continue
60
+ }
61
+ due.push(name)
62
+ }
63
+ for (const name of attempts.keys()) {
64
+ if (!Object.hasOwn(statuses, name)) {
65
+ attempts.delete(name)
66
+ dueAt.delete(name)
67
+ }
68
+ }
69
+
70
+ await Promise.allSettled(due.map((name) => client.mcp.connect({ path: { name } })))
71
+
72
+ // The result is read on the next tick: a server that came back clears
73
+ // its counter there, one still failed waits out its backoff.
74
+ const after = Date.now()
75
+ for (const name of due) {
76
+ const count = (attempts.get(name) ?? 0) + 1
77
+ const wait = Math.min(INITIAL_RETRY_MS * 2 ** (count - 1), MAX_RETRY_MS)
78
+ attempts.set(name, count)
79
+ dueAt.set(name, after + wait)
80
+ delay = Math.min(delay, wait)
81
+ }
82
+ } catch {
83
+ // Status is unavailable while OpenCode is shutting down or restarting;
84
+ // the idle check picks up again when it is back.
85
+ } finally {
86
+ running = false
87
+ const wake = wakeRequested
88
+ wakeRequested = false
89
+ schedule(wake ? INITIAL_RETRY_MS : delay)
90
+ }
91
+ }
92
+
93
+ schedule(INITIAL_RETRY_MS)
94
+
95
+ return {
96
+ // A dropped connection publishes this event; checking right away beats
97
+ // waiting out the idle interval.
98
+ event: async ({ event }) => {
99
+ if (event?.type === "mcp.tools.changed") schedule(INITIAL_RETRY_MS)
100
+ },
101
+ dispose: async () => {
102
+ disposed = true
103
+ clearTimeout(timer)
104
+ },
105
+ }
106
+ }
107
+ `;
108
+
109
+ export const createMcpReconnectRuntime = ({ fsPromises, path, dataDir }) => {
110
+ const pluginDirectory = path.join(dataDir, 'mcp-reconnect');
111
+ const pluginPath = path.join(pluginDirectory, 'openchamber-mcp-reconnect-plugin.js');
112
+
113
+ const prepareManagedOpenCodeEnv = async (rawConfig) => {
114
+ await fsPromises.mkdir(pluginDirectory, { recursive: true });
115
+ await fsPromises.writeFile(pluginPath, createPluginSource(), { mode: 0o600 });
116
+ return {
117
+ OPENCODE_CONFIG_CONTENT: appendManagedPlugin(rawConfig, pathToFileURL(pluginPath).href, 'MCP reconnect plugin'),
118
+ };
119
+ };
120
+
121
+ return { prepareManagedOpenCodeEnv };
122
+ };