@yuriai/web 0.2.31 → 0.2.32-beta.10

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 (201) hide show
  1. package/README.md +19 -0
  2. package/dist/assets/{AgentAvatar-DLAQkFQe.js → AgentAvatar-DLzcNrQ0.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-Bf1yg0yx.js +3 -0
  4. package/dist/assets/{AssistantUnreadBadge-BynxNQMk.js → AssistantUnreadBadge-BUFyxUrT.js} +1 -1
  5. package/dist/assets/{AssistantView-CDZyA9ft.js → AssistantView-CELFybSr.js} +1 -1
  6. package/dist/assets/{DiagramView-DdVFGHQQ.js → DiagramView-DV4P3-Wg.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-C9a7XnAh.js → FadeInOnReveal-BRrU2ivL.js} +1 -1
  8. package/dist/assets/{GuiPluginSurface-v8r-Hex5.js → GuiPluginSurface-NOHaJGy2.js} +1 -1
  9. package/dist/assets/{GuiPluginWindow-Ba1HfrjQ.js → GuiPluginWindow-BykPaQeY.js} +1 -1
  10. package/dist/assets/Icon-OJf0qBKf.js +1 -0
  11. package/dist/assets/{ImageLoadingPlaceholder-Dcy5lc7F.js → ImageLoadingPlaceholder-DlQbo9CM.js} +1 -1
  12. package/dist/assets/{LoadingImage-BxjJ_Xyj.js → LoadingImage-sZ5omN5L.js} +1 -1
  13. package/dist/assets/MarkdownRenderer-BFR9FWQL.js +2 -0
  14. package/dist/assets/MarkdownRendererImpl-iZFUMI3M.js +10 -0
  15. package/dist/assets/{MarkstreamRendererImpl-EpBnVy9J.css → MarkstreamRendererImpl-C6aiJnjl.css} +1 -1
  16. package/dist/assets/MarkstreamRendererImpl-DjC_Y4LS.js +3 -0
  17. package/dist/assets/{MobileDetailNavigation-o54juFXD.js → MobileDetailNavigation-BOZpHdI2.js} +1 -1
  18. package/dist/assets/{MobileResizableSheet-sV9XR-0k.js → MobileResizableSheet-DuAi_epR.js} +1 -1
  19. package/dist/assets/{MobileShareBridge-oqBZ_f6M.js → MobileShareBridge-D1DrqLWf.js} +1 -1
  20. package/dist/assets/MobileTabPageHeader-BT9gWugr.js +2 -0
  21. package/dist/assets/{MultiRunWindow-7W_86vL6.js → MultiRunWindow-C0GYNaUU.js} +1 -1
  22. package/dist/assets/{OnboardingScreen-CnkijSLE.js → OnboardingScreen-CqsI0632.js} +1 -1
  23. package/dist/assets/{OverlayScrollbar-CCtBTJQj.js → OverlayScrollbar-CZD1yU06.js} +1 -1
  24. package/dist/assets/SettingsView-BYO8LY5A.js +29 -0
  25. package/dist/assets/{SettingsWindow-C0HiNvXh.js → SettingsWindow-CM0Ph9WD.js} +1 -1
  26. package/dist/assets/SetupTourDialog-BYlSBPKZ.js +1 -0
  27. package/dist/assets/SetupTourDialog-DrL_4ODI.css +1 -0
  28. package/dist/assets/{TerminalView-y36H_fIe.js → TerminalView-DnyEAShU.js} +1 -1
  29. package/dist/assets/{ToolOutputDialog-BfjBeqGS.js → ToolOutputDialog-BWONfWze.js} +1 -1
  30. package/dist/assets/{VoiceSettings-BONwzGgR.js → VoiceSettings-Ru_0ySgM.js} +2 -2
  31. package/dist/assets/{YuriLogo-BA5FWp-g.js → YuriLogo-CMUoGUHc.js} +1 -1
  32. package/dist/assets/YuriWordmark-DHYo0FlR.js +1 -0
  33. package/dist/assets/{appThemeRegistry-BsLMp3bc.js → appThemeRegistry-BMlAlm0m.js} +1 -1
  34. package/dist/assets/{button-CBjOhOI0.js → button-C-gRcs_2.js} +1 -1
  35. package/dist/assets/{capgoAdapter-DjlyVxy_.js → capgoAdapter-GdNfjwXs.js} +1 -1
  36. package/dist/assets/checkbox-BrJBzET8.js +1 -0
  37. package/dist/assets/{collapsible-B0j5IQ0T.js → collapsible-B7esGYLd.js} +1 -1
  38. package/dist/assets/{context-menu-C4e_bpls.js → context-menu-DWn1nSZC.js} +1 -1
  39. package/dist/assets/desktopHosts-BLU1tGSX.js +1 -0
  40. package/dist/assets/{desktopRelayRestore-AE3_TnQz.js → desktopRelayRestore-2BIIs8mZ.js} +1 -1
  41. package/dist/assets/{diagram-WPmk0Qh6.js → diagram-Bnra5_6g.js} +1 -1
  42. package/dist/assets/{dialog-Dx3IT7dQ.js → dialog-3UseH0hM.js} +1 -1
  43. package/dist/assets/{es-JU--16Gd.js → es-J7a_sZ1u.js} +2 -2
  44. package/dist/assets/{fileMentionTouchSelection-Bizsisaj.js → fileMentionTouchSelection-ByaQJcTS.js} +1 -1
  45. package/dist/assets/{fr-BUZcRuMk.js → fr-BYxUMKWp.js} +2 -2
  46. package/dist/assets/{gitApi-CNgEj6X5.js → gitApi-BdwvoQFb.js} +1 -1
  47. package/dist/assets/historyImportQueries-C8VK9R5_.js +1 -0
  48. package/dist/assets/host-z9PU8q1e.js +1 -0
  49. package/dist/assets/{input-CEJGM-TS.js → input-CmLlZdeD.js} +1 -1
  50. package/dist/assets/insertionBoundaries-BpQ6nLjP.js +1 -0
  51. package/dist/assets/{ja-BwtVLTXD.js → ja-DCdBiJmD.js} +2 -2
  52. package/dist/assets/{ko--sLsRFpA.js → ko-D-Nb_RJY.js} +2 -2
  53. package/dist/assets/main-Dosy2jXg.js +2 -0
  54. package/dist/assets/main-oBh-dk5-.js +169 -0
  55. package/dist/assets/{markdownHeightCache-D6iSNJG2.js → markdownHeightCache-xNkQdlqi.js} +1 -1
  56. package/dist/assets/{mcpQueries-DVSsZeuk.js → mcpQueries-C8zsTQqJ.js} +1 -1
  57. package/dist/assets/miniChat-CI8ryDGT.js +2 -0
  58. package/dist/assets/mobile-e_mTK3dh.js +2 -0
  59. package/dist/assets/{mobileBackNavigation-Dmbf0kw1.js → mobileBackNavigation-sB7c0Pi4.js} +1 -1
  60. package/dist/assets/multirun-DbmgWrsY.js +3 -0
  61. package/dist/assets/{native-config-BaRHaY4y.js → native-config-C_mwkFzh.js} +1 -1
  62. package/dist/assets/{pl-C4_4J5yA.js → pl-AmU4w3aM.js} +2 -2
  63. package/dist/assets/{projectMeta-rrpZdm8D.js → projectMeta-1iUbVl_M.js} +1 -1
  64. package/dist/assets/{pt-BR-DvNC5K1q.js → pt-BR-BI4ft-Fj.js} +2 -2
  65. package/dist/assets/pwa-BdUAGhLt.js +2 -0
  66. package/dist/assets/{queue-abort-optimistic-CSkERbr4.js → queue-abort-optimistic-BwDsaym5.js} +1 -1
  67. package/dist/assets/react-a6PrrNTm.js +1 -0
  68. package/dist/assets/{readiness-BnO7IaZV.js → readiness-D2N0DtZF.js} +1 -1
  69. package/dist/assets/{renderElectronMiniChatApp-Bq3iNKtr.js → renderElectronMiniChatApp-DV0cNt_O.js} +2 -2
  70. package/dist/assets/{renderMobileApp-DiNeMgwp.js → renderMobileApp-b7--jT5z.js} +7 -7
  71. package/dist/assets/{runtimeConfig-BHOiBANF.js → runtimeConfig-DxmJLWUO.js} +1 -1
  72. package/dist/assets/runtimeEndpointReset-jYAYa3Rh.js +149 -0
  73. package/dist/assets/{select-bKMw5JE8.js → select-J8r9SxHt.js} +1 -1
  74. package/dist/assets/sessionLookup-CUQqj2N4.js +1 -0
  75. package/dist/assets/{sortable-tabs-strip-3sKiA7T1.js → sortable-tabs-strip-CiP6RIQa.js} +1 -1
  76. package/dist/assets/{speechSettingsQueries-BDDxw8LP.js → speechSettingsQueries-B3ziGQvb.js} +1 -1
  77. package/dist/assets/src-GtPQ8f4o.css +2 -0
  78. package/dist/assets/{store-X3lU0obe.js → store-OjrIiXCx.js} +5 -5
  79. package/dist/assets/{textarea-EsaDD051.js → textarea-BHgcxJdC.js} +1 -1
  80. package/dist/assets/{tooltip-LLDL5nIZ.js → tooltip-Degmpxnd.js} +1 -1
  81. package/dist/assets/tour-DDI0Zg7l.js +1 -0
  82. package/dist/assets/types-QETHY-S7.js +2 -0
  83. package/dist/assets/{uk-Dvj0JjiC.js → uk-CbdByxxj.js} +2 -2
  84. package/dist/assets/{useAppFontEffects-wIWWE59b.js → useAppFontEffects-LADr3Zl1.js} +53 -53
  85. package/dist/assets/useDesktopWindowControlsLayout-BVNnRHtc.js +1 -0
  86. package/dist/assets/{useDictation-DlEHSN6P.js → useDictation-DFVJpRbm.js} +1 -1
  87. package/dist/assets/{useEffectiveDirectory-DzqpWUC3.js → useEffectiveDirectory-8tqfGdV5.js} +1 -1
  88. package/dist/assets/{useMobileNavigationStore-BWLhXqci.js → useMobileNavigationStore-CLUFv-TZ.js} +13 -13
  89. package/dist/assets/usePluginsStore-B_SIDwsK.js +1 -0
  90. package/dist/assets/useStreamingTextThrottle-VhgGU_te.js +1 -0
  91. package/dist/assets/{useWorkerHighlightedLines-DMS69wKa.js → useWorkerHighlightedLines-jlxakDGs.js} +1 -1
  92. package/dist/assets/{vendor-markstream-react-DfLaSG3W.js → vendor-markstream-react-6zxyQLCD.js} +1 -1
  93. package/dist/assets/{zh-CN-2Y6u8t24.js → zh-CN-ufEVDbXp.js} +2 -2
  94. package/dist/assets/{zh-TW-Z5wVv4Fb.js → zh-TW-DTBlZ4YC.js} +2 -2
  95. package/dist/index.html +8 -8
  96. package/dist/mini-chat.html +8 -8
  97. package/dist/mobile.html +8 -8
  98. package/package.json +1 -1
  99. package/server/index.js +3 -0
  100. package/server/lib/client-auth/pairing.js +2 -0
  101. package/server/lib/client-auth/pairing.test.js +29 -0
  102. package/server/lib/config-sync/DOCUMENTATION.md +8 -4
  103. package/server/lib/config-sync/index.js +1 -1
  104. package/server/lib/config-sync/magpie-auth.js +10 -4
  105. package/server/lib/config-sync/magpie-auth.test.js +4 -0
  106. package/server/lib/config-sync/magpie.js +28 -22
  107. package/server/lib/config-sync/magpie.test.js +127 -2
  108. package/server/lib/config-sync/plugins.js +44 -0
  109. package/server/lib/config-sync/plugins.test.js +64 -0
  110. package/server/lib/config-sync/tar.js +61 -1
  111. package/server/lib/content-search/DOCUMENTATION.md +9 -0
  112. package/server/lib/content-search/routes.js +18 -1
  113. package/server/lib/content-search/routes.test.js +21 -0
  114. package/server/lib/content-search/runtime.js +7 -3
  115. package/server/lib/content-search/runtime.test.js +26 -0
  116. package/server/lib/gui-customization/DOCUMENTATION.md +21 -1
  117. package/server/lib/gui-customization/session-skill.js +2 -2
  118. package/server/lib/gui-customization/session-skill.test.js +3 -1
  119. package/server/lib/gui-customization/skill/SKILL.md +5 -1
  120. package/server/lib/gui-customization/skill/references/global-pages.md +1 -1
  121. package/server/lib/gui-customization/skill/references/gui-api.md +4 -1
  122. package/server/lib/gui-customization/skill/references/icons.md +134 -0
  123. package/server/lib/gui-customization/skill/references/plugin-styles.md +112 -0
  124. package/server/lib/gui-customization/skill/references/ui-surfaces.md +2 -0
  125. package/server/lib/gui-customization/skill/references/work-status.md +110 -0
  126. package/server/lib/history-import/AGENT_CONNECT_LICENSE +21 -0
  127. package/server/lib/history-import/DOCUMENTATION.md +223 -0
  128. package/server/lib/history-import/dev-proxy.integration.test.js +56 -0
  129. package/server/lib/history-import/events.js +322 -0
  130. package/server/lib/history-import/events.test.js +110 -0
  131. package/server/lib/history-import/installations.js +39 -0
  132. package/server/lib/history-import/installations.test.js +24 -0
  133. package/server/lib/history-import/native.js +49 -0
  134. package/server/lib/history-import/native.test.js +42 -0
  135. package/server/lib/history-import/routes.js +48 -0
  136. package/server/lib/history-import/routes.test.js +55 -0
  137. package/server/lib/history-import/service.js +374 -0
  138. package/server/lib/history-import/service.test.js +538 -0
  139. package/server/lib/history-import/settings.js +146 -0
  140. package/server/lib/history-import/settings.test.js +88 -0
  141. package/server/lib/history-import/sources.js +184 -0
  142. package/server/lib/history-import/sources.test.js +190 -0
  143. package/server/lib/history-import/sqlite.js +187 -0
  144. package/server/lib/history-import/store.js +58 -0
  145. package/server/lib/history-import/store.test.js +84 -0
  146. package/server/lib/history-import/targets.js +24 -0
  147. package/server/lib/host-update/DOCUMENTATION.md +6 -0
  148. package/server/lib/host-update/routes.test.js +1 -1
  149. package/server/lib/notifications/native-stream.relay.test.js +1 -0
  150. package/server/lib/opencode/DOCUMENTATION.md +14 -0
  151. package/server/lib/opencode/core-routes.js +1 -0
  152. package/server/lib/opencode/feature-routes-runtime.js +11 -1
  153. package/server/lib/opencode/plugin-routes.test.js +1 -0
  154. package/server/lib/opencode/plugins.js +1 -1
  155. package/server/lib/opencode/plugins.test.js +3 -2
  156. package/server/lib/opencode/proxy.js +29 -4
  157. package/server/lib/opencode/proxy.test.js +85 -1
  158. package/server/lib/opencode/server-utils-runtime.js +2 -0
  159. package/server/lib/opencode/settings-runtime.js +8 -6
  160. package/server/lib/opencode/settings-runtime.test.js +44 -0
  161. package/server/lib/opencode/yuri-routes.js +1 -1
  162. package/server/lib/relay/DOCUMENTATION.md +1 -1
  163. package/server/lib/relay/host-client.js +3 -1
  164. package/server/lib/relay/host-client.test.js +1 -0
  165. package/server/lib/relay/reasoning-projection.e2e.test.ts +1 -0
  166. package/server/lib/relay/relay-server.e2e.test.ts +32 -17
  167. package/server/lib/relay/service.js +2 -0
  168. package/server/lib/relay/tunnel-host.js +26 -1
  169. package/server/lib/relay/tunnel-host.test.js +27 -3
  170. package/server/lib/remote-desktop/runtime.test.js +2 -2
  171. package/server/lib/ui-auth/DOCUMENTATION.md +3 -0
  172. package/server/lib/ui-auth/ui-auth.js +27 -0
  173. package/server/lib/ui-auth/ui-auth.test.js +42 -1
  174. package/server/plugin-gui-proxy.test.js +1 -1
  175. package/dist/assets/AssistantContactStatus-DZGGspw4.js +0 -3
  176. package/dist/assets/Icon-Bh3TaKoN.js +0 -1
  177. package/dist/assets/MarkdownRenderer-CS6Pia5D.js +0 -2
  178. package/dist/assets/MarkdownRendererImpl-Bdwe3qUr.js +0 -10
  179. package/dist/assets/MarkstreamRendererImpl-CCQj9IkL.js +0 -3
  180. package/dist/assets/MobileTabPageHeader-CptcDWNS.js +0 -2
  181. package/dist/assets/SettingsView-CkJpYIMe.js +0 -29
  182. package/dist/assets/SetupTourDialog-BcEbaEO3.js +0 -1
  183. package/dist/assets/SetupTourDialog-CUzqT2sw.css +0 -1
  184. package/dist/assets/YuriWordmark-Cr1vkcue.js +0 -1
  185. package/dist/assets/desktopHosts-CMglnUdS.js +0 -1
  186. package/dist/assets/host-CBfSyi4l.js +0 -1
  187. package/dist/assets/insertionBoundaries-CgYf6gys.js +0 -1
  188. package/dist/assets/main-B8FcBwPM.js +0 -169
  189. package/dist/assets/main-DrqtyqDc.js +0 -2
  190. package/dist/assets/miniChat-CgeCl4RY.js +0 -2
  191. package/dist/assets/mobile-DAhJKHUq.js +0 -2
  192. package/dist/assets/multirun-BbWnHeaY.js +0 -3
  193. package/dist/assets/pwa-Dm_DJEr9.js +0 -2
  194. package/dist/assets/react-Bwr5-XPi.js +0 -1
  195. package/dist/assets/runtimeEndpointReset-DGxT24oE.js +0 -149
  196. package/dist/assets/sessionLookup-DGNxfDsP.js +0 -1
  197. package/dist/assets/src-PTWgTO6W.css +0 -2
  198. package/dist/assets/tour-Db44qwfs.js +0 -1
  199. package/dist/assets/types-Cl7nTpsb.js +0 -2
  200. package/dist/assets/useDesktopWindowControlsLayout-CdUr9mCZ.js +0 -1
  201. package/dist/assets/usePluginsStore-aZl0WTK8.js +0 -1
@@ -0,0 +1,187 @@
1
+ // Cursor editor layout adapted from Agent Connect; see AGENT_CONNECT_LICENSE.
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import Database from 'better-sqlite3';
7
+ import { fail, timestamp, textOf } from './events.js';
8
+
9
+ const MAX_DB_BYTES = 1024 * 1024 * 1024;
10
+ const stamp = async (file) => {
11
+ try { const stat = await fs.lstat(file, { bigint: true });
12
+ if (!stat.isFile() || stat.isSymbolicLink()) fail('invalid_source');
13
+ if (stat.size > BigInt(MAX_DB_BYTES)) fail('source_too_large');
14
+ return `${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
15
+ } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
16
+ };
17
+ const json = (value) => JSON.parse(Buffer.isBuffer(value) ? value.toString('utf8') : value);
18
+
19
+ // Never open the original database: even SQLite readonly opens can create SHM
20
+ // or change read marks. Copy DB + WAL, reject a changing source, then transact on
21
+ // the private snapshot. A busy/changing database is retryable, not empty success.
22
+ async function readSqliteSnapshot(file, read) {
23
+ for (let attempt = 0; attempt < 3; attempt++) {
24
+ const temporary = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-history-'));
25
+ let db;
26
+ try {
27
+ const before = await Promise.all([stamp(file), stamp(`${file}-wal`)]);
28
+ if (!before[0]) fail('source_missing');
29
+ const target = path.join(temporary, 'snapshot.db');
30
+ await fs.copyFile(file, target);
31
+ if (before[1]) await fs.copyFile(`${file}-wal`, `${target}-wal`);
32
+ const after = await Promise.all([stamp(file), stamp(`${file}-wal`)]);
33
+ if (JSON.stringify(before) !== JSON.stringify(after)) continue;
34
+ db = new Database(target, { readonly: true, fileMustExist: true, timeout: 1000 });
35
+ return db.transaction(() => read(db))();
36
+ } finally {
37
+ db?.close();
38
+ await fs.rm(temporary, { recursive: true, force: true });
39
+ }
40
+ }
41
+ fail('source_busy');
42
+ }
43
+
44
+ const kv = (db, key) => {
45
+ const row = db.prepare('SELECT value FROM cursorDiskKV WHERE key = ?').get(key);
46
+ return row?.value == null ? null : json(row.value);
47
+ };
48
+ const folderPath = (value) => {
49
+ if (typeof value === 'string') { try { return value.startsWith('file:') ? fileURLToPath(value) : value; } catch { return ''; } }
50
+ return value?.fsPath ?? value?.path ?? '';
51
+ };
52
+
53
+ async function readCursorEditorSnapshot(file, wantedID, limit, includeCount = false) {
54
+ return readSqliteSnapshot(file, (db) => {
55
+ const tables = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => row.name));
56
+ if (!tables.has('cursorDiskKV')) fail('unsupported_source_version');
57
+ const count = includeCount ? db.prepare(tables.has('composerHeaders')
58
+ ? 'SELECT COUNT(*) AS count FROM composerHeaders'
59
+ : "SELECT COUNT(*) AS count FROM cursorDiskKV WHERE key LIKE 'composerData:%'").get().count : undefined;
60
+ try {
61
+ let heads;
62
+ if (tables.has('composerHeaders')) {
63
+ heads = db.prepare('SELECT composerId, value FROM composerHeaders LIMIT ?').all(limit ?? 5001).map((row) => ({ ...json(row.value), composerId: row.composerId }));
64
+ } else {
65
+ heads = db.prepare("SELECT key, value FROM cursorDiskKV WHERE key LIKE 'composerData:%' LIMIT ?").all(limit ?? 5001).map((row) => ({ ...json(row.value), composerId: row.key.slice('composerData:'.length) }));
66
+ }
67
+ if (heads.length > 5000) fail('too_many_sessions');
68
+ const selected = wantedID ? heads.filter((head) => head.composerId === wantedID) : heads;
69
+ const sessions = selected.map((head) => {
70
+ const composer = kv(db, `composerData:${head.composerId}`);
71
+ if (!composer) fail('source_missing');
72
+ const headers = composer.fullConversationHeadersOnly ?? composer.conversation ?? [];
73
+ if (!Array.isArray(headers) || headers.length > 100000) fail('invalid_source');
74
+ const events = []; const warnings = new Set(['tools_archived', 'usage_unknown']);
75
+ for (const header of headers) {
76
+ const bubble = header.text != null ? header : kv(db, `bubbleId:${head.composerId}:${header.bubbleId}`);
77
+ if (!bubble) { warnings.add('missing_records'); continue; }
78
+ const time = timestamp(bubble.createdAt, timestamp(head.createdAt));
79
+ const tool = bubble.toolFormerData;
80
+ if (header.type === 1 || bubble.type === 1) {
81
+ if (bubble.context?.selectedImages?.length || bubble.images?.length) warnings.add('attachments_omitted');
82
+ if (bubble.text) events.push({ kind: 'user', text: bubble.text, time });
83
+ } else if (tool) {
84
+ events.push({ kind: 'tool', time, name: tool.name, input: tool.rawArgs ?? tool.params ?? '', output: textOf(tool.result), incomplete: tool.status !== 'completed' });
85
+ if (tool.status !== 'completed') warnings.add('unfinished_tools');
86
+ } else if (bubble.thinking?.text) events.push({ kind: 'thinking', text: bubble.thinking.text, time });
87
+ else if (bubble.text) events.push({ kind: 'assistant-text', text: bubble.text, time });
88
+ }
89
+ return { id: head.composerId, title: head.name || composer.name || events.find((event) => event.kind === 'user')?.text?.slice(0, 100) || head.composerId,
90
+ directory: folderPath(head.workspaceIdentifier?.uri ?? composer.workspaceIdentifier?.uri), parentID: head.parentComposerId,
91
+ events, warnings: [...warnings] };
92
+ }).filter((session) => session.events.length);
93
+ return { sessions, count };
94
+ } catch (error) {
95
+ if (!includeCount) throw error;
96
+ return { sessions: [], count, error };
97
+ }
98
+ });
99
+ }
100
+
101
+ export async function readCursorEditor(file, wantedID, limit) {
102
+ return (await readCursorEditorSnapshot(file, wantedID, limit)).sessions;
103
+ }
104
+
105
+ export const readCursorEditorInventory = (file, limit) => readCursorEditorSnapshot(file, undefined, limit, true);
106
+
107
+ // Only the small length-delimited protobuf fields needed for the CLI's ordered
108
+ // message IDs are decoded. Unknown fields are skipped, never guessed as messages.
109
+ function lengthFields(buffer, wanted) {
110
+ const fields = []; let offset = 0;
111
+ const varint = () => {
112
+ let value = 0; let multiplier = 1;
113
+ for (let count = 0; count < 10 && offset < buffer.length; count++) {
114
+ const byte = buffer[offset++]; value += (byte & 127) * multiplier;
115
+ if (!Number.isSafeInteger(value)) fail('invalid_source');
116
+ if (!(byte & 128)) return value;
117
+ multiplier *= 128;
118
+ }
119
+ fail('invalid_source');
120
+ };
121
+ while (offset < buffer.length) {
122
+ const tag = varint(); const wire = tag & 7; const field = Math.floor(tag / 8);
123
+ if (wire === 0) varint();
124
+ else if (wire === 1) offset += 8;
125
+ else if (wire === 5) offset += 4;
126
+ else if (wire === 2) {
127
+ const length = varint(); const end = offset + length;
128
+ if (end > buffer.length) fail('invalid_source');
129
+ if (field === wanted) fields.push(buffer.subarray(offset, end));
130
+ offset = end;
131
+ } else fail('unsupported_source_version');
132
+ if (offset > buffer.length) fail('invalid_source');
133
+ }
134
+ return fields;
135
+ }
136
+
137
+ export async function readCursorCli(file) {
138
+ let sidecar = {};
139
+ try { sidecar = JSON.parse(await fs.readFile(path.join(path.dirname(file), 'meta.json'), 'utf8')); }
140
+ catch (error) { if (error.code !== 'ENOENT') throw error; }
141
+ return readSqliteSnapshot(file, (db) => {
142
+ const raw = db.prepare("SELECT value FROM meta WHERE key = '0'").get()?.value;
143
+ if (!raw) fail('invalid_source');
144
+ const text = Buffer.isBuffer(raw) ? raw.toString('utf8') : raw;
145
+ const meta = JSON.parse(text.trim().startsWith('{') ? text : Buffer.from(text, 'hex').toString('utf8'));
146
+ const getBlob = (id) => {
147
+ const row = db.prepare('SELECT data FROM blobs WHERE id = ?').get(id);
148
+ if (!row) fail('missing_records');
149
+ const value = row.data;
150
+ return Buffer.isBuffer(value) ? value : Buffer.from(value, /^[\[{]/.test(value.trim()) ? 'utf8' : 'hex');
151
+ };
152
+ const root = getBlob(meta.latestRootBlobId);
153
+ const ids = [];
154
+ // Archives are source history; current root follows them. Dedup only blob IDs.
155
+ for (const archive of lengthFields(root, 13)) {
156
+ const key = archive.toString('hex');
157
+ const payload = getBlob(key);
158
+ ids.push(...lengthFields(payload, 1).map((id) => id.toString('hex')));
159
+ }
160
+ ids.push(...lengthFields(root, 1).map((id) => id.toString('hex')));
161
+ if (ids.length > 100000) fail('source_too_large');
162
+ const entries = [...new Set(ids)].map((id) => json(getBlob(id)));
163
+ const time = timestamp(meta.createdAt ?? sidecar.createdAtMs);
164
+ const events = []; const results = new Map(); const warnings = new Set(['tools_archived', 'usage_unknown']);
165
+ for (const message of entries) for (const part of Array.isArray(message.content) ? message.content : []) if (part.type === 'tool-result') results.set(part.toolCallId, part);
166
+ for (const message of entries) {
167
+ if (!['user', 'assistant'].includes(message.role)) continue;
168
+ const content = typeof message.content === 'string' ? [{ type: 'text', text: message.content }] : message.content;
169
+ if (!Array.isArray(content)) fail('invalid_source');
170
+ for (const part of content) {
171
+ if (part.type === 'text') {
172
+ let text = part.text;
173
+ if (message.role === 'user') text = text.match(/<user_query>([\s\S]*?)<\/user_query>/)?.[1] ?? text;
174
+ events.push({ kind: message.role === 'user' ? 'user' : 'assistant-text', text, time });
175
+ } else if (part.type === 'reasoning') events.push({ kind: 'thinking', text: part.text ?? '', time });
176
+ else if (part.type === 'tool-call') {
177
+ const result = results.get(part.toolCallId);
178
+ events.push({ kind: 'tool', time, name: part.toolName, input: part.args ?? part.input ?? {}, output: textOf(result?.result ?? result?.output), incomplete: !result });
179
+ if (!result) warnings.add('unfinished_tools');
180
+ } else warnings.add('attachments_omitted');
181
+ }
182
+ }
183
+ if (!events.length) fail('empty_transcript');
184
+ return { id: meta.agentId ?? path.basename(path.dirname(file)), title: sidecar.title ?? meta.name ?? '', directory: sidecar.cwd ?? '',
185
+ parentID: meta.subagentInfo?.parentAgentId, events, warnings: [...warnings] };
186
+ });
187
+ }
@@ -0,0 +1,58 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import Database from 'better-sqlite3';
4
+
5
+ // Receipts contain identities/status only, never transcript/config contents.
6
+ export function createImportStore(file) {
7
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
8
+ const db = new Database(file);
9
+ db.pragma('journal_mode = WAL');
10
+ db.exec(`CREATE TABLE IF NOT EXISTS import_job (
11
+ id TEXT PRIMARY KEY, owner TEXT NOT NULL, runtime TEXT NOT NULL,
12
+ state TEXT NOT NULL, total INTEGER NOT NULL, created INTEGER NOT NULL
13
+ ); CREATE TABLE IF NOT EXISTS import_receipt (
14
+ job TEXT NOT NULL, position INTEGER NOT NULL, result TEXT NOT NULL,
15
+ PRIMARY KEY(job, position)
16
+ );`);
17
+ if (!db.prepare('PRAGMA table_info(import_job)').all().some((column) => column.name === 'progress')) db.exec('ALTER TABLE import_job ADD COLUMN progress TEXT');
18
+ if (!db.prepare('PRAGMA table_info(import_job)').all().some((column) => column.name === 'request')) db.exec('ALTER TABLE import_job ADD COLUMN request TEXT');
19
+ if (!db.prepare('PRAGMA table_info(import_job)').all().some((column) => column.name === 'dismissed')) db.exec('ALTER TABLE import_job ADD COLUMN dismissed INTEGER NOT NULL DEFAULT 0');
20
+ db.prepare("UPDATE import_job SET state = 'interrupted' WHERE state = 'running'").run();
21
+ const get = (id, owner, runtime) => {
22
+ const row = db.prepare('SELECT * FROM import_job WHERE id = ? AND owner = ? AND runtime = ?').get(id, owner, runtime);
23
+ if (!row) return null;
24
+ const completed = db.prepare('SELECT COUNT(*) AS count FROM import_receipt WHERE job = ?').get(id).count;
25
+ const recent = db.prepare('SELECT position, result FROM import_receipt WHERE job = ? ORDER BY position DESC LIMIT 40').all(id);
26
+ const failures = db.prepare("SELECT position, result FROM import_receipt WHERE job = ? AND (json_extract(result, '$.status') = 'failed' OR json_extract(result, '$.project') = 'failed' OR json_extract(result, '$.index') = 'failed') ORDER BY position LIMIT 40").all(id);
27
+ const results = [...new Map([...failures, ...recent].map((entry) => [entry.position, entry])).values()]
28
+ .sort((left, right) => left.position - right.position).map((entry) => JSON.parse(entry.result));
29
+ return { id: row.id, state: row.state, total: row.total, completed, created: row.created, results, resumable: Boolean(row.request) && !['completed', 'partial'].includes(row.state), dismissed: Boolean(row.dismissed),
30
+ ...(row.progress ? { progress: JSON.parse(row.progress) } : {}) };
31
+ };
32
+ return {
33
+ create: (id, owner, runtime, total, request = null) => db.prepare("INSERT INTO import_job (id, owner, runtime, state, total, created, request) VALUES (?, ?, ?, 'running', ?, ?, ?)").run(id, owner, runtime, total, Date.now(), request ? JSON.stringify(request) : null),
34
+ request: (id, owner, runtime) => {
35
+ const row = db.prepare('SELECT request FROM import_job WHERE id = ? AND owner = ? AND runtime = ?').get(id, owner, runtime);
36
+ return row?.request ? JSON.parse(row.request) : null;
37
+ },
38
+ restart: db.transaction((id, request) => {
39
+ db.prepare('DELETE FROM import_receipt WHERE job = ?').run(id);
40
+ db.prepare("UPDATE import_job SET state = 'running', total = 0, progress = NULL, request = ? WHERE id = ?").run(JSON.stringify(request), id);
41
+ }),
42
+ progress: (id, progress, total = null) => db.prepare('UPDATE import_job SET progress = ?, total = COALESCE(?, total) WHERE id = ?').run(JSON.stringify(progress), total, id),
43
+ append: (id, position, result) => db.prepare('INSERT INTO import_receipt VALUES (?, ?, ?)').run(id, position, JSON.stringify(result)),
44
+ finish: (id, state) => db.prepare('UPDATE import_job SET state = ? WHERE id = ?').run(state, id),
45
+ dismiss: (id, owner, runtime) => db.prepare("UPDATE import_job SET dismissed = 1 WHERE id = ? AND owner = ? AND runtime = ? AND state != 'running'").run(id, owner, runtime).changes > 0,
46
+ latest: (owner, runtime) => {
47
+ const row = db.prepare('SELECT id FROM import_job WHERE owner = ? AND runtime = ? AND dismissed = 0 ORDER BY created DESC LIMIT 1').get(owner, runtime);
48
+ return row ? get(row.id, owner, runtime) : null;
49
+ },
50
+ unfinished: (owner, runtime) => db.prepare(`SELECT j.*, (SELECT COUNT(*) FROM import_receipt r WHERE r.job = j.id) AS completed,
51
+ (SELECT COUNT(*) FROM import_receipt r WHERE r.job = j.id AND (json_extract(result, '$.status') = 'failed' OR json_extract(result, '$.project') = 'failed' OR json_extract(result, '$.index') = 'failed')) AS failures
52
+ FROM import_job j WHERE owner = ? AND runtime = ? AND state NOT IN ('completed', 'partial') AND dismissed = 0 ORDER BY created`).all(owner, runtime)
53
+ .map((row) => ({ id: row.id, state: row.state, total: row.total, completed: row.completed, created: row.created,
54
+ results: [], failures: row.failures, resumable: Boolean(row.request), ...(row.progress ? { progress: JSON.parse(row.progress) } : {}) })),
55
+ get,
56
+ close: () => db.close(),
57
+ };
58
+ }
@@ -0,0 +1,84 @@
1
+ import fs from 'node:fs/promises';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import Database from 'better-sqlite3';
5
+ import { afterEach, beforeEach, expect, test } from 'vitest';
6
+ import { createImportStore } from './store.js';
7
+
8
+ let directory; let store;
9
+ beforeEach(async () => { directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-import-store-')); });
10
+ afterEach(async () => { store?.close(); await fs.rm(directory, { recursive: true, force: true }); });
11
+
12
+ test('old receipts migrate without loss; phase progress and discovered totals survive restart', () => {
13
+ const file = path.join(directory, 'receipts.sqlite'); const old = new Database(file);
14
+ old.exec(`CREATE TABLE import_job (id TEXT PRIMARY KEY, owner TEXT NOT NULL, runtime TEXT NOT NULL,
15
+ state TEXT NOT NULL, total INTEGER NOT NULL, created INTEGER NOT NULL);
16
+ CREATE TABLE import_receipt (job TEXT NOT NULL, position INTEGER NOT NULL, result TEXT NOT NULL, PRIMARY KEY(job, position));
17
+ INSERT INTO import_job VALUES ('old', 'owner', 'runtime', 'completed', 1, 1);
18
+ INSERT INTO import_receipt VALUES ('old', 0, '{"key":"old-item","status":"imported"}');`);
19
+ old.close(); store = createImportStore(file);
20
+ expect(store.get('old', 'owner', 'runtime')).toMatchObject({ state: 'completed', completed: 1, results: [{ key: 'old-item', status: 'imported' }] });
21
+ store.create('new', 'owner', 'runtime', 0);
22
+ store.progress('new', { phase: 'validating', completed: 2, total: 10 });
23
+ expect(store.get('new', 'owner', 'runtime')).toMatchObject({ total: 0, completed: 0, progress: { phase: 'validating', completed: 2, total: 10 } });
24
+ store.progress('new', { phase: 'importing', completed: 1, total: 12 }, 12);
25
+ store.append('new', 0, { key: 'item', status: 'imported' });
26
+ store.close(); store = createImportStore(file);
27
+ expect(store.latest('owner', 'runtime')).toMatchObject({ id: 'new', state: 'interrupted', total: 12, completed: 1,
28
+ progress: { phase: 'importing', completed: 1, total: 12 } });
29
+ expect(store.get('old', 'owner', 'runtime').state).toBe('completed');
30
+ expect(store.get('old', 'owner', 'runtime').resumable).toBe(false);
31
+ });
32
+
33
+ test('private retry selection survives restart; unfinished jobs are scoped and restarting resets only that receipt', () => {
34
+ const file = path.join(directory, 'jobs.sqlite'); store = createImportStore(file);
35
+ const selection = { sources: ['claude'], directory: '/workspace' };
36
+ store.create('one', 'owner', 'runtime', 357, selection);
37
+ store.append('one', 0, { status: 'imported', sessionID: 'saved' });
38
+ store.finish('one', 'interrupted');
39
+ store.create('two', 'owner', 'runtime', 0, selection);
40
+ store.create('other', 'other', 'runtime', 0, selection);
41
+ store.create('runtime', 'owner', 'other', 0, selection);
42
+ store.close(); store = createImportStore(file);
43
+ expect(store.request('one', 'owner', 'runtime')).toEqual(selection);
44
+ expect(store.request('one', 'other', 'runtime')).toBeNull();
45
+ const jobs = store.unfinished('owner', 'runtime');
46
+ expect(jobs.map((job) => job.id)).toEqual(['one', 'two']);
47
+ expect(jobs[0]).toMatchObject({ resumable: true, completed: 1, results: [] });
48
+ expect(JSON.stringify(jobs)).not.toContain('/workspace');
49
+ expect(store.get('one', 'owner', 'runtime')).not.toHaveProperty('request');
50
+ store.restart('one', selection);
51
+ expect(store.get('one', 'owner', 'runtime')).toMatchObject({ state: 'running', completed: 0, total: 0 });
52
+ expect(store.get('two', 'owner', 'runtime')).toMatchObject({ state: 'interrupted' });
53
+ store.finish('one', 'completed');
54
+ expect(store.unfinished('owner', 'runtime').map((job) => job.id)).toEqual(['two']);
55
+ });
56
+
57
+ test('partial imports leave unfinished lists but keep durable failure receipts across restart', () => {
58
+ const file = path.join(directory, 'partial.sqlite'); store = createImportStore(file);
59
+ store.create('partial', 'owner', 'runtime', 1, { sources: ['claude'] });
60
+ store.append('partial', 0, { key: 'bad', status: 'failed', code: 'empty_transcript' });
61
+ store.finish('partial', 'partial');
62
+ expect(store.unfinished('owner', 'runtime')).toEqual([]);
63
+ expect(store.get('partial', 'owner', 'runtime')).toMatchObject({ state: 'partial', completed: 1, resumable: false, results: [{ code: 'empty_transcript' }] });
64
+ store.close(); store = createImportStore(file);
65
+ expect(store.unfinished('owner', 'runtime')).toEqual([]);
66
+ expect(store.get('partial', 'owner', 'runtime').results).toHaveLength(1);
67
+ });
68
+
69
+ test('dismissal is scoped, rejects active jobs, survives restart and retains receipts', () => {
70
+ const file = path.join(directory, 'dismiss.sqlite'); store = createImportStore(file);
71
+ store.create('active', 'owner', 'runtime', 0);
72
+ store.create('failed', 'owner', 'runtime', 357);
73
+ store.append('failed', 0, { status: 'imported', sessionID: 'saved' }); store.finish('failed', 'interrupted');
74
+ expect(store.dismiss('active', 'owner', 'runtime')).toBe(false);
75
+ expect(store.dismiss('failed', 'other', 'runtime')).toBe(false);
76
+ expect(store.dismiss('failed', 'owner', 'other')).toBe(false);
77
+ expect(store.dismiss('failed', 'owner', 'runtime')).toBe(true);
78
+ expect(store.get('failed', 'owner', 'runtime')).toMatchObject({ dismissed: true, completed: 1, results: [{ sessionID: 'saved' }] });
79
+ expect(store.unfinished('owner', 'runtime').map((job) => job.id)).toEqual(['active']);
80
+ expect(store.latest('owner', 'runtime').id).toBe('active');
81
+ store.close(); store = createImportStore(file);
82
+ expect(store.get('failed', 'owner', 'runtime')).toMatchObject({ dismissed: true, completed: 1 });
83
+ expect(store.unfinished('owner', 'runtime').map((job) => job.id)).toEqual(['active']);
84
+ });
@@ -0,0 +1,24 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { fail } from './events.js';
4
+
5
+ export async function resolveImportDirectory(value, allowMissing = false) {
6
+ if (typeof value !== 'string' || !path.isAbsolute(value) || value.length > 4096) fail('invalid_target');
7
+ const directory = path.resolve(value);
8
+ try {
9
+ const real = await fs.realpath(directory);
10
+ if (!(await fs.stat(real)).isDirectory()) fail('invalid_target');
11
+ return real;
12
+ } catch (error) {
13
+ if (!allowMissing || error.code !== 'ENOENT') throw error;
14
+ const parent = path.dirname(directory);
15
+ if (parent === directory) throw error;
16
+ return path.join(await resolveImportDirectory(parent, true), path.basename(directory));
17
+ }
18
+ }
19
+
20
+ export async function ensureImportDirectory(directory) {
21
+ if (await resolveImportDirectory(directory, true) !== directory) fail('target_changed');
22
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
23
+ if (await resolveImportDirectory(directory) !== directory) fail('target_changed');
24
+ }
@@ -1,5 +1,11 @@
1
1
  # Host self-update
2
2
 
3
+ The sidebar retains failed/interrupted Host operations with a red progress ring.
4
+ Continue re-fetches the original channel and requires an exact version/artifact
5
+ kind match before submitting a fresh plan. It never replays expired plan IDs or
6
+ silently substitutes the channel's newest release. Existing operation persistence,
7
+ admission serialization and fresh artifact validation remain authoritative.
8
+
3
9
  `GET /api/system/update?channel=stable|beta` returns the **serving Host's**
4
10
  identity/version, supported capability, selected/query channel, optional update
5
11
  plan (exact version, release notes, OTA/installer/CLI kind, rollback and expiry),
@@ -78,7 +78,7 @@ it('uses the real Relay dispatcher without injecting credentials for GET and POS
78
78
  server.listen(0, '127.0.0.1');
79
79
  await once(server, 'listening');
80
80
  const frames = [];
81
- const tunnel = createTunnelHost({ connectionId: 'host-update', getLocalPort: () => server.address().port,
81
+ const tunnel = createTunnelHost({ authorizeRequest: async () => true, connectionId: 'host-update', getLocalPort: () => server.address().port,
82
82
  sendFrame: (frame) => { frames.push(decodeTunnelFrame(frame)); }, getBufferedAmount: () => 0 });
83
83
  const call = async (stream, method, headers, body) => {
84
84
  await tunnel.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpRequest, stream, encodeJsonPayload({ method, path: '/api/system/update', query: '', headers })));
@@ -29,6 +29,7 @@ it('carries notification SSE and its replay cursor through the real encrypted tu
29
29
  let incoming = Promise.resolve();
30
30
  let outgoing = Promise.resolve();
31
31
  const host = createTunnelHost({
32
+ authorizeRequest: async () => true,
32
33
  connectionId: 'fixture', getLocalPort: () => origin.address().port, getBufferedAmount: () => socket.bufferedAmount,
33
34
  sendFrame: (frame) => {
34
35
  outgoing = outgoing.then(async () => socket.send(await channel.encryptor.encrypt(frame)));
@@ -10,6 +10,9 @@ diagnostics use provider/location/session-active V2 routes and location query
10
10
  encoding, not removed V1 endpoints.
11
11
 
12
12
  ## Entrypoints and structure
13
+ - `feature-routes-runtime.js` registers the Host-owned history importer before
14
+ the generic proxy, using the official client, project registry and session
15
+ index. Its domain contract is in `../history-import/DOCUMENTATION.md`.
13
16
  - `native-goal.js`: official `@opencode/schema/goal` RPC read adapter shared by
14
17
  scheduled tasks, Assistant reconciliation and notification suppression. It
15
18
  validates native state and distinguishes an absent plugin from transport/auth
@@ -29,6 +32,7 @@ encoding, not removed V1 endpoints.
29
32
  from the authenticated client context (null for owner UI sessions), allowing
30
33
  connection shortcuts to exclude themselves without changing management lists.
31
34
  - `plugins.js`: config entries and plugin-directory files are inventory, not compatibility checks. They do not synthesize `compatibility` or `compatible` fields; Settings uses the OpenCode runtime inventory for actual load status and errors.
35
+ - Host user-scope plugin creation (including the setup tour) supplies `$schema: "https://opencode.ai/config.json"` and `lsp: true` when absent in its target config. Existing explicit values win. Project-scope writes do not introduce global defaults. The tour is not exposed in standalone VS Code.
32
36
  - Reads native V2 `plugins` (strings or `{ package, options }`) with legacy `plugin`/tuple fallback. A native array, including an empty one, wins within each document. Entry mutations write only `plugins`, convert retained legacy tuples, and remove the shadowed legacy key in the touched source file. Options, ordering, unrelated configuration and JSONC comments are preserved through the shared atomic config writer; malformed entries or write failures do not replace the original file. Web, Electron and mobile use this host implementation; VS Code mirrors the same persistence contract.
33
37
  - `session-directory-runtime.js`: Host-side physical directory identity for session index/list/detail/live projection. Uses a runtime-scoped, bounded 256-entry cache (60s success / 5s failed resolution), cleared when the upstream URL changes. Local directory lists use session pages and physical-directory filtering to include legacy symlink sessions without mixing worktrees; they never request `/location` to discover project identity. Startup backfill reads one global session stream rather than one stream per project. One request reads one page and preserves opaque cursors; consumers must follow continuations even after filtered-empty pages. Non-loopback upstreams keep their own path namespace.
34
38
  - `packages/web/server/lib/opencode/index.js`: public entrypoint (currently baseline placeholder).
@@ -74,6 +78,7 @@ encoding, not removed V1 endpoints.
74
78
  - `packages/web/server/lib/opencode/project-icon-routes.js`: project icon upload/read/discovery route registration and icon storage orchestration.
75
79
  - `packages/web/server/lib/opencode/skill-routes.js`: route registration for skill config CRUD, supporting files, and skills catalog scan/install flows.
76
80
  - `packages/web/server/lib/opencode/settings-runtime.js`: Settings persistence runtime (disk IO, migrations, normalization, project validation, and persisted update serialization).
81
+ - The absence of a `projects` property identifies pre-registry settings: migrate a previously saved `lastDirectory` once, otherwise initialize `projects: []`. An explicit empty registry is authoritative and never repopulated from `lastDirectory`. Writes establish this baseline from the stored settings before merging incoming changes, so first-launch home-directory persistence cannot register `/root`, `/`, or any other home as a project or suppress the setup tour. The registry is Yuri-owned, independent of OpenCode's discovered projects.
77
82
  - Trusted resource owners can pass a functional update to `persistSettings`; it strictly reads and derives the patch inside the same Host/Electron lock, preserving concurrent writes. These callers validate their affected resource instead of sweeping unrelated offline projects. `projects/registry.js` shares project registration between the existing directory HTTP API and assistant tools; ordinary object-based settings updates retain their existing full-list validation behavior.
78
83
  - Missing theme preferences use `carbonfox-light` / `cursor-dark`, matching the shared UI defaults. Existing per-variant IDs and legacy explicitly selected theme IDs remain authoritative; changing the default does not rewrite a user's saved theme.
79
84
  - Project registry order and `projectSortOrder` are shared Host authority. After a successful changed write, `onProjectOrderChanged` emits `yuri:project-order-changed` on the existing Yuri SSE channel. Clients GET settings on initial mount, tip, and reconnect. Unchanged and failed writes emit no tip; older settings without a sort mode use `manual`.
@@ -81,6 +86,15 @@ encoding, not removed V1 endpoints.
81
86
  - `packages/web/server/lib/opencode/settings-normalization-runtime.js`: path/settings normalization and sanitization helpers runtime used by settings/routes/config wiring.
82
87
  - `packages/web/server/lib/opencode/theme-runtime.js`: custom theme JSON validation and theme directory loading runtime for settings utility routes.
83
88
  - `packages/web/server/lib/opencode/proxy.js`: OpenCode API/SSE forwarding and readiness-gate route registration.
89
+ - After the existing UI/tunnel authentication middleware, the proxy checks
90
+ browser provenance against the existing `isRequestOriginAllowed` policy.
91
+ Only approved origins have Fetch Metadata removed from the upstream copy:
92
+ those headers describe browser → Yuri, not Yuri → OpenCode. Origin, the
93
+ original request headers, Yuri credential validation and managed upstream
94
+ authentication are unchanged. Session/message reads, SSE and the generic
95
+ proxy share this rule. Missing/failed approval leaves metadata intact, so
96
+ unknown browser origins retain upstream cross-site rejection. No service
97
+ CORS configuration or origin allowlist is expanded.
84
98
  - `npm-registry.js`: plugin package lookup used by `GET /api/config/plugins/registry`. It asks the user's own `npm view` first (run in the project directory, so scope registries, auth tokens and mirrors from `.npmrc` apply as they do for `npm install`) and falls back to a direct request to the public registry only when the CLI is unavailable; a CLI 404 is final. Results are cached per name and directory. The latest release's top-level package.json `icon` is returned as `icon` only when it is an `https://` URL or `data:image/` URI of at most ~1.5 MB; nested icon fields are not read or used as fallbacks.
85
99
  - `plugin-icon.js` owns the shared icon sanitizer and optional local package metadata read for Web/Electron/mobile and VS Code. Registry `path-ok` includes the nearest package manifest's top-level `icon` for directories or built entry files. Search stops at the first manifest, root or 32 parents; malformed, unreadable or >2 MiB manifests omit artwork without changing path status. No server-side image fetch occurs. Settings → Plugins renders package artwork directly; GUI sidebar/titlebar entries use official `IconName` without package-image substitution.
86
100
 
@@ -1020,6 +1020,7 @@ export const registerAuthAndAccessRoutes = (app, dependencies) => {
1020
1020
  return res.status(429).json({ error: 'Invalid or expired pairing session' });
1021
1021
  }
1022
1022
  const result = await clientPairingRuntime.redeemPairingSession({
1023
+ viaRelay: Boolean(req.headers['x-yuri-relay-connection']),
1023
1024
  pairingId: req.body?.pairingId,
1024
1025
  secret: req.body?.secret,
1025
1026
  clientLabel: req.body?.clientLabel,
@@ -18,6 +18,7 @@ import { registerScheduledTaskToolRoute } from '../scheduled-tasks/managed-tool-
18
18
  import { registerScheduledTaskSessionSkill } from '../scheduled-tasks/session-skill.js';
19
19
  import { registerCustomizationSessionSkill } from '../gui-customization/session-skill.js';
20
20
  import { registerConversationRoutes } from '../conversations/routes.js';
21
+ import { registerHistoryImportRoutes } from '../history-import/routes.js';
21
22
  import { registerSessionTurnPageRoutes } from '../session-turn-pages/routes.js';
22
23
  import { registerAssistantRoutes } from '../assistants/routes.js';
23
24
  import { createProjectRegistry } from '../projects/registry.js';
@@ -88,10 +89,12 @@ export const createFeatureRoutesRuntime = (dependencies) => {
88
89
  };
89
90
 
90
91
  let assistantRoutesRuntime = null;
92
+ let historyImportRuntime = null;
91
93
 
92
94
  const registerRoutes = async (app, routeDependencies) => {
93
95
  const {
94
96
  express,
97
+ uiAuthController,
95
98
  crypto,
96
99
  fs,
97
100
  os,
@@ -288,6 +291,13 @@ export const createFeatureRoutesRuntime = (dependencies) => {
288
291
  };
289
292
  await refreshAssistantAllowedRoots();
290
293
  const projectRegistry = createProjectRegistry({ persistSettings, validateDirectoryPath });
294
+ historyImportRuntime = registerHistoryImportRoutes(app, {
295
+ express, uiAuthController, dataDir: yuriDataDir,
296
+ createClient: () => makeOpenCodeV2Client({ baseUrl: buildOpenCodeUrl('/', ''), authHeaders: getOpenCodeAuthHeaders(), getRuntimeContract }),
297
+ getRuntimeIdentity: () => buildOpenCodeUrl('/', ''),
298
+ registerProject: (input) => projectRegistry.register(input),
299
+ onImported: (session) => sessionIndexService?.upsert(session),
300
+ });
291
301
  const registerAssistantProject = async (input) => {
292
302
  const result = await projectRegistry.register(input);
293
303
  await refreshAssistantAllowedRoots();
@@ -539,6 +549,6 @@ export const createFeatureRoutesRuntime = (dependencies) => {
539
549
 
540
550
  return {
541
551
  registerRoutes,
542
- close: () => assistantRoutesRuntime?.close(),
552
+ close: async () => { await historyImportRuntime?.close(); await assistantRoutesRuntime?.close(); },
543
553
  };
544
554
  };
@@ -281,6 +281,7 @@ describe('opencode plugin routes', () => {
281
281
  test('POST /entry persists for V2 hot reload without restarting', async () => {
282
282
  const response = await createEntry('a');
283
283
 
284
+ expect(readJson(userConfigPath)).toEqual({ $schema: 'https://opencode.ai/config.json', lsp: true, plugins: ['a'] });
284
285
  expect(response.body).toMatchObject({ success: true, requiresReload: false, application: 'watch' });
285
286
  expect(refreshOpenCodeAfterConfigChange).not.toHaveBeenCalled();
286
287
  });
@@ -256,7 +256,7 @@ function createPluginEntry(entry, workingDirectory) {
256
256
  config = fs.existsSync(targetPath) ? readConfigFile(targetPath) : {};
257
257
  } else {
258
258
  targetPath = layers.paths.customPath || layers.paths.userPath;
259
- config = getConfigForPath(layers, targetPath);
259
+ config = { $schema: 'https://opencode.ai/config.json', lsp: true, ...getConfigForPath(layers, targetPath) };
260
260
  }
261
261
 
262
262
  writePluginArray(config, [...readPluginArray(config), serializePluginEntry({ spec, options: entry.options })], targetPath);
@@ -120,7 +120,7 @@ describe('opencode plugins data layer', () => {
120
120
  });
121
121
 
122
122
  test('converts untouched legacy options on save and preserves unrelated JSONC', () => {
123
- fs.writeFileSync(userConfigPath, '// retained comment\n' + JSON.stringify({ model: 'example/model', plugin: [['old', { nested: { enabled: false } }]] }));
123
+ fs.writeFileSync(userConfigPath, '// retained comment\n' + JSON.stringify({ model: 'example/model', lsp: false, plugin: [['old', { nested: { enabled: false } }]] }));
124
124
  plugins.createPluginEntry({ spec: 'new', scope: 'user' }, projectDir);
125
125
  const text = fs.readFileSync(userConfigPath, 'utf8');
126
126
  expect(text).toContain('// retained comment');
@@ -130,6 +130,7 @@ describe('opencode plugins data layer', () => {
130
130
  expect(text).toContain('"plugins"');
131
131
  expect(text).not.toContain('"plugin"');
132
132
  expect(text).toContain('example/model');
133
+ expect(text).toMatch(/"lsp":\s*false/);
133
134
  });
134
135
 
135
136
  test('prefers native plugins over legacy entries including an empty native array', () => {
@@ -141,7 +142,7 @@ describe('opencode plugins data layer', () => {
141
142
  writeJson(userConfigPath, { plugin: ['shadowed'], plugins: [] });
142
143
  expect(plugins.listPluginEntries(projectDir)).toEqual([]);
143
144
  plugins.createPluginEntry({ spec: 'new' }, projectDir);
144
- expect(readJson(userConfigPath)).toEqual({ plugins: ['new'] });
145
+ expect(readJson(userConfigPath)).toEqual({ $schema: 'https://opencode.ai/config.json', lsp: true, plugins: ['new'] });
145
146
  });
146
147
 
147
148
  test('malformed legacy data and failed atomic writes leave original config intact', () => {
@@ -269,6 +269,7 @@ export const registerOpenCodeProxy = (app, deps) => {
269
269
  /** Optional DI: `{ allowMissingContract: true }` for unit factories only. */
270
270
  getRuntimeContractGateOptions = null,
271
271
  getOpenCodeAuthHeaders,
272
+ isRequestOriginAllowed = null,
272
273
  buildOpenCodeUrl,
273
274
  ensureOpenCodeApiPrefix,
274
275
  onInteractiveSessionRequest,
@@ -286,6 +287,29 @@ export const registerOpenCodeProxy = (app, deps) => {
286
287
  onSessionDeleted = null,
287
288
  } = deps;
288
289
 
290
+ const approvedClientOrigins = new WeakSet();
291
+ const fetchMetadataHeaders = ['sec-fetch-site', 'sec-fetch-mode', 'sec-fetch-dest', 'sec-fetch-user'];
292
+ // UI/tunnel authentication already ran. Validate against Yuri's origin policy
293
+ // before terminating browser metadata at this server-to-server boundary.
294
+ // Unknown origins keep their metadata and remain subject to upstream rejection.
295
+ app.use('/api', async (req, _res, next) => {
296
+ if (req.headers.origin && fetchMetadataHeaders.some(name => req.headers[name]) && isRequestOriginAllowed) {
297
+ try {
298
+ if (await isRequestOriginAllowed(req)) approvedClientOrigins.add(req);
299
+ } catch {
300
+ // Failed approval never grants provenance translation.
301
+ }
302
+ }
303
+ next();
304
+ });
305
+ const forwardRequestHeaders = (req) => {
306
+ const headers = normalizeForwardedDirectoryHeaders(collectForwardProxyHeaders(req.headers, getOpenCodeAuthHeaders()));
307
+ if (approvedClientOrigins.has(req)) {
308
+ for (const name of fetchMetadataHeaders) delete headers[name];
309
+ }
310
+ return headers;
311
+ };
312
+
289
313
  const storeConfigured = typeof getStoredSessionMetadata === 'function';
290
314
  if (deps.sessionDelivery) {
291
315
  registerSessionDeliveryRoute(app, { delivery: deps.sessionDelivery, buildOpenCodeUrl, getOpenCodeAuthHeaders });
@@ -636,9 +660,7 @@ export const registerOpenCodeProxy = (app, deps) => {
636
660
  const strippedUrl = stripIncludeReasoningParam(requestUrl);
637
661
  const eventUrl = new URL(strippedUrl, 'http://yuri.invalid');
638
662
  const upstreamPath = `/api/event${eventUrl.search}`;
639
- const headers = normalizeForwardedDirectoryHeaders(
640
- collectForwardProxyHeaders(req.headers, getOpenCodeAuthHeaders())
641
- );
663
+ const headers = forwardRequestHeaders(req);
642
664
  headers.accept ??= 'text/event-stream';
643
665
  headers['cache-control'] ??= 'no-cache';
644
666
 
@@ -827,7 +849,7 @@ export const registerOpenCodeProxy = (app, deps) => {
827
849
  const fetchSessionListPayload = async (upstreamPath, { req = null, timeoutMs = null, method = 'GET' } = {}) => {
828
850
  const headers = req
829
851
  ? {
830
- ...normalizeForwardedDirectoryHeaders(collectForwardProxyHeaders(req.headers, getOpenCodeAuthHeaders())),
852
+ ...forwardRequestHeaders(req),
831
853
  accept: 'application/json',
832
854
  'accept-encoding': 'identity',
833
855
  }
@@ -1285,6 +1307,9 @@ export const registerOpenCodeProxy = (app, deps) => {
1285
1307
  router: () => resolveProxyTarget(),
1286
1308
  on: {
1287
1309
  proxyReq: (proxyReq, req) => {
1310
+ if (approvedClientOrigins.has(req)) {
1311
+ for (const name of fetchMetadataHeaders) proxyReq.removeHeader(name);
1312
+ }
1288
1313
  // Inject OpenCode auth headers
1289
1314
  const authHeaders = getOpenCodeAuthHeaders();
1290
1315
  if (authHeaders.Authorization) {