@yuriai/web 0.2.19 → 0.2.20

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 (163) hide show
  1. package/README.md +8 -0
  2. package/dist/assets/AgentAvatar-MK9jNcwx.js +1 -0
  3. package/dist/assets/AssistantView-CVf9ta92.js +3 -0
  4. package/dist/assets/{DiagramView-HNaj_sVG.js → DiagramView-ys2UVvx1.js} +1 -1
  5. package/dist/assets/{FadeInOnReveal-Dq1IuEQp.js → FadeInOnReveal-B1g8C4P7.js} +1 -1
  6. package/dist/assets/{GuiPluginSurface-N-iK-MeX.js → GuiPluginSurface-C1KQZUmj.js} +1 -1
  7. package/dist/assets/{GuiPluginWindow-ClutFX_h.js → GuiPluginWindow-D4TIvZDn.js} +1 -1
  8. package/dist/assets/{Icon-tnX3bel1.js → Icon-C93bLV0e.js} +1 -1
  9. package/dist/assets/{ImageLoadingPlaceholder-IE6JO3WM.js → ImageLoadingPlaceholder-DM2ifWd8.js} +1 -1
  10. package/dist/assets/{LoadingImage-DNZmZRZS.js → LoadingImage-BoaGSpZ_.js} +1 -1
  11. package/dist/assets/{MarkdownRenderer-DuA1vlFT.js → MarkdownRenderer-B8LWUc6A.js} +2 -2
  12. package/dist/assets/{MarkdownRendererImpl-BwZ91PA5.js → MarkdownRendererImpl-DL069I2q.js} +1 -1
  13. package/dist/assets/{MarkstreamRendererImpl-kgBwH_VF.js → MarkstreamRendererImpl-CwR_p-oQ.js} +1 -1
  14. package/dist/assets/{MobileDetailNavigation-sm5MbnK3.js → MobileDetailNavigation-C7Z7mVZV.js} +1 -1
  15. package/dist/assets/{MobileResizableSheet-Cw6rRBR2.js → MobileResizableSheet-ChrM2_er.js} +1 -1
  16. package/dist/assets/{MobileShareBridge-BjpB1cz1.js → MobileShareBridge-DtXwoQtk.js} +2 -2
  17. package/dist/assets/MobileTabPageHeader-BT7U61qi.js +2 -0
  18. package/dist/assets/{MultiRunWindow-pslncrAh.js → MultiRunWindow-CFWkmiwx.js} +1 -1
  19. package/dist/assets/{OnboardingScreen-o9e7j2Lk.js → OnboardingScreen-Bb3wmiKY.js} +1 -1
  20. package/dist/assets/{OverlayScrollbar-BA6KEyhj.js → OverlayScrollbar-DD6avzvO.js} +1 -1
  21. package/dist/assets/SettingsView-B4xkRLZ3.js +29 -0
  22. package/dist/assets/SettingsView-BRIvklfP.css +1 -0
  23. package/dist/assets/{SettingsWindow-D-Vjsme7.js → SettingsWindow-jF7nPmJG.js} +1 -1
  24. package/dist/assets/{TerminalView-B4bliT5i.js → TerminalView-Cms4rfIE.js} +1 -1
  25. package/dist/assets/{ToolOutputDialog-D1rZbaHo.js → ToolOutputDialog-CBSb39qy.js} +1 -1
  26. package/dist/assets/{YuriLogo-CDmH1ycw.js → YuriLogo-CeZsIqiE.js} +1 -1
  27. package/dist/assets/{appThemeRegistry-DyTPt9Uq.js → appThemeRegistry-Bps27som.js} +1 -1
  28. package/dist/assets/{assistant-attachment-cache-lEUFn3mr.js → assistant-attachment-cache-C2SmtQG7.js} +1 -1
  29. package/dist/assets/{button-BEOJB042.js → button--mt1oJ-H.js} +1 -1
  30. package/dist/assets/{capgoAdapter-BrU-ms8F.js → capgoAdapter-ZBPKiKyL.js} +1 -1
  31. package/dist/assets/{collapsible-DrQlDm15.js → collapsible-Dh2xZynB.js} +1 -1
  32. package/dist/assets/{desktop-dp2Z0toS.js → desktop-CiqEZVr5.js} +1 -1
  33. package/dist/assets/{desktopHosts-CYKaLp1V.js → desktopHosts-B4HMNmrx.js} +1 -1
  34. package/dist/assets/{desktopRelayRestore-5yuHB356.js → desktopRelayRestore-CRl62mqn.js} +1 -1
  35. package/dist/assets/{device-DzWRCXhq.js → device-Coc5tapU.js} +1 -1
  36. package/dist/assets/{diagram-DyQPPDKS.js → diagram-CrQbE7QP.js} +1 -1
  37. package/dist/assets/{dialog-CooVl0xA.js → dialog-BG9W4FO9.js} +1 -1
  38. package/dist/assets/{dropdown-menu.styles-Bj4YEb3T.js → dropdown-menu.styles-BOP49Dw2.js} +1 -1
  39. package/dist/assets/es-CuWYQYZ1.js +15 -0
  40. package/dist/assets/{fileMentionTouchSelection-8I9u8H6l.js → fileMentionTouchSelection-m4Xsn0cx.js} +1 -1
  41. package/dist/assets/{fileQueries-DbUx7NwP.js → fileQueries-Bd-OEFmO.js} +1 -1
  42. package/dist/assets/{fileReferenceActions-No7p4Kdo.js → fileReferenceActions-BnPPqYXw.js} +1 -1
  43. package/dist/assets/fr-yebDRPGw.js +13 -0
  44. package/dist/assets/{gitApi-BVMvxPtG.js → gitApi-C1pkEDXu.js} +1 -1
  45. package/dist/assets/{gitApiHttp-BtI23x-7.js → gitApiHttp-CoNokuDM.js} +1 -1
  46. package/dist/assets/{gui-BCPFcL_m.js → gui-D3wrcUs6.js} +1 -1
  47. package/dist/assets/{host-BoCxB_x4.js → host-BqNFap4A.js} +1 -1
  48. package/dist/assets/{image-loading-FUFYiO1j.js → image-loading-DVZlFuU5.js} +1 -1
  49. package/dist/assets/{input-B-4VixoV.js → input-BMUm4I0i.js} +1 -1
  50. package/dist/assets/{insertionBoundaries-YVc2e3H2.js → insertionBoundaries-WLpirs0A.js} +1 -1
  51. package/dist/assets/ja-f1wDEfxS.js +15 -0
  52. package/dist/assets/ko-n8CMb8k9.js +15 -0
  53. package/dist/assets/{main-Cs5VJerX.js → main-CNmq04w8.js} +21 -21
  54. package/dist/assets/{main-DZ5HVH-j.js → main-djohnOii.js} +2 -2
  55. package/dist/assets/{markdownHeightCache-SdaL8x58.js → markdownHeightCache-BWrnxGTO.js} +1 -1
  56. package/dist/assets/{mcpQueries-B1ZULr7c.js → mcpQueries-BfSiXImW.js} +1 -1
  57. package/dist/assets/miniChat-DXN8mcdi.js +2 -0
  58. package/dist/assets/mobile--08sYbKy.js +2 -0
  59. package/dist/assets/{mobileBackNavigation-D-cRdrKd.js → mobileBackNavigation-EIV61ZvG.js} +1 -1
  60. package/dist/assets/{multirun-D6bNScic.js → multirun-Dfuqt2Sd.js} +1 -1
  61. package/dist/assets/{native-config-obwt8WA1.js → native-config-Cswl9jqU.js} +1 -1
  62. package/dist/assets/{persistence-BfjCXjLZ.js → persistence-CNEHspb4.js} +1 -1
  63. package/dist/assets/pl-BpveZ1bR.js +15 -0
  64. package/dist/assets/{platform-syRnKuVU.js → platform-Q45KPuGv.js} +1 -1
  65. package/dist/assets/{projectMeta-LtQkG8fN.js → projectMeta-CuVxfoYb.js} +1 -1
  66. package/dist/assets/pt-BR-bq37AHb6.js +15 -0
  67. package/dist/assets/{queryRuntime-BuRnpVtK.js → queryRuntime-DWgXfxGx.js} +1 -1
  68. package/dist/assets/{readiness-BWBtf7Am.js → readiness-DDF6yf-o.js} +1 -1
  69. package/dist/assets/{renderElectronMiniChatApp-EL2J2wQd.js → renderElectronMiniChatApp-Cfs2xjgL.js} +2 -2
  70. package/dist/assets/{renderMobileApp-DOCWKmuC.js → renderMobileApp-B66uW5zc.js} +7 -7
  71. package/dist/assets/runtime-auth-BaBM02zI.js +1 -0
  72. package/dist/assets/{runtime-fetch-BAN5Gnnp.js → runtime-fetch-DfALP7-b.js} +1 -1
  73. package/dist/assets/{runtime-file-download-BzblfnMx.js → runtime-file-download-xvItwYMc.js} +1 -1
  74. package/dist/assets/{runtime-file-resource-D3k0hKDj.js → runtime-file-resource-DtsKbFf3.js} +1 -1
  75. package/dist/assets/{runtime-switch-CAZiOV2G.js → runtime-switch-DhMY9eiB.js} +1 -1
  76. package/dist/assets/{runtimeConfig-D577Rc9x.js → runtimeConfig-DTkP4z43.js} +1 -1
  77. package/dist/assets/runtimeEndpointReset-BMAP5ZCY.js +149 -0
  78. package/dist/assets/{scheduledTaskNavigation-CJEzv5Zr.js → scheduledTaskNavigation-7slq1geN.js} +1 -1
  79. package/dist/assets/{sessionChangeSummary-DAV313F8.js → sessionChangeSummary-BYv_KUyn.js} +1 -1
  80. package/dist/assets/{sessionLookup-CN_iYfk5.js → sessionLookup-Cx0pE6yS.js} +1 -1
  81. package/dist/assets/{sortable-tabs-strip-9okrTn1K.js → sortable-tabs-strip-D_efLXen.js} +1 -1
  82. package/dist/assets/{speechSettingsQueries-BvJCYdR_.js → speechSettingsQueries-BxHtdoOT.js} +2 -2
  83. package/dist/assets/src-DHHaXffU.css +2 -0
  84. package/dist/assets/store-CKBj6kYd.js +15 -0
  85. package/dist/assets/{terminalApi-Dw1h9m3h.js → terminalApi-DFhCeMya.js} +1 -1
  86. package/dist/assets/{textarea-9sBs8Uld.js → textarea-CNvFHvhC.js} +1 -1
  87. package/dist/assets/{tooltip-BkcQKx-p.js → tooltip-C-gdI2Am.js} +1 -1
  88. package/dist/assets/{types-BcumvHrl.js → types-BHKyslK4.js} +1 -1
  89. package/dist/assets/uk-Ds3imyqV.js +15 -0
  90. package/dist/assets/{useAppFontEffects-D9c0mG1P.js → useAppFontEffects-Ucq0gPN8.js} +9 -9
  91. package/dist/assets/{useAssistantUIStore-rdsbsVts.js → useAssistantUIStore-BZt-lLlW.js} +1 -1
  92. package/dist/assets/{useDesktopWindowControlsLayout-Dx-zWLPl.js → useDesktopWindowControlsLayout-BEscodj1.js} +1 -1
  93. package/dist/assets/{useEffectiveDirectory-DPvKdopQ.js → useEffectiveDirectory-BWRQNoDF.js} +1 -1
  94. package/dist/assets/{useFontPreferences-B4LGrKaG.js → useFontPreferences-DmeLn0t9.js} +1 -1
  95. package/dist/assets/{useMobileNavigationStore-9pGm6Lkc.js → useMobileNavigationStore-DzkVc9H_.js} +12 -11
  96. package/dist/assets/{useUIStore-NMQx_cnG.js → useUIStore-CEingF2z.js} +1 -1
  97. package/dist/assets/{useWorkerHighlightedLines-DSzghYUI.js → useWorkerHighlightedLines-Dz6lLZ-1.js} +1 -1
  98. package/dist/assets/zh-CN-BNJ3ElZ9.js +15 -0
  99. package/dist/assets/{zh-TW-CtLsIcFb.js → zh-TW-C0jQloeH.js} +2 -2
  100. package/dist/index.html +21 -21
  101. package/dist/mini-chat.html +21 -21
  102. package/dist/mobile.html +21 -21
  103. package/package.json +1 -1
  104. package/server/lib/assistants/DOCUMENTATION.md +192 -20
  105. package/server/lib/assistants/assign.js +2 -1
  106. package/server/lib/assistants/contact-store.js +151 -17
  107. package/server/lib/assistants/contact-store.test.js +44 -2
  108. package/server/lib/assistants/contact-tools.js +54 -12
  109. package/server/lib/assistants/contact-tools.test.js +21 -0
  110. package/server/lib/assistants/harness.js +39 -16
  111. package/server/lib/assistants/harness.test.js +58 -18
  112. package/server/lib/assistants/opencode-tools.js +167 -0
  113. package/server/lib/assistants/opencode-tools.test.js +295 -0
  114. package/server/lib/assistants/progressive-tools.js +33 -0
  115. package/server/lib/assistants/progressive-tools.test.js +66 -0
  116. package/server/lib/assistants/routes.js +1 -0
  117. package/server/lib/assistants/service.js +87 -40
  118. package/server/lib/assistants/service.test.js +270 -40
  119. package/server/lib/assistants/summary.js +90 -0
  120. package/server/lib/assistants/summary.test.js +86 -0
  121. package/server/lib/assistants/yuri-project.http.test.js +126 -0
  122. package/server/lib/assistants/yuri-tools.js +42 -0
  123. package/server/lib/assistants/yuri-tools.test.js +151 -0
  124. package/server/lib/llm/DOCUMENTATION.md +12 -2
  125. package/server/lib/llm/bridge-client.js +65 -16
  126. package/server/lib/llm/bridge-client.test.js +63 -2
  127. package/server/lib/opencode/DOCUMENTATION.md +2 -0
  128. package/server/lib/opencode/feature-routes-runtime.js +9 -0
  129. package/server/lib/opencode/feature-routes-runtime.test.js +12 -0
  130. package/server/lib/opencode/npm-registry.js +106 -11
  131. package/server/lib/opencode/npm-registry.test.js +64 -0
  132. package/server/lib/opencode/plugin-routes.js +3 -1
  133. package/server/lib/opencode/plugin-routes.test.js +3 -3
  134. package/server/lib/opencode/routes.js +4 -32
  135. package/server/lib/opencode/settings-runtime.js +7 -2
  136. package/server/lib/projects/DOCUMENTATION.md +29 -0
  137. package/server/lib/projects/registry.js +36 -0
  138. package/server/lib/projects/registry.test.js +107 -0
  139. package/server/lib/quota/providers/index.js +6 -2
  140. package/server/lib/quota/providers/index.test.js +6 -1
  141. package/server/lib/relay/DOCUMENTATION.md +3 -3
  142. package/server/lib/relay/host-client.js +4 -6
  143. package/server/lib/relay/host-client.reconnect.test.js +3 -2
  144. package/server/lib/relay/relay-server.e2e.test.ts +144 -1
  145. package/server/lib/small-model/DOCUMENTATION.md +2 -1
  146. package/dist/assets/AgentAvatar-CVIpaYPU.js +0 -1
  147. package/dist/assets/AssistantView-D5vJW3gp.js +0 -3
  148. package/dist/assets/MobileTabPageHeader-CEsc9PYV.js +0 -2
  149. package/dist/assets/SettingsView-20rmUHhk.js +0 -26
  150. package/dist/assets/es-DklBd0ox.js +0 -15
  151. package/dist/assets/fr-CVUs46wM.js +0 -13
  152. package/dist/assets/ja-5reg09JK.js +0 -15
  153. package/dist/assets/ko-DZdC6ooz.js +0 -15
  154. package/dist/assets/miniChat-DUSGfEUO.js +0 -2
  155. package/dist/assets/mobile-CMXtTX1x.js +0 -2
  156. package/dist/assets/pl-BerZSK-a.js +0 -15
  157. package/dist/assets/pt-BR-ydmV6U49.js +0 -15
  158. package/dist/assets/runtime-auth-ef9W7A43.js +0 -1
  159. package/dist/assets/runtimeEndpointReset-C5EiiaQf.js +0 -149
  160. package/dist/assets/src-nJdn6EvY.css +0 -2
  161. package/dist/assets/store-ClIuNNU7.js +0 -15
  162. package/dist/assets/uk-BnTevguX.js +0 -15
  163. package/dist/assets/zh-CN-DT6qIAPJ.js +0 -15
