@yuriai/web 0.2.4 → 0.2.7

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 (178) hide show
  1. package/bin/lib/DOCUMENTATION.md +1 -0
  2. package/dist/assets/{AgentAvatar-BeM4lXfE.js → AgentAvatar-MzDm6uBf.js} +1 -1
  3. package/dist/assets/AssistantView-Be0OKo5o.js +3 -0
  4. package/dist/assets/DiagramView-Rpb6oenk.js +1 -0
  5. package/dist/assets/{FadeInOnReveal-B8BCjwPb.js → FadeInOnReveal-DkmfVoTO.js} +1 -1
  6. package/dist/assets/{GuiPluginSurface-BTmJlTp9.js → GuiPluginSurface-DTH9jNDf.js} +1 -1
  7. package/dist/assets/{GuiPluginWindow-jUuZl9JF.js → GuiPluginWindow-dDG5Uyqb.js} +1 -1
  8. package/dist/assets/{Icon-DofI60x2.js → Icon-BjiyvtB2.js} +1 -1
  9. package/dist/assets/{ImageLoadingPlaceholder-7jM-y96Q.js → ImageLoadingPlaceholder-CUKFQTAG.js} +1 -1
  10. package/dist/assets/{LoadingImage-DV6Neoja.js → LoadingImage-B7cT_4Oe.js} +1 -1
  11. package/dist/assets/MarkdownRenderer-Dk1A4sLM.js +2 -0
  12. package/dist/assets/{MarkdownRendererImpl-DNDAYS1N.js → MarkdownRendererImpl-CZ9lU4VJ.js} +2 -2
  13. package/dist/assets/{MarkstreamRendererImpl-D5Gf8Fja.js → MarkstreamRendererImpl-DastQdu7.js} +1 -1
  14. package/dist/assets/{MobileDetailNavigation-BxOYRnDk.js → MobileDetailNavigation-CittPDZ0.js} +1 -1
  15. package/dist/assets/{MobileResizableSheet-CuRgnS-k.js → MobileResizableSheet-C9YzOQis.js} +1 -1
  16. package/dist/assets/MobileShareBridge-BxsoZnUJ.js +4 -0
  17. package/dist/assets/MobileTabPageHeader-BEgQ3L4u.js +2 -0
  18. package/dist/assets/{MultiRunWindow-CaHNOGs2.js → MultiRunWindow-1o528NZE.js} +1 -1
  19. package/dist/assets/OnboardingScreen-D6iQ5qjF.js +1 -0
  20. package/dist/assets/{OverlayScrollbar-Bi17Olmj.js → OverlayScrollbar-Dbx1atD-.js} +1 -1
  21. package/dist/assets/SettingsView-BGEaQC4R.js +26 -0
  22. package/dist/assets/{SettingsWindow-Bbq4v4yl.js → SettingsWindow-MuJFADe3.js} +1 -1
  23. package/dist/assets/TerminalView-CHDyibi_.js +8 -0
  24. package/dist/assets/{ToolOutputDialog-BoAGzjT3.js → ToolOutputDialog-Bcry3eoE.js} +3 -3
  25. package/dist/assets/{YuriLogo-D9cfwLdW.js → YuriLogo-DvRSd5NN.js} +1 -1
  26. package/dist/assets/appThemeRegistry-CJoBy_eP.js +1 -0
  27. package/dist/assets/{assistant-attachment-cache-Ul88TuFO.js → assistant-attachment-cache-lEUFn3mr.js} +1 -1
  28. package/dist/assets/button-BSFWH-Ok.js +1 -0
  29. package/dist/assets/{capgoAdapter-CrBccKXY.js → capgoAdapter-_oWtDrgf.js} +1 -1
  30. package/dist/assets/{collapsible-UDWFNcbF.js → collapsible-DaevjAvt.js} +1 -1
  31. package/dist/assets/{desktop-CfMDfs6c.js → desktop-dp2Z0toS.js} +1 -1
  32. package/dist/assets/desktopHosts-CYKaLp1V.js +1 -0
  33. package/dist/assets/{desktopRelayRestore-aNSNYVEB.js → desktopRelayRestore-5yuHB356.js} +1 -1
  34. package/dist/assets/device-B7GyZCPd.js +2 -0
  35. package/dist/assets/{diagram-BxF_wECt.js → diagram-7OgmyecX.js} +1 -1
  36. package/dist/assets/dialog-D1pXn_b9.js +1 -0
  37. package/dist/assets/dropdown-menu.styles-CGHPvEgD.js +1 -0
  38. package/dist/assets/{es-iuy57SFI.js → es-DJzbuYpv.js} +1 -1
  39. package/dist/assets/{fileMentionTouchSelection-C4zBwV8-.js → fileMentionTouchSelection-7KLhnK1O.js} +1 -1
  40. package/dist/assets/{fileQueries-voABZL1r.js → fileQueries-DbUx7NwP.js} +1 -1
  41. package/dist/assets/{fileReferenceActions-ui8464r-.js → fileReferenceActions-No7p4Kdo.js} +1 -1
  42. package/dist/assets/{fr-LyrJa2Qb.js → fr-YDYbYIZQ.js} +1 -1
  43. package/dist/assets/gitApi-BEXddXMX.js +10 -0
  44. package/dist/assets/gui-BCPFcL_m.js +1 -0
  45. package/dist/assets/{host-1RDqqL9w.js → host--4S0vJsG.js} +1 -1
  46. package/dist/assets/{image-loading-Bqi69xpy.js → image-loading-FUFYiO1j.js} +1 -1
  47. package/dist/assets/{input-D86Oqf3B.js → input-BhHXFla6.js} +1 -1
  48. package/dist/assets/insertionBoundaries-HkddYmJd.js +1 -0
  49. package/dist/assets/{ja-QqNYiTeY.js → ja-SjX3NBJz.js} +1 -1
  50. package/dist/assets/{ko-CL-s2hwZ.js → ko-BxcUEWjB.js} +1 -1
  51. package/dist/assets/main-BKkCvf3L.js +2 -0
  52. package/dist/assets/main-CXE9lij2.js +169 -0
  53. package/dist/assets/{markdownHeightCache-DB_NzPGt.js → markdownHeightCache-DV2j4PlS.js} +1 -1
  54. package/dist/assets/mcpQueries-xfKOWrAa.js +1 -0
  55. package/dist/assets/miniChat-BKr-HXzy.js +2 -0
  56. package/dist/assets/mobile-CGL4wWLz.js +2 -0
  57. package/dist/assets/{mobileBackNavigation-Dq7VGDkh.js → mobileBackNavigation-VzxRWLxN.js} +1 -1
  58. package/dist/assets/multirun-BmF58wXR.js +3 -0
  59. package/dist/assets/native-config-CYjStyIM.js +1 -0
  60. package/dist/assets/{persistence-Ck0wskDR.js → persistence-BfjCXjLZ.js} +1 -1
  61. package/dist/assets/{pl-AKGY_sFU.js → pl-vh0XFuDb.js} +1 -1
  62. package/dist/assets/platform-DXeTzJHG.js +7 -0
  63. package/dist/assets/{projectMeta-Bouw3u_q.js → projectMeta-DhdEWvmC.js} +1 -1
  64. package/dist/assets/{pt-BR-BFRFGU_b.js → pt-BR-Cv5tssQz.js} +1 -1
  65. package/dist/assets/{queryRuntime-CpsVmMzy.js → queryRuntime-BuRnpVtK.js} +1 -1
  66. package/dist/assets/{readiness--FInk_Rv.js → readiness-uM7foMQ8.js} +1 -1
  67. package/dist/assets/renderElectronMiniChatApp-CYjZYsCZ.js +2 -0
  68. package/dist/assets/renderMobileApp-Dy2bPXrM.js +28 -0
  69. package/dist/assets/runtime-fetch-BAN5Gnnp.js +1 -0
  70. package/dist/assets/{runtime-file-download-J_Vcm3tT.js → runtime-file-download-BzblfnMx.js} +1 -1
  71. package/dist/assets/{runtime-file-resource-Disaet9c.js → runtime-file-resource-D3k0hKDj.js} +1 -1
  72. package/dist/assets/runtime-switch-CAZiOV2G.js +1 -0
  73. package/dist/assets/runtimeConfig-Cjjf4017.js +2 -0
  74. package/dist/assets/runtimeEndpointReset-CNyugOcU.js +149 -0
  75. package/dist/assets/{scheduledTaskNavigation-C6FKpwPD.js → scheduledTaskNavigation-BZ3B5bpN.js} +1 -1
  76. package/dist/assets/{sessionChangeSummary-DS-Su8YI.js → sessionChangeSummary-5npOjhNG.js} +1 -1
  77. package/dist/assets/sessionLookup-ClhS_rqE.js +1 -0
  78. package/dist/assets/{sortable-tabs-strip-CSXgXPyP.js → sortable-tabs-strip-BnTV_KYG.js} +1 -1
  79. package/dist/assets/speechSettingsQueries-CpOY2X9w.js +4 -0
  80. package/dist/assets/src-NlrSCyPZ.css +2 -0
  81. package/dist/assets/{store-CGMD02tA.js → store-CgQdmzpX.js} +2 -2
  82. package/dist/assets/terminalApi-CIbkfDkE.js +1 -0
  83. package/dist/assets/{textarea-CMvxcQhR.js → textarea-Deh9E1KP.js} +1 -1
  84. package/dist/assets/{tooltip-CnIKZ6bg.js → tooltip-DygQ-2xe.js} +1 -1
  85. package/dist/assets/{types-Cjsqoaj2.js → types-C2ml30_A.js} +1 -1
  86. package/dist/assets/{uk-C21_nQhw.js → uk-3a9vdLJ-.js} +1 -1
  87. package/dist/assets/{useAppFontEffects-DzyOIRw0.js → useAppFontEffects-BMXDDJtn.js} +27 -27
  88. package/dist/assets/{useAssistantUIStore-4a569vpy.js → useAssistantUIStore-D7JZlg_Q.js} +1 -1
  89. package/dist/assets/useDesktopWindowControlsLayout-l2q0zXMx.js +1 -0
  90. package/dist/assets/useEffectiveDirectory-rDw8BJo1.js +1 -0
  91. package/dist/assets/{useFontPreferences-BPTEYhfn.js → useFontPreferences-51P_6ZRi.js} +1 -1
  92. package/dist/assets/useMobileNavigationStore-EmnPOl61.js +417 -0
  93. package/dist/assets/useUIStore-NMQx_cnG.js +1 -0
  94. package/dist/assets/{useWorkerHighlightedLines-BNm0Snzz.js → useWorkerHighlightedLines-up7t7cwh.js} +1 -1
  95. package/dist/assets/{zh-CN-C7PVNr9_.js → zh-CN-kwaUr5W5.js} +1 -1
  96. package/dist/assets/{zh-TW-DLLoB3-e.js → zh-TW-BBs44W7l.js} +1 -1
  97. package/dist/index.html +19 -21
  98. package/dist/mini-chat.html +19 -21
  99. package/dist/mobile.html +19 -21
  100. package/package.json +1 -1
  101. package/server/index.d.ts +17 -0
  102. package/server/index.js +22 -1
  103. package/server/lib/assistants/DOCUMENTATION.md +17 -1
  104. package/server/lib/assistants/contact-tools.js +2 -2
  105. package/server/lib/assistants/harness.js +5 -2
  106. package/server/lib/assistants/harness.test.js +48 -1
  107. package/server/lib/host-update/DOCUMENTATION.md +97 -0
  108. package/server/lib/host-update/cli-worker.js +132 -0
  109. package/server/lib/host-update/cli.js +62 -0
  110. package/server/lib/host-update/cli.test.js +59 -0
  111. package/server/lib/host-update/releases.js +44 -0
  112. package/server/lib/host-update/routes.js +33 -0
  113. package/server/lib/host-update/routes.test.js +104 -0
  114. package/server/lib/host-update/runtime.js +140 -0
  115. package/server/lib/host-update/runtime.test.js +141 -0
  116. package/server/lib/llm/DOCUMENTATION.md +24 -5
  117. package/server/lib/llm/completions.js +6 -0
  118. package/server/lib/llm/completions.test.js +14 -0
  119. package/server/lib/llm/generate.js +30 -10
  120. package/server/lib/llm/generate.test.js +64 -1
  121. package/server/lib/opencode/bootstrap-runtime.js +2 -0
  122. package/server/lib/opencode/yuri-routes.js +7 -206
  123. package/server/lib/opencode/yuri-routes.test.js +6 -6
  124. package/server/lib/package-manager.js +1 -1
  125. package/server/lib/projects/project-config.js +5 -1
  126. package/server/lib/projects/project-config.test.js +26 -0
  127. package/server/lib/scheduled-tasks/DOCUMENTATION.md +19 -5
  128. package/server/lib/scheduled-tasks/SESSION_SKILL.md +21 -3
  129. package/server/lib/scheduled-tasks/routes.js +22 -4
  130. package/server/lib/scheduled-tasks/routes.test.js +3 -0
  131. package/server/lib/scheduled-tasks/session-skill-client.mjs +20 -16
  132. package/server/lib/scheduled-tasks/session-skill.js +55 -12
  133. package/server/lib/scheduled-tasks/session-skill.test.js +64 -0
  134. package/server/sse-routes.test.js +3 -0
  135. package/dist/assets/AssistantView-B1-ZOPte.js +0 -3
  136. package/dist/assets/DiagramView-byPKPO9k.js +0 -1
  137. package/dist/assets/GuiPluginLoadingNotice-Ctwyj_6m.js +0 -1
  138. package/dist/assets/MarkdownRenderer-dWW52CAV.js +0 -2
  139. package/dist/assets/MobileShareBridge-CXqDXHZG.js +0 -4
  140. package/dist/assets/MobileTabPageHeader-C7cX5eld.js +0 -2
  141. package/dist/assets/OnboardingScreen-hvLlaoKt.js +0 -1
  142. package/dist/assets/SettingsView-DNNscLOq.js +0 -26
  143. package/dist/assets/TerminalView-LW5vUwDA.js +0 -8
  144. package/dist/assets/appThemeRegistry-BzU8zJgk.js +0 -1
  145. package/dist/assets/button-CT7WL0lp.js +0 -1
  146. package/dist/assets/clipboard-Bj6jZiuP.js +0 -1
  147. package/dist/assets/desktopHosts-BEzVZGiW.js +0 -1
  148. package/dist/assets/device-BDrEmxBm.js +0 -2
  149. package/dist/assets/dialog-BpsbJk8Y.js +0 -1
  150. package/dist/assets/download-progress-MobTWf23.js +0 -1
  151. package/dist/assets/dropdown-menu.styles-MkqoyFTv.js +0 -1
  152. package/dist/assets/gitApi-DqX-QV_L.js +0 -10
  153. package/dist/assets/gitApiHttp-BhcxUxqo.js +0 -7
  154. package/dist/assets/gui-CTKa6rbU.js +0 -1
  155. package/dist/assets/insertionBoundaries-C1W-RfK6.js +0 -1
  156. package/dist/assets/main-CqoNDCJj.js +0 -2
  157. package/dist/assets/main-UG2rPfaK.js +0 -169
  158. package/dist/assets/mcpQueries-DXYEazhg.js +0 -1
  159. package/dist/assets/miniChat-DaI0JRe4.js +0 -2
  160. package/dist/assets/mobile-BMlE5RBZ.js +0 -2
  161. package/dist/assets/multirun-CPqjkmDv.js +0 -3
  162. package/dist/assets/native-config-CbLOUYef.js +0 -1
  163. package/dist/assets/platform-kv0OsX45.js +0 -1
  164. package/dist/assets/reasoning-projection-client-BEhVknv9.js +0 -1
  165. package/dist/assets/renderElectronMiniChatApp-DR2wc2oc.js +0 -2
  166. package/dist/assets/renderMobileApp-CaBsjJFs.js +0 -28
  167. package/dist/assets/runtime-fetch-BclMrQHc.js +0 -1
  168. package/dist/assets/runtime-switch-WzPG6NMR.js +0 -1
  169. package/dist/assets/runtimeConfig-DO1kqEsE.js +0 -2
  170. package/dist/assets/runtimeEndpointReset-D5q3N28H.js +0 -149
  171. package/dist/assets/sessionLookup-DBlBJhz5.js +0 -1
  172. package/dist/assets/speechSettingsQueries-BB9b5zyK.js +0 -4
  173. package/dist/assets/src-hVfg6BZK.css +0 -2
  174. package/dist/assets/terminalApi-B_oHorrS.js +0 -1
  175. package/dist/assets/useDesktopWindowControlsLayout-DtdFMwzW.js +0 -1
  176. package/dist/assets/useEffectiveDirectory-DC4oSzha.js +0 -1
  177. package/dist/assets/useMobileNavigationStore-DDIFIAUa.js +0 -417
  178. package/dist/assets/useUIStore-DqtgX2FB.js +0 -1
