@openchamber/web 1.21.0 → 1.22.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 (180) hide show
  1. package/bin/cli.test.js +35 -0
  2. package/bin/lib/DOCUMENTATION.md +12 -0
  3. package/bin/lib/cli-settings-accessors.js +111 -0
  4. package/bin/lib/cli-settings-accessors.test.js +189 -0
  5. package/bin/lib/cli-startup.js +29 -9
  6. package/bin/lib/commands-connect-url.js +12 -14
  7. package/dist/assets/{CodeMirrorCommentWidgets-C2BopIs3.js → CodeMirrorCommentWidgets-CPvfxh0N.js} +1 -1
  8. package/dist/assets/CommitSection-CC5mFzO2.js +1 -0
  9. package/dist/assets/DiffView-6xGdyI0n.js +4 -0
  10. package/dist/assets/FilesView-Bm3vT63N.js +17 -0
  11. package/dist/assets/GitView-B6y1Y69c.js +6 -0
  12. package/dist/assets/{JsonTreeView-osju7J70.js → JsonTreeView-rwHz84MX.js} +1 -1
  13. package/dist/assets/LinearIssuesView-B0UM_Rkx.js +1 -0
  14. package/dist/assets/MarkdownImageGallery-sGilV9Hs.js +1 -0
  15. package/dist/assets/MarkdownRendererImpl--4sRsKBn.js +12 -0
  16. package/dist/assets/OnboardingScreen-CECL_Cms.js +1 -0
  17. package/dist/assets/{PatchDiff-Dan3mADn.js → PatchDiff-BGPl1s-U.js} +1 -1
  18. package/dist/assets/{PierreDiffViewer-CGoI2v0q.js → PierreDiffViewer-Cvz9Z-io.js} +2 -2
  19. package/dist/assets/PlanView-BFMsnHk3.js +5 -0
  20. package/dist/assets/SettingsView-_Gtn5SdT.js +28 -0
  21. package/dist/assets/{SettingsWindow-DXF-MTHG.js → SettingsWindow-C1Qa09YO.js} +1 -1
  22. package/dist/assets/{ToolOutputDialog-DrCa1JRk.js → ToolOutputDialog-DzQlzMF4.js} +6 -6
  23. package/dist/assets/{ToolPartDiffPreview-B_tfvlNF.js → ToolPartDiffPreview-DfVOfwHy.js} +2 -2
  24. package/dist/assets/{VirtualizedFileDiff-CN_BctrR.js → VirtualizedFileDiff-DT5MDv-u.js} +1 -1
  25. package/dist/assets/WalkthroughView-D8sLH_M8.js +4 -0
  26. package/dist/assets/{computeVirtualFileMetrics-Gi1d5eU1.js → computeVirtualFileMetrics-DmpLWhll.js} +1 -1
  27. package/dist/assets/{contextPanelEmbeddedChat-CpzVNWAv.js → contextPanelEmbeddedChat-BK78t3M_.js} +1 -1
  28. package/dist/assets/de-C3luvSd_.js +9 -0
  29. package/dist/assets/es-CmU4HLv9.js +15 -0
  30. package/dist/assets/fr-Bgyni40l.js +13 -0
  31. package/dist/assets/index-C57jT0Sa.css +1 -0
  32. package/dist/assets/{index-Brm3X9rs.js → index-CWYs7sMK.js} +1 -1
  33. package/dist/assets/index-b0zDkWyg.js +7 -0
  34. package/dist/assets/{isDiffPlainText-pH9kAJQH.js → isDiffPlainText-BO_q5ezD.js} +1 -1
  35. package/dist/assets/{isFilePlainText-CVKy_dgB.js → isFilePlainText-D8qPqUAf.js} +1 -1
  36. package/dist/assets/ja-C1ImKinT.js +15 -0
  37. package/dist/assets/ko-CP7OdxYH.js +15 -0
  38. package/dist/assets/main-D4rd8Hy5.js +928 -0
  39. package/dist/assets/{main-vUCh0VB0.js → main-D7fwjW2z.js} +2 -2
  40. package/dist/assets/{markdown-shiki.worker-CKGJ1J33.js → markdown-shiki.worker-D5fBU-lw.js} +5 -5
  41. package/dist/assets/markdownCore-BcmkWZPO.js +3 -0
  42. package/dist/assets/{miniChat-BlzGEYgE.js → miniChat-D5rraz-g.js} +2 -2
  43. package/dist/assets/{mobile-CkX6H-IT.js → mobile-Cg_DE3KL.js} +2 -2
  44. package/dist/assets/{patchFileDiff-BCTsE43U.js → patchFileDiff-Bpql0QGw.js} +3 -3
  45. package/dist/assets/pl-DQYSiGYX.js +15 -0
  46. package/dist/assets/pt-BR-DytpsW4M.js +15 -0
  47. package/dist/assets/{renderElectronMiniChatApp-CJYe_KOL.js → renderElectronMiniChatApp-B_Bn7BbN.js} +2 -2
  48. package/dist/assets/renderMobileApp-DLfxMzGJ.js +25 -0
  49. package/dist/assets/runtimeEndpointReset-HlRmXFGW.js +16 -0
  50. package/dist/assets/scheduledTasksApi-BPvxrynl.js +1 -0
  51. package/dist/assets/{shikiHighlight-BgTPSITe.js → shikiHighlight-CFAVs_lu.js} +1 -1
  52. package/dist/assets/tr-aizaUvft.js +6 -0
  53. package/dist/assets/uk-DwnRxJZd.js +15 -0
  54. package/dist/assets/useAppFontEffects-DWXGRUPZ.js +7310 -0
  55. package/dist/assets/{useInlineCommentController-DFFv0hae.js → useInlineCommentController-Cc0OCXr0.js} +2 -2
  56. package/dist/assets/useRootScrollLock-BFZtfciC.js +1 -0
  57. package/dist/assets/{vendor-base-ui-_6j2xOWl.js → vendor-base-ui-BeMD8X_w.js} +1 -1
  58. package/dist/assets/{vendor-codemirror-language-data-DkQX2EBa.js → vendor-codemirror-language-data-BGFszm8n.js} +2 -2
  59. package/dist/assets/{vendor-floating-ui-core-CXmKXOXc.js → vendor-floating-ui-core-PuGzNPnN.js} +1 -1
  60. package/dist/assets/{vendor-floating-ui-dom-WyXykhNi.js → vendor-floating-ui-dom-BTvzWks8.js} +1 -1
  61. package/dist/assets/{vendor-floating-ui-react-dom-DKpLs02S.js → vendor-floating-ui-react-dom-DxYCWdHj.js} +1 -1
  62. package/dist/assets/{vendor-floating-ui-utils-BzXdqYpP.js → vendor-floating-ui-utils-D6FqdtJt.js} +1 -1
  63. package/dist/assets/vendor-linkify-it-DZCzzDkK.js +1 -0
  64. package/dist/assets/vendor-marked-linkify-it-CXI_LHIE.js +1 -0
  65. package/dist/assets/vendor-uc.micro-BAd0H0z4.js +1 -0
  66. package/dist/assets/{web-components-DLnGY4fs.js → web-components-CD-GFayc.js} +4 -4
  67. package/dist/assets/zh-CN-UDNMxm7r.js +15 -0
  68. package/dist/assets/zh-TW-BsswdYL-.js +15 -0
  69. package/dist/index.html +5 -5
  70. package/dist/mini-chat.html +3 -3
  71. package/dist/mobile.html +3 -3
  72. package/dist/site.webmanifest +1 -1
  73. package/dist/sw.js +1 -1
  74. package/package.json +2 -2
  75. package/public/site.webmanifest +1 -1
  76. package/server/index.js +6 -2
  77. package/server/lib/cloudflare-tunnel.js +1 -1
  78. package/server/lib/dictation/DOCUMENTATION.md +19 -6
  79. package/server/lib/dictation/local/model-catalog.js +220 -0
  80. package/server/lib/dictation/local/model-catalog.test.js +42 -0
  81. package/server/lib/dictation/local/sherpa-tts.js +41 -20
  82. package/server/lib/dictation/local/worker-process.js +2 -0
  83. package/server/lib/dictation/runtime.js +4 -0
  84. package/server/lib/dictation/service.js +27 -4
  85. package/server/lib/fs/DOCUMENTATION.md +5 -0
  86. package/server/lib/fs/routes.js +150 -0
  87. package/server/lib/fs/routes.test.js +308 -3
  88. package/server/lib/git/DOCUMENTATION.md +4 -3
  89. package/server/lib/git/service.js +128 -6
  90. package/server/lib/git/service.test.js +191 -1
  91. package/server/lib/linear/DOCUMENTATION.md +97 -0
  92. package/server/lib/linear/OAUTH-BROKER-HANDOFF.md +91 -0
  93. package/server/lib/linear/auth.js +436 -0
  94. package/server/lib/linear/auth.test.js +242 -0
  95. package/server/lib/linear/client.js +191 -0
  96. package/server/lib/linear/index.js +61 -0
  97. package/server/lib/linear/issues.js +499 -0
  98. package/server/lib/linear/issues.test.js +512 -0
  99. package/server/lib/linear/mapping.js +188 -0
  100. package/server/lib/linear/mapping.test.js +147 -0
  101. package/server/lib/linear/oauth.js +345 -0
  102. package/server/lib/linear/oauth.test.js +166 -0
  103. package/server/lib/linear/parse.js +23 -0
  104. package/server/lib/linear/routes.js +432 -0
  105. package/server/lib/linear/routes.test.js +661 -0
  106. package/server/lib/linear/status-runtime.js +64 -0
  107. package/server/lib/linear/status-runtime.test.js +167 -0
  108. package/server/lib/linear/status.js +280 -0
  109. package/server/lib/linear/status.test.js +271 -0
  110. package/server/lib/linear/teams.js +72 -0
  111. package/server/lib/linear/teams.test.js +94 -0
  112. package/server/lib/markdown-image-grants/DOCUMENTATION.md +4 -0
  113. package/server/lib/markdown-image-grants/routes.js +3 -1
  114. package/server/lib/markdown-image-grants/routes.test.js +14 -0
  115. package/server/lib/openchamber-sessions/routes.js +4 -1
  116. package/server/lib/openchamber-sessions/routes.test.js +23 -0
  117. package/server/lib/opencode/env-runtime.js +17 -1
  118. package/server/lib/opencode/env-runtime.test.js +56 -0
  119. package/server/lib/opencode/feature-routes-runtime.js +2 -0
  120. package/server/lib/opencode/lifecycle.js +48 -9
  121. package/server/lib/opencode/lifecycle.test.js +125 -1
  122. package/server/lib/opencode/managed-process-registry.d.ts +13 -0
  123. package/server/lib/opencode/managed-process-registry.js +213 -163
  124. package/server/lib/opencode/managed-process-registry.test.mjs +285 -0
  125. package/server/lib/opencode/project-directory-runtime.js +16 -11
  126. package/server/lib/opencode/project-directory-runtime.test.js +32 -12
  127. package/server/lib/opencode/pwa-manifest-routes.js +1 -1
  128. package/server/lib/opencode/routes-upgrade.test.js +96 -12
  129. package/server/lib/opencode/routes.js +53 -5
  130. package/server/lib/opencode/settings-helpers.js +3 -0
  131. package/server/lib/opencode/settings-helpers.test.js +10 -0
  132. package/server/lib/opencode/static-routes-runtime.js +3 -3
  133. package/server/lib/opencode/theme-runtime.js +1 -1
  134. package/server/lib/opencode/theme-runtime.test.js +129 -0
  135. package/server/lib/projects/project-config.js +33 -5
  136. package/server/lib/projects/project-config.test.js +85 -0
  137. package/server/lib/quota/DOCUMENTATION.md +19 -0
  138. package/server/lib/quota/providers/copilot.js +26 -10
  139. package/server/lib/quota/providers/copilot.test.js +78 -0
  140. package/server/lib/scheduled-tasks/DOCUMENTATION.md +7 -0
  141. package/server/lib/small-model/DOCUMENTATION.md +11 -5
  142. package/server/lib/small-model/call.js +64 -20
  143. package/server/lib/small-model/call.test.js +184 -2
  144. package/server/lib/tts/DOCUMENTATION.md +1 -0
  145. package/server/lib/tts/language-detect.js +210 -0
  146. package/server/lib/tts/language-detect.test.js +76 -0
  147. package/server/lib/tts/routes.js +23 -1
  148. package/server/lib/tts/routes.test.js +26 -0
  149. package/server/lib/tunnels/install-help.js +2 -2
  150. package/server/lib/tunnels/install-help.test.js +9 -0
  151. package/server/lib/walkthrough/languages.js +1 -0
  152. package/dist/assets/CommitSection-HJeMUAWb.js +0 -1
  153. package/dist/assets/DiffView-D5cvbEPb.js +0 -4
  154. package/dist/assets/FilesView-DPU8aNPL.js +0 -17
  155. package/dist/assets/GitView-Ct6xWrVH.js +0 -6
  156. package/dist/assets/MarkdownImageGallery-EujHSZ2M.js +0 -1
  157. package/dist/assets/MarkdownRendererImpl-CPzu4kIr.js +0 -12
  158. package/dist/assets/OnboardingScreen-w2VG4fWY.js +0 -1
  159. package/dist/assets/PlanView-Dgg-WTEc.js +0 -4
  160. package/dist/assets/SessionSwitcherDropdown-CJTrc8K7.js +0 -1
  161. package/dist/assets/SettingsView-D9yRuFZw.js +0 -28
  162. package/dist/assets/WalkthroughView-D9Q4lr5x.js +0 -4
  163. package/dist/assets/de-B_LdJwEM.js +0 -9
  164. package/dist/assets/es-CubfsAYV.js +0 -15
  165. package/dist/assets/fr-5qJM0nFS.js +0 -13
  166. package/dist/assets/index-BW82eK5v.css +0 -1
  167. package/dist/assets/index-rlLjZUM5.js +0 -7
  168. package/dist/assets/ja-DJYIBUlH.js +0 -15
  169. package/dist/assets/ko-DcUBkB7y.js +0 -15
  170. package/dist/assets/main-DLBxKIoX.js +0 -926
  171. package/dist/assets/markdownCore-DG6GHLF4.js +0 -3
  172. package/dist/assets/pl-rB6BLcio.js +0 -15
  173. package/dist/assets/pt-BR-DcwtlO-o.js +0 -15
  174. package/dist/assets/renderMobileApp-hQJTnr8B.js +0 -25
  175. package/dist/assets/runtimeEndpointReset-BDh7r8BL.js +0 -15
  176. package/dist/assets/scheduledTasksApi-CAGPh_gZ.js +0 -1
  177. package/dist/assets/uk-INZlFD9A.js +0 -15
  178. package/dist/assets/useAppFontEffects-Cll4gnsh.js +0 -7268
  179. package/dist/assets/zh-CN-Dzda8xa1.js +0 -15
  180. package/dist/assets/zh-TW-Cwn3rNYZ.js +0 -15