@@ -1,3 +1,4 @@
1
+ import { execFile } from 'child_process';
1
2
  import fs from 'fs';
2
3
  import path from 'path';
3
4
  import { fileURLToPath } from 'url';
@@ -12,6 +13,7 @@ const NPM_REGISTRY_BASE = 'https://registry.npmjs.org';
12
13
  * @property {string|null} latest
13
14
  * @property {string[]} versions
14
15
  * @property {Record<string, string>} distTags
16
+ * @property {string} [icon] sanitized `magpie.icon` of the latest release
15
17
  *
16
18
  * @typedef {Object} NpmLookupError
17
19
  * @property {false} ok
@@ -79,13 +81,101 @@ function cacheResult(name, payload) {
79
81
  }
80
82
  }
81
83
 
84
+ const NPM_ICON_MAX_LENGTH = 3 << 19;
85
+
86
+ /**
87
+ * A package's own picture, as magpie reads `magpie.icon` from package.json:
88
+ * an https URL or a data:image URI, at most ~1.5 MB. Anything else is dropped.
89
+ * Nothing is fetched here; the client renders it as an image.
90
+ *
91
+ * @param {unknown} value
92
+ * @returns {string | undefined}
93
+ */
94
+ export function sanitizePluginIcon(value) {
95
+ const icon = typeof value === 'string' ? value.trim() : '';
96
+ return icon.length > 0 && icon.length <= NPM_ICON_MAX_LENGTH && /^(https:\/\/|data:image\/)/i.test(icon)
97
+ ? icon
98
+ : undefined;
99
+ }
100
+
101
+ const VALID_NPM_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;
102
+ const NPM_CLI_TIMEOUT_MS = 15_000;
103
+
104
+ /**
105
+ * Ask the user's own npm CLI. It resolves `.npmrc` (per-scope `@scope:registry`,
106
+ * auth tokens, mirrors, proxies) exactly as `npm install` would, which a bare
107
+ * request to registry.npmjs.org cannot do for private or mirrored scopes.
108
+ *
109
+ * Resolves to `null` when the CLI is unavailable or fails for a reason other than
110
+ * the package being absent, so the caller can fall back to a direct request.
111
+ *
112
+ * @param {string} name npm package name
113
+ * @param {string | undefined} cwd directory whose `.npmrc` applies
114
+ * @returns {Promise<NpmLookupResult | null>}
115
+ */
116
+ function lookupViaNpmCli(name, cwd) {
117
+ if (!VALID_NPM_NAME.test(name)) return Promise.resolve(null);
118
+ return new Promise((resolve) => {
119
+ execFile(
120
+ process.platform === 'win32' ? 'npm.cmd' : 'npm',
121
+ ['view', name, 'dist-tags', 'versions', 'magpie.icon', '--json'],
122
+ {
123
+ cwd: cwd || undefined,
124
+ timeout: NPM_CLI_TIMEOUT_MS,
125
+ windowsHide: true,
126
+ maxBuffer: 16 * 1024 * 1024,
127
+ shell: process.platform === 'win32',
128
+ },
129
+ (error, stdout, stderr) => {
130
+ if (error) {
131
+ const output = `${stdout}\n${stderr}`;
132
+ if (/\bE404\b|404 Not Found/i.test(output)) {
133
+ resolve({ ok: false, status: 404, error: 'Package not found' });
134
+ return;
135
+ }
136
+ resolve(null);
137
+ return;
138
+ }
139
+ try {
140
+ const data = JSON.parse(stdout);
141
+ const distTags = parseDistTags(data?.['dist-tags']);
142
+ const versions = Array.isArray(data?.versions)
143
+ ? data.versions.filter((version) => typeof version === 'string')
144
+ : typeof data?.versions === 'string' ? [data.versions] : [];
145
+ const icon = sanitizePluginIcon(data?.['magpie.icon'] ?? data?.magpie?.icon);
146
+ resolve({ ok: true, latest: distTags.latest ?? null, versions, distTags, ...(icon ? { icon } : {}) });
147
+ } catch {
148
+ resolve(null);
149
+ }
150
+ },
151
+ );
152
+ });
153
+ }
154
+
155
+ /** Seam so tests can isolate the direct-request path from the developer's npm. */
156
+ export const npmCli = { lookup: lookupViaNpmCli };
157
+
158
+ /**
159
+ * Fetch package metadata: the npm CLI first (honours scope registries and auth),
160
+ * then a direct request to the public registry when the CLI cannot answer.
161
+ *
162
+ * @param {string} name npm package name
163
+ * @param {{ cwd?: string }} [options]
164
+ * @returns {Promise<NpmLookupResult>}
165
+ */
166
+ export async function lookupNpmPackage(name, options = {}) {
167
+ const viaCli = await npmCli.lookup(name, options.cwd);
168
+ if (viaCli) return viaCli;
169
+ return lookupNpmPackageOverHttp(name);
170
+ }
171
+
82
172
  /**
83
- * Fetch package metadata directly from the npm registry.
173
+ * Fetch package metadata directly from the public npm registry.
84
174
  *
85
175
  * @param {string} name npm package name
86
176
  * @returns {Promise<NpmLookupResult>}
87
177
  */