@@ -103,8 +103,8 @@ export const CONTACT_SYSTEM_PROMPT = [
103
103
  'Reply in short chat bubbles: a few sentences each, separated by a blank line.',
104
104
  'Talk like a person in the user\'s language. One short spoken bubble at a time — never a wall of paragraphs.',
105
105
  'Reply in the language of the user\'s messages, unless they explicitly request another language. Infer it from their latest substantive message and conversation context, never from the app interface locale. For ambiguous messages or background follow-ups, continue the established conversation language.',
106
- 'Keep private reasoning and tool traces private. Communicate your next concrete action, verified milestones, and blockers in short natural messages in the same conversation language.',
107
- 'Before starting work, send a short message explaining the next action. During multi-step work, send a message when a meaningful result arrives or the direction changes. Publish these messages during execution; keep the final answer to the remaining outcome instead of repeating earlier updates.',
106
+ 'Keep private reasoning and tool traces private.',
107
+ 'Send a progress message when it tells the user something they do not already know: a direction they may want to correct, a finding that matters, a blocker, or that the work will take a while. Skip messages that would only repeat the plan or narrate a step. Keep the final answer to the remaining outcome instead of repeating earlier updates.',
108
108
  'Public message protocol: put each user-facing progress message at the START of your response in its own yuri-message JSON fence, with a single-line JSON object {"text":"Your short message"}. Then emit the next tool call or final answer. A closed message fence is delivered immediately while you are still generating. Include only text intended for the user. Tool results are evidence for you to summarize in your own words; never copy their stock confirmation wording into your reply.',
109
109
  'Do not expose tool traces, Activity, or editor actions.',
110
110
  'You have bash, read, write, and edit in the working directory. Use them for pwd, files, and shell. Never say you have no terminal or cannot read files. Ignore any temporary generator workspace in the environment.',
@@ -453,6 +453,9 @@ export function createContactStreamFn(createChatCompletion, {
453
453
  const publicReader = createPublicMessageReader(publishPublicMessage);
454
454
  const result = await createChatCompletion({
455
455
  signal,
456
+ timeoutMs: 0,
457
+ retryEmptyTextUntilCancelled: true,
458
+ textEnvelope: true,
456
459
  body: {
457
460
  model: `${model.provider === 'yuri' ? '' : `${model.provider}/`}${model.id}`.replace(/^\//, '') || model.name,
458
461
  providerID: typeof model.name === 'string' && model.name.includes('/')
@@ -17,8 +17,52 @@ import {
17
17
  runContactTurn,
18
18
  } from './harness.js'
19
19
  import { PI_CODING_TOOL_NAMES } from './pi-tools.js'
20
+ import { createChatCompletion as gatewayCompletion } from '../llm/completions.js'
20
21
 
21
22
  describe('createContactStreamFn', () => {
23
+ it('continues eight real Agent tool rounds through gateway recovery without replaying completed tools', async () => {
24
+ vi.useFakeTimers()
25
+ try {
26
+ const getAssistantSettings = vi.fn(async () => ({ id: 'a', name: 'Fixture', defaultPrompt: 'fixture' }))
27
+ const tools = createContactTools({ readAssistantSettings: getAssistantSettings, currentAssistant: { id: 'a', name: 'Fixture' } })
28
+ let round = 0
29
+ const attempts = new Map()
30
+ const remove = vi.fn(async () => {})
31
+ const generate = vi.fn(async ({ sessionID, prompt }) => {
32
+ const index = Number(sessionID.slice(4))
33
+ const attempt = (attempts.get(index) || 0) + 1
34
+ attempts.set(index, attempt)
35
+ expect((prompt.match(/Yuri tool result name=get_assistant_settings call=/g) || []).length).toBe(index - 1)
36
+ // More than the old three-attempt limit, and longer than its 90s deadline.
37
+ if ((index === 3 && attempt <= 9) || (index === 4 && attempt <= 3)) return { text: '' }
38
+ const text = index <= 8
39
+ ? '```yuri-tool\n{"name":"get_assistant_settings","arguments":{}}\n```'
40
+ : '```yuri-final\n{"status":"complete","text":"Verified all eight steps."}\n```'
41
+ return { text: JSON.stringify({ text }) }
42
+ })
43
+ const client = {
44
+ agent: { get: async () => ({ data: { id: 'yuri-text', permissions: [{ action: '*', resource: '*', effect: 'deny' }] } }) },
45
+ session: { create: async () => ({ id: `ses_${++round}` }), generate, remove, interrupt: vi.fn() },
46
+ }
47
+ const completion = (input) => gatewayCompletion({
48
+ ...input, buildOpenCodeUrl: () => 'http://127.0.0.1:4096', getOpenCodeAuthHeaders: () => ({}),
49
+ clientFactory: () => client, ensureTempDirectory: async () => '/tmp/yuri-text',
50
+ loadCatalog: async () => ({ models: [{ providerID: 'p', modelID: 'm' }] }),
51
+ })
52
+ const outcome = runContactTurn({
53
+ assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: 'Run eight lookups in order.',
54
+ tools, createChatCompletion: completion, signal: new AbortController().signal,
55
+ }).then(value => ({ value }), error => ({ error }))
56
+ await vi.advanceTimersByTimeAsync(200_000)
57
+ expect(await outcome).toMatchObject({ value: { text: 'Verified all eight steps.' } })
58
+ expect(getAssistantSettings).toHaveBeenCalledTimes(8)
59
+ expect(round).toBe(9)
60
+ expect(generate).toHaveBeenCalledTimes(21)
61
+ expect(remove).toHaveBeenCalledTimes(9)
62
+ expect(vi.getTimerCount()).toBe(0)
63
+ } finally { vi.useRealTimers() }
64
+ })
65
+
22
66
  it('forwards the assistant variant while keeping private reasoning out of bubbles', async () => {
23
67
  const onBubbleDelta = vi.fn();
24
68
  const completion = vi.fn(async ({ onTextDelta }) => {
@@ -30,7 +74,10 @@ describe('createContactStreamFn', () => {
30
74
  history: [], userText: '你好', createChatCompletion: completion, onBubbleDelta,
31
75
  });
32
76
  expect(completion.mock.calls.length).toBeGreaterThan(0);
33
- for (const [request] of completion.mock.calls) expect(request.body.variant).toBe('high');
77
+ for (const [request] of completion.mock.calls) {
78
+ expect(request.body.variant).toBe('high');
79
+ expect(request).toMatchObject({ timeoutMs: 0, retryEmptyTextUntilCancelled: true, textEnvelope: true });
80
+ }
34
81
  expect(result.bubbles).toEqual(['已完成。']);
35
82
  expect(JSON.stringify(onBubbleDelta.mock.calls)).not.toContain('Private reasoning');
36
83
  });
@@ -0,0 +1,97 @@
1
+ # Host self-update
2
+
3
+ `GET /api/system/update?channel=stable|beta` returns the **serving Host's**
4
+ identity/version, supported capability, selected/query channel, optional update
5
+ plan (exact version, release notes, OTA/installer/CLI kind, rollback and expiry),
6
+ and the current operation. Omitting the channel follows the Host's persisted
7
+ selection. A check never selects a channel or clears a staged desktop bundle.
8
+ Discovery errors return HTTP 502 with `checkError` and the operation snapshot,
9
+ not a false up-to-date result. Active tasks remain visible regardless of the
10
+ queried channel; discovery is skipped while an update is active.
11
+
12
+ `POST /api/system/update` accepts `{ version, channel, planId,
13
+ allowDowngrade?: true }`. Validation and admission are serialized. Plans are
14
+ Host/process/platform/architecture/current-version/channel/artifact bound,
15
+ expire after ten minutes, and are freshly revalidated before admission. GET
16
+ reuses successful release discovery for at most one minute (two channel slots).
17
+ An exact active/completed retry returns the existing operation; conflicting
18
+ active requests, stale plans and changed releases return 409. A beta-to-stable
19
+ rollback requires explicit `allowDowngrade`; stable never selects a prerelease.
20
+ Accepted requests return 202 before starting work. Failed tasks can be retried
21
+ only after validation again. No caller-supplied command, URL or update kind is
22
+ accepted. Errors contain stable codes, never installer output or credentials.
23
+
24
+ States are `checking`, `downloading`, `installing`, `restarting`, `succeeded`,
25
+ `failed`. Unknown percentage is null. The channel and accepted task are atomically
26
+ persisted with private permissions. A new Host verifies a restarting task against
27
+ its actual running version; interrupted pre-restart tasks fail rather than
28
+ appearing successful. Package installation failure is not package rollback.
29
+
30
+ ## Ownership
31
+
32
+ - `runtime.js` owns plans, admission, durable task state and restart verification.
33
+ - `routes.js` requires a real paired-client bearer or authenticated password UI
34
+ session, refuses URL-auth tokens, unauthenticated loopback and cross-site cookie
35
+ requests. All paired device kinds can update their Host. This is the same
36
+ authorization over direct HTTP and Relay; Relay grants no privilege.
37
+ - `releases.js` selects installable exact npm versions from `latest` / `beta`
38
+ tags with beta sequence ordering. GitHub tag release notes are optional; a
39
+ failed registry lookup is not optional.
40
+ - `cli.js` launches a hidden detached Node helper and awaits its preflight before
41
+ gracefully stopping the Host. Synchronous package-manager ownership probes run
42
+ in that helper, never on an Electron/server main thread.
43
+ - `cli-worker.js` verifies the global install and registered daemon, locks the
44
+ stable installation entry, revalidates registry integrity, waits for the old
45
+ process to exit, installs the exact version, restarts through the global CLI
46
+ entry and verifies `/health` version/identity. Runtime, bind host, port,
47
+ API-only mode and password environment are preserved. Passwords never enter
48
+ task state or helper argv. Install failure attempts to restart the surviving
49
+ CLI files but cannot promise recovery from a partially replaced package.
50
+ - Electron injects `host-update.mjs` through `startWebUiServer` and shares
51
+ `DesktopOta` / `DesktopInstaller`, existing download events and graceful
52
+ shutdown / `quitAndInstall`. It never runs a package manager. Local desktop
53
+ check/download activity is exposed by the same GET and blocks remote admission;
54
+ remote tasks block competing updater IPC. Installer feeds remain pinned to the
55
+ release selected by the existing desktop decision, including beta isolation.
56
+
57
+ ## Deliberate limitations
58
+
59
+ Automatic CLI installation currently requires one registered, writable global
60
+ POSIX daemon. Development checkouts, containers, Windows CLI installations,
61
+ foreground/service-managed launches and concurrent registered CLI daemons report
62
+ unsupported or fail preflight without stopping the Host. Use their installation
63
+ or service manager instead. Other data scopes sharing one global installation
64
+ must be administratively drained; the installation lock prevents competing
65
+ remote helpers but does not coordinate arbitrary external package managers.
66
+ A helper killed before its `finally` cleanup leaves an installation lock in the
67
+ user cache; an operator must verify no helper remains before removing that lock.
68
+ Workers deliberately do not race to reap presumed stale locks.
69
+
70
+ Packaged non-Preview Electron supports OTA and native installers; development and
71
+ Preview report unsupported. Native-main injection requires a new desktop installer,
72
+ not merely a UI/backend OTA to an older shell. Mobile/web clients operate the
73
+ selected Host through `runtimeFetch`; standalone VS Code returns explicit 501.
74
+ The retired unversioned `/api/yuri/update-install` returns 409 `update_plan_required`.
75
+
76
+ The shared UI puts an icon beside the Host's Yuri version in About and the
77
+ desktop remote-instance menu, with an available-update dot and a confirmation
78
+ dialog showing channel, notes, method and rollback warning.
79
+ The existing outer About beta switch selects the query/submit channel; the
80
+ dialog has no independent channel checkbox or preference. In-flight mutations
81
+ retain their captured channel and cannot overwrite another channel's Query data.
82
+ `hostUpdateDialogModel.ts` adapts the Host DTO to
83
+ the existing client updater's shared `UpdateDialogView`; both use the same
84
+ overlay, Markdown changelog, scroll/progress/error and footer rendering. No
85
+ separate remote dialog is maintained. Query keys include
86
+ transport and generation; endpoint changes discard the dialog/mutation scope.
87
+ Polling is visible/mounted-only: two seconds during activity, five minutes idle,
88
+ and fifteen seconds after a connection error. Reconnect preserves the last task
89
+ and never treats a dropped connection as success.
90
+
91
+ ## Verification
92
+
93
+ Focused Vitest: `runtime.test.js`, `routes.test.js` (real auth and Relay HTTP
94
+ dispatcher), Electron `host-update.test.mjs` / `desktop-ota.test.mjs` /
95
+ `desktop-installer.test.mjs`, UI `HostVersionUpdate.test.tsx` /
96
+ `AboutSettings.test.tsx`. Installation and native process replacement need a
97
+ controlled disposable installation; these tests do not update the running app.
@@ -0,0 +1,132 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { createHash } from 'node:crypto';
5
+ import { spawn } from 'node:child_process';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { detectPackageManagerDetails } from '../package-manager.js';
8
+ import { writeUpdateState } from './runtime.js';
9
+ import { releaseParts } from './releases.js';
10
+
11
+ function run(command, args, options = {}) {
12
+ return new Promise((resolve, reject) => {
13
+ const child = spawn(command, args, { stdio: 'ignore', windowsHide: true, ...options });
14
+ child.once('error', reject);
15
+ child.once('exit', (code) => code === 0 ? resolve() : reject(new Error('Update command failed')));
16
+ });
17
+ }
18
+
19
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error.code !== 'ESRCH'; } };
20
+ const send = (message) => new Promise((resolve, reject) => process.send(message, (error) => error ? reject(error) : resolve()));
21
+
22
+ function prepare(config) {
23
+ if (!Number.isInteger(config.port) || !Number.isInteger(config.pid) || !releaseParts(config.release?.version ?? '0.0.0')) throw new Error('Invalid update configuration');
24
+ const details = detectPackageManagerDetails();
25
+ if (!['install-path-owner', 'global-root-owner', 'cached'].includes(details.reason)
26
+ || fs.realpathSync(details.packagePath) !== fs.realpathSync(config.packageRoot)) throw new Error('Package manager does not own this installation');
27
+ const installationPath = details.globalNodeModulesRoot && path.join(details.globalNodeModulesRoot, '@yuriai', 'web');
28
+ if (!installationPath || fs.realpathSync(installationPath) !== fs.realpathSync(config.packageRoot)) throw new Error('Cannot resolve the stable global package entry');
29
+ const runDir = path.join(config.dataDir, 'run');
30
+ const instance = JSON.parse(fs.readFileSync(path.join(runDir, `yuri-${config.port}.json`), 'utf8'));
31
+ const pid = Number(fs.readFileSync(path.join(runDir, `yuri-${config.port}.pid`), 'utf8'));
32
+ if (pid !== config.pid || instance.launchMode !== 'daemon') throw new Error('Automatic CLI updates require a registered daemon');
33
+ for (const file of fs.readdirSync(runDir)) {
34
+ if (!/^yuri-\d+\.pid$/.test(file) || file === `yuri-${config.port}.pid`) continue;
35
+ const otherPid = Number(fs.readFileSync(path.join(runDir, file), 'utf8'));
36
+ if (Number.isInteger(otherPid) && otherPid > 0 && alive(otherPid)) throw new Error('Stop other CLI instances before updating this installation');
37
+ }
38
+ fs.accessSync(config.packageRoot, fs.constants.W_OK);
39
+ return { details, instance, installationPath };
40
+ }
41
+
42
+ function acquireLock(packageRoot) {
43
+ const key = createHash('sha256').update(path.resolve(packageRoot)).digest('hex').slice(0, 24);
44
+ const directory = path.join(os.homedir(), '.cache', 'yuri', 'update-locks');
45
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
46
+ const file = path.join(directory, `${key}.lock`);
47
+ try { fs.writeFileSync(file, String(process.pid), { flag: 'wx', mode: 0o600 }); }
48
+ catch (error) {
49
+ if (error.code !== 'EEXIST') throw error;
50
+ // Never race another worker by unlinking a presumed stale lock. A helper
51
+ // killed outside normal cleanup requires explicit operator recovery.
52
+ throw new Error('Installation update lock exists; check the updater before retrying');
53
+ }
54
+ return () => { if (fs.readFileSync(file, 'utf8') === String(process.pid)) fs.unlinkSync(file); };
55
+ }
56
+
57
+ let drain;
58
+ let cancel;
59
+ const drained = new Promise((resolve, reject) => { drain = resolve; cancel = () => reject(new Error('Update handoff cancelled')); });
60
+ let started = false;
61
+ process.on('message', (message) => {
62
+ if (message?.mode === 'drain') { drain(); return; }
63
+ if (message?.mode === 'cancel') { cancel(); return; }
64
+ if (started) return;
65
+ started = true;
66
+ void (async () => {
67
+ let releaseLock;
68
+ let accepted = false;
69
+ try {
70
+ const config = message;
71
+ const { details, instance, installationPath } = prepare(config);
72
+ if (config.mode === 'probe') { await send({ ready: true }); return; }
73
+ releaseLock = acquireLock(installationPath);
74
+ const metadataResponse = await fetch(`https://registry.npmjs.org/@yuriai/web/${config.release.version}`, { signal: AbortSignal.timeout(10000) });
75
+ if (!metadataResponse.ok || (await metadataResponse.json()).dist?.integrity !== config.release.integrity) throw new Error('Package integrity changed');
76
+ const state = config.state;
77
+ const report = async (patch) => {
78
+ const persisted = JSON.parse(fs.readFileSync(config.stateFile, 'utf8'));
79
+ if (persisted.operation?.id !== state.operation.id) throw new Error('Update task was superseded');
80
+ Object.assign(state.operation, patch, { updatedAt: Date.now() });
81
+ await writeUpdateState(config.stateFile, state);
82
+ };
83
+ await send({ ready: true });
84
+ accepted = true;
85
+ await Promise.race([drained, delay(30000).then(() => { throw new Error('Host did not hand off the update'); })]);
86
+ const deadline = Date.now() + 30000;
87
+ while (alive(config.pid)) {
88
+ if (Date.now() >= deadline) throw new Error('Host did not shut down');
89
+ await delay(100);
90
+ }
91
+ await report({ status: 'installing' });
92
+ const target = `@yuriai/web@${config.release.version}`;
93
+ const args = details.packageManager === 'yarn' ? ['global', 'add', target]
94
+ : details.packageManager === 'npm' ? ['install', '-g', target, '--force'] : ['add', '-g', target];
95
+ let installFailed = false;
96
+ try {
97
+ await run(details.packageManagerCommand, args, { timeout: 10 * 60_000 });
98
+ const installed = JSON.parse(fs.readFileSync(path.join(installationPath, 'package.json'), 'utf8'));
99
+ if (installed.version !== config.release.version) throw new Error('Installed version mismatch');
100
+ } catch { installFailed = true; }
101
+ await report({ status: installFailed ? 'failed' : 'restarting', error: installFailed ? 'cli_install_failed' : null });
102
+ // Password stays in the inherited environment, never argv or task state.
103
+ const restartArgs = [path.join(installationPath, 'bin', 'cli.js'), 'serve', '--port', String(config.port), '--json'];
104
+ if (instance.host) restartArgs.push('--host', instance.host);
105
+ if (instance.apiOnly) restartArgs.push('--api-only');
106
+ await run(process.execPath, restartArgs, { env: { ...process.env, ...(instance.uiPassword ? { YURI_UI_PASSWORD: instance.uiPassword } : {}) }, timeout: 60000 });
107
+ if (!installFailed) {
108
+ const host = instance.host && !['0.0.0.0', '::'].includes(instance.host) ? instance.host : '127.0.0.1';
109
+ const response = await fetch(`http://${host.includes(':') ? `[${host}]` : host}:${config.port}/health`, { signal: AbortSignal.timeout(10000) });
110
+ const health = await response.json();
111
+ if (!response.ok || health.yuriVersion !== config.release.version || (health.serverId && health.serverId !== state.operation.serverId)) throw new Error('Restart version verification failed');
112
+ await report({ status: 'succeeded', progress: 100 });
113
+ }
114
+ } catch {
115
+ if (!accepted) {
116
+ if (process.connected) await send({ error: 'CLI update preflight failed: use a writable global installation with one registered daemon' });
117
+ } else {
118
+ const state = message.state;
119
+ try {
120
+ const persisted = JSON.parse(fs.readFileSync(message.stateFile, 'utf8'));
121
+ if (persisted.operation?.id === state.operation.id) {
122
+ Object.assign(state.operation, { status: 'failed', error: 'cli_update_failed', updatedAt: Date.now() });
123
+ await writeUpdateState(message.stateFile, state);
124
+ }
125
+ } catch { /* A failed durable write must not overwrite another task or prevent lock cleanup. */ }
126
+ }
127
+ } finally {
128
+ releaseLock?.();
129
+ process.exit(0);
130
+ }
131
+ })();
132
+ });
@@ -0,0 +1,62 @@
1
+ import { fork } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { existsSync } from 'node:fs';
4
+ import { discoverCliRelease } from './releases.js';
5
+
6
+ const workerFile = fileURLToPath(new URL('./cli-worker.js', import.meta.url));
7
+
8
+ function startWorker(message, detached = false) {
9
+ const child = fork(workerFile, [], { detached, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'], execArgv: [] });
10
+ const ready = new Promise((resolve, reject) => {
11
+ const timer = setTimeout(() => { child.kill(); reject(new Error('Update helper timed out')); }, 30000);
12
+ child.once('error', (error) => { clearTimeout(timer); reject(error); });
13
+ child.once('exit', () => { clearTimeout(timer); reject(new Error('Update helper exited before handoff')); });
14
+ child.once('message', (result) => {
15
+ clearTimeout(timer);
16
+ if (result.error) reject(new Error(result.error));
17
+ else resolve(result);
18
+ });
19
+ });
20
+ child.send(message);
21
+ return { child, ready };
22
+ }
23
+
24
+ export function createCliUpdateAdapter({ packageRoot, dataDir, getPort, shutdown, currentVersion, env = process.env }) {
25
+ const unsupported = process.platform === 'win32' || !packageRoot.replaceAll('\\', '/').includes('/node_modules/')
26
+ || existsSync('/.dockerenv') || env.CONTAINER || env.container || env.INVOCATION_ID || env.PM2_HOME;
27
+ const configuration = () => ({ packageRoot, dataDir, port: getPort(), pid: process.pid });
28
+ let checkedAt = 0;
29
+ const adapter = {
30
+ host: 'cli', external: true, supported: !unsupported,
31
+ reason: unsupported ? 'managed_or_development_installation' : null,
32
+ inspect: (channel) => discoverCliRelease(channel, currentVersion),
33
+ async refreshSupport() {
34
+ if (unsupported || Date.now() - checkedAt < 60_000) return;
35
+ try { await adapter.assertReady(); adapter.supported = true; adapter.reason = null; }
36
+ catch { adapter.supported = false; adapter.reason = 'registered_writable_daemon_required'; }
37
+ checkedAt = Date.now();
38
+ },
39
+ async assertReady() {
40
+ const { child, ready } = startWorker({ mode: 'probe', ...configuration() });
41
+ try { await ready; } finally { if (child.connected) child.disconnect(); child.unref(); }
42
+ },
43
+ async execute({ release, stateFile, state, report }) {
44
+ const { child, ready } = startWorker({ mode: 'update', ...configuration(), release, stateFile, state }, true);
45
+ let prepared = false;
46
+ let handedOff = false;
47
+ try {
48
+ await ready;
49
+ prepared = true;
50
+ await report({ status: 'installing' });
51
+ child.send({ mode: 'drain' });
52
+ handedOff = true;
53
+ } finally {
54
+ if (prepared && !handedOff && child.connected) child.send({ mode: 'cancel' });
55
+ if (child.connected) child.disconnect();
56
+ child.unref();
57
+ }
58
+ await shutdown();
59
+ },
60
+ };
61
+ return adapter;
62
+ }
@@ -0,0 +1,59 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { beforeEach, expect, it, vi } from 'vitest';
3
+ import { createCliUpdateAdapter } from './cli.js';
4
+
5
+ const fixture = vi.hoisted(() => ({ fork: vi.fn(), inspect: vi.fn(), reject: false, children: [] }));
6
+ vi.mock('node:child_process', () => ({ fork: (...args) => fixture.fork(...args) }));
7
+ vi.mock('node:fs', () => ({ existsSync: () => false }));
8
+ vi.mock('./releases.js', () => ({ discoverCliRelease: (...args) => fixture.inspect(...args) }));
9
+
10
+ beforeEach(() => {
11
+ fixture.reject = false; fixture.children = []; fixture.inspect.mockReset(); fixture.fork.mockReset();
12
+ fixture.fork.mockImplementation(() => {
13
+ const child = Object.assign(new EventEmitter(), {
14
+ connected: true, unref: vi.fn(), kill: vi.fn(), disconnect: vi.fn(), send: vi.fn(),
15
+ });
16
+ child.send.mockImplementation((message) => {
17
+ if (message.mode !== 'drain') queueMicrotask(() => child.emit('message', fixture.reject ? { error: 'preflight rejected' } : { ready: true }));
18
+ });
19
+ fixture.children.push(child);
20
+ return child;
21
+ });
22
+ });
23
+ const adapter = (shutdown) => createCliUpdateAdapter({ packageRoot: '/installation/node_modules/@yuriai/web', dataDir: '/data', getPort: () => 3000, currentVersion: '2.0.0', shutdown, env: {} });
24
+
25
+ it('checks install ownership outside the serving process and preserves beta discovery', async () => {
26
+ const host = adapter(vi.fn());
27
+ await host.assertReady();
28
+ expect(fixture.fork.mock.calls[0][2]).toMatchObject({ windowsHide: true, stdio: ['ignore', 'ignore', 'ignore', 'ipc'] });
29
+ expect(fixture.children[0].send).toHaveBeenCalledWith(expect.objectContaining({ mode: 'probe', port: 3000, pid: process.pid }));
30
+ await host.inspect('beta');
31
+ expect(fixture.inspect).toHaveBeenCalledWith('beta', '2.0.0');
32
+ });
33
+
34
+ it('hands the exact accepted task to a detached helper before graceful shutdown', async () => {
35
+ const shutdown = vi.fn(async () => {
36
+ expect(fixture.children[0].send).toHaveBeenCalledWith({ mode: 'drain' });
37
+ });
38
+ const release = { version: '2.1.0-beta.3', kind: 'cli-package', integrity: 'sha512-test' };
39
+ const report = vi.fn();
40
+ await adapter(shutdown).execute({ release, stateFile: '/data/task.json', state: { operation: { id: 'op' } }, report });
41
+ expect(fixture.fork.mock.calls[0][2].detached).toBe(true);
42
+ expect(fixture.children[0].send.mock.calls[0][0]).toMatchObject({ mode: 'update', release, stateFile: '/data/task.json' });
43
+ expect(report).toHaveBeenCalledWith({ status: 'installing' });
44
+ expect(shutdown).toHaveBeenCalledOnce();
45
+ });
46
+
47
+ it('leaves the current Host running when helper preflight fails', async () => {
48
+ fixture.reject = true;
49
+ const shutdown = vi.fn();
50
+ await expect(adapter(shutdown).execute({ release: { version: '2.0.1' }, state: {}, stateFile: '/data/task.json', report: vi.fn() })).rejects.toThrow('preflight');
51
+ expect(shutdown).not.toHaveBeenCalled();
52
+ expect(fixture.children[0].send).not.toHaveBeenCalledWith({ mode: 'drain' });
53
+ });
54
+
55
+ it('advertises development and externally supervised installations as unsupported', () => {
56
+ const host = createCliUpdateAdapter({ packageRoot: '/source/web', dataDir: '/data', env: {} });
57
+ expect(host.supported).toBe(false);
58
+ expect(fixture.fork).not.toHaveBeenCalled();
59
+ });
@@ -0,0 +1,44 @@
1
+ const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-beta\.(0|[1-9]\d*))?$/;
2
+
3
+ export function releaseParts(version) {
4
+ const match = typeof version === 'string' && version.match(VERSION);
5
+ return match ? [Number(match[1]), Number(match[2]), Number(match[3]), match[4] === undefined ? Infinity : Number(match[4])] : null;
6
+ }
7
+
8
+ export function compareVersions(a, b) {
9
+ const left = releaseParts(a);
10
+ const right = releaseParts(b);
11
+ if (!left || !right) throw new Error('Invalid release version');
12
+ for (let i = 0; i < left.length; i++) {
13
+ if (left[i] !== right[i]) return left[i] > right[i] ? 1 : -1;
14
+ }
15
+ return 0;
16
+ }
17
+
18
+ export async function discoverCliRelease(channel, currentVersion, fetchImpl = fetch) {
19
+ const response = await fetchImpl('https://registry.npmjs.org/@yuriai/web', {
20
+ headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(10000),
21
+ });
22
+ if (!response.ok) throw new Error('Unable to check the Yuri package registry');
23
+ const registry = await response.json();
24
+ const tags = registry['dist-tags'] ?? {};
25
+ const candidates = (channel === 'beta' ? [tags.latest, tags.beta] : [tags.latest])
26
+ .filter((v) => releaseParts(v) && (channel === 'beta' || !v.includes('-')))
27
+ .sort(compareVersions);
28
+ const version = candidates.at(-1);
29
+ const metadata = registry.versions?.[version];
30
+ if (!version || metadata?.version !== version || !metadata.dist?.integrity) throw new Error('No installable release in this channel');
31
+ const rollback = channel === 'stable' && currentVersion.includes('-') && compareVersions(version, currentVersion) < 0;
32
+ if (!rollback && compareVersions(version, currentVersion) <= 0) return null;
33
+ let releaseNotes = null;
34
+ try {
35
+ const notes = await fetchImpl(`https://api.github.com/repos/yee94/yuri/releases/tags/v${version}`, {
36
+ headers: { Accept: 'application/vnd.github+json' }, signal: AbortSignal.timeout(5000),
37
+ });
38
+ if (notes.ok) {
39
+ const body = (await notes.json()).body;
40
+ releaseNotes = typeof body === 'string' ? body : null;
41
+ }
42
+ } catch { /* Release notes are optional; registry failure is not. */ }
43
+ return { version, kind: 'cli-package', releaseNotes, rollback, integrity: metadata.dist.integrity, restartRequired: true };
44
+ }
@@ -0,0 +1,33 @@
1
+ /** Auth runs here as well as the global gate; Relay's loopback is not trusted. */
2
+ export function registerHostUpdateRoutes(app, { express, runtime, uiAuthController }) {
3
+ const authorize = async (req, res, next) => {
4
+ try {
5
+ // Only a real bearer can bypass browser-origin protection. URL tokens
6
+ // and unauthenticated loopback requests never authorize self-update.
7
+ const bearer = /^Bearer\s+\S+$/i.test(req.headers.authorization ?? '');
8
+ const authRequest = bearer ? Object.assign(Object.create(req), { headers: { ...req.headers, cookie: undefined } }) : req;
9
+ const context = await uiAuthController.resolveAuthContext(authRequest, res, { allowClientAuth: true, allowUrlToken: false });
10
+ if (!context || (!uiAuthController.enabled && context.type === 'session')) return res.status(401).json({ error: 'update_authentication_required' });
11
+ const origin = req.headers.origin;
12
+ if (context.type !== 'client' && (req.headers['sec-fetch-site'] === 'cross-site' || (origin && origin !== `${req.protocol}://${req.get('host')}`))) {
13
+ return res.status(403).json({ error: 'update_origin_forbidden' });
14
+ }
15
+ next();
16
+ } catch (error) { next(error); }
17
+ };
18
+ app.get('/api/system/update', authorize, async (req, res) => {
19
+ res.setHeader('Cache-Control', 'no-store');
20
+ try {
21
+ const result = await runtime.get(req.query.channel);
22
+ res.status(result.checkFailed ? 502 : 200).json(result);
23
+ } catch (error) { res.status(error.status ?? 500).json({ error: error.code ?? 'update_check_failed' }); }
24
+ });
25
+ app.post('/api/system/update', authorize, express.json({ limit: '16kb' }), async (req, res) => {
26
+ res.setHeader('Cache-Control', 'no-store');
27
+ try { res.status(202).json({ operation: await runtime.start(req.body) }); }
28
+ catch (error) {
29
+ const snapshot = await runtime.get().catch(() => null);
30
+ res.status(error.status ?? 500).json({ error: error.code ?? 'update_start_failed', operation: snapshot?.operation ?? null });
31
+ }
32
+ });
33
+ }
@@ -0,0 +1,104 @@
1
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
2
+ import express from 'express';
3
+ import request from 'supertest';
4
+ import http from 'node:http';
5
+ import { once } from 'node:events';
6
+ import { mkdtemp, rm } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ import crypto from 'node:crypto';
10
+ import { createUiAuth } from '../ui-auth/ui-auth.js';
11
+ import { createRemoteClientAuthRuntime } from '../client-auth/remote-clients.js';
12
+ import * as fsPromises from 'node:fs/promises';
13
+ import { createHostUpdateRuntime } from './runtime.js';
14
+ import { registerHostUpdateRoutes } from './routes.js';
15
+ import { createTunnelHost } from '../relay/tunnel-host.js';
16
+ import { TunnelFrameType, encodeTunnelFrame, encodeJsonPayload, decodeTunnelFrame } from '../relay/tunnel-codec.js';
17
+
18
+ let directory;
19
+ let app;
20
+ let runtime;
21
+ let adapter;
22
+ let token;
23
+ let uiAuth;
24
+ beforeEach(async () => {
25
+ directory = await mkdtemp(path.join(os.tmpdir(), 'host-update-auth-'));
26
+ const clients = createRemoteClientAuthRuntime({ fsPromises, path, crypto, storePath: path.join(directory, 'clients.json') });
27
+ const created = await clients.createClient({ label: 'Test phone', clientKind: 'mobile' });
28
+ token = created.token;
29
+ uiAuth = createUiAuth({ password: null, clientAuthController: clients, readSettingsFromDiskMigrated: async () => ({}) });
30
+ adapter = { host: 'electron', supported: true, inspect: vi.fn(async () => ({ version: '2.0.1', kind: 'ota', releaseNotes: 'Notes', rollback: false })), execute: vi.fn() };
31
+ runtime = createHostUpdateRuntime({ adapter, stateFile: path.join(directory, 'state.json'), currentVersion: '2.0.0', getServerId: async () => 'host-a' });
32
+ app = express();
33
+ registerHostUpdateRoutes(app, { express, runtime, uiAuthController: uiAuth });
34
+ });
35
+ afterEach(async () => { uiAuth.dispose(); vi.useRealTimers(); await rm(directory, { recursive: true, force: true }); });
36
+
37
+ it('rejects unauthenticated loopback, forged cookies and URL credentials', async () => {
38
+ for (const url of ['/api/system/update', `/api/system/update?yuri_url_token=${token}`]) {
39
+ expect((await request(app).get(url).set('Cookie', 'yuri_ui_session=forged')).status).toBe(401);
40
+ }
41
+ expect(adapter.inspect).not.toHaveBeenCalled();
42
+ });
43
+
44
+ it('allows paired mobile bearer updates, but rejects malformed, stale and conflicting plans', async () => {
45
+ const plan = await request(app).get('/api/system/update?channel=beta').set('Authorization', `Bearer ${token}`);
46
+ expect(plan.status).toBe(200);
47
+ expect(plan.body).toMatchObject({ channel: 'beta', serverId: 'host-a', update: { kind: 'ota' } });
48
+ expect(plan.headers['cache-control']).toBe('no-store');
49
+ const body = { version: plan.body.update.version, channel: 'beta', planId: plan.body.update.planId };
50
+ expect((await request(app).post('/api/system/update').set('Authorization', `Bearer ${token}`).send({ ...body, version: 'x;evil' })).status).toBe(400);
51
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
52
+ const accepted = await request(app).post('/api/system/update').set('Authorization', `Bearer ${token}`).send(body);
53
+ expect(accepted.status).toBe(202);
54
+ const duplicate = await request(app).post('/api/system/update').set('Authorization', `Bearer ${token}`).send(body);
55
+ expect(duplicate.body.operation.id).toBe(accepted.body.operation.id);
56
+ const conflict = await request(app).post('/api/system/update').set('Authorization', `Bearer ${token}`).send({ ...body, version: '2.0.2' });
57
+ expect(conflict.status).toBe(409);
58
+ expect(conflict.body.operation.status).toBe('checking');
59
+ });
60
+
61
+ it('keeps the current task visible when update discovery fails', async () => {
62
+ adapter.inspect.mockRejectedValue(new Error('offline'));
63
+ const response = await request(app).get('/api/system/update').set('Authorization', `Bearer ${token}`);
64
+ expect(response.status).toBe(502);
65
+ expect(response.body).toMatchObject({ checkError: 'update_check_failed', operation: null });
66
+ });
67
+
68
+ it('rejects cross-site cookie sessions even with a syntactically valid but unverified bearer', async () => {
69
+ const fake = { enabled: true, resolveAuthContext: vi.fn(async () => ({ type: 'session' })) };
70
+ const secured = express();
71
+ registerHostUpdateRoutes(secured, { express, runtime, uiAuthController: fake });
72
+ const response = await request(secured).post('/api/system/update').set('Origin', 'https://attacker.example').set('Authorization', 'Bearer invalid').send({});
73
+ expect(response.status).toBe(403);
74
+ });
75
+
76
+ it('uses the real Relay dispatcher without injecting credentials for GET and POST', async () => {
77
+ const server = http.createServer(app);
78
+ server.listen(0, '127.0.0.1');
79
+ await once(server, 'listening');
80
+ const frames = [];
81
+ const tunnel = createTunnelHost({ connectionId: 'host-update', getLocalPort: () => server.address().port,
82
+ sendFrame: (frame) => { frames.push(decodeTunnelFrame(frame)); }, getBufferedAmount: () => 0 });
83
+ const call = async (stream, method, headers, body) => {
84
+ await tunnel.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpRequest, stream, encodeJsonPayload({ method, path: '/api/system/update', query: '', headers })));
85
+ if (body) await tunnel.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpBody, stream, Buffer.from(JSON.stringify(body))));
86
+ await tunnel.handleFrame(encodeTunnelFrame(TunnelFrameType.StreamEnd, stream, new Uint8Array()));
87
+ await vi.waitFor(() => expect(frames.some((frame) => frame.streamId === stream && frame.frameType === TunnelFrameType.StreamEnd)).toBe(true));
88
+ const own = frames.filter((frame) => frame.streamId === stream);
89
+ const head = JSON.parse(new TextDecoder().decode(own.find((frame) => frame.frameType === TunnelFrameType.HttpResponse).payload));
90
+ const data = JSON.parse(Buffer.concat(own.filter((frame) => frame.frameType === TunnelFrameType.HttpBody).map((frame) => Buffer.from(frame.payload))).toString());
91
+ return { head, data };
92
+ };
93
+ try {
94
+ expect((await call(1, 'GET', {})).head.status).toBe(401);
95
+ const plan = await call(3, 'GET', { authorization: `Bearer ${token}` });
96
+ expect(plan.head.status).toBe(200);
97
+ const accepted = await call(5, 'POST', { authorization: `Bearer ${token}`, 'content-type': 'application/json' }, {
98
+ version: plan.data.update.version, channel: plan.data.channel, planId: plan.data.update.planId,
99
+ });
100
+ expect(accepted.head.status).toBe(202);
101
+ expect((await call(7, 'GET', { authorization: `Bearer ${token}` })).data.operation.id).toBe(accepted.data.operation.id);
102
+ await new Promise((resolve) => setTimeout(resolve, 550));
103
+ } finally { tunnel.close(); server.closeAllConnections(); await new Promise((resolve) => server.close(resolve)); }
104
+ });