@@ -0,0 +1,436 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { isPlainObject, readEnv, readFiniteNumber, readTrimmedString } from './parse.js';
5
+
6
+ const DEFAULT_LINEAR_CLIENT_ID = '91bbe26a69a2c8568d3683f1e01e776c';
7
+ const DEFAULT_LINEAR_SCOPES = 'read,write,comments:create';
8
+ const DEFAULT_LINEAR_BROKER_URL = 'https://api.openchamber.dev/v1/oauth/linear';
9
+ const ACCESS_TOKEN_REFRESH_SKEW_MS = 2 * 60_000;
10
+ const LEGACY_WORKSPACE_ID = 'legacy';
11
+ const SESSION_COMMENTS_SETTING_KEY = 'linearSessionComments';
12
+
13
+ function resolveDataDir() {
14
+ const fromEnv = readEnv('OPENCHAMBER_DATA_DIR');
15
+ if (fromEnv) {
16
+ return path.resolve(fromEnv);
17
+ }
18
+ return path.join(os.homedir(), '.config', 'openchamber');
19
+ }
20
+
21
+ function storageFile() {
22
+ return path.join(resolveDataDir(), 'linear-auth.json');
23
+ }
24
+
25
+ function settingsFile() {
26
+ return path.join(resolveDataDir(), 'settings.json');
27
+ }
28
+
29
+ function ensureStorageDir() {
30
+ const dir = resolveDataDir();
31
+ if (!fs.existsSync(dir)) {
32
+ fs.mkdirSync(dir, { recursive: true });
33
+ }
34
+ }
35
+
36
+ function readJsonFile(filePath) {
37
+ if (!fs.existsSync(filePath)) {
38
+ return null;
39
+ }
40
+ try {
41
+ const raw = fs.readFileSync(filePath, 'utf8');
42
+ const trimmed = raw.trim();
43
+ if (!trimmed) {
44
+ return null;
45
+ }
46
+ const parsed = JSON.parse(trimmed);
47
+ if (!isPlainObject(parsed)) {
48
+ return null;
49
+ }
50
+ return parsed;
51
+ } catch (error) {
52
+ console.error('Failed to read Linear auth file:', error);
53
+ return null;
54
+ }
55
+ }
56
+
57
+ function writeJsonFile(filePath, payload) {
58
+ ensureStorageDir();
59
+ const tmpFile = `${filePath}.${process.pid}.${Date.now()}.tmp`;
60
+ fs.writeFileSync(tmpFile, JSON.stringify(payload, null, 2), 'utf8');
61
+ try {
62
+ fs.chmodSync(tmpFile, 0o600);
63
+ } catch {
64
+ // best-effort
65
+ }
66
+ fs.renameSync(tmpFile, filePath);
67
+ try {
68
+ fs.chmodSync(filePath, 0o600);
69
+ } catch {
70
+ // best-effort
71
+ }
72
+ }
73
+
74
+ function normalizeUser(user) {
75
+ if (!isPlainObject(user)) {
76
+ return null;
77
+ }
78
+ const id = readTrimmedString(user.id);
79
+ if (!id) {
80
+ return null;
81
+ }
82
+ return {
83
+ id,
84
+ name: readTrimmedString(user.name) || null,
85
+ displayName: readTrimmedString(user.displayName) || null,
86
+ email: readTrimmedString(user.email) || null,
87
+ avatarUrl: readTrimmedString(user.avatarUrl) || null,
88
+ };
89
+ }
90
+
91
+ function normalizeOrganization(organization) {
92
+ if (!isPlainObject(organization)) {
93
+ return null;
94
+ }
95
+ const id = readTrimmedString(organization.id);
96
+ const name = readTrimmedString(organization.name);
97
+ if (!id || !name) {
98
+ return null;
99
+ }
100
+ return {
101
+ id,
102
+ name,
103
+ urlKey: readTrimmedString(organization.urlKey) || null,
104
+ };
105
+ }
106
+
107
+ function resolveLinearWorkspaceId({ organization, user, workspaceId } = {}) {
108
+ const explicit = readTrimmedString(workspaceId);
109
+ if (explicit) return explicit;
110
+ const organizationId = organization ? readTrimmedString(organization.id) : '';
111
+ if (organizationId) return organizationId;
112
+ const userId = user ? readTrimmedString(user.id) : '';
113
+ if (userId) return `user:${userId}`;
114
+ return LEGACY_WORKSPACE_ID;
115
+ }
116
+
117
+ function normalizeAuthEntry(raw) {
118
+ if (!isPlainObject(raw)) {
119
+ return null;
120
+ }
121
+ const accessToken = readTrimmedString(raw.accessToken);
122
+ if (!accessToken) {
123
+ return null;
124
+ }
125
+ const user = normalizeUser(raw.user);
126
+ const organization = normalizeOrganization(raw.organization);
127
+ return {
128
+ accessToken,
129
+ refreshToken: readTrimmedString(raw.refreshToken) || null,
130
+ tokenType: readTrimmedString(raw.tokenType) || 'bearer',
131
+ expiresAt: readFiniteNumber(raw.expiresAt),
132
+ scope: readTrimmedString(raw.scope),
133
+ createdAt: readFiniteNumber(raw.createdAt),
134
+ authorizedAt: readFiniteNumber(raw.authorizedAt) || readFiniteNumber(raw.createdAt),
135
+ user,
136
+ organization,
137
+ current: Boolean(raw.current),
138
+ workspaceId: resolveLinearWorkspaceId({
139
+ organization,
140
+ user,
141
+ workspaceId: raw.workspaceId,
142
+ }),
143
+ };
144
+ }
145
+
146
+ function normalizeAuthList(raw) {
147
+ const source = Array.isArray(raw?.workspaces)
148
+ ? raw.workspaces
149
+ : (raw?.accessToken ? [raw] : []);
150
+ const list = source.map((entry) => normalizeAuthEntry(entry)).filter(Boolean);
151
+
152
+ if (!list.length) {
153
+ return { list: [], changed: Boolean(raw && (raw.accessToken || Array.isArray(raw.workspaces))) };
154
+ }
155
+
156
+ let changed = Array.isArray(raw?.workspaces) === false && Boolean(raw?.accessToken);
157
+ const seen = new Set();
158
+ const deduped = [];
159
+ for (const entry of list) {
160
+ if (seen.has(entry.workspaceId)) {
161
+ changed = true;
162
+ continue;
163
+ }
164
+ seen.add(entry.workspaceId);
165
+ deduped.push(entry);
166
+ }
167
+
168
+ let currentFound = false;
169
+ deduped.forEach((entry) => {
170
+ if (entry.current && !currentFound) {
171
+ currentFound = true;
172
+ } else if (entry.current && currentFound) {
173
+ entry.current = false;
174
+ changed = true;
175
+ }
176
+ });
177
+
178
+ if (!currentFound && deduped[0]) {
179
+ deduped[0].current = true;
180
+ changed = true;
181
+ }
182
+
183
+ return { list: deduped, changed };
184
+ }
185
+
186
+ function readAuthList() {
187
+ const data = readJsonFile(storageFile());
188
+ if (!data) {
189
+ return [];
190
+ }
191
+ const { list, changed } = normalizeAuthList(data);
192
+ if (changed) {
193
+ writeAuthList(list);
194
+ }
195
+ return list;
196
+ }
197
+
198
+ function writeAuthList(list) {
199
+ if (!list.length) {
200
+ const filePath = storageFile();
201
+ if (fs.existsSync(filePath)) {
202
+ fs.unlinkSync(filePath);
203
+ }
204
+ return;
205
+ }
206
+ writeJsonFile(storageFile(), { workspaces: list });
207
+ }
208
+
209
+ function readSettings() {
210
+ return readJsonFile(settingsFile()) || {};
211
+ }
212
+
213
+ function writeSettings(settings) {
214
+ writeJsonFile(settingsFile(), settings);
215
+ }
216
+
217
+ function readSettingString(key) {
218
+ const stored = readSettings()[key];
219
+ return readTrimmedString(stored);
220
+ }
221
+
222
+ export function getLinearAuth() {
223
+ const list = readAuthList();
224
+ if (!list.length) {
225
+ return null;
226
+ }
227
+ return list.find((entry) => entry.current) || list[0];
228
+ }
229
+
230
+ export function getLinearAuthByWorkspaceId(workspaceId) {
231
+ const id = readTrimmedString(workspaceId);
232
+ if (!id) {
233
+ return getLinearAuth();
234
+ }
235
+ return readAuthList().find((entry) => entry.workspaceId === id) || null;
236
+ }
237
+
238
+ export function getLinearAuthWorkspaces() {
239
+ return readAuthList().map((entry) => ({
240
+ id: entry.workspaceId,
241
+ name: entry.organization?.name || null,
242
+ urlKey: entry.organization?.urlKey || null,
243
+ current: Boolean(entry.current),
244
+ user: entry.user || null,
245
+ authorizedAt: entry.authorizedAt || entry.createdAt || null,
246
+ }));
247
+ }
248
+
249
+ export function setLinearAuth(input, options = {}) {
250
+ const accessToken = readTrimmedString(input?.accessToken);
251
+ if (!accessToken) {
252
+ throw new Error('accessToken is required');
253
+ }
254
+ const activate = options.activate !== false;
255
+ const list = readAuthList();
256
+ const current = list.find((entry) => entry.current) || list[0] || null;
257
+
258
+ const nextUser = Object.prototype.hasOwnProperty.call(input, 'user')
259
+ ? normalizeUser(input.user)
260
+ : current?.user || null;
261
+ const nextOrganization = Object.prototype.hasOwnProperty.call(input, 'organization')
262
+ ? normalizeOrganization(input.organization)
263
+ : current?.organization || null;
264
+ const workspaceId = resolveLinearWorkspaceId({
265
+ organization: nextOrganization,
266
+ user: nextUser,
267
+ workspaceId: input?.workspaceId || (nextOrganization || nextUser ? '' : current?.workspaceId),
268
+ });
269
+
270
+ const existingIndex = list.findIndex((entry) => entry.workspaceId === workspaceId);
271
+ const previous = existingIndex >= 0 ? list[existingIndex] : (
272
+ nextOrganization || nextUser ? null : current
273
+ );
274
+ const targetIndex = existingIndex >= 0
275
+ ? existingIndex
276
+ : (previous && !nextOrganization && !nextUser ? list.indexOf(previous) : -1);
277
+ const wasCurrent = previous?.current === true;
278
+
279
+ const next = {
280
+ accessToken,
281
+ refreshToken: Object.prototype.hasOwnProperty.call(input, 'refreshToken')
282
+ ? (readTrimmedString(input.refreshToken) || null)
283
+ : previous?.refreshToken || null,
284
+ tokenType: readTrimmedString(input?.tokenType) || previous?.tokenType || 'bearer',
285
+ expiresAt: readFiniteNumber(input?.expiresAt) ?? previous?.expiresAt ?? null,
286
+ scope: readTrimmedString(input?.scope) || previous?.scope || '',
287
+ createdAt: previous?.createdAt || Date.now(),
288
+ authorizedAt: Object.prototype.hasOwnProperty.call(input, 'authorizedAt')
289
+ ? (readFiniteNumber(input.authorizedAt) || Date.now())
290
+ : (activate ? Date.now() : (previous?.authorizedAt || previous?.createdAt || Date.now())),
291
+ user: nextUser,
292
+ organization: nextOrganization,
293
+ current: false,
294
+ workspaceId,
295
+ };
296
+
297
+ if (targetIndex >= 0) {
298
+ list[targetIndex] = next;
299
+ } else {
300
+ list.push(next);
301
+ }
302
+
303
+ const writtenIndex = targetIndex >= 0 ? targetIndex : list.length - 1;
304
+ if (activate || !list.some((entry) => entry.current)) {
305
+ list.forEach((entry, index) => {
306
+ entry.current = index === writtenIndex;
307
+ });
308
+ } else {
309
+ list[writtenIndex].current = wasCurrent;
310
+ }
311
+
312
+ writeAuthList(list);
313
+ return list[writtenIndex];
314
+ }
315
+
316
+ export function activateLinearAuth(workspaceId) {
317
+ const id = readTrimmedString(workspaceId);
318
+ if (!id) {
319
+ return false;
320
+ }
321
+ const list = readAuthList();
322
+ const index = list.findIndex((entry) => entry.workspaceId === id);
323
+ if (index === -1) {
324
+ return false;
325
+ }
326
+ list.forEach((entry, idx) => {
327
+ entry.current = idx === index;
328
+ });
329
+ writeAuthList(list);
330
+ return true;
331
+ }
332
+
333
+ export function clearLinearAuth(workspaceId) {
334
+ try {
335
+ const list = readAuthList();
336
+ if (!list.length) {
337
+ return true;
338
+ }
339
+ const id = readTrimmedString(workspaceId);
340
+ const remaining = id
341
+ ? list.filter((entry) => entry.workspaceId !== id)
342
+ : list.filter((entry) => !entry.current);
343
+ if (!remaining.length) {
344
+ writeAuthList([]);
345
+ return true;
346
+ }
347
+ if (!remaining.some((entry) => entry.current)) {
348
+ remaining[0].current = true;
349
+ }
350
+ writeAuthList(remaining);
351
+ return true;
352
+ } catch (error) {
353
+ console.error('Failed to clear Linear auth file:', error);
354
+ return false;
355
+ }
356
+ }
357
+
358
+ export function isLinearAccessTokenStale(expiresAt, now = Date.now()) {
359
+ const expiry = readFiniteNumber(expiresAt);
360
+ if (expiry == null) {
361
+ return true;
362
+ }
363
+ return expiry - ACCESS_TOKEN_REFRESH_SKEW_MS <= now;
364
+ }
365
+
366
+ export function toLinearPublicStatus(auth, workspaces = getLinearAuthWorkspaces()) {
367
+ if (!auth?.accessToken) {
368
+ return { connected: false };
369
+ }
370
+ return {
371
+ connected: true,
372
+ user: auth.user || null,
373
+ organization: auth.organization || null,
374
+ scope: auth.scope || undefined,
375
+ workspaces,
376
+ };
377
+ }
378
+
379
+ export function getLinearClientId() {
380
+ const fromEnv = readEnv('OPENCHAMBER_LINEAR_CLIENT_ID');
381
+ if (fromEnv) return fromEnv;
382
+ const stored = readSettingString('linearClientId');
383
+ if (stored) return stored;
384
+ return DEFAULT_LINEAR_CLIENT_ID;
385
+ }
386
+
387
+ export function getLinearClientSecret() {
388
+ const fromEnv = readEnv('OPENCHAMBER_LINEAR_CLIENT_SECRET');
389
+ if (fromEnv) return fromEnv;
390
+ return readSettingString('linearClientSecret');
391
+ }
392
+
393
+ export function getLinearScopes() {
394
+ const fromEnv = readEnv('OPENCHAMBER_LINEAR_SCOPES');
395
+ if (fromEnv) return fromEnv;
396
+ const stored = readSettingString('linearScopes');
397
+ if (stored) return stored;
398
+ return DEFAULT_LINEAR_SCOPES;
399
+ }
400
+
401
+ export function getLinearBrokerUrl() {
402
+ const fromEnv = readEnv('OPENCHAMBER_LINEAR_BROKER_URL');
403
+ if (fromEnv) return fromEnv.replace(/\/+$/, '');
404
+ const stored = readSettingString('linearBrokerUrl');
405
+ if (stored) return stored.replace(/\/+$/, '');
406
+ return DEFAULT_LINEAR_BROKER_URL;
407
+ }
408
+
409
+ export function getLinearRedirectUri() {
410
+ const fromEnv = readEnv('OPENCHAMBER_LINEAR_REDIRECT_URI');
411
+ if (fromEnv) return fromEnv;
412
+ const stored = readSettingString('linearRedirectUri');
413
+ if (stored) return stored;
414
+ return `${getLinearBrokerUrl()}/callback`;
415
+ }
416
+
417
+ /**
418
+ * Status comments are opt-in: they are written into a Linear workspace other
419
+ * people read, so nothing is posted until the user turns them on.
420
+ */
421
+ export function getLinearSessionCommentsEnabled() {
422
+ return readSettings()[SESSION_COMMENTS_SETTING_KEY] === true;
423
+ }
424
+
425
+ export function setLinearSessionCommentsEnabled(enabled) {
426
+ const next = enabled === true;
427
+ const settings = readSettings();
428
+ settings[SESSION_COMMENTS_SETTING_KEY] = next;
429
+ writeSettings(settings);
430
+ return next;
431
+ }
432
+
433
+ export function getLinearAuthFilePath() {
434
+ return storageFile();
435
+ }
436
+ export const DEFAULT_LINEAR_CLIENT_ID_VALUE = DEFAULT_LINEAR_CLIENT_ID;
@@ -0,0 +1,242 @@
1
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
2
+ import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
5
+ import {
6
+ getLinearAuth,
7
+ getLinearAuthWorkspaces,
8
+ setLinearAuth,
9
+ activateLinearAuth,
10
+ clearLinearAuth,
11
+ toLinearPublicStatus,
12
+ getLinearClientId,
13
+ getLinearRedirectUri,
14
+ isLinearAccessTokenStale,
15
+ getLinearAuthFilePath,
16
+ DEFAULT_LINEAR_CLIENT_ID_VALUE,
17
+ } from './auth.js';
18
+
19
+ const makeTempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'openchamber-linear-auth-'));
20
+
21
+ describe('Linear auth storage', () => {
22
+ let dataDir;
23
+ let previousDataDir;
24
+ let previousPort;
25
+ let previousClientId;
26
+ let previousRedirect;
27
+
28
+ beforeEach(() => {
29
+ previousDataDir = process.env.OPENCHAMBER_DATA_DIR;
30
+ previousPort = process.env.OPENCHAMBER_PORT;
31
+ previousClientId = process.env.OPENCHAMBER_LINEAR_CLIENT_ID;
32
+ previousRedirect = process.env.OPENCHAMBER_LINEAR_REDIRECT_URI;
33
+ dataDir = makeTempDir();
34
+ process.env.OPENCHAMBER_DATA_DIR = dataDir;
35
+ delete process.env.OPENCHAMBER_LINEAR_CLIENT_ID;
36
+ delete process.env.OPENCHAMBER_LINEAR_SCOPES;
37
+ delete process.env.OPENCHAMBER_LINEAR_REDIRECT_URI;
38
+ delete process.env.OPENCHAMBER_PORT;
39
+ });
40
+
41
+ afterEach(() => {
42
+ restoreEnv('OPENCHAMBER_DATA_DIR', previousDataDir);
43
+ restoreEnv('OPENCHAMBER_PORT', previousPort);
44
+ restoreEnv('OPENCHAMBER_LINEAR_CLIENT_ID', previousClientId);
45
+ restoreEnv('OPENCHAMBER_LINEAR_REDIRECT_URI', previousRedirect);
46
+ fs.rmSync(dataDir, { recursive: true, force: true });
47
+ });
48
+
49
+ it('returns disconnected when no auth file exists', () => {
50
+ expect(getLinearAuth()).toBeNull();
51
+ expect(toLinearPublicStatus(null)).toEqual({ connected: false });
52
+ });
53
+
54
+ it('persists tokens without exposing them on the public status', () => {
55
+ setLinearAuth({
56
+ accessToken: 'lin_oauth_access',
57
+ refreshToken: 'lin_oauth_refresh',
58
+ expiresAt: Date.now() + 60_000,
59
+ scope: 'read,write',
60
+ user: { id: 'user-1', name: 'Ada', displayName: 'Ada Lovelace', email: 'ada@example.com', avatarUrl: 'https://example.com/a.png' },
61
+ organization: { id: 'org-1', name: 'OpenChamber', urlKey: 'openchamber' },
62
+ });
63
+
64
+ const stored = getLinearAuth();
65
+ expect(stored.accessToken).toBe('lin_oauth_access');
66
+ expect(stored.refreshToken).toBe('lin_oauth_refresh');
67
+ expect(stored.workspaceId).toBe('org-1');
68
+ const publicStatus = toLinearPublicStatus(stored);
69
+ expect(publicStatus).toEqual({
70
+ connected: true,
71
+ user: {
72
+ id: 'user-1',
73
+ name: 'Ada',
74
+ displayName: 'Ada Lovelace',
75
+ email: 'ada@example.com',
76
+ avatarUrl: 'https://example.com/a.png',
77
+ },
78
+ organization: { id: 'org-1', name: 'OpenChamber', urlKey: 'openchamber' },
79
+ scope: 'read,write',
80
+ workspaces: [{
81
+ id: 'org-1',
82
+ name: 'OpenChamber',
83
+ urlKey: 'openchamber',
84
+ current: true,
85
+ user: {
86
+ id: 'user-1',
87
+ name: 'Ada',
88
+ displayName: 'Ada Lovelace',
89
+ email: 'ada@example.com',
90
+ avatarUrl: 'https://example.com/a.png',
91
+ },
92
+ authorizedAt: stored.authorizedAt,
93
+ }],
94
+ });
95
+ expect(JSON.stringify(publicStatus)).not.toContain('lin_oauth');
96
+ const file = JSON.parse(fs.readFileSync(getLinearAuthFilePath(), 'utf8'));
97
+ expect(file.accessToken).toBeUndefined();
98
+ expect(file.workspaces).toHaveLength(1);
99
+ expect(file.workspaces[0].accessToken).toBe('lin_oauth_access');
100
+ });
101
+
102
+ it('keeps the previous refresh token when a later write omits it', () => {
103
+ setLinearAuth({
104
+ accessToken: 'access-1',
105
+ refreshToken: 'refresh-1',
106
+ expiresAt: 1,
107
+ });
108
+ setLinearAuth({
109
+ accessToken: 'access-2',
110
+ expiresAt: 2,
111
+ });
112
+ expect(getLinearAuth().refreshToken).toBe('refresh-1');
113
+ expect(getLinearAuth().accessToken).toBe('access-2');
114
+ });
115
+
116
+ it('rotates the refresh token when a new one is provided', () => {
117
+ setLinearAuth({
118
+ accessToken: 'access-1',
119
+ refreshToken: 'refresh-1',
120
+ });
121
+ setLinearAuth({
122
+ accessToken: 'access-2',
123
+ refreshToken: 'refresh-2',
124
+ });
125
+ expect(getLinearAuth().refreshToken).toBe('refresh-2');
126
+ });
127
+
128
+ it('rejects a write without an access token', () => {
129
+ expect(() => setLinearAuth({ refreshToken: 'refresh-1' })).toThrow('accessToken is required');
130
+ });
131
+
132
+ it('treats a missing or past expiry as stale', () => {
133
+ expect(isLinearAccessTokenStale(null)).toBe(true);
134
+ expect(isLinearAccessTokenStale(Date.now() - 1)).toBe(true);
135
+ expect(isLinearAccessTokenStale(Date.now() + 10 * 60_000)).toBe(false);
136
+ });
137
+
138
+ it('uses the baked-in client id unless env or settings override it', () => {
139
+ expect(getLinearClientId()).toBe(DEFAULT_LINEAR_CLIENT_ID_VALUE);
140
+ process.env.OPENCHAMBER_LINEAR_CLIENT_ID = 'env-client';
141
+ expect(getLinearClientId()).toBe('env-client');
142
+ });
143
+
144
+ it('uses the stable public broker callback by default', () => {
145
+ process.env.OPENCHAMBER_PORT = '3001';
146
+ expect(getLinearRedirectUri()).toBe('https://api.openchamber.dev/v1/oauth/linear/callback');
147
+ process.env.OPENCHAMBER_LINEAR_REDIRECT_URI = 'http://localhost:3000/linear/oauth/callback';
148
+ expect(getLinearRedirectUri()).toBe('http://localhost:3000/linear/oauth/callback');
149
+ });
150
+
151
+ it('deletes the auth file on clear', () => {
152
+ setLinearAuth({ accessToken: 'access-1', refreshToken: 'refresh-1' });
153
+ expect(fs.existsSync(getLinearAuthFilePath())).toBe(true);
154
+ expect(clearLinearAuth()).toBe(true);
155
+ expect(fs.existsSync(getLinearAuthFilePath())).toBe(false);
156
+ expect(getLinearAuth()).toBeNull();
157
+ });
158
+
159
+ it('migrates a legacy single-workspace file', () => {
160
+ fs.writeFileSync(getLinearAuthFilePath(), JSON.stringify({
161
+ accessToken: 'legacy-access',
162
+ refreshToken: 'legacy-refresh',
163
+ user: { id: 'user-1', name: 'Ada' },
164
+ organization: { id: 'org-1', name: 'OpenChamber', urlKey: 'openchamber' },
165
+ }), 'utf8');
166
+
167
+ const stored = getLinearAuth();
168
+ expect(stored.accessToken).toBe('legacy-access');
169
+ expect(stored.workspaceId).toBe('org-1');
170
+ expect(stored.current).toBe(true);
171
+ const file = JSON.parse(fs.readFileSync(getLinearAuthFilePath(), 'utf8'));
172
+ expect(file.workspaces).toHaveLength(1);
173
+ expect(file.accessToken).toBeUndefined();
174
+ });
175
+
176
+ it('stores a second workspace and activates it without dropping the first', () => {
177
+ setLinearAuth({
178
+ accessToken: 'access-a',
179
+ refreshToken: 'refresh-a',
180
+ user: { id: 'user-a', name: 'Ada' },
181
+ organization: { id: 'org-a', name: 'Alpha', urlKey: 'alpha' },
182
+ });
183
+ setLinearAuth({
184
+ accessToken: 'access-b',
185
+ refreshToken: 'refresh-b',
186
+ user: { id: 'user-b', name: 'Ben' },
187
+ organization: { id: 'org-b', name: 'Beta', urlKey: 'beta' },
188
+ });
189
+
190
+ expect(getLinearAuth().workspaceId).toBe('org-b');
191
+ expect(getLinearAuthWorkspaces().map((entry) => entry.id).sort()).toEqual(['org-a', 'org-b']);
192
+ expect(activateLinearAuth('org-a')).toBe(true);
193
+ expect(getLinearAuth().workspaceId).toBe('org-a');
194
+ expect(getLinearAuth().accessToken).toBe('access-a');
195
+ expect(getLinearAuthWorkspaces().find((entry) => entry.id === 'org-b').current).toBe(false);
196
+ });
197
+
198
+ it('drops only the current workspace on unscoped clear', () => {
199
+ setLinearAuth({
200
+ accessToken: 'access-a',
201
+ organization: { id: 'org-a', name: 'Alpha', urlKey: 'alpha' },
202
+ user: { id: 'user-a', name: 'Ada' },
203
+ });
204
+ setLinearAuth({
205
+ accessToken: 'access-b',
206
+ organization: { id: 'org-b', name: 'Beta', urlKey: 'beta' },
207
+ user: { id: 'user-b', name: 'Ben' },
208
+ });
209
+ expect(clearLinearAuth()).toBe(true);
210
+ expect(getLinearAuth().workspaceId).toBe('org-a');
211
+ expect(getLinearAuth().accessToken).toBe('access-a');
212
+ expect(getLinearAuthWorkspaces()).toHaveLength(1);
213
+ });
214
+
215
+ it('does not bump authorizedAt when a later write opts out of activate', () => {
216
+ setLinearAuth({
217
+ accessToken: 'access-1',
218
+ user: { id: 'user-1', name: 'Ada' },
219
+ organization: { id: 'org-1', name: 'OpenChamber', urlKey: 'openchamber' },
220
+ });
221
+ const file = JSON.parse(fs.readFileSync(getLinearAuthFilePath(), 'utf8'));
222
+ file.workspaces[0].authorizedAt = 111;
223
+ fs.writeFileSync(getLinearAuthFilePath(), JSON.stringify(file, null, 2), 'utf8');
224
+
225
+ setLinearAuth({
226
+ accessToken: 'access-1',
227
+ user: { id: 'user-1', name: 'Ada' },
228
+ organization: { id: 'org-1', name: 'OpenChamber', urlKey: 'openchamber' },
229
+ workspaceId: 'org-1',
230
+ }, { activate: false });
231
+ expect(getLinearAuth().authorizedAt).toBe(111);
232
+ expect(getLinearAuth().current).toBe(true);
233
+ });
234
+ });
235
+
236
+ function restoreEnv(name, previous) {
237
+ if (previous === undefined) {
238
+ delete process.env[name];
239
+ return;
240
+ }
241
+ process.env[name] = previous;
242
+ }