@yuriai/web 0.1.26 → 0.2.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dist/assets/{AgentAvatar-C2p8G_Xw.js → AgentAvatar-BeM4lXfE.js} +1 -1
- package/dist/assets/AssistantView-Dm8d0x2w.js +3 -0
- package/dist/assets/DiagramView-C4ZjTE0G.js +1 -0
- package/dist/assets/{FadeInOnReveal-DhAYqopy.js → FadeInOnReveal-B8BCjwPb.js} +1 -1
- package/dist/assets/GuiPluginLoadingNotice-DjO_uy_0.js +1 -0
- package/dist/assets/GuiPluginSurface-BvRr8l5C.js +1 -0
- package/dist/assets/GuiPluginWindow-DiSlroCy.js +1 -0
- package/dist/assets/{Icon-DKFfVCeK.js → Icon-DofI60x2.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-DD2g7FjK.js → ImageLoadingPlaceholder-CZSbfJci.js} +1 -1
- package/dist/assets/{LoadingImage-Dc7hnEQ7.js → LoadingImage-BA2Cwg_Q.js} +1 -1
- package/dist/assets/MarkdownRenderer-CMuViXr5.js +2 -0
- package/dist/assets/MarkdownRendererImpl-6Bnt3u0h.js +10 -0
- package/dist/assets/MarkstreamRendererImpl-hkXOvfpV.js +3 -0
- package/dist/assets/MobileDetailNavigation-28tDmA9W.js +1 -0
- package/dist/assets/MobileResizableSheet-CuRgnS-k.js +1 -0
- package/dist/assets/MobileShareBridge-3FLzBi3t.js +4 -0
- package/dist/assets/MobileTabPageHeader-Ca_SmN6a.js +2 -0
- package/dist/assets/{MultiRunWindow-DnKgSNFU.js → MultiRunWindow-D-_kpGx3.js} +1 -1
- package/dist/assets/OnboardingScreen-hvLlaoKt.js +1 -0
- package/dist/assets/OverlayScrollbar-Bi17Olmj.js +1 -0
- package/dist/assets/SettingsView-DKdzVs_l.js +26 -0
- package/dist/assets/{SettingsWindow-DfZZulsn.js → SettingsWindow-BBsVtas5.js} +1 -1
- package/dist/assets/TerminalView-BvQNcWMM.js +8 -0
- package/dist/assets/{ToolOutputDialog-Hdg-97em.js → ToolOutputDialog-CP3O-GS5.js} +3 -3
- package/dist/assets/{YuriLogo-CgTkNYZf.js → YuriLogo-D9cfwLdW.js} +1 -1
- package/dist/assets/appThemeRegistry-BpEwes4H.js +1 -0
- package/dist/assets/assistant-attachment-cache-Cqs65voA.js +1 -0
- package/dist/assets/button-CT7WL0lp.js +1 -0
- package/dist/assets/{capgoAdapter-CophGZfT.js → capgoAdapter-DX784Pe3.js} +1 -1
- package/dist/assets/clipboard-Bj6jZiuP.js +1 -0
- package/dist/assets/{collapsible-CbQmi7qt.js → collapsible-UDWFNcbF.js} +1 -1
- package/dist/assets/desktop-CfMDfs6c.js +1 -0
- package/dist/assets/desktopHosts-BEzVZGiW.js +1 -0
- package/dist/assets/desktopRelayRestore-aNSNYVEB.js +1 -0
- package/dist/assets/device-BDrEmxBm.js +2 -0
- package/dist/assets/{diagram-DWkoS1Uc.js → diagram-BxF_wECt.js} +1 -1
- package/dist/assets/dialog-BpsbJk8Y.js +1 -0
- package/dist/assets/download-progress-MobTWf23.js +1 -0
- package/dist/assets/dropdown-menu.styles-D6MTYFvx.js +1 -0
- package/dist/assets/{es-Le3f45R2.js → es-iuy57SFI.js} +2 -2
- package/dist/assets/{fileMentionTouchSelection-D8FLYpv9.js → fileMentionTouchSelection-B_i_7dYW.js} +2 -2
- package/dist/assets/fileQueries-voABZL1r.js +1 -0
- package/dist/assets/fileReferenceActions-CgsqIeIM.js +1 -0
- package/dist/assets/fileReferenceParser-1HHDBUum.js +1 -0
- package/dist/assets/{fr-Knp2_Wkz.js → fr-LyrJa2Qb.js} +2 -2
- package/dist/assets/gitApi-CrDc4tQM.js +10 -0
- package/dist/assets/gitApiHttp-BKM9BbT8.js +7 -0
- package/dist/assets/gui-CTKa6rbU.js +1 -0
- package/dist/assets/host-CIYNejrE.js +1 -0
- package/dist/assets/image-loading-ClQZD7Z9.js +1 -0
- package/dist/assets/{input-CAhwlkOT.js → input-D86Oqf3B.js} +1 -1
- package/dist/assets/insertionBoundaries--Mxpk0of.js +1 -0
- package/dist/assets/{ja-_KJ_VLgM.js → ja-QqNYiTeY.js} +2 -2
- package/dist/assets/{ko-CmWIeRHF.js → ko-CL-s2hwZ.js} +2 -2
- package/dist/assets/main-B-pfFh5C.js +2 -0
- package/dist/assets/main-CBw2dbar.js +169 -0
- package/dist/assets/markdown-worker-oBGEB9Eg.js +1 -0
- package/dist/assets/{markdownHeightCache-CylzGsAe.js → markdownHeightCache-DB_NzPGt.js} +1 -1
- package/dist/assets/mcpQueries-U-JjFZe4.js +1 -0
- package/dist/assets/miniChat-Divc4WsR.js +2 -0
- package/dist/assets/mobile-CHlohOym.js +2 -0
- package/dist/assets/{mobileBackNavigation-BX1Pz7aE.js → mobileBackNavigation-BTsVwetY.js} +1 -1
- package/dist/assets/multirun-0upiMbGe.js +3 -0
- package/dist/assets/native-BMAEg2E6.js +1 -0
- package/dist/assets/native-config-C83Wsn8E.js +1 -0
- package/dist/assets/native-errors-06if6eu-.js +1 -0
- package/dist/assets/path-utils-jGozTg9d.js +1 -0
- package/dist/assets/pathNormalization-ewtPqJWn.js +1 -0
- package/dist/assets/persistence-Ck0wskDR.js +3 -0
- package/dist/assets/{pl-BoXY-ki3.js → pl-AKGY_sFU.js} +2 -2
- package/dist/assets/platform-kv0OsX45.js +1 -0
- package/dist/assets/projectMeta-Dby3r3KM.js +1 -0
- package/dist/assets/{pt-BR-C3gsTrhe.js → pt-BR-BFRFGU_b.js} +2 -2
- package/dist/assets/queryRuntime-CpsVmMzy.js +1 -0
- package/dist/assets/react-BYRXYlGz.js +1 -0
- package/dist/assets/readiness-BQJwpJCM.js +1 -0
- package/dist/assets/reasoning-projection-client-BEhVknv9.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-DCn2MimJ.js +2 -0
- package/dist/assets/renderMobileApp-Ci07NPvv.js +28 -0
- package/dist/assets/runtime-fetch-BclMrQHc.js +1 -0
- package/dist/assets/runtime-file-download-CZ2qtdn9.js +1 -0
- package/dist/assets/runtime-file-resource-CEkq2Pj2.js +2 -0
- package/dist/assets/runtime-file-store-BVRgEtI-.js +1 -0
- package/dist/assets/runtime-switch-WzPG6NMR.js +1 -0
- package/dist/assets/runtimeAPIRegistry-C2VogTny.js +1 -0
- package/dist/assets/runtimeConfig-CW8O4Hdh.js +2 -0
- package/dist/assets/{runtimeEndpointReset-DmY_4gYI.css → runtimeEndpointReset-HYSytKO-.css} +1 -1
- package/dist/assets/runtimeEndpointReset-sMvhXyD5.js +149 -0
- package/dist/assets/{scheduledTaskNavigation-meXpw7b3.js → scheduledTaskNavigation-tOa4Azh_.js} +1 -1
- package/dist/assets/scheduling-DCTDfxV-.js +1 -0
- package/dist/assets/sessionChangeSummary-D1S2fFAs.js +1 -0
- package/dist/assets/sessionLookup-CB0s60IX.js +1 -0
- package/dist/assets/sortable-tabs-strip-CSXgXPyP.js +1 -0
- package/dist/assets/speechSettingsQueries-OwiKVz92.js +4 -0
- package/dist/assets/src-r07HspQy.css +2 -0
- package/dist/assets/{store-CnVXA4NH.js → store-CGMD02tA.js} +3 -3
- package/dist/assets/terminalApi-DbFIyF-J.js +1 -0
- package/dist/assets/textarea-CMvxcQhR.js +1 -0
- package/dist/assets/toolHelpers-DL452NVK.js +2 -0
- package/dist/assets/{tooltip-CFuO3PUH.js → tooltip-CnIKZ6bg.js} +1 -1
- package/dist/assets/types-CCb-BgPn.js +2 -0
- package/dist/assets/{uk-VUOVH9qH.js → uk-C21_nQhw.js} +2 -2
- package/dist/assets/url-MRa-FtQa.js +1 -0
- package/dist/assets/{useAppFontEffects-DSHn-okJ.js → useAppFontEffects-B-fcxfDS.js} +53 -53
- package/dist/assets/{useAssistantUIStore-D7JZlg_Q.js → useAssistantUIStore-4a569vpy.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-ak-khGJO.js +1 -0
- package/dist/assets/useEffectiveDirectory-gmGePjIo.js +1 -0
- package/dist/assets/{useFontPreferences-Daujs94n.js → useFontPreferences-Dx-plsme.js} +1 -1
- package/dist/assets/useMobileNavigationStore-Qofc0k-e.js +417 -0
- package/dist/assets/useUIStore-DqtgX2FB.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-BmZl_Azr.js → useWorkerHighlightedLines-CpGZT6ts.js} +2 -2
- package/dist/assets/vendor-effect-DV9F8PTZ.js +33 -0
- package/dist/assets/vendor-opencode-client-fxfj4IA_.js +12 -0
- package/dist/assets/vendor-opencode-plugin-CQ5ogY33.js +1 -0
- package/dist/assets/vendor-solid-js-Dmt4_-Zk.js +1 -0
- package/dist/assets/yuri-mark-black-DxEnMyCE.svg +1 -0
- package/dist/assets/{zh-CN-CqOn122C.js → zh-CN-C7PVNr9_.js} +2 -2
- package/dist/assets/{zh-TW-53yr6Fdj.js → zh-TW-DLLoB3-e.js} +2 -2
- package/dist/index.html +30 -21
- package/dist/mini-chat.html +33 -32
- package/dist/mobile.html +36 -21
- package/package.json +1 -1
- package/server/index.d.ts +2 -0
- package/server/index.js +8 -1
- package/server/lib/content-search/DOCUMENTATION.md +5 -1
- package/server/lib/content-search/runtime.js +24 -0
- package/server/lib/content-search/runtime.test.js +19 -0
- package/server/lib/fs/DOCUMENTATION.md +1 -0
- package/server/lib/fs/binary-file.d.ts +3 -0
- package/server/lib/fs/binary-file.js +21 -0
- package/server/lib/fs/routes.js +1 -21
- package/server/lib/fs/routes.test.js +43 -0
- package/server/lib/opencode/DOCUMENTATION.md +5 -0
- package/server/lib/opencode/gui-plugin-source.js +14 -0
- package/server/lib/opencode/gui-plugin-source.test.js +28 -0
- package/server/lib/opencode/plugin-gui-response.d.ts +7 -0
- package/server/lib/opencode/plugin-gui-response.js +62 -0
- package/server/lib/opencode/plugin-gui-response.test.js +89 -0
- package/server/lib/opencode/proxy.js +32 -0
- package/server/lib/relay/DOCUMENTATION.md +1 -0
- package/server/lib/relay/relay-server.e2e.test.ts +73 -3
- package/server/lib/request-cors.js +2 -2
- package/server/lib/request-cors.test.js +3 -0
- package/server/lib/session-index/DOCUMENTATION.md +4 -0
- package/server/lib/session-index/sync-runtime.js +3 -0
- package/server/lib/session-index/sync-runtime.test.js +18 -0
- package/server/plugin-gui-proxy.test.js +134 -0
- package/dist/assets/AssistantView-BpH66j_M.js +0 -3
- package/dist/assets/DiagramView-BUSKNHpA.js +0 -1
- package/dist/assets/MarkdownRenderer-Cv0uQm6P.js +0 -2
- package/dist/assets/MarkdownRendererImpl-DdA8OTyc.js +0 -10
- package/dist/assets/MarkstreamRendererImpl-C_pmUgRH.js +0 -3
- package/dist/assets/MobileDetailNavigation-C8ay670M.js +0 -1
- package/dist/assets/MobileShareBridge-BRKIMBu6.js +0 -4
- package/dist/assets/MobileTabPageHeader-DFCwfVMX.js +0 -2
- package/dist/assets/OnboardingScreen-Dau5R5ew.js +0 -1
- package/dist/assets/OverlayScrollbar-CWK4F7aC.js +0 -2
- package/dist/assets/SettingsView-Ciha0BxW.js +0 -26
- package/dist/assets/TerminalView-CIbymc9n.js +0 -8
- package/dist/assets/appThemeRegistry-dIFOkzfO.js +0 -1
- package/dist/assets/assistant-attachment-cache-CLnqffXU.js +0 -1
- package/dist/assets/button-LPikURUk.js +0 -1
- package/dist/assets/desktopHosts-DW8THEMC.js +0 -1
- package/dist/assets/desktopRelayRestore-BFn1FsR3.js +0 -1
- package/dist/assets/dialog-D8AYQa70.js +0 -1
- package/dist/assets/dropdown-menu.styles-3mrmi5fY.js +0 -1
- package/dist/assets/gitApi-CVqZBJOp.js +0 -10
- package/dist/assets/image-loading-23c-W-bq.js +0 -1
- package/dist/assets/insertionBoundaries-QcQpX59t.js +0 -1
- package/dist/assets/main-BcPly9IC.js +0 -169
- package/dist/assets/main-Di7p8GjN.js +0 -2
- package/dist/assets/markdown-worker-7FvUo2nm.js +0 -2
- package/dist/assets/mcpQueries-CW2h7NXI.js +0 -1
- package/dist/assets/miniChat-Cs-7LXyP.js +0 -2
- package/dist/assets/mobile-CGsmrhgA.js +0 -2
- package/dist/assets/multirun-BX9ykMyO.js +0 -3
- package/dist/assets/native-config-FUMqP3sd.js +0 -1
- package/dist/assets/persistence-Dzooc9Xg.js +0 -3
- package/dist/assets/platform-BT4vb0rs.js +0 -7
- package/dist/assets/projectMeta-BFtPKaOK.js +0 -1
- package/dist/assets/queryRuntime-DKGLQtb9.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-Bq0m9Qhc.js +0 -2
- package/dist/assets/renderMobileApp-P5KrVIBw.js +0 -28
- package/dist/assets/runtime-file-download-DAOam_oV.js +0 -1
- package/dist/assets/runtime-file-resource-C1k5nbWb.js +0 -2
- package/dist/assets/runtime-switch-CAZiOV2G.js +0 -1
- package/dist/assets/runtimeConfig-9HBA_MyT.js +0 -2
- package/dist/assets/runtimeEndpointReset-DeytUJtO.js +0 -149
- package/dist/assets/sessionChangeSummary-C9h6xZd8.js +0 -1
- package/dist/assets/sessionLookup-D15ec6WY.js +0 -1
- package/dist/assets/sortable-tabs-strip-Qxgcs21u.js +0 -1
- package/dist/assets/speechSettingsQueries-BiiCAU-s.js +0 -4
- package/dist/assets/src-DlJVKekb.css +0 -2
- package/dist/assets/terminalApi-bFOdIit8.js +0 -1
- package/dist/assets/textarea-bZ1VMrmO.js +0 -1
- package/dist/assets/types-ziSFePSf.js +0 -2
- package/dist/assets/url-Be8VCT8M.js +0 -1
- package/dist/assets/useDesktopWindowControlsLayout-BJfaVDLo.js +0 -1
- package/dist/assets/useEffectiveDirectory-D4M0iYdf.js +0 -1
- package/dist/assets/useMobileNavigationStore-B5EmTMWP.js +0 -417
- package/dist/assets/useUIStore-NMQx_cnG.js +0 -1
- package/dist/assets/vendor-opencode-client-XDI8AfPJ.js +0 -12
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
|
|
3
|
+
const REVISION_HEADER = 'x-yuri-gui-revision';
|
|
4
|
+
const CODE_HEADER = 'x-yuri-gui-code';
|
|
5
|
+
const FULL_RESPONSE_HEADERS = new Set([
|
|
6
|
+
REVISION_HEADER, CODE_HEADER, 'if-none-match', 'if-modified-since',
|
|
7
|
+
'if-match', 'if-unmodified-since', 'if-range', 'range',
|
|
8
|
+
]);
|
|
9
|
+
|
|
10
|
+
/** Only the official GUI read opts into Yuri's code-only reuse protocol. */
|
|
11
|
+
export const preparePluginGuiRequest = (method, requestPath, headers) => {
|
|
12
|
+
if (method !== 'GET') return null;
|
|
13
|
+
const url = new URL(requestPath, 'http://yuri.invalid');
|
|
14
|
+
if (url.pathname !== '/api/plugin/gui'
|
|
15
|
+
|| url.searchParams.getAll('id').length !== 1
|
|
16
|
+
|| !url.searchParams.get('id')) return null;
|
|
17
|
+
|
|
18
|
+
let revision = null;
|
|
19
|
+
const forwarded = {};
|
|
20
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
21
|
+
const name = key.toLowerCase();
|
|
22
|
+
if (name === REVISION_HEADER && /^[a-f0-9]{64}$/.test(value)) revision = value;
|
|
23
|
+
if (!FULL_RESPONSE_HEADERS.has(name)) forwarded[key] = value;
|
|
24
|
+
}
|
|
25
|
+
forwarded['accept-encoding'] = 'identity';
|
|
26
|
+
return { headers: forwarded, revision };
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
30
|
+
|
|
31
|
+
/** No history/cache: only this request's complete, validated upstream 200 can omit code. */
|
|
32
|
+
export const projectPluginGuiResponse = async (response, requestedRevision) => {
|
|
33
|
+
if (response.status !== 200) return response;
|
|
34
|
+
const headers = new Headers(response.headers);
|
|
35
|
+
headers.set('cache-control', 'private, no-store');
|
|
36
|
+
headers.delete(REVISION_HEADER);
|
|
37
|
+
headers.delete(CODE_HEADER);
|
|
38
|
+
headers.delete('etag');
|
|
39
|
+
headers.delete('last-modified');
|
|
40
|
+
headers.delete('content-length');
|
|
41
|
+
headers.delete('content-encoding');
|
|
42
|
+
headers.delete('transfer-encoding');
|
|
43
|
+
|
|
44
|
+
// Fetch has decoded compression. Keep original bytes even for malformed JSON.
|
|
45
|
+
let body = Buffer.from(await response.arrayBuffer());
|
|
46
|
+
if (/^application\/(?:json|[^;]+\+json)(?:\s*;|$)/i.test(headers.get('content-type') || '')) {
|
|
47
|
+
let envelope;
|
|
48
|
+
try { envelope = JSON.parse(body.toString('utf8')); } catch { /* Preserve upstream bytes. */ }
|
|
49
|
+
const bundle = isRecord(envelope) && isRecord(envelope.location) ? envelope.data : null;
|
|
50
|
+
if (isRecord(bundle) && typeof bundle.code === 'string'
|
|
51
|
+
&& typeof bundle.revision === 'string' && bundle.revision.length > 0
|
|
52
|
+
&& isRecord(bundle.options)) {
|
|
53
|
+
const revision = createHash('sha256').update(bundle.revision).digest('hex');
|
|
54
|
+
headers.set(REVISION_HEADER, revision);
|
|
55
|
+
if (requestedRevision === revision) {
|
|
56
|
+
body = Buffer.from(JSON.stringify({ ...envelope, data: { ...bundle, code: '' } }));
|
|
57
|
+
headers.set(CODE_HEADER, 'cached');
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return new Response(body, { status: response.status, statusText: response.statusText, headers });
|
|
62
|
+
};
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { preparePluginGuiRequest, projectPluginGuiResponse } from './plugin-gui-response.js';
|
|
4
|
+
|
|
5
|
+
const revision = 'revision-with-private-path';
|
|
6
|
+
const token = createHash('sha256').update(revision).digest('hex');
|
|
7
|
+
const envelope = { location: { directory: '/workspace' }, data: { code: 'module.exports = {};', revision, options: { key: 'current-value' } } };
|
|
8
|
+
const response = (value, status = 200) => new Response(JSON.stringify(value), {
|
|
9
|
+
status, headers: { 'content-type': 'application/json', 'x-upstream': 'kept', etag: 'upstream-etag' },
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
describe('GUI code-only revision protocol', () => {
|
|
13
|
+
it('is exact GET with one nonempty id and strips only GUI/conditional request controls', () => {
|
|
14
|
+
for (const [method, path] of [
|
|
15
|
+
['POST', '/api/plugin/gui?id=x'], ['HEAD', '/api/plugin/gui?id=x'],
|
|
16
|
+
['GET', '/api/plugin/gui/child?id=x'], ['GET', '/api/plugin/gui/?id=x'],
|
|
17
|
+
['GET', '/api/plugin'], ['GET', '/api/plugin/gui'], ['GET', '/api/plugin/gui?id='],
|
|
18
|
+
['GET', '/api/plugin/gui?id=x&id=y'],
|
|
19
|
+
]) expect(preparePluginGuiRequest(method, path, {})).toBeNull();
|
|
20
|
+
const headers = { 'X-Yuri-Gui-Revision': token, 'If-None-Match': 'old', 'If-Modified-Since': 'yesterday',
|
|
21
|
+
Range: 'bytes=0-20', Authorization: 'upstream-auth', 'x-opencode-directory': '/workspace', accept: 'application/json' };
|
|
22
|
+
expect(preparePluginGuiRequest('GET', '/api/plugin/gui?id=x&location%5Bdirectory%5D=%2Fworkspace', headers)).toEqual({
|
|
23
|
+
revision: token, headers: { Authorization: 'upstream-auth', 'x-opencode-directory': '/workspace', accept: 'application/json', 'accept-encoding': 'identity' },
|
|
24
|
+
});
|
|
25
|
+
expect(headers['If-None-Match']).toBe('old');
|
|
26
|
+
for (const value of ['*', token.toUpperCase(), '"' + token + '"', 'not-a-token']) {
|
|
27
|
+
expect(preparePluginGuiRequest('GET', '/api/plugin/gui?id=x', { 'x-yuri-gui-revision': value }).revision).toBeNull();
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it('keeps original bytes without opt-in and returns only a hashed revision', async () => {
|
|
32
|
+
const raw = JSON.stringify(envelope, null, 2) + '\n';
|
|
33
|
+
const result = await projectPluginGuiResponse(new Response(raw, { headers: { 'content-type': 'application/json' } }), null);
|
|
34
|
+
expect(await result.text()).toBe(raw);
|
|
35
|
+
expect(result.headers.get('x-yuri-gui-revision')).toBe(token);
|
|
36
|
+
expect(result.headers.get('x-yuri-gui-code')).toBeNull();
|
|
37
|
+
expect(result.headers.get('cache-control')).toBe('private, no-store');
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
it('omits only code on a matching revision, retaining fresh options and all envelope fields', async () => {
|
|
41
|
+
for (const options of [{ key: 'new-value' }, { changed: [1, null] }]) {
|
|
42
|
+
const input = { ...envelope, extra: 1, data: { ...envelope.data, options, extra: true } };
|
|
43
|
+
const result = await projectPluginGuiResponse(response(input), token);
|
|
44
|
+
expect(result.status).toBe(200);
|
|
45
|
+
expect(result.headers.get('x-yuri-gui-code')).toBe('cached');
|
|
46
|
+
expect(result.headers.get('etag')).toBeNull();
|
|
47
|
+
expect(result.headers.get('x-upstream')).toBe('kept');
|
|
48
|
+
expect(await result.json()).toEqual({ ...input, data: { ...input.data, code: '' } });
|
|
49
|
+
}
|
|
50
|
+
const changed = { ...envelope, data: { ...envelope.data, revision: 'new-revision' } };
|
|
51
|
+
const result = await projectPluginGuiResponse(response(changed), token);
|
|
52
|
+
expect(result.headers.get('x-yuri-gui-code')).toBeNull();
|
|
53
|
+
expect(result.headers.get('x-yuri-gui-revision')).not.toBe(token);
|
|
54
|
+
expect(await result.json()).toEqual(changed);
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it.each([401, 403, 404, 429, 500, 503])('never replaces upstream %i with historical success', async (status) => {
|
|
58
|
+
const upstream = response(envelope, status);
|
|
59
|
+
expect(await projectPluginGuiResponse(upstream, token)).toBe(upstream);
|
|
60
|
+
expect(await upstream.json()).toEqual(envelope);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it.each([
|
|
64
|
+
{ ...envelope.data, code: 1 }, { ...envelope.data, revision: '' },
|
|
65
|
+
{ ...envelope.data, revision: null }, { ...envelope.data, options: null },
|
|
66
|
+
{ ...envelope.data, options: [] }, { code: 'x', revision },
|
|
67
|
+
])('does not issue a revision receipt for malformed bundles: %j', async (data) => {
|
|
68
|
+
const input = { ...envelope, data };
|
|
69
|
+
const result = await projectPluginGuiResponse(response(input), token);
|
|
70
|
+
expect(result.headers.get('x-yuri-gui-revision')).toBeNull();
|
|
71
|
+
expect(result.headers.get('x-yuri-gui-code')).toBeNull();
|
|
72
|
+
expect(await result.json()).toEqual(input);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('preserves malformed JSON and non-JSON success bytes without a receipt', async () => {
|
|
76
|
+
for (const [body, contentType] of [['{invalid', 'application/json'], ['<html>not a GUI</html>', 'text/html']]) {
|
|
77
|
+
const result = await projectPluginGuiResponse(new Response(body, { headers: { 'content-type': contentType } }), token);
|
|
78
|
+
expect(await result.text()).toBe(body);
|
|
79
|
+
expect(result.headers.get('x-yuri-gui-code')).toBeNull();
|
|
80
|
+
}
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('does not hide a failed body read behind a matching revision', async () => {
|
|
84
|
+
const upstream = new Response(new ReadableStream({
|
|
85
|
+
start(controller) { controller.error(new Error('upstream body failed')); },
|
|
86
|
+
}), { headers: { 'content-type': 'application/json' } });
|
|
87
|
+
await expect(projectPluginGuiResponse(upstream, token)).rejects.toThrow('upstream body failed');
|
|
88
|
+
});
|
|
89
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createProxyMiddleware } from 'http-proxy-middleware';
|
|
2
2
|
import { isSensitiveCredentialResponse } from './credential-boundary.js';
|
|
3
|
+
import { preparePluginGuiRequest, projectPluginGuiResponse } from './plugin-gui-response.js';
|
|
3
4
|
import { registerSessionDeliveryRoute } from './session-delivery-runtime.js';
|
|
4
5
|
import { stripSessionMessageNativePayload } from '../session-turn-pages/native-payload.js';
|
|
5
6
|
|
|
@@ -1363,5 +1364,36 @@ export const registerOpenCodeProxy = (app, deps) => {
|
|
|
1363
1364
|
});
|
|
1364
1365
|
|
|
1365
1366
|
app.use('/api', applyProxyResponseDeadline);
|
|
1367
|
+
app.use('/api', async (req, res, next) => {
|
|
1368
|
+
if (req.method !== 'GET' || req.path !== '/plugin/gui') return next();
|
|
1369
|
+
const upstreamPath = toUpstreamOpenCodeApiPath(req.url);
|
|
1370
|
+
const gui = preparePluginGuiRequest(req.method, upstreamPath, normalizeForwardedDirectoryHeaders(
|
|
1371
|
+
collectForwardProxyHeaders(req.headers, getOpenCodeAuthHeaders()),
|
|
1372
|
+
));
|
|
1373
|
+
if (!gui) return next();
|
|
1374
|
+
|
|
1375
|
+
const controller = new AbortController();
|
|
1376
|
+
const abort = () => controller.abort();
|
|
1377
|
+
req.once('aborted', abort);
|
|
1378
|
+
res.once('close', abort);
|
|
1379
|
+
try {
|
|
1380
|
+
const upstream = await fetch(buildOpenCodeUrl(upstreamPath, ''), {
|
|
1381
|
+
method: req.method, headers: gui.headers, signal: controller.signal, redirect: 'manual',
|
|
1382
|
+
});
|
|
1383
|
+
const response = await projectPluginGuiResponse(upstream, gui.revision);
|
|
1384
|
+
const body = Buffer.from(await response.arrayBuffer());
|
|
1385
|
+
if (res.writableEnded || res.destroyed) return;
|
|
1386
|
+
res.status(response.status);
|
|
1387
|
+
applyForwardProxyResponseHeaders(response.headers, res);
|
|
1388
|
+
res.end(body);
|
|
1389
|
+
} catch (error) {
|
|
1390
|
+
if (!controller.signal.aborted && !req[PROXY_TIMEOUT_MARKER]) {
|
|
1391
|
+
sendProxyErrorResponse(res, isProxyTimeoutError(error) ? 504 : 503);
|
|
1392
|
+
}
|
|
1393
|
+
} finally {
|
|
1394
|
+
req.off('aborted', abort);
|
|
1395
|
+
res.off('close', abort);
|
|
1396
|
+
}
|
|
1397
|
+
});
|
|
1366
1398
|
app.use('/api', apiProxy);
|
|
1367
1399
|
};
|
|
@@ -55,6 +55,7 @@ Private Relay is transparent for allowlisted HTTP paths, so most “works on LAN
|
|
|
55
55
|
|
|
56
56
|
- **Same path, real Host route required.** Clients call the ordinary `/api/...` path through the tunnel. If that route is missing on the Host process currently holding the relay claim (wrong git worktree, stale packaged Desktop build, or a backend that never registered the Yuri route before the OpenCode proxy/SPA fallback), the tunnel still returns HTTP 200 with SPA HTML or proxied OpenCode content. Symptom: chat and status work, Provider/model catalog does not.
|
|
57
57
|
- **HTTP allowlist is prefix-based for `/api/`.** New REST/SSE APIs under `/api/` do not need a tunnel-host allowlist edit. New **WebSocket** paths still need both tunnel-host allowlisting (`isTunnelWsPathAllowed` / exact `ALLOWED_WS_PATHS`, plus the **`/api/preview/proxy/` prefix** for Preview HMR only) and `isUrlAuthWebSocketPath` (see the `relay-transport` skill). Config sync (`/api/yuri/config-sync/*`, ticket 05/06) therefore works over Relay without a tunnel-host allowlist change; identity and credential grants remain endpoint concerns (`relay:<serverId>`, pairing-settings / inbound host grant).
|
|
58
|
+
- GUI code reuse uses the same `GET /api/plugin/gui?id=…` path: the tunnel preserves `X-Yuri-Gui-Revision` requests and `X-Yuri-Gui-Revision` / `X-Yuri-Gui-Code` responses. The authenticated Host still fetches upstream on each call; matching responses are 200 with current options and empty code, never a tunnel-cached bundle or 304. `Cache-Control: private, no-store` crosses unchanged. The Web GUI proxy integration test exercises this actual dispatcher path.
|
|
58
59
|
- **Transport identity ≠ runtime key.** After LAN⇄relay swaps, UI catalog loaders commit only when `useConfigStore.catalogTransportIdentity` matches `getRuntimeTransportIdentity()`. `runtimeEndpointReset.ts` must write that transport fingerprint on both full endpoint reset and in-place transport reconnect. Writing `runtimeKey` instead leaves Providers empty because the stable device/instance id is shared across LAN and relay.
|
|
59
60
|
- **Safe catalog projection stays Host-owned.** Provider credentials never cross the browser; Relay only carries the already-allowlisted `GET /api/config/catalog/providers` JSON. Keep Host projection, client parser bounds, and `partial` rules in sync (empty `release_date` is absent, not partial).
|
|
60
61
|
|
|
@@ -36,6 +36,14 @@ import { VolcengineTranscriptionSession } from '../dictation/volcengine-session.
|
|
|
36
36
|
import { openRuntimeWebSocket } from '../../../../ui/src/lib/relay/runtime-socket.ts';
|
|
37
37
|
import { refreshRuntimeUrlAuthToken } from '../../../../ui/src/lib/runtime-auth.ts';
|
|
38
38
|
import { requestSpeechSession } from '../../../../ui/src/lib/voice/direct-session.ts';
|
|
39
|
+
import { createGuiClient } from '../../../../ui/src/lib/opencode/gui.ts';
|
|
40
|
+
import { createWebFilesAPI } from '../../../src/api/files.ts';
|
|
41
|
+
|
|
42
|
+
// Web's source aliases are not exported Node package subpaths. Forward them to
|
|
43
|
+
// the real implementations so this Node E2E exercises the same transport singleton.
|
|
44
|
+
vi.mock('@yuriai/ui/lib/runtime-fetch', () => import('../../../../ui/src/lib/runtime-fetch.ts'));
|
|
45
|
+
vi.mock('@yuriai/ui/lib/runtime-file-resource', () => import('../../../../ui/src/lib/runtime-file-resource.ts'));
|
|
46
|
+
vi.mock('@yuriai/ui/lib/runtime-file-download', () => import('../../../../ui/src/lib/runtime-file-download.ts'));
|
|
39
47
|
|
|
40
48
|
const timeoutMs = 10_000;
|
|
41
49
|
const previewPng = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=', 'base64');
|
|
@@ -162,8 +170,19 @@ const startOrigin = async () => {
|
|
|
162
170
|
const mediaDirectory = await mkdtemp(path.join(os.tmpdir(), 'relay-video-'));
|
|
163
171
|
const videoPath = path.join(mediaDirectory, 'clip.mp4');
|
|
164
172
|
await fsPromises.writeFile(videoPath, Buffer.from('0123456789'));
|
|
173
|
+
const previewPath = path.join(mediaDirectory, '中文 预览.preview');
|
|
174
|
+
const previewContent = '远端 初始内容';
|
|
175
|
+
await fsPromises.writeFile(previewPath, previewContent);
|
|
176
|
+
// Generated plugin assets are not required for a clean checkout's relay tests.
|
|
177
|
+
// Set YURI_RELAY_GUI_BUNDLE to validate an external plugin's built CJS through this same chain.
|
|
178
|
+
const guiCode = process.env.YURI_RELAY_GUI_BUNDLE
|
|
179
|
+
? await fsPromises.readFile(process.env.YURI_RELAY_GUI_BUNDLE, 'utf8')
|
|
180
|
+
: `module.exports.default={setup(){}};/*${'large plugin bundle 中文\n'.repeat(110_000)}*/`;
|
|
181
|
+
const guiBundle = { code: guiCode, revision: crypto.createHash('sha256').update(guiCode).digest('hex'), options: {} };
|
|
182
|
+
const pluginInventory = [{ id: 'preview-fixture', source: { type: 'package', target: 'preview-fixture', version: '0.1.0' }, features: { gui: true }, state: { status: 'active' } }];
|
|
183
|
+
const guiRequests: string[] = [];
|
|
165
184
|
const rawFiles = express();
|
|
166
|
-
registerFsRoutes({ get: (route: string, handler: express.RequestHandler) => { if (
|
|
185
|
+
registerFsRoutes({ get: (route: string, handler: express.RequestHandler) => { if (['/api/fs/raw', '/api/fs/stat', '/api/fs/read'].includes(route)) rawFiles.get(route, handler); }, post() {}, put() {} }, {
|
|
167
186
|
fsPromises, os, path, spawn, crypto: globalThis.crypto, normalizeDirectoryPath: (value: string) => value,
|
|
168
187
|
resolveProjectDirectory: async () => ({ directory: mediaDirectory }), buildAugmentedPath: () => '',
|
|
169
188
|
resolveGitBinaryForSpawn: () => 'git', yuriUserConfigRoot: mediaDirectory,
|
|
@@ -245,10 +264,26 @@ const startOrigin = async () => {
|
|
|
245
264
|
});
|
|
246
265
|
return;
|
|
247
266
|
}
|
|
267
|
+
if ((pathname === '/api/plugin' || pathname === '/api/plugin/gui') && req.method === 'GET') {
|
|
268
|
+
await uiAuth.requireAuth(req, res, () => {
|
|
269
|
+
const url = new URL(req.url ?? '/', 'http://origin');
|
|
270
|
+
if (!req.headers['x-yuri-relay-connection'] || url.searchParams.has('location[directory]')
|
|
271
|
+
|| (pathname.endsWith('/gui') && url.searchParams.get('id') !== 'preview-fixture')) {
|
|
272
|
+
res.status(400).end(); return;
|
|
273
|
+
}
|
|
274
|
+
guiRequests.push(pathname);
|
|
275
|
+
res.json({ data: pathname.endsWith('/gui') ? guiBundle : pluginInventory });
|
|
276
|
+
});
|
|
277
|
+
return;
|
|
278
|
+
}
|
|
279
|
+
if (pathname === '/api/fs/stat' || pathname === '/api/fs/read') {
|
|
280
|
+
await uiAuth.requireAuth(req, res, () => rawFiles(req, rawRes));
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
248
283
|
if (pathname === '/api/fs/raw' && req.method === 'GET') {
|
|
249
284
|
await uiAuth.requireAuth(req, res, () => {
|
|
250
285
|
const filePath = new URL(req.url ?? '/', 'http://origin').searchParams.get('path');
|
|
251
|
-
if (filePath === videoPath) { rawFiles(req, rawRes); return; }
|
|
286
|
+
if (filePath === videoPath || filePath === previewPath) { rawFiles(req, rawRes); return; }
|
|
252
287
|
if (filePath !== '/remote/icons-zoom.png' || !req.headers['x-yuri-relay-connection']) {
|
|
253
288
|
res.status(404).end(); return;
|
|
254
289
|
}
|
|
@@ -302,7 +337,7 @@ const startOrigin = async () => {
|
|
|
302
337
|
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
|
303
338
|
const port = (server.address() as net.AddressInfo).port;
|
|
304
339
|
return {
|
|
305
|
-
port, videoPath, bearerRequests, observedOrigins, getHostSubscriptions: () => hostSubscriptions,
|
|
340
|
+
port, videoPath, previewPath, previewContent, guiBundle, pluginInventory, guiRequests, bearerRequests, observedOrigins, getHostSubscriptions: () => hostSubscriptions,
|
|
306
341
|
stop: async () => {
|
|
307
342
|
dictation.stop();
|
|
308
343
|
for (const client of wss.clients) client.terminate();
|
|
@@ -518,6 +553,41 @@ describe('private relay compiled-process boundary', () => {
|
|
|
518
553
|
configureRuntimeUrlResolver({ apiBaseUrl: 'https://relay-runtime.example' });
|
|
519
554
|
setRuntimeBearerToken('client-token');
|
|
520
555
|
adoptRelayTunnel({ relayUrl: relay.url, serverId: identity.serverId, hostEncPubJwk: identity.hostEncPubJwk }, client);
|
|
556
|
+
vi.stubGlobal('window', { location: new URL('https://relay-runtime.example'), addEventListener() {}, removeEventListener() {} });
|
|
557
|
+
try {
|
|
558
|
+
const gui = createGuiClient(new AbortController().signal);
|
|
559
|
+
const files = createWebFilesAPI({ getDirectory: () => path.dirname(origin.previewPath) });
|
|
560
|
+
expect(Buffer.byteLength(origin.guiBundle.code)).toBeGreaterThan(2_270_000);
|
|
561
|
+
for (const route of ['/api/plugin', '/api/plugin/gui?id=preview-fixture', `/api/fs/stat?path=${encodeURIComponent(origin.previewPath)}`, `/api/fs/raw?path=${encodeURIComponent(origin.previewPath)}`]) {
|
|
562
|
+
expect((await client.fetch(route)).status).toBe(401);
|
|
563
|
+
expect((await client.fetch(route, { headers: { authorization: 'Bearer invalid-token' } })).status).toBe(401);
|
|
564
|
+
}
|
|
565
|
+
expect((await gui.plugin.list()).data).toEqual(origin.pluginInventory);
|
|
566
|
+
expect((await gui.plugin.gui({ id: 'preview-fixture' })).data).toEqual(origin.guiBundle);
|
|
567
|
+
const initialStat = await files.statFile(origin.previewPath, { fingerprint: true });
|
|
568
|
+
expect(initialStat).toMatchObject({ isFile: true, size: Buffer.byteLength(origin.previewContent) });
|
|
569
|
+
expect(await files.readFile(origin.previewPath)).toMatchObject({ content: origin.previewContent, exists: true });
|
|
570
|
+
expect(await files.readFile(origin.previewPath, { optional: true })).toMatchObject({ content: origin.previewContent, exists: true });
|
|
571
|
+
const updated = '远端 更新后的内容 ✓';
|
|
572
|
+
await fsPromises.writeFile(origin.previewPath, updated);
|
|
573
|
+
const updatedStat = await files.statFile(origin.previewPath, { fingerprint: true });
|
|
574
|
+
expect(updatedStat.size).toBe(Buffer.byteLength(updated));
|
|
575
|
+
expect(updatedStat.sha256).not.toBe(initialStat.sha256);
|
|
576
|
+
expect(await files.readFile(origin.previewPath)).toMatchObject({ content: updated });
|
|
577
|
+
const beforeRestart = relay;
|
|
578
|
+
relay = undefined;
|
|
579
|
+
await stopRelay(beforeRestart);
|
|
580
|
+
await eventually(() => client!.getStatus().state !== 'connected', 'client did not observe Relay shutdown');
|
|
581
|
+
relay = await startCompiledRelay(binary, port);
|
|
582
|
+
await eventually(() => host!.getStatus().state === 'connected' && client!.getStatus().state === 'connected', 'GUI tunnel did not reconnect');
|
|
583
|
+
// Retain the actual SDK client across reconnection, rather than replacing it.
|
|
584
|
+
expect((await gui.plugin.list()).data).toEqual(origin.pluginInventory);
|
|
585
|
+
expect((await gui.plugin.gui({ id: 'preview-fixture' })).data).toEqual(origin.guiBundle);
|
|
586
|
+
expect(await files.readFile(origin.previewPath)).toMatchObject({ content: updated });
|
|
587
|
+
expect(origin.guiRequests).toEqual(['/api/plugin', '/api/plugin/gui', '/api/plugin', '/api/plugin/gui']);
|
|
588
|
+
} finally {
|
|
589
|
+
vi.unstubAllGlobals();
|
|
590
|
+
}
|
|
521
591
|
await verifyStreamingAsrOverRelay();
|
|
522
592
|
// Only the external synthesizer is mocked: runtime routing, auth, Host route,
|
|
523
593
|
// encrypted tunnel and compiled Relay process all remain real.
|
|
@@ -4,12 +4,12 @@ export const applyRuntimeCorsHeaders = ({ origin, setHeader }) => {
|
|
|
4
4
|
setHeader('Access-Control-Allow-Origin', origin);
|
|
5
5
|
setHeader('Access-Control-Allow-Credentials', 'true');
|
|
6
6
|
setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
|
|
7
|
-
setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory,X-OpenCode-Directory-Encoding,X-Message-Queue-Upload-Token,X-Message-Queue-Sha256,X-Message-Queue-Content-Length,X-Yuri-Content-Length,X-Yuri-Sha256,X-Yuri-Mime,X-Yuri-Filename');
|
|
7
|
+
setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization,Accept,X-Requested-With,Cache-Control,X-OpenCode-Directory,X-OpenCode-Directory-Encoding,X-Message-Queue-Upload-Token,X-Message-Queue-Sha256,X-Message-Queue-Content-Length,X-Yuri-Content-Length,X-Yuri-Sha256,X-Yuri-Mime,X-Yuri-Filename,X-Yuri-Gui-Revision');
|
|
8
8
|
// Packaged clients (Electron yuri-ui://app, Capacitor, Vite HMR) are
|
|
9
9
|
// cross-origin to the runtime API. Without an expose list, browsers hide
|
|
10
10
|
// custom response headers from JS — including the optional-read existence
|
|
11
11
|
// marker that FilesAPI.readFile({ optional: true }) requires.
|
|
12
|
-
setHeader('Access-Control-Expose-Headers', 'x-next-cursor, x-yuri-file-exists, x-speech-pitch, x-speech-volume');
|
|
12
|
+
setHeader('Access-Control-Expose-Headers', 'x-next-cursor, x-yuri-file-exists, x-speech-pitch, x-speech-volume, x-yuri-gui-revision, x-yuri-gui-code');
|
|
13
13
|
setHeader('Access-Control-Max-Age', PREFLIGHT_CACHE_SECONDS);
|
|
14
14
|
setHeader('Vary', 'Origin');
|
|
15
15
|
};
|
|
@@ -18,6 +18,9 @@ describe('applyRuntimeCorsHeaders', () => {
|
|
|
18
18
|
expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Sha256');
|
|
19
19
|
expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Content-Length');
|
|
20
20
|
expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Filename');
|
|
21
|
+
expect(headers.get('Access-Control-Allow-Headers')).toContain('X-Yuri-Gui-Revision');
|
|
22
|
+
expect(headers.get('Access-Control-Expose-Headers')).toContain('x-yuri-gui-revision');
|
|
23
|
+
expect(headers.get('Access-Control-Expose-Headers')).toContain('x-yuri-gui-code');
|
|
21
24
|
expect(headers.get('Access-Control-Expose-Headers')).toContain('x-next-cursor');
|
|
22
25
|
expect(headers.get('Access-Control-Expose-Headers')).toContain('x-yuri-file-exists');
|
|
23
26
|
});
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Session Index Runtime
|
|
2
2
|
|
|
3
|
+
Directory refresh retains its previous snapshot when the pagination budget is
|
|
4
|
+
exhausted before filling the visible root limit. Filtered global pages with a
|
|
5
|
+
continuation are partial results, not authoritative empty directories.
|
|
6
|
+
|
|
3
7
|
## Missing local directories
|
|
4
8
|
|
|
5
9
|
The Host probes local directory existence asynchronously before background root
|
|
@@ -301,6 +301,9 @@ export const createSessionIndexSyncRuntime = ({
|
|
|
301
301
|
active.push(session);
|
|
302
302
|
}
|
|
303
303
|
|
|
304
|
+
if (hitPageBudget && active.length < SESSION_LIMIT) {
|
|
305
|
+
throw new Error('Directory scan incomplete; retaining prior session index');
|
|
306
|
+
}
|
|
304
307
|
const oldest = active[active.length - 1];
|
|
305
308
|
const cursorNumber = lastCursorToken && Number.isFinite(Number(lastCursorToken))
|
|
306
309
|
? Number(lastCursorToken)
|
|
@@ -41,6 +41,24 @@ const isFullyIdle = (runtime) => (
|
|
|
41
41
|
);
|
|
42
42
|
|
|
43
43
|
describe('session index background sync runtime', () => {
|
|
44
|
+
it('preserves prior directory rows when filtered global pages exhaust the scan budget', async () => {
|
|
45
|
+
const service = createService([{ directory: '/repo', sessions: [session('existing', 10)] }]);
|
|
46
|
+
let page = 0;
|
|
47
|
+
const runtime = createSessionIndexSyncRuntime({
|
|
48
|
+
sessionIndexService: service,
|
|
49
|
+
buildOpenCodeUrl: (route) => `http://opencode.test${route}`,
|
|
50
|
+
getOpenCodeAuthHeaders: () => ({}),
|
|
51
|
+
waitForOpenCodeReady: async () => true,
|
|
52
|
+
fetchFn: async () => Response.json({ data: [], cursor: { next: `page-${++page}` } }),
|
|
53
|
+
});
|
|
54
|
+
try {
|
|
55
|
+
runtime.enqueue(['/repo']);
|
|
56
|
+
await waitUntil(() => isFullyIdle(runtime));
|
|
57
|
+
expect(page).toBe(5);
|
|
58
|
+
expect(service.replaceDirectory).not.toHaveBeenCalled();
|
|
59
|
+
expect(service.snapshot().directories[0].sessions[0].id).toBe('existing');
|
|
60
|
+
} finally { runtime.stop(); }
|
|
61
|
+
});
|
|
44
62
|
it('does not probe indexed directories at startup', async () => {
|
|
45
63
|
const service = createService([{ directory: '/repo', sessions: [], hasMore: false }]);
|
|
46
64
|
service.removeEmptyDirectory = vi.fn(() => true);
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it } from 'vitest';
|
|
2
|
+
import express from 'express';
|
|
3
|
+
import { gzipSync } from 'node:zlib';
|
|
4
|
+
import { registerOpenCodeProxy } from './lib/opencode/proxy.js';
|
|
5
|
+
import { createTunnelHost } from './lib/relay/tunnel-host.js';
|
|
6
|
+
import { TunnelFrameType, decodeTunnelFrame, encodeJsonPayload, encodeTunnelFrame } from './lib/relay/tunnel-codec.js';
|
|
7
|
+
|
|
8
|
+
const servers = [];
|
|
9
|
+
const listen = async (app) => {
|
|
10
|
+
const server = await new Promise((resolve) => { const listening = app.listen(0, '127.0.0.1', () => resolve(listening)); });
|
|
11
|
+
servers.push(server);
|
|
12
|
+
return server.address().port;
|
|
13
|
+
};
|
|
14
|
+
afterEach(async () => {
|
|
15
|
+
await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => { server.closeAllConnections(); server.close(resolve); })));
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
const setup = async ({ timeoutMs = 1000 } = {}) => {
|
|
19
|
+
const seen = [];
|
|
20
|
+
const state = { status: 200, revision: 'r1', options: { current: 1 }, compressed: false, stalled: false };
|
|
21
|
+
const upstream = express();
|
|
22
|
+
upstream.all('/api/plugin/gui', (req, res) => {
|
|
23
|
+
seen.push({ method: req.method, url: req.originalUrl, headers: req.headers });
|
|
24
|
+
if (state.stalled) {
|
|
25
|
+
res.set('content-type', 'application/json');
|
|
26
|
+
res.write('{"location":');
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
const body = JSON.stringify({ location: { directory: '/workspace' }, data: { code: 'x'.repeat(128 * 1024), revision: state.revision, options: state.options } });
|
|
30
|
+
res.status(state.status).set('content-type', 'application/json').set('x-upstream', 'kept');
|
|
31
|
+
if (state.compressed) {
|
|
32
|
+
const compressed = gzipSync(body);
|
|
33
|
+
res.set('content-encoding', 'gzip').set('content-length', String(compressed.length)).end(compressed);
|
|
34
|
+
} else res.end(body);
|
|
35
|
+
});
|
|
36
|
+
const upstreamPort = await listen(upstream);
|
|
37
|
+
const app = express();
|
|
38
|
+
app.use((req, res, next) => req.headers.authorization === 'Bearer client-test' ? next() : res.status(401).end('unauthorized'));
|
|
39
|
+
registerOpenCodeProxy(app, {
|
|
40
|
+
fs: {}, os: {}, path: {}, OPEN_CODE_READY_GRACE_MS: 0, LONG_REQUEST_TIMEOUT_MS: timeoutMs,
|
|
41
|
+
getRuntime: () => ({ openCodePort: upstreamPort, isOpenCodeReady: true }),
|
|
42
|
+
getOpenCodeAuthHeaders: () => ({ Authorization: 'Basic upstream-test' }),
|
|
43
|
+
buildOpenCodeUrl: (path) => `http://127.0.0.1:${upstreamPort}${path}`,
|
|
44
|
+
ensureOpenCodeApiPrefix: () => {},
|
|
45
|
+
});
|
|
46
|
+
const port = await listen(app);
|
|
47
|
+
const requestPath = '/api/plugin/gui?id=plugin%2Fone&location%5Bdirectory%5D=%2Fworkspace';
|
|
48
|
+
const read = (headers = {}) => fetch(`http://127.0.0.1:${port}${requestPath}`, { headers: { Authorization: 'Bearer client-test', ...headers } });
|
|
49
|
+
return { seen, state, port, requestPath, read };
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
describe('Web/Electron shared backend GUI response', () => {
|
|
53
|
+
it('times out an incomplete upstream body rather than reusing historical code success', async () => {
|
|
54
|
+
const { read, state, seen } = await setup({ timeoutMs: 100 });
|
|
55
|
+
const first = await read();
|
|
56
|
+
const token = first.headers.get('x-yuri-gui-revision');
|
|
57
|
+
await first.arrayBuffer();
|
|
58
|
+
state.stalled = true;
|
|
59
|
+
const failed = await read({ 'X-Yuri-Gui-Revision': token });
|
|
60
|
+
expect(failed.status).toBe(504);
|
|
61
|
+
expect(failed.headers.get('x-yuri-gui-code')).toBeNull();
|
|
62
|
+
expect(await failed.json()).toEqual({ error: 'OpenCode upstream timed out' });
|
|
63
|
+
expect(seen).toHaveLength(2);
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('fetches each full upstream response, preserves query/auth, and transfers fresh options with code reuse', async () => {
|
|
67
|
+
const { read, seen, state, requestPath } = await setup();
|
|
68
|
+
const first = await read();
|
|
69
|
+
const token = first.headers.get('x-yuri-gui-revision');
|
|
70
|
+
expect(token).toMatch(/^[a-f0-9]{64}$/);
|
|
71
|
+
const full = await first.json();
|
|
72
|
+
state.options = { current: 2 };
|
|
73
|
+
state.compressed = true;
|
|
74
|
+
const second = await read({ 'X-Yuri-Gui-Revision': token, 'If-None-Match': '*', 'If-Modified-Since': 'yesterday' });
|
|
75
|
+
expect(second.status).toBe(200);
|
|
76
|
+
expect(second.headers.get('cache-control')).toBe('private, no-store');
|
|
77
|
+
expect(second.headers.get('x-yuri-gui-code')).toBe('cached');
|
|
78
|
+
expect(second.headers.get('content-encoding')).toBeNull();
|
|
79
|
+
expect(second.headers.get('x-upstream')).toBe('kept');
|
|
80
|
+
const thinText = await second.text();
|
|
81
|
+
expect(thinText.length).toBeLessThan(256);
|
|
82
|
+
expect(JSON.parse(thinText)).toEqual({ ...full, data: { ...full.data, code: '', options: { current: 2 } } });
|
|
83
|
+
expect(seen).toHaveLength(2);
|
|
84
|
+
expect(seen[1]).toMatchObject({ method: 'GET', url: requestPath, headers: { authorization: 'Basic upstream-test', 'accept-encoding': 'identity' } });
|
|
85
|
+
expect(seen[1].headers['x-yuri-gui-revision']).toBeUndefined();
|
|
86
|
+
expect(seen[1].headers['if-none-match']).toBeUndefined();
|
|
87
|
+
expect(seen[1].headers['if-modified-since']).toBeUndefined();
|
|
88
|
+
state.revision = 'r2';
|
|
89
|
+
const changed = await read({ 'X-Yuri-Gui-Revision': token });
|
|
90
|
+
expect(changed.headers.get('x-yuri-gui-code')).toBeNull();
|
|
91
|
+
expect((await changed.json()).data.code).toBe(full.data.code);
|
|
92
|
+
state.status = 404;
|
|
93
|
+
const failed = await read({ 'X-Yuri-Gui-Revision': token });
|
|
94
|
+
expect(failed.status).toBe(404);
|
|
95
|
+
expect(failed.headers.get('x-yuri-gui-code')).toBeNull();
|
|
96
|
+
expect((await failed.json()).data.code).toBe(full.data.code);
|
|
97
|
+
expect(seen).toHaveLength(4);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('carries revision headers and current options through the actual relay HTTP path and auth gate', async () => {
|
|
101
|
+
const { read, port, state, requestPath, seen } = await setup();
|
|
102
|
+
const first = await read();
|
|
103
|
+
const token = first.headers.get('x-yuri-gui-revision');
|
|
104
|
+
await first.arrayBuffer();
|
|
105
|
+
state.options = { current: 7 };
|
|
106
|
+
const frames = [];
|
|
107
|
+
let finish;
|
|
108
|
+
const ended = new Promise((resolve) => { finish = resolve; });
|
|
109
|
+
const host = createTunnelHost({ connectionId: 'gui-response', getLocalPort: () => port, getBufferedAmount: () => 0,
|
|
110
|
+
sendFrame: (bytes) => { const frame = decodeTunnelFrame(bytes); frames.push(frame); if (frame.frameType === TunnelFrameType.StreamEnd) finish(); },
|
|
111
|
+
});
|
|
112
|
+
try {
|
|
113
|
+
const url = new URL(requestPath, 'http://yuri.invalid');
|
|
114
|
+
await host.handleFrame(encodeTunnelFrame(TunnelFrameType.HttpRequest, 1, encodeJsonPayload({
|
|
115
|
+
method: 'GET', path: url.pathname, query: url.search.slice(1), acceptEncoding: 'gzip',
|
|
116
|
+
headers: { authorization: 'Bearer client-test', 'x-yuri-gui-revision': token },
|
|
117
|
+
})));
|
|
118
|
+
await ended;
|
|
119
|
+
const head = JSON.parse(new TextDecoder().decode(frames.find((frame) => frame.frameType === TunnelFrameType.HttpResponse).payload));
|
|
120
|
+
expect(head.status).toBe(200);
|
|
121
|
+
expect(head.headers['x-yuri-gui-code']).toBe('cached');
|
|
122
|
+
expect(head.headers['x-yuri-gui-revision']).toBe(token);
|
|
123
|
+
expect(head.headers['cache-control']).toBe('private, no-store');
|
|
124
|
+
const body = new Blob(frames.filter((frame) => frame.frameType === TunnelFrameType.HttpBody).map((frame) => frame.payload));
|
|
125
|
+
const text = head.encoding === 'gzip'
|
|
126
|
+
? await new Response(body.stream().pipeThrough(new DecompressionStream('gzip'))).text() : await body.text();
|
|
127
|
+
expect(JSON.parse(text).data).toEqual({ code: '', revision: 'r1', options: { current: 7 } });
|
|
128
|
+
expect(seen).toHaveLength(2);
|
|
129
|
+
const denied = await fetch(`http://127.0.0.1:${port}${requestPath}`, { headers: { 'X-Yuri-Gui-Revision': token } });
|
|
130
|
+
expect(denied.status).toBe(401);
|
|
131
|
+
expect(seen).toHaveLength(2);
|
|
132
|
+
} finally { host.close(); }
|
|
133
|
+
});
|
|
134
|
+
});
|