@yuriai/web 0.2.19 → 0.2.20-beta.3
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/dist/assets/AgentAvatar-D5KPQI1N.js +1 -0
- package/dist/assets/AssistantView-huAUB-2Y.js +3 -0
- package/dist/assets/{DiagramView-HNaj_sVG.js → DiagramView-DWV04Xws.js} +1 -1
- package/dist/assets/{FadeInOnReveal-Dq1IuEQp.js → FadeInOnReveal-CdoLG8fY.js} +1 -1
- package/dist/assets/{GuiPluginSurface-N-iK-MeX.js → GuiPluginSurface-DhD8BqvL.js} +1 -1
- package/dist/assets/{GuiPluginWindow-ClutFX_h.js → GuiPluginWindow-ezsy5l_y.js} +1 -1
- package/dist/assets/{Icon-tnX3bel1.js → Icon-DvqOB4Dx.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-IE6JO3WM.js → ImageLoadingPlaceholder-BVlgaa2r.js} +1 -1
- package/dist/assets/{LoadingImage-DNZmZRZS.js → LoadingImage-BSG8jmn5.js} +1 -1
- package/dist/assets/MarkdownRenderer-BiRplAST.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-BwZ91PA5.js → MarkdownRendererImpl-CH8TUMKZ.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-kgBwH_VF.js → MarkstreamRendererImpl-Bmz56IzM.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-sm5MbnK3.js → MobileDetailNavigation-kKHM_dU3.js} +1 -1
- package/dist/assets/{MobileResizableSheet-Cw6rRBR2.js → MobileResizableSheet-jHNytoyX.js} +1 -1
- package/dist/assets/{MobileShareBridge-BjpB1cz1.js → MobileShareBridge-CSDivsPk.js} +2 -2
- package/dist/assets/{MobileTabPageHeader-CEsc9PYV.js → MobileTabPageHeader-BkWvNBtr.js} +1 -1
- package/dist/assets/{MultiRunWindow-pslncrAh.js → MultiRunWindow-DbllgaJR.js} +1 -1
- package/dist/assets/{OnboardingScreen-o9e7j2Lk.js → OnboardingScreen-DONIcirJ.js} +1 -1
- package/dist/assets/{OverlayScrollbar-BA6KEyhj.js → OverlayScrollbar-DB2eeXFh.js} +1 -1
- package/dist/assets/{SettingsView-20rmUHhk.js → SettingsView-6D55BNjw.js} +1 -1
- package/dist/assets/{SettingsWindow-D-Vjsme7.js → SettingsWindow-BrrnHfnR.js} +1 -1
- package/dist/assets/{TerminalView-B4bliT5i.js → TerminalView-8JYW5f-c.js} +1 -1
- package/dist/assets/{ToolOutputDialog-D1rZbaHo.js → ToolOutputDialog-DZO89hKv.js} +1 -1
- package/dist/assets/{YuriLogo-CDmH1ycw.js → YuriLogo-CYdRUurL.js} +1 -1
- package/dist/assets/{appThemeRegistry-DyTPt9Uq.js → appThemeRegistry-Nb-sUfbK.js} +1 -1
- package/dist/assets/{assistant-attachment-cache-lEUFn3mr.js → assistant-attachment-cache-C2SmtQG7.js} +1 -1
- package/dist/assets/{button-BEOJB042.js → button-nola46HU.js} +1 -1
- package/dist/assets/{capgoAdapter-BrU-ms8F.js → capgoAdapter-CHeo9q51.js} +1 -1
- package/dist/assets/{collapsible-DrQlDm15.js → collapsible-BQaMLh6O.js} +1 -1
- package/dist/assets/{desktop-dp2Z0toS.js → desktop-CiqEZVr5.js} +1 -1
- package/dist/assets/{desktopHosts-CYKaLp1V.js → desktopHosts-B4HMNmrx.js} +1 -1
- package/dist/assets/{desktopRelayRestore-5yuHB356.js → desktopRelayRestore-CRl62mqn.js} +1 -1
- package/dist/assets/{device-DzWRCXhq.js → device-Coc5tapU.js} +1 -1
- package/dist/assets/{diagram-DyQPPDKS.js → diagram-COti_aKS.js} +1 -1
- package/dist/assets/{dialog-CooVl0xA.js → dialog-B2CTTXwv.js} +1 -1
- package/dist/assets/{dropdown-menu.styles-Bj4YEb3T.js → dropdown-menu.styles-BzpQaok_.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-8I9u8H6l.js → fileMentionTouchSelection-CXepBNtQ.js} +1 -1
- package/dist/assets/{fileQueries-DbUx7NwP.js → fileQueries-Bd-OEFmO.js} +1 -1
- package/dist/assets/{fileReferenceActions-No7p4Kdo.js → fileReferenceActions-BnPPqYXw.js} +1 -1
- package/dist/assets/{gitApi-BVMvxPtG.js → gitApi-B7AeNXrj.js} +1 -1
- package/dist/assets/{gitApiHttp-BtI23x-7.js → gitApiHttp-CoNokuDM.js} +1 -1
- package/dist/assets/{gui-BCPFcL_m.js → gui-D3wrcUs6.js} +1 -1
- package/dist/assets/{host-BoCxB_x4.js → host-BCXyr41J.js} +1 -1
- package/dist/assets/{image-loading-FUFYiO1j.js → image-loading-DVZlFuU5.js} +1 -1
- package/dist/assets/{input-B-4VixoV.js → input-DGnhaqoc.js} +1 -1
- package/dist/assets/{insertionBoundaries-YVc2e3H2.js → insertionBoundaries-Db0R1aBj.js} +1 -1
- package/dist/assets/{main-Cs5VJerX.js → main-DQ0F0yuL.js} +21 -21
- package/dist/assets/{main-DZ5HVH-j.js → main-d2AaD_PZ.js} +2 -2
- package/dist/assets/{markdownHeightCache-SdaL8x58.js → markdownHeightCache-C_JI5qIR.js} +1 -1
- package/dist/assets/{mcpQueries-B1ZULr7c.js → mcpQueries-BgFj7wfO.js} +1 -1
- package/dist/assets/miniChat-BHdsTyJ3.js +2 -0
- package/dist/assets/mobile-BEhQq4tx.js +2 -0
- package/dist/assets/{mobileBackNavigation-D-cRdrKd.js → mobileBackNavigation-s9RsXUUH.js} +1 -1
- package/dist/assets/{multirun-D6bNScic.js → multirun-BZsBsBAj.js} +1 -1
- package/dist/assets/{native-config-obwt8WA1.js → native-config-BmrfOzkM.js} +1 -1
- package/dist/assets/{persistence-BfjCXjLZ.js → persistence-CNEHspb4.js} +1 -1
- package/dist/assets/{platform-syRnKuVU.js → platform-Q45KPuGv.js} +1 -1
- package/dist/assets/{projectMeta-LtQkG8fN.js → projectMeta-BCGIXTbR.js} +1 -1
- package/dist/assets/{queryRuntime-BuRnpVtK.js → queryRuntime-DWgXfxGx.js} +1 -1
- package/dist/assets/{readiness-BWBtf7Am.js → readiness-BxT5OBkk.js} +1 -1
- package/dist/assets/{renderElectronMiniChatApp-EL2J2wQd.js → renderElectronMiniChatApp-BbfF6SjM.js} +2 -2
- package/dist/assets/{renderMobileApp-DOCWKmuC.js → renderMobileApp-ulSQxT-l.js} +4 -4
- package/dist/assets/runtime-auth-BaBM02zI.js +1 -0
- package/dist/assets/{runtime-fetch-BAN5Gnnp.js → runtime-fetch-DfALP7-b.js} +1 -1
- package/dist/assets/{runtime-file-download-BzblfnMx.js → runtime-file-download-xvItwYMc.js} +1 -1
- package/dist/assets/{runtime-file-resource-D3k0hKDj.js → runtime-file-resource-DtsKbFf3.js} +1 -1
- package/dist/assets/{runtime-switch-CAZiOV2G.js → runtime-switch-DhMY9eiB.js} +1 -1
- package/dist/assets/{runtimeConfig-D577Rc9x.js → runtimeConfig-BHRHZbwI.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-C5EiiaQf.js → runtimeEndpointReset-H2W1kxcO.js} +3 -3
- package/dist/assets/{scheduledTaskNavigation-CJEzv5Zr.js → scheduledTaskNavigation-CkBcoGV4.js} +1 -1
- package/dist/assets/{sessionChangeSummary-DAV313F8.js → sessionChangeSummary-CAU-06Bu.js} +1 -1
- package/dist/assets/{sessionLookup-CN_iYfk5.js → sessionLookup-YvkfClst.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-9okrTn1K.js → sortable-tabs-strip-pCvZjmMt.js} +1 -1
- package/dist/assets/{speechSettingsQueries-BvJCYdR_.js → speechSettingsQueries-1LD5eEHK.js} +2 -2
- package/dist/assets/{src-nJdn6EvY.css → src-DGCTlpkW.css} +1 -1
- package/dist/assets/{terminalApi-Dw1h9m3h.js → terminalApi-DFhCeMya.js} +1 -1
- package/dist/assets/{textarea-9sBs8Uld.js → textarea-DSHEMw8t.js} +1 -1
- package/dist/assets/{tooltip-BkcQKx-p.js → tooltip-BwTvgqWG.js} +1 -1
- package/dist/assets/types-CiQgQf3s.js +2 -0
- package/dist/assets/{useAppFontEffects-D9c0mG1P.js → useAppFontEffects-Cz9eoInx.js} +9 -9
- package/dist/assets/{useAssistantUIStore-rdsbsVts.js → useAssistantUIStore-BZt-lLlW.js} +1 -1
- package/dist/assets/{useDesktopWindowControlsLayout-Dx-zWLPl.js → useDesktopWindowControlsLayout-HpOlTBoV.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-DPvKdopQ.js → useEffectiveDirectory-DE-YccE8.js} +1 -1
- package/dist/assets/{useFontPreferences-B4LGrKaG.js → useFontPreferences-DmeLn0t9.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-9pGm6Lkc.js → useMobileNavigationStore-DPE5LVui.js} +4 -4
- package/dist/assets/{useUIStore-NMQx_cnG.js → useUIStore-CEingF2z.js} +1 -1
- package/dist/assets/{useWorkerHighlightedLines-DSzghYUI.js → useWorkerHighlightedLines-o-elkNrd.js} +1 -1
- package/dist/index.html +21 -21
- package/dist/mini-chat.html +21 -21
- package/dist/mobile.html +21 -21
- package/package.json +1 -1
- package/server/lib/assistants/DOCUMENTATION.md +188 -16
- package/server/lib/assistants/assign.js +2 -1
- package/server/lib/assistants/contact-tools.js +11 -10
- package/server/lib/assistants/harness.js +23 -9
- package/server/lib/assistants/harness.test.js +34 -10
- package/server/lib/assistants/opencode-tools.js +167 -0
- package/server/lib/assistants/opencode-tools.test.js +295 -0
- package/server/lib/assistants/progressive-tools.js +33 -0
- package/server/lib/assistants/progressive-tools.test.js +66 -0
- package/server/lib/assistants/routes.js +1 -0
- package/server/lib/assistants/service.js +24 -35
- package/server/lib/assistants/service.test.js +208 -21
- package/server/lib/assistants/yuri-project.http.test.js +126 -0
- package/server/lib/assistants/yuri-tools.js +42 -0
- package/server/lib/assistants/yuri-tools.test.js +151 -0
- package/server/lib/opencode/DOCUMENTATION.md +1 -0
- package/server/lib/opencode/feature-routes-runtime.js +9 -0
- package/server/lib/opencode/feature-routes-runtime.test.js +12 -0
- package/server/lib/opencode/routes.js +4 -32
- package/server/lib/opencode/settings-runtime.js +7 -2
- package/server/lib/projects/DOCUMENTATION.md +29 -0
- package/server/lib/projects/registry.js +36 -0
- package/server/lib/projects/registry.test.js +107 -0
- package/server/lib/quota/magpie.js +2 -2
- package/server/lib/quota/providers/index.js +6 -2
- package/server/lib/quota/providers/index.test.js +6 -1
- package/server/lib/relay/DOCUMENTATION.md +3 -3
- package/server/lib/relay/host-client.js +4 -6
- package/server/lib/relay/host-client.reconnect.test.js +3 -2
- package/server/lib/relay/relay-server.e2e.test.ts +144 -1
- package/dist/assets/AgentAvatar-CVIpaYPU.js +0 -1
- package/dist/assets/AssistantView-D5vJW3gp.js +0 -3
- package/dist/assets/MarkdownRenderer-DuA1vlFT.js +0 -2
- package/dist/assets/miniChat-DUSGfEUO.js +0 -2
- package/dist/assets/mobile-CMXtTX1x.js +0 -2
- package/dist/assets/runtime-auth-ef9W7A43.js +0 -1
- package/dist/assets/types-BcumvHrl.js +0 -2
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { createContactTools } from './contact-tools.js';
|
|
3
|
+
import { runContactTurn } from './harness.js';
|
|
4
|
+
import { createYuriContactToolGroups, createYuriContactTools } from './yuri-tools.js';
|
|
5
|
+
import { createProgressiveTools } from './progressive-tools.js';
|
|
6
|
+
|
|
7
|
+
const call = (name, args) => ({ completion: { choices: [{ message: { content: '', tool_calls: [{
|
|
8
|
+
id: `call_${name}`, type: 'function', function: { name, arguments: JSON.stringify(args) },
|
|
9
|
+
}] } }] } });
|
|
10
|
+
const names = (body) => body.tools.map((tool) => tool.function.name);
|
|
11
|
+
const turn = (tools, createChatCompletion, extra = {}) => runContactTurn({
|
|
12
|
+
assistant: { providerID: 'p', modelID: 'm' }, history: [], userText: 'Perform the requested operation.', tools, createChatCompletion, ...extra,
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
describe('assistant-only progressive business tools', () => {
|
|
16
|
+
it('keeps only registration from the eleven-tool expansion, with safe projections', async () => {
|
|
17
|
+
expect(createYuriContactTools()).toEqual([]);
|
|
18
|
+
const registerProject = vi.fn(async () => ({ project: { id: 'p', path: '/workspace', label: 'App', secret: 'private' }, created: true, settings: { token: 'private' } }));
|
|
19
|
+
const tools = createYuriContactTools({ registerProject });
|
|
20
|
+
expect(tools.map((tool) => tool.name)).toEqual(['register_project']);
|
|
21
|
+
const result = await tools[0].execute('register', { path: '/workspace' });
|
|
22
|
+
expect(result.details).toEqual({ project: { id: 'p', path: '/workspace', label: 'App' }, created: true });
|
|
23
|
+
expect(result.terminate).toBe(false);
|
|
24
|
+
expect(JSON.stringify(result)).not.toContain('private');
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it.each([null, [], { path: '' }, { path: 123 }, { path: '/workspace', url: 'https://example.test' }, { path: '/workspace', label: null }])('rejects malformed registration before invoking the owner: %j', async (params) => {
|
|
28
|
+
const registerProject = vi.fn();
|
|
29
|
+
const result = await createYuriContactTools({ registerProject })[0].execute('bad', params);
|
|
30
|
+
expect(result).toMatchObject({ isError: true, details: { error: 'validation_error' } });
|
|
31
|
+
expect(registerProject).not.toHaveBeenCalled();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('propagates cancellation and never exposes upstream errors', async () => {
|
|
35
|
+
const registerProject = vi.fn(async () => { throw new Error('Bearer private'); });
|
|
36
|
+
const tool = createYuriContactTools({ registerProject })[0];
|
|
37
|
+
const failure = await tool.execute('failed', { path: '/workspace' });
|
|
38
|
+
expect(failure.isError).toBe(true);
|
|
39
|
+
expect(JSON.stringify(failure)).not.toContain('private');
|
|
40
|
+
const controller = new AbortController(); controller.abort();
|
|
41
|
+
await expect(tool.execute('cancelled', { path: '/workspace' }, controller.signal)).rejects.toThrow();
|
|
42
|
+
expect(registerProject).toHaveBeenCalledTimes(1);
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it('omits unavailable groups, rejects unknown/extra arguments and makes repeat loads idempotent', async () => {
|
|
46
|
+
const source = createYuriContactTools({ registerProject: vi.fn() });
|
|
47
|
+
const progressive = createProgressiveTools({ tools: source, groups: createYuriContactToolGroups(source) });
|
|
48
|
+
const loader = progressive.getTools()[0];
|
|
49
|
+
expect(loader.parameters.properties.domain.enum).toEqual(['yuri.projects']);
|
|
50
|
+
for (const params of [{ domain: 'yuri.tasks' }, { domain: 'yuri.projects', url: '/' }, {}, null]) {
|
|
51
|
+
expect((await loader.execute('bad', params)).isError).toBe(true);
|
|
52
|
+
expect(progressive.getTools().map((tool) => tool.name)).toEqual(['load_tools']);
|
|
53
|
+
}
|
|
54
|
+
expect((await loader.execute('load', { domain: 'yuri.projects' })).addedToolNames).toEqual(['register_project']);
|
|
55
|
+
expect((await loader.execute('again', { domain: 'yuri.projects' })).details.alreadyLoaded).toBe(true);
|
|
56
|
+
expect(progressive.getTools().map((tool) => tool.name)).toEqual(['load_tools', 'register_project']);
|
|
57
|
+
expect(source.map((tool) => tool.name)).toEqual(['register_project']);
|
|
58
|
+
expect(createProgressiveTools({ tools: source, groups: createYuriContactToolGroups(source) }).getTools().map((tool) => tool.name)).toEqual(['load_tools']);
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
it('really mounts schemas and executors on the next model round, then resets on the next contact turn', async () => {
|
|
62
|
+
const registerProject = vi.fn(async () => ({ project: { id: 'p', path: '/workspace' }, created: true }));
|
|
63
|
+
const tools = [...createContactTools({}), ...createYuriContactTools({ registerProject })];
|
|
64
|
+
let round = 0;
|
|
65
|
+
const result = await turn(tools, async ({ body }) => {
|
|
66
|
+
round++;
|
|
67
|
+
if (round === 1) {
|
|
68
|
+
expect(names(body)).toContain('assign_session');
|
|
69
|
+
expect(names(body)).toContain('load_tools');
|
|
70
|
+
for (const name of ['register_project', 'create_assistant', 'update_avatar', 'schedule_task', 'update_scheduled_task']) expect(names(body)).not.toContain(name);
|
|
71
|
+
expect(JSON.stringify(body)).not.toContain('register_project');
|
|
72
|
+
return call('load_tools', { domain: 'yuri.projects' });
|
|
73
|
+
}
|
|
74
|
+
expect(names(body)).toContain('register_project');
|
|
75
|
+
expect(names(body)).not.toContain('schedule_task');
|
|
76
|
+
const registration = body.tools.find((tool) => tool.function.name === 'register_project');
|
|
77
|
+
expect(registration.function.parameters.required).toEqual(['path']);
|
|
78
|
+
if (round === 2) return call('register_project', { path: '/workspace' });
|
|
79
|
+
expect(body.messages.findLast((message) => message.name === 'register_project')?.content).toContain('/workspace');
|
|
80
|
+
return { text: 'Registered.' };
|
|
81
|
+
});
|
|
82
|
+
expect(result.tools.map((tool) => tool.name)).toContain('register_project');
|
|
83
|
+
expect(registerProject).toHaveBeenCalledTimes(1);
|
|
84
|
+
await turn(tools, async ({ body }) => {
|
|
85
|
+
expect(names(body)).not.toContain('register_project');
|
|
86
|
+
return { text: 'New turn.' };
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('rejects guessed hidden calls before execution and corrects to the visible loader', async () => {
|
|
91
|
+
const registerProject = vi.fn(async () => ({ project: { id: 'p', path: '/workspace' }, created: true }));
|
|
92
|
+
let round = 0;
|
|
93
|
+
await turn(createYuriContactTools({ registerProject }), async ({ body }) => {
|
|
94
|
+
round++;
|
|
95
|
+
if (round === 1) return call('register_project', { path: '/workspace' });
|
|
96
|
+
expect(registerProject).not.toHaveBeenCalled();
|
|
97
|
+
if (round === 2) {
|
|
98
|
+
expect(names(body)).not.toContain('register_project');
|
|
99
|
+
expect(JSON.stringify(body.messages)).toContain('load_tools');
|
|
100
|
+
return call('load_tools', { domain: 'yuri.projects' });
|
|
101
|
+
}
|
|
102
|
+
return { text: 'Loaded, no mutation requested.' };
|
|
103
|
+
});
|
|
104
|
+
expect(registerProject).not.toHaveBeenCalled();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it('cannot load and execute a hidden operation in the same response', async () => {
|
|
108
|
+
const registerProject = vi.fn();
|
|
109
|
+
let round = 0;
|
|
110
|
+
await turn(createYuriContactTools({ registerProject }), async ({ body }) => {
|
|
111
|
+
round++;
|
|
112
|
+
expect(names(body)).not.toContain('register_project');
|
|
113
|
+
if (round === 1) {
|
|
114
|
+
const response = call('load_tools', { domain: 'yuri.projects' });
|
|
115
|
+
response.completion.choices[0].message.tool_calls.push(call('register_project', { path: '/workspace' }).completion.choices[0].message.tool_calls[0]);
|
|
116
|
+
return response;
|
|
117
|
+
}
|
|
118
|
+
return { text: 'No operation executed.' };
|
|
119
|
+
});
|
|
120
|
+
expect(registerProject).not.toHaveBeenCalled();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
it.each(['assistants', 'tasks'])('loads existing %s operations without altering their owners', async (domain) => {
|
|
124
|
+
const createAssistant = vi.fn(async () => ({ id: 'bot', name: 'Peer', providerID: 'p', modelID: 'm' }));
|
|
125
|
+
const updateScheduledTask = vi.fn(async () => ({ task: { id: 'task', name: 'Task', enabled: false } }));
|
|
126
|
+
const name = domain === 'assistants' ? 'create_assistant' : 'update_scheduled_task';
|
|
127
|
+
const params = domain === 'assistants' ? { name: 'Peer', providerID: 'p', modelID: 'm' } : { projectID: 'p', taskID: 'task', enabled: false };
|
|
128
|
+
let round = 0;
|
|
129
|
+
await turn(createContactTools({ createAssistant, updateScheduledTask }), async ({ body }) => {
|
|
130
|
+
round++;
|
|
131
|
+
if (round === 1) {
|
|
132
|
+
expect(names(body)).not.toContain(name);
|
|
133
|
+
return call('load_tools', { domain: `yuri.${domain}` });
|
|
134
|
+
}
|
|
135
|
+
if (round === 2) return call(name, params);
|
|
136
|
+
return { text: 'Done.' };
|
|
137
|
+
});
|
|
138
|
+
expect(domain === 'assistants' ? createAssistant : updateScheduledTask).toHaveBeenCalledTimes(1);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it('never offers the loader or mutations in a background read-only review, even with all tools supplied', async () => {
|
|
142
|
+
const registerProject = vi.fn();
|
|
143
|
+
const tools = [...createContactTools({}), ...createYuriContactTools({ registerProject })];
|
|
144
|
+
await turn(tools, async ({ body }) => {
|
|
145
|
+
expect(names(body)).toContain('list_scheduled_tasks');
|
|
146
|
+
for (const name of ['load_tools', 'register_project', 'create_assistant', 'schedule_task', 'update_avatar']) expect(names(body)).not.toContain(name);
|
|
147
|
+
return { text: 'Reviewed.' };
|
|
148
|
+
}, { readOnly: true });
|
|
149
|
+
expect(registerProject).not.toHaveBeenCalled();
|
|
150
|
+
});
|
|
151
|
+
});
|
|
@@ -63,6 +63,7 @@ This module provides OpenCode server integration utilities for the web server ru
|
|
|
63
63
|
- `packages/web/server/lib/opencode/project-icon-routes.js`: project icon upload/read/discovery route registration and icon storage orchestration.
|
|
64
64
|
- `packages/web/server/lib/opencode/skill-routes.js`: route registration for skill config CRUD, supporting files, and skills catalog scan/install flows.
|
|
65
65
|
- `packages/web/server/lib/opencode/settings-runtime.js`: Settings persistence runtime (disk IO, migrations, normalization, project validation, and persisted update serialization).
|
|
66
|
+
- Trusted resource owners can pass a functional update to `persistSettings`; it strictly reads and derives the patch inside the same Host/Electron lock, preserving concurrent writes. These callers validate their affected resource instead of sweeping unrelated offline projects. `projects/registry.js` shares project registration between the existing directory HTTP API and assistant tools; ordinary object-based settings updates retain their existing full-list validation behavior.
|
|
66
67
|
- Missing theme preferences use `carbonfox-light` / `cursor-dark`, matching the shared UI defaults. Existing per-variant IDs and legacy explicitly selected theme IDs remain authoritative; changing the default does not rewrite a user's saved theme.
|
|
67
68
|
- Project registry order and `projectSortOrder` are shared Host authority. After a successful changed write, `onProjectOrderChanged` emits `yuri:project-order-changed` on the existing Yuri SSE channel. Clients GET settings on initial mount, tip, and reconnect. Unchanged and failed writes emit no tip; older settings without a sort mode use `manual`.
|
|
68
69
|
- `packages/web/server/lib/opencode/settings-helpers.js`: Settings payload sanitization/format helpers runtime for response shaping and persisted merge prep.
|
|
@@ -20,6 +20,7 @@ import { registerScheduledTaskSessionSkill } from '../scheduled-tasks/session-sk
|
|
|
20
20
|
import { registerConversationRoutes } from '../conversations/routes.js';
|
|
21
21
|
import { registerSessionTurnPageRoutes } from '../session-turn-pages/routes.js';
|
|
22
22
|
import { registerAssistantRoutes } from '../assistants/routes.js';
|
|
23
|
+
import { createProjectRegistry } from '../projects/registry.js';
|
|
23
24
|
import { registerLlmRoutes } from '../llm/routes.js';
|
|
24
25
|
import { registerMessageQueueRoutes } from '../message-queue/routes.js';
|
|
25
26
|
import { getBrowserProviderHost } from '../browser-provider/host.js';
|
|
@@ -283,6 +284,13 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
|
|
283
284
|
.filter((value) => typeof value === 'string'));
|
|
284
285
|
};
|
|
285
286
|
await refreshAssistantAllowedRoots();
|
|
287
|
+
const projectRegistry = createProjectRegistry({ persistSettings, validateDirectoryPath });
|
|
288
|
+
const registerAssistantProject = async (input) => {
|
|
289
|
+
const result = await projectRegistry.register(input);
|
|
290
|
+
await refreshAssistantAllowedRoots();
|
|
291
|
+
// Full settings may contain credentials; only return the affected resource.
|
|
292
|
+
return { project: result.project, created: result.created };
|
|
293
|
+
};
|
|
286
294
|
const broadcastAssistantRevisionTip = createYuriEventBroadcaster({
|
|
287
295
|
getYuriEventClients,
|
|
288
296
|
writeSseEvent,
|
|
@@ -305,6 +313,7 @@ export const createFeatureRoutesRuntime = (dependencies) => {
|
|
|
305
313
|
getOpenCodeAuthHeaders,
|
|
306
314
|
getServerId,
|
|
307
315
|
getAllowedRoots: () => assistantAllowedRoots,
|
|
316
|
+
registerProject: registerAssistantProject,
|
|
308
317
|
listProjects: async () => {
|
|
309
318
|
const settings = await readSettingsFromDiskMigrated();
|
|
310
319
|
return sanitizeProjects(settings?.projects ?? [])
|
|
@@ -31,6 +31,18 @@ describe('feature routes runtime composition', () => {
|
|
|
31
31
|
expect(source).toMatch(/label: project\.label\.trim\(\)/);
|
|
32
32
|
});
|
|
33
33
|
|
|
34
|
+
it('wires only project registration and live roots into the assistant extension tools', async () => {
|
|
35
|
+
const source = await fs.readFile(new URL('./feature-routes-runtime.js', import.meta.url), 'utf8');
|
|
36
|
+
const routes = await fs.readFile(new URL('../assistants/routes.js', import.meta.url), 'utf8');
|
|
37
|
+
expect(source).toContain('createProjectRegistry({ persistSettings, validateDirectoryPath })');
|
|
38
|
+
expect(source).toMatch(/projectRegistry.register\(input\);\s*await refreshAssistantAllowedRoots\(\)/);
|
|
39
|
+
expect(source).toContain('registerProject: registerAssistantProject');
|
|
40
|
+
expect(routes).toContain('registerProject: dependencies.registerProject');
|
|
41
|
+
for (const name of ['updateProject', 'removeProject', 'runScheduledTask', 'deleteScheduledTask']) {
|
|
42
|
+
expect(routes).not.toContain(`${name}: dependencies.${name}`);
|
|
43
|
+
}
|
|
44
|
+
});
|
|
45
|
+
|
|
34
46
|
it('fans contact turn events out on the Yuri SSE bus separately from revision tips', async () => {
|
|
35
47
|
const source = await fs.readFile(new URL('./feature-routes-runtime.js', import.meta.url), 'utf8');
|
|
36
48
|
expect(source).toMatch(/const broadcastContactTurnEvent = createYuriEventBroadcaster\(/);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createProjectRegistry } from '../projects/registry.js';
|
|
2
2
|
import { projectBootstrapSettingsResponse } from './settings-helpers.js';
|
|
3
3
|
import {
|
|
4
4
|
evaluateOpenCodeHealthBody,
|
|
@@ -33,7 +33,6 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
|
|
|
33
33
|
readSettingsFromDisk,
|
|
34
34
|
readSettingsFromDiskMigrated,
|
|
35
35
|
persistSettings,
|
|
36
|
-
sanitizeProjects,
|
|
37
36
|
validateDirectoryPath,
|
|
38
37
|
resolveProjectDirectory,
|
|
39
38
|
getProviderSources,
|
|
@@ -801,43 +800,16 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
|
|
|
801
800
|
return res.status(400).json({ error: 'Path is required' });
|
|
802
801
|
}
|
|
803
802
|
|
|
804
|
-
const
|
|
805
|
-
if (!validated.ok) {
|
|
806
|
-
return res.status(400).json({ error: validated.error });
|
|
807
|
-
}
|
|
808
|
-
|
|
809
|
-
const resolvedPath = validated.directory;
|
|
810
|
-
const currentSettings = await readSettingsFromDisk();
|
|
811
|
-
const existingProjects = sanitizeProjects(currentSettings.projects) || [];
|
|
812
|
-
const existing = existingProjects.find((project) => project.path === resolvedPath) || null;
|
|
813
|
-
|
|
814
|
-
const nextProjects = existing
|
|
815
|
-
? existingProjects
|
|
816
|
-
: [
|
|
817
|
-
...existingProjects,
|
|
818
|
-
{
|
|
819
|
-
id: createProjectIdFromPath(resolvedPath),
|
|
820
|
-
path: resolvedPath,
|
|
821
|
-
addedAt: Date.now(),
|
|
822
|
-
lastOpenedAt: Date.now(),
|
|
823
|
-
},
|
|
824
|
-
];
|
|
825
|
-
|
|
826
|
-
const activeProjectId = existing ? existing.id : nextProjects[nextProjects.length - 1].id;
|
|
827
|
-
|
|
828
|
-
const updated = await persistSettings({
|
|
829
|
-
projects: nextProjects,
|
|
830
|
-
activeProjectId,
|
|
831
|
-
lastDirectory: resolvedPath,
|
|
832
|
-
});
|
|
803
|
+
const { project, settings: updated } = await createProjectRegistry({ persistSettings, validateDirectoryPath }).register({ path: requestedPath, activate: true });
|
|
833
804
|
|
|
834
805
|
return res.json({
|
|
835
806
|
success: true,
|
|
836
807
|
restarted: false,
|
|
837
|
-
path:
|
|
808
|
+
path: project.path,
|
|
838
809
|
settings: updated,
|
|
839
810
|
});
|
|
840
811
|
} catch (error) {
|
|
812
|
+
if (error?.code === 'validation_error') return res.status(400).json({ error: error.message });
|
|
841
813
|
console.error('Failed to update OpenCode working directory:', error);
|
|
842
814
|
return res.status(500).json({ error: error.message || 'Failed to update working directory' });
|
|
843
815
|
}
|
|
@@ -851,10 +851,15 @@ export const createSettingsRuntime = (deps) => {
|
|
|
851
851
|
};
|
|
852
852
|
|
|
853
853
|
const persistSettings = async (changes) => runPersistedWrite(async () => {
|
|
854
|
+
const updateCurrent = typeof changes === 'function';
|
|
855
|
+
const current = updateCurrent
|
|
856
|
+
? await readSettingsFromDiskStrict()
|
|
857
|
+
: await readSettingsFromDisk();
|
|
858
|
+
if (updateCurrent && Array.isArray(current)) throw new Error('Settings file is malformed (array payload)');
|
|
859
|
+
if (typeof changes === 'function') changes = await changes(current);
|
|
854
860
|
// Log field names only — changes can carry credentials (UI password,
|
|
855
861
|
// client tokens) that must never reach the log file.
|
|
856
862
|
console.log('[persistSettings] Updating fields:', Object.keys(changes || {}).join(', ') || '(none)');
|
|
857
|
-
const current = await readSettingsFromDisk();
|
|
858
863
|
const sanitized = sanitizeSettingsUpdate(changes);
|
|
859
864
|
let next = mergePersistedSettings(current, sanitized);
|
|
860
865
|
|
|
@@ -882,7 +887,7 @@ export const createSettingsRuntime = (deps) => {
|
|
|
882
887
|
// Validating project paths hits the filesystem for every entry, so only
|
|
883
888
|
// do it when the incoming update actually touches the projects list —
|
|
884
889
|
// not on every theme/window-state/etc. save.
|
|
885
|
-
if (Object.prototype.hasOwnProperty.call(sanitized, 'projects') && Array.isArray(next.projects)) {
|
|
890
|
+
if (!updateCurrent && Object.prototype.hasOwnProperty.call(sanitized, 'projects') && Array.isArray(next.projects)) {
|
|
886
891
|
const validated = await validateProjectEntries(next.projects);
|
|
887
892
|
next = { ...next, projects: validated };
|
|
888
893
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
# Projects
|
|
2
|
+
|
|
3
|
+
`registry.js` owns registering existing directories. It reuses `validateDirectoryPath`, deterministic
|
|
4
|
+
path-derived IDs and the settings runtime's serialized persistence. The existing
|
|
5
|
+
`POST /api/opencode/directory` API and assistant business tools share this owner.
|
|
6
|
+
The HTTP API still selects the active directory; assistant registration does not
|
|
7
|
+
change an existing active selection. The first registered project becomes active
|
|
8
|
+
through the existing settings invariant.
|
|
9
|
+
|
|
10
|
+
Registration is not filesystem creation or cloning. Those operations must finish
|
|
11
|
+
before registration. Paths are validated and canonicalized before deduplication.
|
|
12
|
+
Concurrent registrations apply against the latest settings under the existing
|
|
13
|
+
Host/Electron exclusive write lock, preserving unrelated settings and projects
|
|
14
|
+
(including temporarily unavailable directories). Existing IDs, ordering, custom
|
|
15
|
+
labels and metadata survive repeat registration. It does not add project label-edit
|
|
16
|
+
or removal APIs, and never deletes files, sessions or task storage.
|
|
17
|
+
|
|
18
|
+
Trusted registry operations use the settings owner's functional update form.
|
|
19
|
+
It performs a strict read inside the same persistence lock and follows the normal
|
|
20
|
+
normalization, migration, atomic write and project-order SSE notification paths.
|
|
21
|
+
Unlike full-list UI replacement, this form does not sweep other projects for
|
|
22
|
+
missing directories: callers validate the affected resource. Corrupt reads and
|
|
23
|
+
failed writes are errors, not empty state or successful registration. No new
|
|
24
|
+
database, settings file, HTTP mutation surface or client sync protocol is added.
|
|
25
|
+
|
|
26
|
+
`registry.test.js` covers canonical alias deduplication, concurrent append/settings
|
|
27
|
+
writes, persistence, offline-project retention, corrupt
|
|
28
|
+
reads and failed-write preservation. Assistant HTTP integration is covered in
|
|
29
|
+
`../assistants/yuri-project.http.test.js`.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { createProjectIdFromPath } from './project-id.js';
|
|
2
|
+
|
|
3
|
+
const fail = (code, message) => { throw Object.assign(new Error(message), { code }); };
|
|
4
|
+
const string = (value, field, max = 4096) => {
|
|
5
|
+
if (typeof value !== 'string' || !value.trim() || value.trim().length > max) {
|
|
6
|
+
fail('validation_error', `${field} must be a nonempty string (maximum ${max} characters).`);
|
|
7
|
+
}
|
|
8
|
+
return value.trim();
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// Registry mutations share the settings owner's exclusive read/modify/write path.
|
|
12
|
+
export const createProjectRegistry = ({ persistSettings, validateDirectoryPath }) => {
|
|
13
|
+
const register = async (input = {}) => {
|
|
14
|
+
const validated = await validateDirectoryPath(string(input.path, 'path'));
|
|
15
|
+
if (!validated.ok) fail('validation_error', validated.error || 'Project directory is unavailable.');
|
|
16
|
+
const directory = validated.directory;
|
|
17
|
+
const label = input.label === undefined ? undefined : string(input.label, 'label', 80);
|
|
18
|
+
let project;
|
|
19
|
+
let created = false;
|
|
20
|
+
const settings = await persistSettings((current) => {
|
|
21
|
+
const projects = Array.isArray(current.projects) ? current.projects : [];
|
|
22
|
+
const existing = projects.find((entry) => entry.path === directory);
|
|
23
|
+
created = !existing;
|
|
24
|
+
project = existing || { id: createProjectIdFromPath(directory), path: directory, addedAt: Date.now(), lastOpenedAt: Date.now(), ...(label ? { label } : {}) };
|
|
25
|
+
return {
|
|
26
|
+
projects: created ? [...projects, project] : projects,
|
|
27
|
+
...(input.activate === true ? { activeProjectId: project.id, lastDirectory: directory } : {}),
|
|
28
|
+
};
|
|
29
|
+
});
|
|
30
|
+
const saved = settings.projects?.find((entry) => entry.id === project.id);
|
|
31
|
+
if (!saved) fail('project_unavailable', 'The directory disappeared before the project could be registered. No session was opened.');
|
|
32
|
+
return { project: saved, created, settings };
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
return { register };
|
|
36
|
+
};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
6
|
+
import { createSettingsRuntime } from '../opencode/settings-runtime.js';
|
|
7
|
+
import { createSettingsNormalizationRuntime } from '../opencode/settings-normalization-runtime.js';
|
|
8
|
+
import { createProjectDirectoryRuntime } from '../opencode/project-directory-runtime.js';
|
|
9
|
+
import { createProjectRegistry } from './registry.js';
|
|
10
|
+
|
|
11
|
+
const setup = async () => {
|
|
12
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-registry-'));
|
|
13
|
+
const settingsPath = path.join(directory, 'settings.json');
|
|
14
|
+
const tips = vi.fn();
|
|
15
|
+
let failWrites = false;
|
|
16
|
+
const normalization = createSettingsNormalizationRuntime({ os, path, processLike: process });
|
|
17
|
+
const runtime = createSettingsRuntime({
|
|
18
|
+
fsPromises: { ...fs, rename: (...args) => failWrites ? Promise.reject(new Error('write failed')) : fs.rename(...args) },
|
|
19
|
+
path, crypto, SETTINGS_FILE_PATH: settingsPath, ...normalization,
|
|
20
|
+
sanitizeSettingsUpdate: (patch) => patch,
|
|
21
|
+
mergePersistedSettings: (current, patch) => ({ ...current, ...patch }),
|
|
22
|
+
formatSettingsResponse: (settings) => settings,
|
|
23
|
+
resolveDirectoryCandidate: (value) => value,
|
|
24
|
+
onProjectOrderChanged: tips,
|
|
25
|
+
});
|
|
26
|
+
const { validateDirectoryPath } = createProjectDirectoryRuntime({
|
|
27
|
+
fsPromises: fs, path, normalizeDirectoryPath: normalization.normalizeDirectoryPath,
|
|
28
|
+
});
|
|
29
|
+
const registry = createProjectRegistry({ persistSettings: runtime.persistSettings, validateDirectoryPath });
|
|
30
|
+
const workspace = path.join(directory, 'workspace');
|
|
31
|
+
await fs.mkdir(workspace);
|
|
32
|
+
return { directory, settingsPath, workspace, registry, runtime, tips,
|
|
33
|
+
failWrites: () => { failWrites = true; },
|
|
34
|
+
cleanup: () => fs.rm(directory, { recursive: true, force: true }),
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
describe('shared project registry owner', () => {
|
|
39
|
+
it('registers and deduplicates canonical aliases without deleting files', async () => {
|
|
40
|
+
const app = await setup();
|
|
41
|
+
try {
|
|
42
|
+
const first = await app.registry.register({ path: app.workspace, label: 'App' });
|
|
43
|
+
const alias = path.join(app.directory, 'alias');
|
|
44
|
+
await fs.symlink(app.workspace, alias);
|
|
45
|
+
const second = await app.registry.register({ path: alias });
|
|
46
|
+
expect(first.created).toBe(true);
|
|
47
|
+
expect(second).toMatchObject({ created: false, project: { id: first.project.id, label: 'App' } });
|
|
48
|
+
expect((await app.runtime.readSettingsFromDiskStrict()).projects).toHaveLength(1);
|
|
49
|
+
expect(app.tips).toHaveBeenCalledTimes(1);
|
|
50
|
+
expect((await fs.stat(app.workspace)).isDirectory()).toBe(true);
|
|
51
|
+
} finally { await app.cleanup(); }
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it('serializes concurrent registrations against the latest settings and preserves unrelated/offline projects', async () => {
|
|
55
|
+
const app = await setup();
|
|
56
|
+
try {
|
|
57
|
+
const other = path.join(app.directory, 'other');
|
|
58
|
+
await fs.mkdir(other);
|
|
59
|
+
await fs.writeFile(app.settingsPath, JSON.stringify({
|
|
60
|
+
projects: [{ id: 'offline', path: path.join(app.directory, 'offline'), addedAt: 1, lastOpenedAt: 1 }],
|
|
61
|
+
theme: 'saved', activeProjectId: 'offline', lastDirectory: 'keep-this-selection',
|
|
62
|
+
}));
|
|
63
|
+
const results = await Promise.all([
|
|
64
|
+
app.registry.register({ path: app.workspace }), app.registry.register({ path: other }),
|
|
65
|
+
app.runtime.persistSettings({ theme: 'new-theme' }),
|
|
66
|
+
]);
|
|
67
|
+
const saved = await app.runtime.readSettingsFromDiskStrict();
|
|
68
|
+
expect(saved.projects.map((project) => project.path)).toEqual(expect.arrayContaining([path.join(app.directory, 'offline'), await fs.realpath(app.workspace), await fs.realpath(other)]));
|
|
69
|
+
expect(saved.projects).toHaveLength(3);
|
|
70
|
+
expect(saved.projects[0].path).toBe(path.join(app.directory, 'offline'));
|
|
71
|
+
expect(saved.theme).toBe('new-theme');
|
|
72
|
+
expect(saved.activeProjectId).not.toBe(results[0].project.id);
|
|
73
|
+
expect(saved.lastDirectory).toBe('keep-this-selection');
|
|
74
|
+
const restarted = createProjectRegistry({ persistSettings: app.runtime.persistSettings,
|
|
75
|
+
validateDirectoryPath: async () => ({ ok: true, directory: await fs.realpath(app.workspace) }) });
|
|
76
|
+
expect((await restarted.register({ path: app.workspace })).created).toBe(false);
|
|
77
|
+
} finally { await app.cleanup(); }
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
it('rejects missing/file directories without a write or revision tip', async () => {
|
|
81
|
+
const app = await setup();
|
|
82
|
+
try {
|
|
83
|
+
await fs.writeFile(app.settingsPath, JSON.stringify({ theme: 'saved' }));
|
|
84
|
+
const before = await fs.readFile(app.settingsPath, 'utf8');
|
|
85
|
+
await expect(app.registry.register({ path: path.join(app.directory, 'missing') })).rejects.toMatchObject({ code: 'validation_error' });
|
|
86
|
+
await expect(app.registry.register({ path: app.settingsPath })).rejects.toMatchObject({ code: 'validation_error' });
|
|
87
|
+
expect(await fs.readFile(app.settingsPath, 'utf8')).toBe(before);
|
|
88
|
+
expect(app.tips).not.toHaveBeenCalled();
|
|
89
|
+
} finally { await app.cleanup(); }
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it('preserves the previous committed settings on failed writes, and never overwrites corrupt settings', async () => {
|
|
93
|
+
const app = await setup();
|
|
94
|
+
try {
|
|
95
|
+
await fs.writeFile(app.settingsPath, JSON.stringify({ theme: 'saved' }));
|
|
96
|
+
app.failWrites();
|
|
97
|
+
await expect(app.registry.register({ path: app.workspace })).rejects.toThrow('write failed');
|
|
98
|
+
expect(await app.runtime.readSettingsFromDiskStrict()).toEqual({ theme: 'saved' });
|
|
99
|
+
expect(app.tips).not.toHaveBeenCalled();
|
|
100
|
+
for (const corrupt of ['{broken', '[]', 'null']) {
|
|
101
|
+
await fs.writeFile(app.settingsPath, corrupt);
|
|
102
|
+
await expect(app.registry.register({ path: app.workspace })).rejects.toThrow();
|
|
103
|
+
expect(await fs.readFile(app.settingsPath, 'utf8')).toBe(corrupt);
|
|
104
|
+
}
|
|
105
|
+
} finally { await app.cleanup(); }
|
|
106
|
+
});
|
|
107
|
+
});
|
|
@@ -46,7 +46,7 @@ export function projectMagpieQuotas(payload, source, now = Date.now()) {
|
|
|
46
46
|
usedPercent: w.unlimited ? null : percent(w.used), remainingPercent: w.unlimited ? null : percent(w.remaining),
|
|
47
47
|
resetAt, resetAfterSeconds: resetAt === null ? null : Math.max(0, Math.ceil((resetAt - now) / 1000)),
|
|
48
48
|
valueLabel: w.unlimited ? '∞' : text(w.display) || (Number.isFinite(w.amount) && Number.isFinite(w.limit) && w.limit > 0 ? `${w.amount} / ${w.limit}${text(w.unit) ? ` ${w.unit}` : ''}` : null),
|
|
49
|
-
label: w.name, disablePace: true,
|
|
49
|
+
label: w.name, accountName: account.name, disablePace: true,
|
|
50
50
|
};
|
|
51
51
|
account.windows[`${i}:${w.name}`] = window;
|
|
52
52
|
// Magpie serializes this informational window as used: 0 without its
|
|
@@ -57,7 +57,7 @@ export function projectMagpieQuotas(payload, source, now = Date.now()) {
|
|
|
57
57
|
result.usage.windows[key] = window;
|
|
58
58
|
}
|
|
59
59
|
if (account.balance) {
|
|
60
|
-
const window = { ...emptyWindow(), valueLabel: account.balance, label: 'credits_balance', disablePace: true };
|
|
60
|
+
const window = { ...emptyWindow(), valueLabel: account.balance, label: 'credits_balance', accountName: account.name, disablePace: true };
|
|
61
61
|
account.windows.balance = window;
|
|
62
62
|
result.usage.windows[`${account.name} · ${q.kind} (${result.usage.accounts.length + 1})`] = window;
|
|
63
63
|
}
|
|
@@ -158,12 +158,16 @@ export const fetchQuotaForProvider = async (providerId) => {
|
|
|
158
158
|
try {
|
|
159
159
|
return await provider.fetchQuota();
|
|
160
160
|
} catch (error) {
|
|
161
|
+
const message = error instanceof Error ? error.message : 'Request failed';
|
|
162
|
+
// Credential source unreachable means we cannot know whether the provider is configured;
|
|
163
|
+
// never report it as a configured provider failure.
|
|
164
|
+
const credentialSourceUnavailable = message === 'Unable to read OpenCode credentials';
|
|
161
165
|
return buildResult({
|
|
162
166
|
providerId: provider.providerId,
|
|
163
167
|
providerName: provider.providerName,
|
|
164
168
|
ok: false,
|
|
165
|
-
configured:
|
|
166
|
-
error:
|
|
169
|
+
configured: !credentialSourceUnavailable,
|
|
170
|
+
error: message
|
|
167
171
|
});
|
|
168
172
|
}
|
|
169
173
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { describe, expect, it } from 'vitest';
|
|
2
2
|
|
|
3
3
|
import * as google from './google/index.js';
|
|
4
|
-
import { listConfiguredQuotaProviders } from './index.js';
|
|
4
|
+
import { fetchQuotaForProvider, listConfiguredQuotaProviders } from './index.js';
|
|
5
5
|
|
|
6
6
|
describe('quota provider registry', () => {
|
|
7
7
|
it('exposes google provider configuration helpers through the provider module', () => {
|
|
@@ -14,4 +14,9 @@ describe('quota provider registry', () => {
|
|
|
14
14
|
it('reports unavailable credentials instead of an empty configured-provider list', async () => {
|
|
15
15
|
await expect(listConfiguredQuotaProviders()).rejects.toThrow('Unable to read OpenCode credentials');
|
|
16
16
|
});
|
|
17
|
+
|
|
18
|
+
it('does not report a provider as configured when the credential source is unavailable', async () => {
|
|
19
|
+
const result = await fetchQuotaForProvider('claude');
|
|
20
|
+
expect(result).toMatchObject({ ok: false, configured: false, error: 'Unable to read OpenCode credentials' });
|
|
21
|
+
});
|
|
17
22
|
});
|
|
@@ -24,7 +24,7 @@ Host side (`packages/web/server/lib/relay/`):
|
|
|
24
24
|
- `service.js` — thin entrypoint: relay config (enabled flag + endpoints), the management routes (`GET/POST /api/yuri/relay/{status,enable,disable}`, `POST /api/yuri/relay/endpoints`), a `getPairingCandidate()` accessor (the relay transport candidate folded into pairing-v2 links when enabled, consumed by the pairing-session route in `core-routes.js`), and lifecycle wiring. **Multi-relay:** `settings.privateRelay = { enabled, relayUrl, extraRelayUrls }` — the host dials EVERY configured endpoint simultaneously with one identity (same serverId); clients treat `serverId + relayUrl` as the instance identity, so the same machine exposed via two domains appears as two separately named instances. The primary (`relayUrl`) owns push registration and stays the default pairing candidate. A pairing link created for an endpoint the host does not have yet APPENDS it as an extra endpoint instead of replacing the primary, so devices paired over the old domain keep working. `POST /relay/endpoints` (owner session / `desktop-local` only) replaces the extra-endpoint list wholesale and starts/stops host connections incrementally. Paired desktop operators may also add an endpoint through pairing creation. Host lifecycle is gated by `isRelayHostRuntime()` (`desktop` or `ssh-remote`): other runtimes (`bun run dev`, `dev:web:hmr`, ordinary CLI `serve`, VS Code, plain `node server`) report `state: 'unavailable'`, refuse `/relay/enable`, `/relay/disable`, `/relay/endpoints`, and relay pairing with 403, never mint a relay identity, never advertise `relayAvailable`, and never call `startRelayHost`. Direct `node server/index.js` forces `YURI_RUNTIME=web` unless it is already `ssh-remote`, so a leftover desktop env cannot open the host-control socket. On host runtimes, started from `packages/web/server/index.js` when demand/opt-in enables the relay. Desktop auto-clears `privateRelay.enabled` when demand drops; `ssh-remote` keeps an explicit opt-in (e.g. `yuri serve --relay-host`) sticky until disabled. The relay endpoint has no hosted default and must be configured in settings or pinned via the `YURI_RELAY_URL` env var; when set it overrides the stored setting for the host connection, the pairing candidate, and status, so paired clients inherit the endpoint automatically. Endpoint identity is scheme/host/path only: accepted schemes are `ws://` and `wss://`; URLs with userinfo are rejected (no silent default fallback); query and fragment are stripped before persistence and pairing candidates. Custom endpoint persistence and Host control-connection switching are explicit authenticated management actions. Pairing creation with `relayUrl` requires an owner UI session, local `desktop-local` shell client, or paired `desktop` operator; `/relay/enable` follows its API auth gate. `derivePushSendUrlFromRelayUrl` maps a canonical Relay `wss://`/`ws://` URL to the same host's `https://`/`http://` `/v1/push/send` path (register is `/v1/push/register-token`); `YURI_PUSH_RELAY_URL` on the Host overrides that derivation. The isolated Push process lives in `packages/relay-server/src/push/` and does not share Layer 1 credentials or tunnel state.
|
|
25
25
|
- `identity.js` — the host's stable identity: the long-lived signing keypair (shared with the push relay, defines the routing id) plus a long-lived encryption keypair (the E2EE trust anchor). Reused across restarts; never rotated implicitly.
|
|
26
26
|
- `signing-key.js` — storage/derivation of the signing keypair and the routing id, shared with the notifications runtime. Canonical public JWK hashing matches `packages/relay-server/src/push/crypto.js`.
|
|
27
|
-
- `host-client.js` — the long-lived connection manager: one outbound control connection to the relay, a per-client data connection for each connected device, reconnect
|
|
27
|
+
- `host-client.js` — the long-lived connection manager: one outbound control connection to the relay, a per-client data connection for each connected device, reconnect, and the E2EE responder handshake per connection. Control reconnect keeps a fixed 3-second cadence until stopped; failure history clears only after the control socket stays up for `controlStableMs` (15s default), not on a brief WebSocket `open`.
|
|
28
28
|
- `host-lock.js` — the per-machine host claim. Every local instance sharing the data dir shares the relay identity (same serverId), so concurrent relay hosts evict each other at the relay worker (`4001: Control replaced`) and paired devices land on whichever local process won last. The claim file (`<data-dir>/relay-host.lock`, `{ pid }`) makes this deterministic: `service.js` only starts the host when no LIVE process holds the claim (stale claims from dead pids are ignored), goes to `standby` otherwise, and a 30s watcher both takes over when the claimant dies and stands down when another process claims. Explicit user intent — creating a pairing link or hitting `/relay/enable` — force-claims; the previous holder's watcher sees the takeover and backs off instead of fighting. The claim is cooperative (the relay worker still enforces the single host slot); it only decides which process keeps retrying.
|
|
29
29
|
- `tunnel-host.js` — the per-connection dispatcher: decrypts tunnel frames and forwards HTTP/SSE/WS to the local server over loopback, then streams responses back. Enforces a path allowlist and never injects credentials.
|
|
30
30
|
- `e2ee.js`, `tunnel-codec.js` — host-side (JS) mirrors of the shared crypto and framing (see "Two implementations" below).
|
|
@@ -34,7 +34,7 @@ Client side (`packages/ui/src/lib/relay/`):
|
|
|
34
34
|
- `protocol.ts` — the shared contract: constants, frame types, message shapes. The normative source both implementations follow.
|
|
35
35
|
- `crypto.ts`, `handshake.ts` — the E2EE primitives and handshake state machines (initiator + responder).
|
|
36
36
|
- `tunnel-codec.ts` — Layer 3 frame codec, fragmentation, and outbound frame batching.
|
|
37
|
-
- `tunnel-client.ts` — the client tunnel: exposes a `fetch()`-compatible and a WebSocket-compatible surface backed by the encrypted tunnel.
|
|
37
|
+
- `tunnel-client.ts` — the client tunnel: exposes a `fetch()`-compatible and a WebSocket-compatible surface backed by the encrypted tunnel. Transient closures (including `4029` capacity/pending timeout and replacement) retry indefinitely at a fixed 3-second foreground cadence, or 60 seconds while hidden/offline. Online, visibility-visible and system-resume interrupt retry waits; an apparently connected tunnel is probed immediately. Authentication rejection stays terminal and later requests fail explicitly rather than waiting forever. Keepalive tracks send and receive separately: outbound requests cannot conceal a dead return path, and inbound-only SSE still sends pings so the Host idle reaper does not evict a healthy client. Reset fails every old stream; retries never replay mutation requests automatically.
|
|
38
38
|
- `tunnel-payloads.ts`, `runtime-tunnel.ts`, `runtime-socket.ts` — payload helpers, the active-tunnel singleton, and the shared "open a runtime WebSocket the right way" helper.
|
|
39
39
|
|
|
40
40
|
Relay is not a separate link format: it is one transport candidate inside the unified **pairing v2** payload (`packages/ui/src/lib/connectionPayload.ts`). A relay candidate is `{ type: 'relay', relayUrl, serverId, hostEncPubJwk }` — no embedded token; the client redeems the one-time pairing secret over the tunnel like any other candidate.
|
|
@@ -149,7 +149,7 @@ Catalog loaders (`loadProviders` / `loadAgents`) and assistant Query keys gate w
|
|
|
149
149
|
- The host dispatcher never injects credentials; the server authenticates each tunneled request.
|
|
150
150
|
- The tunnel is transparent to the app: adding relay support to a feature should not require the feature to know the relay exists — it goes through the shared runtime transport helpers.
|
|
151
151
|
- The two implementations stay byte-compatible and the wire format is versioned/negotiated so mixed client/host app versions degrade gracefully rather than break. The Layer 1 Relay does not inspect application versions; unsupported Host/Client features are omitted at the endpoints.
|
|
152
|
-
- Host-control reconnect storms are bounded at both ends: the Host
|
|
152
|
+
- Host-control reconnect storms are bounded at both ends: the Host keeps a fixed 3-second retry cadence, and the Relay rate-limits host-control upgrades per IP and per `serverId` (`4029`) without replacing a live control socket.
|
|
153
153
|
- Concurrent service starts recheck the endpoint's active Host after awaiting identity, so each endpoint has one managed Host and stopping the service closes every started Host.
|
|
154
154
|
- Tunneled HTTP/WS always dial `getLocalPort()` on loopback; there is no client-selected target-port override on the host dispatcher.
|
|
155
155
|
|
|
@@ -9,12 +9,10 @@ import { RELAY_PROTOCOL_VERSION, RelayCloseCode, createHostHandshake } from './e
|
|
|
9
9
|
import { createOutboundFrameBatcher, decodeFrameBatch } from './tunnel-codec.js';
|
|
10
10
|
import { createTunnelHost } from './tunnel-host.js';
|
|
11
11
|
|
|
12
|
-
const BACKOFF_BASE_MS =
|
|
12
|
+
const BACKOFF_BASE_MS = 3000;
|
|
13
13
|
const BACKOFF_CAP_MS = 30000;
|
|
14
|
-
//
|
|
15
|
-
//
|
|
16
|
-
// forever at 1s. Only a control socket that stays up this long is treated as
|
|
17
|
-
// a healthy registration.
|
|
14
|
+
// Keep retry cadence fixed, and clear failure history only after the control
|
|
15
|
+
// socket remains stable rather than treating a brief open as healthy.
|
|
18
16
|
const CONTROL_STABLE_MS = 15_000;
|
|
19
17
|
const DATA_SOCKET_OPEN_TIMEOUT_MS = 15000;
|
|
20
18
|
// Clients send a tunnel Ping at least every ~30s when idle, so a data socket
|
|
@@ -300,7 +298,7 @@ export const startRelayHost = ({ relayUrl, identity, localPort, getLocalPort, on
|
|
|
300
298
|
|
|
301
299
|
const scheduleReconnect = () => {
|
|
302
300
|
if (stopped || reconnectTimer) return;
|
|
303
|
-
const delay = Math.min(backoffBaseMs
|
|
301
|
+
const delay = Math.min(backoffBaseMs, backoffCapMs);
|
|
304
302
|
consecutiveFailures += 1;
|
|
305
303
|
setState('reconnecting');
|
|
306
304
|
reconnectTimer = setTimeout(() => {
|
|
@@ -38,7 +38,7 @@ describe('relay host-client control reconnect', () => {
|
|
|
38
38
|
relay = null;
|
|
39
39
|
});
|
|
40
40
|
|
|
41
|
-
it('
|
|
41
|
+
it('keeps retrying a brief-open control failure at a fixed interval', async () => {
|
|
42
42
|
relay = await startDroppingRelay();
|
|
43
43
|
host = startRelayHost({
|
|
44
44
|
relayUrl: relay.url,
|
|
@@ -58,6 +58,7 @@ describe('relay host-client control reconnect', () => {
|
|
|
58
58
|
const firstGap = relay.openedAt[1] - relay.openedAt[0];
|
|
59
59
|
const secondGap = relay.openedAt[2] - relay.openedAt[1];
|
|
60
60
|
expect(firstGap).toBeGreaterThanOrEqual(50);
|
|
61
|
-
expect(secondGap).
|
|
61
|
+
expect(secondGap).toBeGreaterThanOrEqual(50);
|
|
62
|
+
expect(Math.abs(secondGap - firstGap)).toBeLessThan(60);
|
|
62
63
|
});
|
|
63
64
|
});
|