88
- export async function lookupNpmPackage(name) {
178
+ async function lookupNpmPackageOverHttp(name) {
89
179
  try {
90
180
  const response = await fetch(`${NPM_REGISTRY_BASE}/${encodeName(name)}`, {
91
181
  headers: {
@@ -98,11 +188,14 @@ export async function lookupNpmPackage(name) {
98
188
  if (response.ok) {
99
189
  const data = await response.json();
100
190
  const distTags = parseDistTags(data?.['dist-tags']);
191
+ const latest = distTags.latest ?? null;
192
+ const icon = sanitizePluginIcon(latest ? data?.versions?.[latest]?.magpie?.icon : undefined);
101
193
  return {
102
194
  ok: true,
103
- latest: distTags.latest ?? null,
195
+ latest,
104
196
  versions: parseVersions(data?.versions),
105
197
  distTags,
198
+ ...(icon ? { icon } : {}),
106
199
  };
107
200
  }
108
201
 
@@ -124,29 +217,31 @@ export async function lookupNpmPackage(name) {
124
217
  * @returns {Promise<NpmLookupResult>}
125
218
  */
126
219
  export async function getNpmInfo(name, options = {}) {
127
- const { forceRefresh = false } = options;
128
- const cached = _cache.get(name);
220
+ const { forceRefresh = false, cwd } = options;
221
+ // The cwd selects which `.npmrc` applies, so it is part of the cache identity.
222
+ const cacheKey = cwd ? `${cwd}\0${name}` : name;
223
+ const cached = _cache.get(cacheKey);
129
224
  if (cached && !forceRefresh && Date.now() - cached.fetchedAt < NPM_CACHE_TTL_MS) {
130
225
  return cached.payload;
131
226
  }
132
227
 
133
- const existing = _inFlight.get(name);
228
+ const existing = _inFlight.get(cacheKey);
134
229
  if (existing && !forceRefresh) {
135
230
  return existing;
136
231
  }
137
232
 
138
233
  const lookup = (async () => {
139
- const result = await lookupNpmPackage(name);
140
- cacheResult(name, result);
234
+ const result = await lookupNpmPackage(name, { cwd });
235
+ cacheResult(cacheKey, result);
141
236
  return result;
142
237
  })();
143
238
 
144
- _inFlight.set(name, lookup);
239
+ _inFlight.set(cacheKey, lookup);
145
240
  try {
146
241
  return await lookup;
147
242
  } finally {
148
- if (_inFlight.get(name) === lookup) {
149
- _inFlight.delete(name);
243
+ if (_inFlight.get(cacheKey) === lookup) {
244
+ _inFlight.delete(cacheKey);
150
245
  }
151
246
  }
152
247
  }
@@ -13,18 +13,54 @@ function jsonResponse(body, status = 200) {
13
13
  }));
14
14
  }
15
15
 
16
+ const originalCliLookup = npm.npmCli.lookup;
17
+
16
18
  describe('npm registry client', () => {
17
19
  beforeEach(() => {
18
20
  npm.clearCache();
19
21
  Date.now = originalDateNow;
20
22
  fetchMock = mock(() => jsonResponse({}));
21
23
  globalThis.fetch = fetchMock;
24
+ npm.npmCli.lookup = async () => null;
22
25
  });
23
26
 
24
27
  afterEach(() => {
25
28
  npm.clearCache();
26
29
  globalThis.fetch = originalFetch;
27
30
  Date.now = originalDateNow;
31
+ npm.npmCli.lookup = originalCliLookup;
32
+ });
33
+
34
+ test('npm CLI answer wins and skips the direct request (scope registries/auth)', async () => {
35
+ npm.npmCli.lookup = async () => ({ ok: true, latest: '2.0.0', versions: ['1.0.0', '2.0.0'], distTags: { latest: '2.0.0' } });
36
+
37
+ const result = await npm.lookupNpmPackage('@private/pkg', { cwd: '/proj' });
38
+
39
+ expect(result).toMatchObject({ ok: true, latest: '2.0.0' });
40
+ expect(fetchMock).not.toHaveBeenCalled();
41
+ });
42
+
43
+ test('CLI 404 is definitive and not retried over HTTP', async () => {
44
+ npm.npmCli.lookup = async () => ({ ok: false, status: 404, error: 'Package not found' });
45
+
46
+ const result = await npm.lookupNpmPackage('@private/missing');
47
+
48
+ expect(result).toMatchObject({ ok: false, status: 404 });
49
+ expect(fetchMock).not.toHaveBeenCalled();
50
+ });
51
+
52
+ test('cache is separated by cwd because .npmrc differs per project', async () => {
53
+ let calls = 0;
54
+ npm.npmCli.lookup = async () => {
55
+ calls += 1;
56
+ return { ok: true, latest: '1.0.0', versions: ['1.0.0'], distTags: { latest: '1.0.0' } };
57
+ };
58
+
59
+ await npm.getNpmInfo('foo', { cwd: '/a' });
60
+ await npm.getNpmInfo('foo', { cwd: '/b' });
61
+ await npm.getNpmInfo('foo', { cwd: '/a' });
62
+
63
+ expect(calls).toBe(2);
28
64
  });
29
65
 
30
66
  test('200 success returns latest versions and dist tags', async () => {
@@ -176,4 +212,32 @@ describe('npm registry client', () => {
176
212
 
177
213
  expect(fetchMock.mock.calls[0][1].headers['User-Agent']).toMatch(/^yuri-server\//);
178
214
  });
215
+ test('npm CLI answer carries a vetted magpie.icon', async () => {
216
+ npm.npmCli.lookup = async () => ({ ok: true, latest: '1.0.0', versions: ['1.0.0'], distTags: { latest: '1.0.0' }, icon: 'https://cdn.example/a.png' });
217
+
218
+ const result = await npm.getNpmInfo('@scope/pkg', { cwd: '/proj' });
219
+
220
+ expect(result.icon).toBe('https://cdn.example/a.png');
221
+ });
222
+
223
+ test('registry fallback reads magpie.icon from the latest release', async () => {
224
+ fetchMock.mockImplementation(() => jsonResponse({
225
+ 'dist-tags': { latest: '1.0.0' },
226
+ versions: { '1.0.0': { magpie: { icon: 'data:image/svg+xml;base64,AAAA' } } },
227
+ }));
228
+
229
+ const result = await npm.lookupNpmPackage('foo');
230
+
231
+ expect(result.icon).toBe('data:image/svg+xml;base64,AAAA');
232
+ });
233
+
234
+ test('sanitizePluginIcon keeps only https and data:image, within the size cap', () => {
235
+ expect(npm.sanitizePluginIcon('https://x/y.png')).toBe('https://x/y.png');
236
+ expect(npm.sanitizePluginIcon(' data:image/png;base64,AA ')).toBe('data:image/png;base64,AA');
237
+ expect(npm.sanitizePluginIcon('http://x/y.png')).toBeUndefined();
238
+ expect(npm.sanitizePluginIcon('javascript:alert(1)')).toBeUndefined();
239
+ expect(npm.sanitizePluginIcon('data:text/html;base64,AA')).toBeUndefined();
240
+ expect(npm.sanitizePluginIcon(42)).toBeUndefined();
241
+ expect(npm.sanitizePluginIcon(`https://x/${'a'.repeat(3 << 19)}`)).toBeUndefined();
242
+ });
179
243
  });
@@ -149,7 +149,7 @@ export const registerPluginRoutes = (app, dependencies) => {
149
149
 
150
150
  const npmInfoByName = new Map();
151
151
  await Promise.all(Array.from(npmJobs.keys()).map(async (name) => {
152
- npmInfoByName.set(name, await getNpmInfo(name, { forceRefresh: refresh }));
152
+ npmInfoByName.set(name, await getNpmInfo(name, { forceRefresh: refresh, cwd: directory || undefined }));
153
153
  }));
154
154
 
155
155
  const results = [];
@@ -198,6 +198,7 @@ export const registerPluginRoutes = (app, dependencies) => {
198
198
  currentVersion,
199
199
  latestVersion: info.latest,
200
200
  versions: info.versions,
201
+ ...(info.icon ? { icon: info.icon } : {}),
201
202
  });
202
203
  continue;
203
204
  }
@@ -210,6 +211,7 @@ export const registerPluginRoutes = (app, dependencies) => {
210
211
  latestVersion: info.latest,
211
212
  versions: info.versions,
212
213
  hasUpdate: currentVersion !== null && isExactSemver(currentVersion) && currentVersion !== info.latest,
214
+ ...(info.icon ? { icon: info.icon } : {}),
213
215
  });
214
216
  }
215
217
 
@@ -219,7 +219,7 @@ describe('opencode plugin routes', () => {
219
219
  await request(app).get('/api/config/plugins/registry?specs=foo@1,foo@2,foo@3').expect(200);
220
220
 
221
221
  expect(getNpmInfo).toHaveBeenCalledTimes(1);
222
- expect(getNpmInfo).toHaveBeenCalledWith('foo', { forceRefresh: false });
222
+ expect(getNpmInfo).toHaveBeenCalledWith('foo', { forceRefresh: false, cwd: expect.any(String) });
223
223
  });
224
224
 
225
225
  test('GET /registry forwards refresh true to npm lookup', async () => {
@@ -228,7 +228,7 @@ describe('opencode plugin routes', () => {
228
228
 
229
229
  await request(app).get('/api/config/plugins/registry?specs=foo&refresh=true').expect(200);
230
230
 
231
- expect(getNpmInfo).toHaveBeenCalledWith('foo', { forceRefresh: true });
231
+ expect(getNpmInfo).toHaveBeenCalledWith('foo', { forceRefresh: true, cwd: expect.any(String) });
232
232
  });
233
233
 
234
234
  test('GET /registry rejects more than 100 unique specs', async () => {
@@ -261,7 +261,7 @@ describe('opencode plugin routes', () => {
261
261
 
262
262
  const response = await request(app).get('/api/config/plugins/registry?specs=%40scope%2Ffoo%401.0.0').expect(200);
263
263
 
264
- expect(getNpmInfo).toHaveBeenCalledWith('@scope/foo', { forceRefresh: false });
264
+ expect(getNpmInfo).toHaveBeenCalledWith('@scope/foo', { forceRefresh: false, cwd: expect.any(String) });
265
265
  expect(response.body.results[0]).toMatchObject({ kind: 'npm-ok', spec: '@scope/foo@1.0.0', name: '@scope/foo' });
266
266
  });
267
267
 
@@ -1,4 +1,4 @@
1
- import { createProjectIdFromPath } from '../projects/project-id.js';
1
+ import { createProjectRegistry } from '../projects/registry.js';
2
2
  import { projectBootstrapSettingsResponse } from './settings-helpers.js';
3
3
  import {
4
4
  evaluateOpenCodeHealthBody,
@@ -33,7 +33,6 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
33
33
  readSettingsFromDisk,
34
34
  readSettingsFromDiskMigrated,
35
35
  persistSettings,
36
- sanitizeProjects,
37
36
  validateDirectoryPath,
38
37
  resolveProjectDirectory,
39
38
  getProviderSources,
@@ -801,43 +800,16 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
801
800
  return res.status(400).json({ error: 'Path is required' });
802
801
  }
803
802
 
804
- const validated = await validateDirectoryPath(requestedPath);
805
- if (!validated.ok) {
806
- return res.status(400).json({ error: validated.error });
807
- }
808
-
809
- const resolvedPath = validated.directory;
810
- const currentSettings = await readSettingsFromDisk();
811
- const existingProjects = sanitizeProjects(currentSettings.projects) || [];
812
- const existing = existingProjects.find((project) => project.path === resolvedPath) || null;
813
-
814
- const nextProjects = existing
815
- ? existingProjects
816
- : [
817
- ...existingProjects,
818
- {
819
- id: createProjectIdFromPath(resolvedPath),
820
- path: resolvedPath,
821
- addedAt: Date.now(),
822
- lastOpenedAt: Date.now(),
823
- },
824
- ];
825
-
826
- const activeProjectId = existing ? existing.id : nextProjects[nextProjects.length - 1].id;
827
-
828
- const updated = await persistSettings({
829
- projects: nextProjects,
830
- activeProjectId,
831
- lastDirectory: resolvedPath,
832
- });
803
+ const { project, settings: updated } = await createProjectRegistry({ persistSettings, validateDirectoryPath }).register({ path: requestedPath, activate: true });
833
804
 
834
805
  return res.json({
835
806
  success: true,
836
807
  restarted: false,
837
- path: resolvedPath,
808
+ path: project.path,
838
809
  settings: updated,
839
810
  });
840
811
  } catch (error) {
812
+ if (error?.code === 'validation_error') return res.status(400).json({ error: error.message });
841
813
  console.error('Failed to update OpenCode working directory:', error);
842
814
  return res.status(500).json({ error: error.message || 'Failed to update working directory' });
843
815
  }
@@ -851,10 +851,15 @@ export const createSettingsRuntime = (deps) => {
851
851
  };
852
852
 
853
853
  const persistSettings = async (changes) => runPersistedWrite(async () => {
854
+ const updateCurrent = typeof changes === 'function';
855
+ const current = updateCurrent
856
+ ? await readSettingsFromDiskStrict()
857
+ : await readSettingsFromDisk();
858
+ if (updateCurrent && Array.isArray(current)) throw new Error('Settings file is malformed (array payload)');
859
+ if (typeof changes === 'function') changes = await changes(current);
854
860
  // Log field names only — changes can carry credentials (UI password,
855
861
  // client tokens) that must never reach the log file.
856
862
  console.log('[persistSettings] Updating fields:', Object.keys(changes || {}).join(', ') || '(none)');
857
- const current = await readSettingsFromDisk();
858
863
  const sanitized = sanitizeSettingsUpdate(changes);
859
864
  let next = mergePersistedSettings(current, sanitized);
860
865
 
@@ -882,7 +887,7 @@ export const createSettingsRuntime = (deps) => {
882
887
  // Validating project paths hits the filesystem for every entry, so only
883
888
  // do it when the incoming update actually touches the projects list —
884
889
  // not on every theme/window-state/etc. save.
885
- if (Object.prototype.hasOwnProperty.call(sanitized, 'projects') && Array.isArray(next.projects)) {
890
+ if (!updateCurrent && Object.prototype.hasOwnProperty.call(sanitized, 'projects') && Array.isArray(next.projects)) {
886
891
  const validated = await validateProjectEntries(next.projects);
887
892
  next = { ...next, projects: validated };
888
893
  }
@@ -0,0 +1,29 @@
1
+ # Projects
2
+
3
+ `registry.js` owns registering existing directories. It reuses `validateDirectoryPath`, deterministic
4
+ path-derived IDs and the settings runtime's serialized persistence. The existing
5
+ `POST /api/opencode/directory` API and assistant business tools share this owner.
6
+ The HTTP API still selects the active directory; assistant registration does not
7
+ change an existing active selection. The first registered project becomes active
8
+ through the existing settings invariant.
9
+
10
+ Registration is not filesystem creation or cloning. Those operations must finish
11
+ before registration. Paths are validated and canonicalized before deduplication.
12
+ Concurrent registrations apply against the latest settings under the existing
13
+ Host/Electron exclusive write lock, preserving unrelated settings and projects
14
+ (including temporarily unavailable directories). Existing IDs, ordering, custom
15
+ labels and metadata survive repeat registration. It does not add project label-edit
16
+ or removal APIs, and never deletes files, sessions or task storage.
17
+
18
+ Trusted registry operations use the settings owner's functional update form.
19
+ It performs a strict read inside the same persistence lock and follows the normal
20
+ normalization, migration, atomic write and project-order SSE notification paths.
21
+ Unlike full-list UI replacement, this form does not sweep other projects for
22
+ missing directories: callers validate the affected resource. Corrupt reads and
23
+ failed writes are errors, not empty state or successful registration. No new
24
+ database, settings file, HTTP mutation surface or client sync protocol is added.
25
+
26
+ `registry.test.js` covers canonical alias deduplication, concurrent append/settings
27
+ writes, persistence, offline-project retention, corrupt
28
+ reads and failed-write preservation. Assistant HTTP integration is covered in
29
+ `../assistants/yuri-project.http.test.js`.
@@ -0,0 +1,36 @@
1
+ import { createProjectIdFromPath } from './project-id.js';
2
+
3
+ const fail = (code, message) => { throw Object.assign(new Error(message), { code }); };
4
+ const string = (value, field, max = 4096) => {
5
+ if (typeof value !== 'string' || !value.trim() || value.trim().length > max) {
6
+ fail('validation_error', `${field} must be a nonempty string (maximum ${max} characters).`);
7
+ }
8
+ return value.trim();
9
+ };
10
+
11
+ // Registry mutations share the settings owner's exclusive read/modify/write path.
12
+ export const createProjectRegistry = ({ persistSettings, validateDirectoryPath }) => {
13
+ const register = async (input = {}) => {
14
+ const validated = await validateDirectoryPath(string(input.path, 'path'));
15
+ if (!validated.ok) fail('validation_error', validated.error || 'Project directory is unavailable.');
16
+ const directory = validated.directory;
17
+ const label = input.label === undefined ? undefined : string(input.label, 'label', 80);
18
+ let project;
19
+ let created = false;
20
+ const settings = await persistSettings((current) => {
21
+ const projects = Array.isArray(current.projects) ? current.projects : [];
22
+ const existing = projects.find((entry) => entry.path === directory);
23
+ created = !existing;
24
+ project = existing || { id: createProjectIdFromPath(directory), path: directory, addedAt: Date.now(), lastOpenedAt: Date.now(), ...(label ? { label } : {}) };
25
+ return {
26
+ projects: created ? [...projects, project] : projects,
27
+ ...(input.activate === true ? { activeProjectId: project.id, lastDirectory: directory } : {}),
28
+ };
29
+ });
30
+ const saved = settings.projects?.find((entry) => entry.id === project.id);
31
+ if (!saved) fail('project_unavailable', 'The directory disappeared before the project could be registered. No session was opened.');
32
+ return { project: saved, created, settings };
33
+ };
34
+
35
+ return { register };
36
+ };
@@ -0,0 +1,107 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { describe, expect, it, vi } from 'vitest';
6
+ import { createSettingsRuntime } from '../opencode/settings-runtime.js';
7
+ import { createSettingsNormalizationRuntime } from '../opencode/settings-normalization-runtime.js';
8
+ import { createProjectDirectoryRuntime } from '../opencode/project-directory-runtime.js';
9
+ import { createProjectRegistry } from './registry.js';
10
+
11
+ const setup = async () => {
12
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-registry-'));
13
+ const settingsPath = path.join(directory, 'settings.json');
14
+ const tips = vi.fn();
15
+ let failWrites = false;
16
+ const normalization = createSettingsNormalizationRuntime({ os, path, processLike: process });
17
+ const runtime = createSettingsRuntime({
18
+ fsPromises: { ...fs, rename: (...args) => failWrites ? Promise.reject(new Error('write failed')) : fs.rename(...args) },
19
+ path, crypto, SETTINGS_FILE_PATH: settingsPath, ...normalization,
20
+ sanitizeSettingsUpdate: (patch) => patch,
21
+ mergePersistedSettings: (current, patch) => ({ ...current, ...patch }),
22
+ formatSettingsResponse: (settings) => settings,
23
+ resolveDirectoryCandidate: (value) => value,
24
+ onProjectOrderChanged: tips,
25
+ });
26
+ const { validateDirectoryPath } = createProjectDirectoryRuntime({
27
+ fsPromises: fs, path, normalizeDirectoryPath: normalization.normalizeDirectoryPath,
28
+ });
29
+ const registry = createProjectRegistry({ persistSettings: runtime.persistSettings, validateDirectoryPath });
30
+ const workspace = path.join(directory, 'workspace');
31
+ await fs.mkdir(workspace);
32
+ return { directory, settingsPath, workspace, registry, runtime, tips,
33
+ failWrites: () => { failWrites = true; },
34
+ cleanup: () => fs.rm(directory, { recursive: true, force: true }),
35
+ };
36
+ };
37
+
38
+ describe('shared project registry owner', () => {
39
+ it('registers and deduplicates canonical aliases without deleting files', async () => {
40
+ const app = await setup();
41
+ try {
42
+ const first = await app.registry.register({ path: app.workspace, label: 'App' });
43
+ const alias = path.join(app.directory, 'alias');
44
+ await fs.symlink(app.workspace, alias);
45
+ const second = await app.registry.register({ path: alias });
46
+ expect(first.created).toBe(true);
47
+ expect(second).toMatchObject({ created: false, project: { id: first.project.id, label: 'App' } });
48
+ expect((await app.runtime.readSettingsFromDiskStrict()).projects).toHaveLength(1);
49
+ expect(app.tips).toHaveBeenCalledTimes(1);
50
+ expect((await fs.stat(app.workspace)).isDirectory()).toBe(true);
51
+ } finally { await app.cleanup(); }
52
+ });
53
+
54
+ it('serializes concurrent registrations against the latest settings and preserves unrelated/offline projects', async () => {
55
+ const app = await setup();
56
+ try {
57
+ const other = path.join(app.directory, 'other');
58
+ await fs.mkdir(other);
59
+ await fs.writeFile(app.settingsPath, JSON.stringify({
60
+ projects: [{ id: 'offline', path: path.join(app.directory, 'offline'), addedAt: 1, lastOpenedAt: 1 }],
61
+ theme: 'saved', activeProjectId: 'offline', lastDirectory: 'keep-this-selection',
62
+ }));
63
+ const results = await Promise.all([
64
+ app.registry.register({ path: app.workspace }), app.registry.register({ path: other }),
65
+ app.runtime.persistSettings({ theme: 'new-theme' }),
66
+ ]);
67
+ const saved = await app.runtime.readSettingsFromDiskStrict();
68
+ expect(saved.projects.map((project) => project.path)).toEqual(expect.arrayContaining([path.join(app.directory, 'offline'), await fs.realpath(app.workspace), await fs.realpath(other)]));
69
+ expect(saved.projects).toHaveLength(3);
70
+ expect(saved.projects[0].path).toBe(path.join(app.directory, 'offline'));
71
+ expect(saved.theme).toBe('new-theme');
72
+ expect(saved.activeProjectId).not.toBe(results[0].project.id);
73
+ expect(saved.lastDirectory).toBe('keep-this-selection');
74
+ const restarted = createProjectRegistry({ persistSettings: app.runtime.persistSettings,
75
+ validateDirectoryPath: async () => ({ ok: true, directory: await fs.realpath(app.workspace) }) });
76
+ expect((await restarted.register({ path: app.workspace })).created).toBe(false);
77
+ } finally { await app.cleanup(); }
78
+ });
79
+
80
+ it('rejects missing/file directories without a write or revision tip', async () => {
81
+ const app = await setup();
82
+ try {
83
+ await fs.writeFile(app.settingsPath, JSON.stringify({ theme: 'saved' }));
84
+ const before = await fs.readFile(app.settingsPath, 'utf8');
85
+ await expect(app.registry.register({ path: path.join(app.directory, 'missing') })).rejects.toMatchObject({ code: 'validation_error' });
86
+ await expect(app.registry.register({ path: app.settingsPath })).rejects.toMatchObject({ code: 'validation_error' });
87
+ expect(await fs.readFile(app.settingsPath, 'utf8')).toBe(before);
88
+ expect(app.tips).not.toHaveBeenCalled();
89
+ } finally { await app.cleanup(); }
90
+ });
91
+
92
+ it('preserves the previous committed settings on failed writes, and never overwrites corrupt settings', async () => {
93
+ const app = await setup();
94
+ try {
95
+ await fs.writeFile(app.settingsPath, JSON.stringify({ theme: 'saved' }));
96
+ app.failWrites();
97
+ await expect(app.registry.register({ path: app.workspace })).rejects.toThrow('write failed');
98
+ expect(await app.runtime.readSettingsFromDiskStrict()).toEqual({ theme: 'saved' });
99
+ expect(app.tips).not.toHaveBeenCalled();
100
+ for (const corrupt of ['{broken', '[]', 'null']) {
101
+ await fs.writeFile(app.settingsPath, corrupt);
102
+ await expect(app.registry.register({ path: app.workspace })).rejects.toThrow();
103
+ expect(await fs.readFile(app.settingsPath, 'utf8')).toBe(corrupt);
104
+ }
105
+ } finally { await app.cleanup(); }
106
+ });
107
+ });
@@ -158,12 +158,16 @@ export const fetchQuotaForProvider = async (providerId) => {
158
158
  try {
159
159
  return await provider.fetchQuota();
160
160
  } catch (error) {
161
+ const message = error instanceof Error ? error.message : 'Request failed';
162
+ // Credential source unreachable means we cannot know whether the provider is configured;
163
+ // never report it as a configured provider failure.
164
+ const credentialSourceUnavailable = message === 'Unable to read OpenCode credentials';
161
165
  return buildResult({
162
166
  providerId: provider.providerId,
163
167
  providerName: provider.providerName,
164
168
  ok: false,
165
- configured: true,
166
- error: error instanceof Error ? error.message : 'Request failed'
169
+ configured: !credentialSourceUnavailable,
170
+ error: message
167
171
  });
168
172
  }
169
173
  };
@@ -1,7 +1,7 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
 
3
3
  import * as google from './google/index.js';
4
- import { listConfiguredQuotaProviders } from './index.js';
4
+ import { fetchQuotaForProvider, listConfiguredQuotaProviders } from './index.js';
5
5
 
6
6
  describe('quota provider registry', () => {
7
7
  it('exposes google provider configuration helpers through the provider module', () => {
@@ -14,4 +14,9 @@ describe('quota provider registry', () => {
14
14
  it('reports unavailable credentials instead of an empty configured-provider list', async () => {
15
15
  await expect(listConfiguredQuotaProviders()).rejects.toThrow('Unable to read OpenCode credentials');
16
16
  });
17
+
18
+ it('does not report a provider as configured when the credential source is unavailable', async () => {
19
+ const result = await fetchQuotaForProvider('claude');
20
+ expect(result).toMatchObject({ ok: false, configured: false, error: 'Unable to read OpenCode credentials' });
21
+ });
17
22
  });
@@ -24,7 +24,7 @@ Host side (`packages/web/server/lib/relay/`):
24
24
  - `service.js` — thin entrypoint: relay config (enabled flag + endpoints), the management routes (`GET/POST /api/yuri/relay/{status,enable,disable}`, `POST /api/yuri/relay/endpoints`), a `getPairingCandidate()` accessor (the relay transport candidate folded into pairing-v2 links when enabled, consumed by the pairing-session route in `core-routes.js`), and lifecycle wiring. **Multi-relay:** `settings.privateRelay = { enabled, relayUrl, extraRelayUrls }` — the host dials EVERY configured endpoint simultaneously with one identity (same serverId); clients treat `serverId + relayUrl` as the instance identity, so the same machine exposed via two domains appears as two separately named instances. The primary (`relayUrl`) owns push registration and stays the default pairing candidate. A pairing link created for an endpoint the host does not have yet APPENDS it as an extra endpoint instead of replacing the primary, so devices paired over the old domain keep working. `POST /relay/endpoints` (owner session / `desktop-local` only) replaces the extra-endpoint list wholesale and starts/stops host connections incrementally. Paired desktop operators may also add an endpoint through pairing creation. Host lifecycle is gated by `isRelayHostRuntime()` (`desktop` or `ssh-remote`): other runtimes (`bun run dev`, `dev:web:hmr`, ordinary CLI `serve`, VS Code, plain `node server`) report `state: 'unavailable'`, refuse `/relay/enable`, `/relay/disable`, `/relay/endpoints`, and relay pairing with 403, never mint a relay identity, never advertise `relayAvailable`, and never call `startRelayHost`. Direct `node server/index.js` forces `YURI_RUNTIME=web` unless it is already `ssh-remote`, so a leftover desktop env cannot open the host-control socket. On host runtimes, started from `packages/web/server/index.js` when demand/opt-in enables the relay. Desktop auto-clears `privateRelay.enabled` when demand drops; `ssh-remote` keeps an explicit opt-in (e.g. `yuri serve --relay-host`) sticky until disabled. The relay endpoint has no hosted default and must be configured in settings or pinned via the `YURI_RELAY_URL` env var; when set it overrides the stored setting for the host connection, the pairing candidate, and status, so paired clients inherit the endpoint automatically. Endpoint identity is scheme/host/path only: accepted schemes are `ws://` and `wss://`; URLs with userinfo are rejected (no silent default fallback); query and fragment are stripped before persistence and pairing candidates. Custom endpoint persistence and Host control-connection switching are explicit authenticated management actions. Pairing creation with `relayUrl` requires an owner UI session, local `desktop-local` shell client, or paired `desktop` operator; `/relay/enable` follows its API auth gate. `derivePushSendUrlFromRelayUrl` maps a canonical Relay `wss://`/`ws://` URL to the same host's `https://`/`http://` `/v1/push/send` path (register is `/v1/push/register-token`); `YURI_PUSH_RELAY_URL` on the Host overrides that derivation. The isolated Push process lives in `packages/relay-server/src/push/` and does not share Layer 1 credentials or tunnel state.
25
25
  - `identity.js` — the host's stable identity: the long-lived signing keypair (shared with the push relay, defines the routing id) plus a long-lived encryption keypair (the E2EE trust anchor). Reused across restarts; never rotated implicitly.
26
26
  - `signing-key.js` — storage/derivation of the signing keypair and the routing id, shared with the notifications runtime. Canonical public JWK hashing matches `packages/relay-server/src/push/crypto.js`.
27
- - `host-client.js` — the long-lived connection manager: one outbound control connection to the relay, a per-client data connection for each connected device, reconnect/backoff, and the E2EE responder handshake per connection. Control reconnect backoff does not reset on WebSocket `open`; `consecutiveFailures` clears only after the control socket stays up for `controlStableMs` (15s default), so an open-then-drop loop backs off to 30s instead of retrying every 1s.
27
+ - `host-client.js` — the long-lived connection manager: one outbound control connection to the relay, a per-client data connection for each connected device, reconnect, and the E2EE responder handshake per connection. Control reconnect keeps a fixed 3-second cadence until stopped; failure history clears only after the control socket stays up for `controlStableMs` (15s default), not on a brief WebSocket `open`.
28
28
  - `host-lock.js` — the per-machine host claim. Every local instance sharing the data dir shares the relay identity (same serverId), so concurrent relay hosts evict each other at the relay worker (`4001: Control replaced`) and paired devices land on whichever local process won last. The claim file (`<data-dir>/relay-host.lock`, `{ pid }`) makes this deterministic: `service.js` only starts the host when no LIVE process holds the claim (stale claims from dead pids are ignored), goes to `standby` otherwise, and a 30s watcher both takes over when the claimant dies and stands down when another process claims. Explicit user intent — creating a pairing link or hitting `/relay/enable` — force-claims; the previous holder's watcher sees the takeover and backs off instead of fighting. The claim is cooperative (the relay worker still enforces the single host slot); it only decides which process keeps retrying.
29
29
  - `tunnel-host.js` — the per-connection dispatcher: decrypts tunnel frames and forwards HTTP/SSE/WS to the local server over loopback, then streams responses back. Enforces a path allowlist and never injects credentials.
30
30
  - `e2ee.js`, `tunnel-codec.js` — host-side (JS) mirrors of the shared crypto and framing (see "Two implementations" below).
@@ -34,7 +34,7 @@ Client side (`packages/ui/src/lib/relay/`):
34
34
  - `protocol.ts` — the shared contract: constants, frame types, message shapes. The normative source both implementations follow.
35
35
  - `crypto.ts`, `handshake.ts` — the E2EE primitives and handshake state machines (initiator + responder).
36
36
  - `tunnel-codec.ts` — Layer 3 frame codec, fragmentation, and outbound frame batching.
37
- - `tunnel-client.ts` — the client tunnel: exposes a `fetch()`-compatible and a WebSocket-compatible surface backed by the encrypted tunnel.
37
+ - `tunnel-client.ts` — the client tunnel: exposes a `fetch()`-compatible and a WebSocket-compatible surface backed by the encrypted tunnel. Transient closures (including `4029` capacity/pending timeout and replacement) retry indefinitely at a fixed 3-second foreground cadence, or 60 seconds while hidden/offline. Online, visibility-visible and system-resume interrupt retry waits; an apparently connected tunnel is probed immediately. Authentication rejection stays terminal and later requests fail explicitly rather than waiting forever. Keepalive tracks send and receive separately: outbound requests cannot conceal a dead return path, and inbound-only SSE still sends pings so the Host idle reaper does not evict a healthy client. Reset fails every old stream; retries never replay mutation requests automatically.
38
38
  - `tunnel-payloads.ts`, `runtime-tunnel.ts`, `runtime-socket.ts` — payload helpers, the active-tunnel singleton, and the shared "open a runtime WebSocket the right way" helper.
39
39
 
40
40
  Relay is not a separate link format: it is one transport candidate inside the unified **pairing v2** payload (`packages/ui/src/lib/connectionPayload.ts`). A relay candidate is `{ type: 'relay', relayUrl, serverId, hostEncPubJwk }` — no embedded token; the client redeems the one-time pairing secret over the tunnel like any other candidate.
@@ -149,7 +149,7 @@ Catalog loaders (`loadProviders` / `loadAgents`) and assistant Query keys gate w
149
149
  - The host dispatcher never injects credentials; the server authenticates each tunneled request.
150
150
  - The tunnel is transparent to the app: adding relay support to a feature should not require the feature to know the relay exists — it goes through the shared runtime transport helpers.
151
151
  - The two implementations stay byte-compatible and the wire format is versioned/negotiated so mixed client/host app versions degrade gracefully rather than break. The Layer 1 Relay does not inspect application versions; unsupported Host/Client features are omitted at the endpoints.
152
- - Host-control reconnect storms are bounded at both ends: the Host does not reset backoff on a brief `open`, and the Relay rate-limits host-control upgrades per IP and per `serverId` (`4029`) without replacing a live control socket.
152
+ - Host-control reconnect storms are bounded at both ends: the Host keeps a fixed 3-second retry cadence, and the Relay rate-limits host-control upgrades per IP and per `serverId` (`4029`) without replacing a live control socket.
153
153
  - Concurrent service starts recheck the endpoint's active Host after awaiting identity, so each endpoint has one managed Host and stopping the service closes every started Host.
154
154
  - Tunneled HTTP/WS always dial `getLocalPort()` on loopback; there is no client-selected target-port override on the host dispatcher.
155
155