@yuriai/web 0.2.1 → 0.2.6
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.
- package/bin/lib/DOCUMENTATION.md +1 -0
- package/dist/assets/{AgentAvatar-BeM4lXfE.js → AgentAvatar-MzDm6uBf.js} +1 -1
- package/dist/assets/AssistantView-Ct7V8lpF.js +3 -0
- package/dist/assets/DiagramView-Ch2D2gUQ.js +1 -0
- package/dist/assets/{FadeInOnReveal-B8BCjwPb.js → FadeInOnReveal-DkmfVoTO.js} +1 -1
- package/dist/assets/{GuiPluginSurface-DIPLwOYq.js → GuiPluginSurface-sdtt33qQ.js} +1 -1
- package/dist/assets/{GuiPluginWindow-jUuZl9JF.js → GuiPluginWindow-dDG5Uyqb.js} +1 -1
- package/dist/assets/{Icon-DofI60x2.js → Icon-BjiyvtB2.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-7jM-y96Q.js → ImageLoadingPlaceholder-CUKFQTAG.js} +1 -1
- package/dist/assets/{LoadingImage-DV6Neoja.js → LoadingImage-B7cT_4Oe.js} +1 -1
- package/dist/assets/MarkdownRenderer-C1giOHSB.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-B0JOirRM.js → MarkdownRendererImpl-CtfnAdo-.js} +2 -2
- package/dist/assets/{MarkstreamRendererImpl-96Mp8TZ6.js → MarkstreamRendererImpl-CWtvbZSX.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-9ZlwSUXP.js → MobileDetailNavigation-CUx-H4fe.js} +1 -1
- package/dist/assets/{MobileResizableSheet-CuRgnS-k.js → MobileResizableSheet-C9YzOQis.js} +1 -1
- package/dist/assets/MobileShareBridge-DUwPWQNz.js +4 -0
- package/dist/assets/MobileTabPageHeader-BtLdnDa3.js +2 -0
- package/dist/assets/{MultiRunWindow-Bhl5GdPt.js → MultiRunWindow-Gs-5PM3Z.js} +1 -1
- package/dist/assets/OnboardingScreen-D6iQ5qjF.js +1 -0
- package/dist/assets/{OverlayScrollbar-Bi17Olmj.js → OverlayScrollbar-Dbx1atD-.js} +1 -1
- package/dist/assets/SettingsView-BJy3bKbz.js +26 -0
- package/dist/assets/{SettingsWindow-wet6Qnx3.js → SettingsWindow-w3K1Dbo1.js} +1 -1
- package/dist/assets/TerminalView-DnmN2KHj.js +8 -0
- package/dist/assets/{ToolOutputDialog-UrL8sue9.js → ToolOutputDialog-Ctr_rqwb.js} +3 -3
- package/dist/assets/{YuriLogo-D9cfwLdW.js → YuriLogo-DvRSd5NN.js} +1 -1
- package/dist/assets/appThemeRegistry-3MgV1x6f.js +1 -0
- package/dist/assets/{assistant-attachment-cache-Ul88TuFO.js → assistant-attachment-cache-lEUFn3mr.js} +1 -1
- package/dist/assets/button-BSFWH-Ok.js +1 -0
- package/dist/assets/{capgoAdapter-BvTGibVJ.js → capgoAdapter-CpthNQYY.js} +1 -1
- package/dist/assets/{collapsible-UDWFNcbF.js → collapsible-DaevjAvt.js} +1 -1
- package/dist/assets/{desktop-CfMDfs6c.js → desktop-dp2Z0toS.js} +1 -1
- package/dist/assets/desktopHosts-CYKaLp1V.js +1 -0
- package/dist/assets/{desktopRelayRestore-aNSNYVEB.js → desktopRelayRestore-5yuHB356.js} +1 -1
- package/dist/assets/device-B7GyZCPd.js +2 -0
- package/dist/assets/{diagram-BxF_wECt.js → diagram-7OgmyecX.js} +1 -1
- package/dist/assets/dialog-D1pXn_b9.js +1 -0
- package/dist/assets/dropdown-menu.styles-CGHPvEgD.js +1 -0
- package/dist/assets/{es-iuy57SFI.js → es-DJzbuYpv.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-BLvRkcZy.js → fileMentionTouchSelection-1havvnZN.js} +1 -1
- package/dist/assets/{fileQueries-voABZL1r.js → fileQueries-DbUx7NwP.js} +1 -1
- package/dist/assets/{fileReferenceActions-ui8464r-.js → fileReferenceActions-No7p4Kdo.js} +1 -1
- package/dist/assets/{fr-LyrJa2Qb.js → fr-YDYbYIZQ.js} +1 -1
- package/dist/assets/gitApi-Bw4AQDuA.js +10 -0
- package/dist/assets/gui-BCPFcL_m.js +1 -0
- package/dist/assets/{host-1RDqqL9w.js → host--4S0vJsG.js} +1 -1
- package/dist/assets/{image-loading-Bqi69xpy.js → image-loading-FUFYiO1j.js} +1 -1
- package/dist/assets/{input-D86Oqf3B.js → input-BhHXFla6.js} +1 -1
- package/dist/assets/insertionBoundaries-_8AmjaTs.js +1 -0
- package/dist/assets/{ja-QqNYiTeY.js → ja-SjX3NBJz.js} +1 -1
- package/dist/assets/{ko-CL-s2hwZ.js → ko-BxcUEWjB.js} +1 -1
- package/dist/assets/main-C09TKUe7.js +169 -0
- package/dist/assets/main-C5PgzX4P.js +2 -0
- package/dist/assets/{markdownHeightCache-DB_NzPGt.js → markdownHeightCache-DV2j4PlS.js} +1 -1
- package/dist/assets/mcpQueries-B-cYFZaO.js +1 -0
- package/dist/assets/miniChat-C_az-fSk.js +2 -0
- package/dist/assets/mobile-CnXTR6QC.js +2 -0
- package/dist/assets/{mobileBackNavigation-CyumxcRr.js → mobileBackNavigation-DSDlOhh6.js} +1 -1
- package/dist/assets/multirun-DgLVkagL.js +3 -0
- package/dist/assets/native-config-w5ntuSb5.js +1 -0
- package/dist/assets/{persistence-Ck0wskDR.js → persistence-BfjCXjLZ.js} +1 -1
- package/dist/assets/{pl-AKGY_sFU.js → pl-vh0XFuDb.js} +1 -1
- package/dist/assets/platform-DXeTzJHG.js +7 -0
- package/dist/assets/{projectMeta-WDYXNks8.js → projectMeta-OMvGIxob.js} +1 -1
- package/dist/assets/{pt-BR-BFRFGU_b.js → pt-BR-Cv5tssQz.js} +1 -1
- package/dist/assets/{queryRuntime-CpsVmMzy.js → queryRuntime-BuRnpVtK.js} +1 -1
- package/dist/assets/{readiness-Dp48zAJz.js → readiness-6XMJtgLY.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-rvO-rcnc.js +2 -0
- package/dist/assets/renderMobileApp-DheZQr5N.js +28 -0
- package/dist/assets/runtime-fetch-BAN5Gnnp.js +1 -0
- package/dist/assets/{runtime-file-download-J_Vcm3tT.js → runtime-file-download-BzblfnMx.js} +1 -1
- package/dist/assets/{runtime-file-resource-Disaet9c.js → runtime-file-resource-D3k0hKDj.js} +1 -1
- package/dist/assets/runtime-switch-CAZiOV2G.js +1 -0
- package/dist/assets/runtimeConfig-cAbdKbv6.js +2 -0
- package/dist/assets/runtimeEndpointReset-CPsJLvK2.js +149 -0
- package/dist/assets/{scheduledTaskNavigation-C6FKpwPD.js → scheduledTaskNavigation-BZ3B5bpN.js} +1 -1
- package/dist/assets/{sessionChangeSummary-BJbopgHT.js → sessionChangeSummary-BEB6JZpN.js} +1 -1
- package/dist/assets/sessionLookup-BI5wTzCJ.js +1 -0
- package/dist/assets/{sortable-tabs-strip-CSXgXPyP.js → sortable-tabs-strip-BnTV_KYG.js} +1 -1
- package/dist/assets/speechSettingsQueries-DZ9a20QR.js +4 -0
- package/dist/assets/src-NlrSCyPZ.css +2 -0
- package/dist/assets/{store-CGMD02tA.js → store-CgQdmzpX.js} +2 -2
- package/dist/assets/terminalApi-CIbkfDkE.js +1 -0
- package/dist/assets/{textarea-CMvxcQhR.js → textarea-Deh9E1KP.js} +1 -1
- package/dist/assets/{tooltip-CnIKZ6bg.js → tooltip-DygQ-2xe.js} +1 -1
- package/dist/assets/{types-BUsGt9HF.js → types-BihDq7ZW.js} +1 -1
- package/dist/assets/{uk-C21_nQhw.js → uk-3a9vdLJ-.js} +1 -1
- package/dist/assets/{useAppFontEffects-IGLoyUFr.js → useAppFontEffects-CKCYZ3VJ.js} +27 -27
- package/dist/assets/{useAssistantUIStore-4a569vpy.js → useAssistantUIStore-D7JZlg_Q.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-CloJ_VZ3.js +1 -0
- package/dist/assets/useEffectiveDirectory-CuajC8G4.js +1 -0
- package/dist/assets/{useFontPreferences-BPTEYhfn.js → useFontPreferences-51P_6ZRi.js} +1 -1
- package/dist/assets/useMobileNavigationStore-07uYrwvK.js +417 -0
- package/dist/assets/useUIStore-NMQx_cnG.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-Cgiz5cUq.js → useWorkerHighlightedLines-2Vw7Hzud.js} +1 -1
- package/dist/assets/{zh-CN-C7PVNr9_.js → zh-CN-kwaUr5W5.js} +1 -1
- package/dist/assets/{zh-TW-DLLoB3-e.js → zh-TW-BBs44W7l.js} +1 -1
- package/dist/index.html +19 -21
- package/dist/mini-chat.html +19 -21
- package/dist/mobile.html +19 -21
- package/package.json +1 -1
- package/server/index.d.ts +17 -0
- package/server/index.js +22 -1
- package/server/lib/assistants/DOCUMENTATION.md +16 -0
- package/server/lib/assistants/harness.js +3 -0
- package/server/lib/assistants/harness.test.js +48 -1
- package/server/lib/host-update/DOCUMENTATION.md +97 -0
- package/server/lib/host-update/cli-worker.js +132 -0
- package/server/lib/host-update/cli.js +62 -0
- package/server/lib/host-update/cli.test.js +59 -0
- package/server/lib/host-update/releases.js +44 -0
- package/server/lib/host-update/routes.js +33 -0
- package/server/lib/host-update/routes.test.js +104 -0
- package/server/lib/host-update/runtime.js +140 -0
- package/server/lib/host-update/runtime.test.js +141 -0
- package/server/lib/llm/DOCUMENTATION.md +24 -5
- package/server/lib/llm/completions.js +6 -0
- package/server/lib/llm/completions.test.js +14 -0
- package/server/lib/llm/generate.js +30 -10
- package/server/lib/llm/generate.test.js +64 -1
- package/server/lib/opencode/bootstrap-runtime.js +2 -0
- package/server/lib/opencode/yuri-routes.js +7 -206
- package/server/lib/opencode/yuri-routes.test.js +6 -6
- package/server/lib/projects/project-config.js +5 -1
- package/server/lib/projects/project-config.test.js +26 -0
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +19 -5
- package/server/lib/scheduled-tasks/SESSION_SKILL.md +21 -3
- package/server/lib/scheduled-tasks/routes.js +22 -4
- package/server/lib/scheduled-tasks/routes.test.js +3 -0
- package/server/lib/scheduled-tasks/session-skill-client.mjs +20 -16
- package/server/lib/scheduled-tasks/session-skill.js +55 -12
- package/server/lib/scheduled-tasks/session-skill.test.js +64 -0
- package/server/sse-routes.test.js +3 -0
- package/dist/assets/AssistantView-7qr-iEdP.js +0 -3
- package/dist/assets/DiagramView-CD2lyJo4.js +0 -1
- package/dist/assets/GuiPluginLoadingNotice-DjO_uy_0.js +0 -1
- package/dist/assets/MarkdownRenderer-Db-If3tk.js +0 -2
- package/dist/assets/MobileShareBridge-DM3xAVdm.js +0 -4
- package/dist/assets/MobileTabPageHeader-LVBIRzcs.js +0 -2
- package/dist/assets/OnboardingScreen-hvLlaoKt.js +0 -1
- package/dist/assets/SettingsView-NfjqTxIN.js +0 -26
- package/dist/assets/TerminalView-BXulu3RW.js +0 -8
- package/dist/assets/appThemeRegistry-BlucERDr.js +0 -1
- package/dist/assets/button-CT7WL0lp.js +0 -1
- package/dist/assets/clipboard-Bj6jZiuP.js +0 -1
- package/dist/assets/desktopHosts-BEzVZGiW.js +0 -1
- package/dist/assets/device-BDrEmxBm.js +0 -2
- package/dist/assets/dialog-BpsbJk8Y.js +0 -1
- package/dist/assets/download-progress-MobTWf23.js +0 -1
- package/dist/assets/dropdown-menu.styles-MkqoyFTv.js +0 -1
- package/dist/assets/gitApi-DgBiaLFA.js +0 -10
- package/dist/assets/gitApiHttp-BhcxUxqo.js +0 -7
- package/dist/assets/gui-CTKa6rbU.js +0 -1
- package/dist/assets/insertionBoundaries-YFGFUgWP.js +0 -1
- package/dist/assets/main-BniroGdt.js +0 -2
- package/dist/assets/main-CdSf07-K.js +0 -169
- package/dist/assets/mcpQueries-C-nazLvB.js +0 -1
- package/dist/assets/miniChat-tsfTW6ta.js +0 -2
- package/dist/assets/mobile-DKmqw9JK.js +0 -2
- package/dist/assets/multirun-oqrPQGWy.js +0 -3
- package/dist/assets/native-config-Ban8ER0D.js +0 -1
- package/dist/assets/platform-kv0OsX45.js +0 -1
- package/dist/assets/reasoning-projection-client-BEhVknv9.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-CD4LwiXX.js +0 -2
- package/dist/assets/renderMobileApp-NSBm1xYQ.js +0 -28
- package/dist/assets/runtime-fetch-BclMrQHc.js +0 -1
- package/dist/assets/runtime-switch-WzPG6NMR.js +0 -1
- package/dist/assets/runtimeConfig-CG-Ua9P-.js +0 -2
- package/dist/assets/runtimeEndpointReset-BEXrIK9C.js +0 -149
- package/dist/assets/scheduling-DCTDfxV-.js +0 -1
- package/dist/assets/sessionLookup-sLNgV6qV.js +0 -1
- package/dist/assets/speechSettingsQueries-CHUF4UQ6.js +0 -4
- package/dist/assets/src-DISp5rL3.css +0 -2
- package/dist/assets/terminalApi-B_oHorrS.js +0 -1
- package/dist/assets/useDesktopWindowControlsLayout-DepZ1Abm.js +0 -1
- package/dist/assets/useEffectiveDirectory-Dhn1RiMm.js +0 -1
- package/dist/assets/useMobileNavigationStore-BPOHzqoM.js +0 -417
- package/dist/assets/useUIStore-DqtgX2FB.js +0 -1
|
@@ -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)
|
|
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
|
+
});
|