@yuriai/web 0.2.15 → 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.
Files changed (148) hide show
  1. package/dist/assets/AgentAvatar-D5KPQI1N.js +1 -0
  2. package/dist/assets/AssistantView-huAUB-2Y.js +3 -0
  3. package/dist/assets/{DiagramView-C8uoLQ35.js → DiagramView-DWV04Xws.js} +1 -1
  4. package/dist/assets/{FadeInOnReveal-CxIQc2_J.js → FadeInOnReveal-CdoLG8fY.js} +1 -1
  5. package/dist/assets/{GuiPluginSurface-CFQNrorE.js → GuiPluginSurface-DhD8BqvL.js} +1 -1
  6. package/dist/assets/{GuiPluginWindow-pZqqyXGs.js → GuiPluginWindow-ezsy5l_y.js} +1 -1
  7. package/dist/assets/Icon-DvqOB4Dx.js +1 -0
  8. package/dist/assets/{ImageLoadingPlaceholder-B5t9zOYn.js → ImageLoadingPlaceholder-BVlgaa2r.js} +1 -1
  9. package/dist/assets/{LoadingImage-ByZs_EGY.js → LoadingImage-BSG8jmn5.js} +1 -1
  10. package/dist/assets/MarkdownRenderer-BiRplAST.js +2 -0
  11. package/dist/assets/{MarkdownRendererImpl-BEFLoojj.js → MarkdownRendererImpl-CH8TUMKZ.js} +1 -1
  12. package/dist/assets/{MarkstreamRendererImpl-BD0HFc5P.js → MarkstreamRendererImpl-Bmz56IzM.js} +1 -1
  13. package/dist/assets/{MobileDetailNavigation-BuQ4p5oW.js → MobileDetailNavigation-kKHM_dU3.js} +1 -1
  14. package/dist/assets/{MobileResizableSheet-BdOIJ61C.js → MobileResizableSheet-jHNytoyX.js} +1 -1
  15. package/dist/assets/{MobileShareBridge-UNsCJGaT.js → MobileShareBridge-CSDivsPk.js} +2 -2
  16. package/dist/assets/{MobileTabPageHeader-Bz9YF_Sc.js → MobileTabPageHeader-BkWvNBtr.js} +1 -1
  17. package/dist/assets/{MultiRunWindow-CNd8aJN7.js → MultiRunWindow-DbllgaJR.js} +1 -1
  18. package/dist/assets/{OnboardingScreen-CXIYe29y.js → OnboardingScreen-DONIcirJ.js} +1 -1
  19. package/dist/assets/{OverlayScrollbar-0_OUbhJe.js → OverlayScrollbar-DB2eeXFh.js} +1 -1
  20. package/dist/assets/{SettingsView-U_aHjrBx.js → SettingsView-6D55BNjw.js} +12 -12
  21. package/dist/assets/{SettingsWindow-C-FWiRJy.js → SettingsWindow-BrrnHfnR.js} +1 -1
  22. package/dist/assets/{TerminalView-Dl95RuIA.js → TerminalView-8JYW5f-c.js} +1 -1
  23. package/dist/assets/ToolOutputDialog-DZO89hKv.js +10 -0
  24. package/dist/assets/{YuriLogo-_lN4cqhJ.js → YuriLogo-CYdRUurL.js} +1 -1
  25. package/dist/assets/{appThemeRegistry-ByDzLana.js → appThemeRegistry-Nb-sUfbK.js} +1 -1
  26. package/dist/assets/{assistant-attachment-cache-lEUFn3mr.js → assistant-attachment-cache-C2SmtQG7.js} +1 -1
  27. package/dist/assets/{button-DFX-UCuQ.js → button-nola46HU.js} +1 -1
  28. package/dist/assets/{capgoAdapter-DB7INL7g.js → capgoAdapter-CHeo9q51.js} +1 -1
  29. package/dist/assets/{collapsible-CDkbWw1M.js → collapsible-BQaMLh6O.js} +1 -1
  30. package/dist/assets/{desktop-dp2Z0toS.js → desktop-CiqEZVr5.js} +1 -1
  31. package/dist/assets/{desktopHosts-CYKaLp1V.js → desktopHosts-B4HMNmrx.js} +1 -1
  32. package/dist/assets/{desktopRelayRestore-5yuHB356.js → desktopRelayRestore-CRl62mqn.js} +1 -1
  33. package/dist/assets/{device-DzWRCXhq.js → device-Coc5tapU.js} +1 -1
  34. package/dist/assets/{diagram-JdjLWkpD.js → diagram-COti_aKS.js} +1 -1
  35. package/dist/assets/{dialog-jQrYy1B7.js → dialog-B2CTTXwv.js} +1 -1
  36. package/dist/assets/{dropdown-menu.styles-EKni18O6.js → dropdown-menu.styles-BzpQaok_.js} +1 -1
  37. package/dist/assets/{es-BJGEAUsH.js → es-DklBd0ox.js} +1 -1
  38. package/dist/assets/{fileMentionTouchSelection-CkO5Pveg.js → fileMentionTouchSelection-CXepBNtQ.js} +1 -1
  39. package/dist/assets/{fileQueries-DbUx7NwP.js → fileQueries-Bd-OEFmO.js} +1 -1
  40. package/dist/assets/{fileReferenceActions-No7p4Kdo.js → fileReferenceActions-BnPPqYXw.js} +1 -1
  41. package/dist/assets/{fr-CFAAV_Hr.js → fr-CVUs46wM.js} +1 -1
  42. package/dist/assets/{gitApi-0Rr-brg2.js → gitApi-B7AeNXrj.js} +1 -1
  43. package/dist/assets/{gitApiHttp-BtI23x-7.js → gitApiHttp-CoNokuDM.js} +1 -1
  44. package/dist/assets/{gui-BCPFcL_m.js → gui-D3wrcUs6.js} +1 -1
  45. package/dist/assets/{host-BoCxB_x4.js → host-BCXyr41J.js} +1 -1
  46. package/dist/assets/{image-loading-FUFYiO1j.js → image-loading-DVZlFuU5.js} +1 -1
  47. package/dist/assets/{input-g3JXmugD.js → input-DGnhaqoc.js} +1 -1
  48. package/dist/assets/{insertionBoundaries-CLKaunvi.js → insertionBoundaries-Db0R1aBj.js} +1 -1
  49. package/dist/assets/{ja-1qFce7BA.js → ja-5reg09JK.js} +1 -1
  50. package/dist/assets/{ko-BDwpL-64.js → ko-DZdC6ooz.js} +1 -1
  51. package/dist/assets/main-DQ0F0yuL.js +169 -0
  52. package/dist/assets/{main-D0kTACo9.js → main-d2AaD_PZ.js} +2 -2
  53. package/dist/assets/{markdownHeightCache-BsFt9Iuh.js → markdownHeightCache-C_JI5qIR.js} +1 -1
  54. package/dist/assets/{mcpQueries-D0LNcR1q.js → mcpQueries-BgFj7wfO.js} +1 -1
  55. package/dist/assets/miniChat-BHdsTyJ3.js +2 -0
  56. package/dist/assets/mobile-BEhQq4tx.js +2 -0
  57. package/dist/assets/{mobileBackNavigation-DPmsYwPj.js → mobileBackNavigation-s9RsXUUH.js} +1 -1
  58. package/dist/assets/{multirun-BLDsdBIC.js → multirun-BZsBsBAj.js} +1 -1
  59. package/dist/assets/{native-config-ByqoltPf.js → native-config-BmrfOzkM.js} +1 -1
  60. package/dist/assets/{persistence-BfjCXjLZ.js → persistence-CNEHspb4.js} +1 -1
  61. package/dist/assets/{pl-COzHGIeC.js → pl-BerZSK-a.js} +1 -1
  62. package/dist/assets/{platform-syRnKuVU.js → platform-Q45KPuGv.js} +1 -1
  63. package/dist/assets/{projectMeta-UNs8fviv.js → projectMeta-BCGIXTbR.js} +1 -1
  64. package/dist/assets/{pt-BR-B6ps5NQH.js → pt-BR-ydmV6U49.js} +1 -1
  65. package/dist/assets/{queryRuntime-BuRnpVtK.js → queryRuntime-DWgXfxGx.js} +1 -1
  66. package/dist/assets/{readiness-Dl3hJelb.js → readiness-BxT5OBkk.js} +1 -1
  67. package/dist/assets/{renderElectronMiniChatApp-ShVOG0Py.js → renderElectronMiniChatApp-BbfF6SjM.js} +2 -2
  68. package/dist/assets/{renderMobileApp-Dda4hoGA.js → renderMobileApp-ulSQxT-l.js} +6 -6
  69. package/dist/assets/runtime-auth-BaBM02zI.js +1 -0
  70. package/dist/assets/{runtime-fetch-BAN5Gnnp.js → runtime-fetch-DfALP7-b.js} +1 -1
  71. package/dist/assets/{runtime-file-download-BzblfnMx.js → runtime-file-download-xvItwYMc.js} +1 -1
  72. package/dist/assets/{runtime-file-resource-D3k0hKDj.js → runtime-file-resource-DtsKbFf3.js} +1 -1
  73. package/dist/assets/{runtime-switch-CAZiOV2G.js → runtime-switch-DhMY9eiB.js} +1 -1
  74. package/dist/assets/{runtimeConfig-CijjWK-g.js → runtimeConfig-BHRHZbwI.js} +1 -1
  75. package/dist/assets/{runtimeEndpointReset-CB04brBn.js → runtimeEndpointReset-H2W1kxcO.js} +4 -4
  76. package/dist/assets/{scheduledTaskNavigation-DPl7XI48.js → scheduledTaskNavigation-CkBcoGV4.js} +1 -1
  77. package/dist/assets/{sessionChangeSummary-CRPfojF7.js → sessionChangeSummary-CAU-06Bu.js} +1 -1
  78. package/dist/assets/{sessionLookup-7qVMN2KO.js → sessionLookup-YvkfClst.js} +1 -1
  79. package/dist/assets/{sortable-tabs-strip-Bp_bMUwf.js → sortable-tabs-strip-pCvZjmMt.js} +1 -1
  80. package/dist/assets/{speechSettingsQueries-DkLz1lXd.js → speechSettingsQueries-1LD5eEHK.js} +2 -2
  81. package/dist/assets/src-DGCTlpkW.css +2 -0
  82. package/dist/assets/{store-CKaWYiP4.js → store-ClIuNNU7.js} +2 -2
  83. package/dist/assets/{terminalApi-Dw1h9m3h.js → terminalApi-DFhCeMya.js} +1 -1
  84. package/dist/assets/{textarea-BuvlUTo2.js → textarea-DSHEMw8t.js} +1 -1
  85. package/dist/assets/{tooltip-Byl6nrXB.js → tooltip-BwTvgqWG.js} +1 -1
  86. package/dist/assets/types-CiQgQf3s.js +2 -0
  87. package/dist/assets/{uk-StL0Y7Ti.js → uk-BnTevguX.js} +1 -1
  88. package/dist/assets/{useAppFontEffects-CL3-doYG.js → useAppFontEffects-Cz9eoInx.js} +53 -53
  89. package/dist/assets/{useAssistantUIStore-rdsbsVts.js → useAssistantUIStore-BZt-lLlW.js} +1 -1
  90. package/dist/assets/{useDesktopWindowControlsLayout-BCwpHdQs.js → useDesktopWindowControlsLayout-HpOlTBoV.js} +1 -1
  91. package/dist/assets/{useEffectiveDirectory-D2Yehntp.js → useEffectiveDirectory-DE-YccE8.js} +1 -1
  92. package/dist/assets/{useFontPreferences-B4LGrKaG.js → useFontPreferences-DmeLn0t9.js} +1 -1
  93. package/dist/assets/{useMobileNavigationStore-uTICFg9r.js → useMobileNavigationStore-DPE5LVui.js} +22 -22
  94. package/dist/assets/{useUIStore-NMQx_cnG.js → useUIStore-CEingF2z.js} +1 -1
  95. package/dist/assets/useWorkerHighlightedLines-o-elkNrd.js +7 -0
  96. package/dist/assets/{vendor-framer-motion-D8hQsul-.js → vendor-framer-motion-BQ3-sJMO.js} +1 -1
  97. package/dist/assets/vendor-motion-B4xmxmaP.js +1 -0
  98. package/dist/assets/{zh-CN-CxO7ZteK.js → zh-CN-DT6qIAPJ.js} +1 -1
  99. package/dist/assets/{zh-TW-9MJgbinh.js → zh-TW-CtLsIcFb.js} +1 -1
  100. package/dist/index.html +21 -21
  101. package/dist/mini-chat.html +21 -21
  102. package/dist/mobile.html +21 -21
  103. package/package.json +1 -1
  104. package/server/lib/assistants/DOCUMENTATION.md +205 -6
  105. package/server/lib/assistants/assign.js +2 -1
  106. package/server/lib/assistants/contact-attachments.http.test.js +1 -1
  107. package/server/lib/assistants/contact-greeting.js +18 -0
  108. package/server/lib/assistants/contact-tools.js +11 -10
  109. package/server/lib/assistants/harness.js +23 -7
  110. package/server/lib/assistants/harness.test.js +35 -7
  111. package/server/lib/assistants/opencode-tools.js +167 -0
  112. package/server/lib/assistants/opencode-tools.test.js +295 -0
  113. package/server/lib/assistants/progressive-tools.js +33 -0
  114. package/server/lib/assistants/progressive-tools.test.js +66 -0
  115. package/server/lib/assistants/routes.js +1 -0
  116. package/server/lib/assistants/service.js +40 -9
  117. package/server/lib/assistants/service.test.js +401 -26
  118. package/server/lib/assistants/yuri-project.http.test.js +126 -0
  119. package/server/lib/assistants/yuri-tools.js +42 -0
  120. package/server/lib/assistants/yuri-tools.test.js +151 -0
  121. package/server/lib/opencode/DOCUMENTATION.md +1 -0
  122. package/server/lib/opencode/feature-routes-runtime.js +9 -0
  123. package/server/lib/opencode/feature-routes-runtime.test.js +12 -0
  124. package/server/lib/opencode/routes.js +4 -32
  125. package/server/lib/opencode/settings-runtime.js +7 -2
  126. package/server/lib/projects/DOCUMENTATION.md +29 -0
  127. package/server/lib/projects/registry.js +36 -0
  128. package/server/lib/projects/registry.test.js +107 -0
  129. package/server/lib/quota/magpie.js +2 -2
  130. package/server/lib/quota/providers/index.js +6 -2
  131. package/server/lib/quota/providers/index.test.js +6 -1
  132. package/server/lib/relay/DOCUMENTATION.md +3 -3
  133. package/server/lib/relay/host-client.js +4 -6
  134. package/server/lib/relay/host-client.reconnect.test.js +3 -2
  135. package/server/lib/relay/relay-server.e2e.test.ts +144 -1
  136. package/dist/assets/AgentAvatar-DJCC3Aqe.js +0 -1
  137. package/dist/assets/AssistantView-C4PAEb1I.js +0 -3
  138. package/dist/assets/Icon-C1nXIg7J.js +0 -1
  139. package/dist/assets/MarkdownRenderer-BYncw2H5.js +0 -2
  140. package/dist/assets/ToolOutputDialog-CA3uzAb9.js +0 -10
  141. package/dist/assets/main-RLZoG0Uv.js +0 -169
  142. package/dist/assets/miniChat-DBqehQQO.js +0 -2
  143. package/dist/assets/mobile-CZ_s2Xj0.js +0 -2
  144. package/dist/assets/runtime-auth-ef9W7A43.js +0 -1
  145. package/dist/assets/src-dSUmXLC4.css +0 -2
  146. package/dist/assets/types-CbUh5q3D.js +0 -2
  147. package/dist/assets/useWorkerHighlightedLines-BzXvnL_U.js +0 -7
  148. package/dist/assets/vendor-motion-DufQFNcM.js +0 -1
@@ -0,0 +1,126 @@
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 http from 'node:http';
6
+ import express from 'express';
7
+ import { describe, expect, it, vi } from 'vitest';
8
+
9
+ const external = vi.hoisted(() => ({ complete: null, client: null }));
10
+ vi.mock('../llm/completions.js', () => ({ createChatCompletion: (input) => external.complete(input) }));
11
+ vi.mock('../opencode/v2-client.js', () => ({ makeOpenCodeV2Client: () => external.client }));
12
+ vi.mock('@opencode/client', () => ({ OpenCode: { make: () => external.client } }));
13
+ import { registerAssistantRoutes } from './routes.js';
14
+ import { registerConversationRoutes } from '../conversations/routes.js';
15
+ import { registerOpenCodeRoutes } from '../opencode/routes.js';
16
+ import { createSettingsRuntime } from '../opencode/settings-runtime.js';
17
+ import { createSettingsNormalizationRuntime } from '../opencode/settings-normalization-runtime.js';
18
+ import { createProjectDirectoryRuntime } from '../opencode/project-directory-runtime.js';
19
+ import { createProjectRegistry } from '../projects/registry.js';
20
+
21
+ const call = (name, args) => ({ completion: { choices: [{ message: { content: '', tool_calls: [{ id: `call_${name}`, type: 'function', function: { name, arguments: JSON.stringify(args) } }] } }] } });
22
+
23
+ describe('HTTP → real contact Agent → project registry → worker admission', () => {
24
+ it('registers a cloned directory, sends hello and persists a real session card without manual Settings', async () => {
25
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-project-http-'));
26
+ const workspace = path.join(directory, 'cloned-app');
27
+ await fs.mkdir(workspace);
28
+ const canonical = await fs.realpath(workspace);
29
+ const normalization = createSettingsNormalizationRuntime({ os, path, processLike: process });
30
+ const settings = createSettingsRuntime({ fsPromises: fs, path, crypto, SETTINGS_FILE_PATH: path.join(directory, 'settings.json'), ...normalization,
31
+ sanitizeSettingsUpdate: (patch) => patch, mergePersistedSettings: (current, patch) => ({ ...current, ...patch }),
32
+ formatSettingsResponse: (value) => value, resolveDirectoryCandidate: (value) => value,
33
+ });
34
+ const { validateDirectoryPath } = createProjectDirectoryRuntime({ fsPromises: fs, path, normalizeDirectoryPath: normalization.normalizeDirectoryPath });
35
+ const registry = createProjectRegistry({ persistSettings: settings.persistSettings, validateDirectoryPath });
36
+ const creates = vi.fn(async () => ({ id: 'ses_hello' }));
37
+ const prompts = vi.fn(async () => ({ id: 'inbox_hello', type: 'user' }));
38
+ external.client = {
39
+ provider: { list: async () => ({ data: [{ id: 'p' }] }) },
40
+ model: { list: async () => ({ data: [{ id: 'm', providerID: 'p' }] }) },
41
+ skill: { list: async () => ({ data: [] }) },
42
+ session: { create: creates, prompt: prompts, active: async () => ({}) },
43
+ };
44
+ const roots = [];
45
+ const refresh = async () => {
46
+ const current = await settings.readSettingsFromDiskStrict();
47
+ roots.splice(0, roots.length, ...(current.projects || []).map((project) => project.path));
48
+ };
49
+ let round = 0;
50
+ external.complete = async ({ body }) => {
51
+ round++;
52
+ if (round === 1) {
53
+ expect(body.tools.some((tool) => tool.function.name === 'register_project')).toBe(false);
54
+ expect(body.tools.some((tool) => tool.function.name === 'websearch')).toBe(false);
55
+ return call('load_tools', { domain: 'opencode.web' });
56
+ }
57
+ if (round === 2) {
58
+ expect(body.tools.some((tool) => tool.function.name === 'websearch')).toBe(true);
59
+ return call('load_tools', { domain: 'yuri.projects' });
60
+ }
61
+ if (round === 3) {
62
+ expect(body.tools.some((tool) => tool.function.name === 'register_project')).toBe(true);
63
+ return call('register_project', { path: workspace, label: 'Cloned App' });
64
+ }
65
+ if (round === 4) {
66
+ expect(body.messages.find((message) => message.name === 'register_project')?.content).toContain(canonical);
67
+ return call('assign_session', { projectPath: canonical, prompt: 'hello' });
68
+ }
69
+ return { text: '已在这个项目里创建会话并发送 hello。' };
70
+ };
71
+ const app = express(); app.use(express.json());
72
+ const runtime = registerAssistantRoutes(app, {
73
+ dbPath: path.join(directory, 'assistants.sqlite'), yuriDataDir: directory,
74
+ getAllowedRoots: () => roots, refreshAllowedRoots: refresh,
75
+ listProjects: async () => (await settings.readSettingsFromDiskStrict()).projects || [],
76
+ registerProject: async (input) => { const result = await registry.register(input); await refresh(); return result; },
77
+ buildOpenCodeUrl: (pathname) => `http://upstream.invalid${pathname}`, getOpenCodeAuthHeaders: () => ({}),
78
+ });
79
+ registerOpenCodeRoutes(app, { ...settings, validateDirectoryPath, formatSettingsResponse: (value) => value });
80
+ registerConversationRoutes(app, { buildOpenCodeUrl: (pathname) => `http://upstream.invalid${pathname}`, getOpenCodeAuthHeaders: () => ({}) });
81
+ const server = http.createServer(app);
82
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
83
+ const base = `http://127.0.0.1:${server.address().port}`;
84
+ const request = async (route, body) => {
85
+ const response = await fetch(`${base}${route}`, { method: body ? 'POST' : 'GET', headers: { 'content-type': 'application/json' }, ...(body ? { body: JSON.stringify(body) } : {}) });
86
+ expect(response.ok).toBe(true);
87
+ return response.json();
88
+ };
89
+ try {
90
+ const assistant = await request('/api/yuri/assistants', { name: 'Test Bot', providerID: 'p', modelID: 'm' });
91
+ const admitted = await request(`/api/yuri/assistants/${assistant.id}/messages`, { messageID: 'create-project-chat', text: `Add ${workspace} and open a session saying hello` });
92
+ expect(admitted.admitted).toBe(true);
93
+ expect((await runtime.service.whenContactTurnSettled(admitted.messageID)).status).toBe('complete');
94
+ expect(creates).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ location: { directory: canonical } }));
95
+ expect(prompts).toHaveBeenCalledWith(expect.objectContaining({ sessionID: 'ses_hello', text: 'hello' }));
96
+ expect(prompts.mock.calls[0][0]).not.toHaveProperty('skills');
97
+ expect(prompts.mock.calls[0][0]).not.toHaveProperty('tools');
98
+ expect(JSON.stringify(creates.mock.calls[0][0])).not.toContain('load_tools');
99
+ expect(JSON.stringify(creates.mock.calls[0][0])).not.toContain('opencode.web');
100
+ const page = await request(`/api/yuri/assistants/${assistant.id}/contact/messages`);
101
+ expect(page.messages.flatMap((message) => message.parts)).toContainEqual(expect.objectContaining({ type: 'card', cardType: 'session', sessionID: 'ses_hello', directory: canonical }));
102
+ const persisted = await settings.readSettingsFromDiskStrict();
103
+ expect(persisted.projects).toHaveLength(1);
104
+ expect(persisted.projects[0]).toMatchObject({ path: canonical, label: 'Cloned App' });
105
+ // The pre-existing UI API uses the same registration owner and identity.
106
+ const ui = await request('/api/opencode/directory', { path: workspace });
107
+ expect(ui.settings.projects).toHaveLength(1);
108
+ expect(ui.path).toBe(canonical);
109
+ expect(ui.settings.activeProjectId).toBe(persisted.projects[0].id);
110
+ // Ordinary Session admission after a contact load still receives only its own prompt.
111
+ const modelRounds = round;
112
+ const session = await request('/api/yuri/conversations', {
113
+ input: { type: 'prompt' }, directory: canonical, messageID: 'ordinary-session',
114
+ model: { providerID: 'p', modelID: 'm' }, parts: [{ type: 'text', text: 'ordinary hello' }],
115
+ });
116
+ expect(session.ok).toBe(true);
117
+ expect(prompts.mock.calls.at(-1)[0]).toEqual({ sessionID: 'ses_hello', id: 'ordinary-session', text: 'ordinary hello', delivery: 'steer' });
118
+ expect(round).toBe(modelRounds);
119
+ } finally {
120
+ runtime.close(); server.closeAllConnections();
121
+ await new Promise((resolve) => server.close(resolve));
122
+ external.complete = null; external.client = null;
123
+ await fs.rm(directory, { recursive: true, force: true });
124
+ }
125
+ });
126
+ });
@@ -0,0 +1,42 @@
1
+ export function createYuriContactToolGroups(tools) {
2
+ return [
3
+ { id: 'yuri.projects', description: 'Register an existing workspace before opening a coding session.', names: ['register_project'] },
4
+ { id: 'yuri.assistants', description: 'Create a Bot or change its avatar.', names: ['create_assistant', 'update_avatar'] },
5
+ { id: 'yuri.tasks', description: 'Create or update scheduled tasks (including pause/resume).', names: ['schedule_task', 'update_scheduled_task'] },
6
+ ].map(({ id, description, names }) => ({ id, description, tools: tools.filter((tool) => names.includes(tool.name)) }))
7
+ .filter((group) => group.tools.length > 0);
8
+ }
9
+
10
+ const result = (details, isError = false) => ({
11
+ content: [{ type: 'text', text: JSON.stringify(details) }], details, isError, terminate: false,
12
+ });
13
+
14
+ /** Assistant-local business capability; never registered with OpenCode or its skills catalog. */
15
+ export function createYuriContactTools({ registerProject } = {}) {
16
+ if (typeof registerProject !== 'function') return [];
17
+ return [{
18
+ name: 'register_project', label: 'Register project',
19
+ description: 'Register an existing user-requested absolute Host directory as a Yuri project, then call assign_session with the returned project.path in the same turn. Does not clone/create files or switch an existing active project. Never register a guessed directory or assistant-workspaces.',
20
+ parameters: { type: 'object', additionalProperties: false, required: ['path'], properties: {
21
+ path: { type: 'string', minLength: 1, maxLength: 4096, description: 'Existing absolute Host directory resolved from the user request or filesystem discovery.' },
22
+ label: { type: 'string', minLength: 1, maxLength: 80, description: 'Optional project display name.' },
23
+ } },
24
+ execute: async (_id, params, signal) => {
25
+ signal?.throwIfAborted();
26
+ if (!params || Array.isArray(params) || typeof params !== 'object'
27
+ || Object.keys(params).some((key) => !['path', 'label'].includes(key))
28
+ || typeof params.path !== 'string' || !params.path.trim() || params.path.length > 4096
29
+ || (params.label !== undefined && (typeof params.label !== 'string' || !params.label.trim() || params.label.length > 80))) {
30
+ return result({ error: 'validation_error' }, true);
31
+ }
32
+ try {
33
+ const { project, created } = await registerProject(params, signal);
34
+ return result({ project: { id: project.id, path: project.path, ...(project.label ? { label: project.label } : {}) }, created });
35
+ } catch (error) {
36
+ signal?.throwIfAborted();
37
+ const code = ['validation_error', 'workspace_forbidden', 'project_unavailable'].includes(error?.code) ? error.code : 'yuri_operation_failed';
38
+ return result({ error: code, message: 'Registration failed. Check the project catalog before retrying; do not claim success.' }, true);
39
+ }
40
+ },
41
+ }];
42
+ }
@@ -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 { createProjectIdFromPath } from '../projects/project-id.js';
1
+ import { createProjectRegistry } from '../projects/registry.js';
2
2
  import { projectBootstrapSettingsResponse } from './settings-helpers.js';
3
3
  import {
4
4
  evaluateOpenCodeHealthBody,
@@ -33,7 +33,6 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
33
33
  readSettingsFromDisk,
34
34
  readSettingsFromDiskMigrated,
35
35
  persistSettings,
36
- sanitizeProjects,
37
36
  validateDirectoryPath,
38
37
  resolveProjectDirectory,
39
38
  getProviderSources,
@@ -801,43 +800,16 @@ export const registerOpenCodeRoutes = (app, dependencies) => {
801
800
  return res.status(400).json({ error: 'Path is required' });
802
801
  }
803
802
 
804
- const validated = await validateDirectoryPath(requestedPath);
805
- if (!validated.ok) {
806
- return res.status(400).json({ error: validated.error });
807
- }
808
-
809
- const resolvedPath = validated.directory;
810
- const currentSettings = await readSettingsFromDisk();
811
- const existingProjects = sanitizeProjects(currentSettings.projects) || [];
812
- const existing = existingProjects.find((project) => project.path === resolvedPath) || null;
813
-
814
- const nextProjects = existing
815
- ? existingProjects
816
- : [
817
- ...existingProjects,
818
- {
819
- id: createProjectIdFromPath(resolvedPath),
820
- path: resolvedPath,
821
- addedAt: Date.now(),
822
- lastOpenedAt: Date.now(),
823
- },
824
- ];
825
-
826
- const activeProjectId = existing ? existing.id : nextProjects[nextProjects.length - 1].id;
827
-
828
- const updated = await persistSettings({
829
- projects: nextProjects,
830
- activeProjectId,
831
- lastDirectory: resolvedPath,
832
- });
803
+ const { project, settings: updated } = await createProjectRegistry({ persistSettings, validateDirectoryPath }).register({ path: requestedPath, activate: true });
833
804
 
834
805
  return res.json({
835
806
  success: true,
836
807
  restarted: false,
837
- path: resolvedPath,
808
+ path: project.path,
838
809
  settings: updated,
839
810
  });
840
811
  } catch (error) {
812
+ if (error?.code === 'validation_error') return res.status(400).json({ error: error.message });
841
813
  console.error('Failed to update OpenCode working directory:', error);
842
814
  return res.status(500).json({ error: error.message || 'Failed to update working directory' });
843
815
  }
@@ -851,10 +851,15 @@ export const createSettingsRuntime = (deps) => {
851
851
  };
852
852
 
853
853
  const persistSettings = async (changes) => runPersistedWrite(async () => {
854
+ const updateCurrent = typeof changes === 'function';
855
+ const current = updateCurrent
856
+ ? await readSettingsFromDiskStrict()
857
+ : await readSettingsFromDisk();
858
+ if (updateCurrent && Array.isArray(current)) throw new Error('Settings file is malformed (array payload)');
859
+ if (typeof changes === 'function') changes = await changes(current);
854
860
  // Log field names only — changes can carry credentials (UI password,
855
861
  // client tokens) that must never reach the log file.
856
862
  console.log('[persistSettings] Updating fields:', Object.keys(changes || {}).join(', ') || '(none)');
857
- const current = await readSettingsFromDisk();
858
863
  const sanitized = sanitizeSettingsUpdate(changes);
859
864
  let next = mergePersistedSettings(current, sanitized);
860
865
 
@@ -882,7 +887,7 @@ export const createSettingsRuntime = (deps) => {
882
887
  // Validating project paths hits the filesystem for every entry, so only
883
888
  // do it when the incoming update actually touches the projects list —
884
889
  // not on every theme/window-state/etc. save.
885
- if (Object.prototype.hasOwnProperty.call(sanitized, 'projects') && Array.isArray(next.projects)) {
890
+ if (!updateCurrent && Object.prototype.hasOwnProperty.call(sanitized, 'projects') && Array.isArray(next.projects)) {
886
891
  const validated = await validateProjectEntries(next.projects);
887
892
  next = { ...next, projects: validated };
888
893
  }
@@ -0,0 +1,29 @@
1
+ # Projects
2
+
3
+ `registry.js` owns registering existing directories. It reuses `validateDirectoryPath`, deterministic
4
+ path-derived IDs and the settings runtime's serialized persistence. The existing
5
+ `POST /api/opencode/directory` API and assistant business tools share this owner.
6
+ The HTTP API still selects the active directory; assistant registration does not
7
+ change an existing active selection. The first registered project becomes active
8
+ through the existing settings invariant.
9
+
10
+ Registration is not filesystem creation or cloning. Those operations must finish
11
+ before registration. Paths are validated and canonicalized before deduplication.
12
+ Concurrent registrations apply against the latest settings under the existing
13
+ Host/Electron exclusive write lock, preserving unrelated settings and projects
14
+ (including temporarily unavailable directories). Existing IDs, ordering, custom
15
+ labels and metadata survive repeat registration. It does not add project label-edit
16
+ or removal APIs, and never deletes files, sessions or task storage.
17
+
18
+ Trusted registry operations use the settings owner's functional update form.
19
+ It performs a strict read inside the same persistence lock and follows the normal
20
+ normalization, migration, atomic write and project-order SSE notification paths.
21
+ Unlike full-list UI replacement, this form does not sweep other projects for
22
+ missing directories: callers validate the affected resource. Corrupt reads and
23
+ failed writes are errors, not empty state or successful registration. No new
24
+ database, settings file, HTTP mutation surface or client sync protocol is added.
25
+
26
+ `registry.test.js` covers canonical alias deduplication, concurrent append/settings
27
+ writes, persistence, offline-project retention, corrupt
28
+ reads and failed-write preservation. Assistant HTTP integration is covered in
29
+ `../assistants/yuri-project.http.test.js`.
@@ -0,0 +1,36 @@
1
+ import { createProjectIdFromPath } from './project-id.js';
2
+
3
+ const fail = (code, message) => { throw Object.assign(new Error(message), { code }); };
4
+ const string = (value, field, max = 4096) => {
5
+ if (typeof value !== 'string' || !value.trim() || value.trim().length > max) {
6
+ fail('validation_error', `${field} must be a nonempty string (maximum ${max} characters).`);
7
+ }
8
+ return value.trim();
9
+ };
10
+
11
+ // Registry mutations share the settings owner's exclusive read/modify/write path.
12
+ export const createProjectRegistry = ({ persistSettings, validateDirectoryPath }) => {
13
+ const register = async (input = {}) => {
14
+ const validated = await validateDirectoryPath(string(input.path, 'path'));
15
+ if (!validated.ok) fail('validation_error', validated.error || 'Project directory is unavailable.');
16
+ const directory = validated.directory;
17
+ const label = input.label === undefined ? undefined : string(input.label, 'label', 80);
18
+ let project;
19
+ let created = false;
20
+ const settings = await persistSettings((current) => {
21
+ const projects = Array.isArray(current.projects) ? current.projects : [];
22
+ const existing = projects.find((entry) => entry.path === directory);
23
+ created = !existing;
24
+ project = existing || { id: createProjectIdFromPath(directory), path: directory, addedAt: Date.now(), lastOpenedAt: Date.now(), ...(label ? { label } : {}) };
25
+ return {
26
+ projects: created ? [...projects, project] : projects,
27
+ ...(input.activate === true ? { activeProjectId: project.id, lastDirectory: directory } : {}),
28
+ };
29
+ });
30
+ const saved = settings.projects?.find((entry) => entry.id === project.id);
31
+ if (!saved) fail('project_unavailable', 'The directory disappeared before the project could be registered. No session was opened.');
32
+ return { project: saved, created, settings };
33
+ };
34
+
35
+ return { register };
36
+ };
@@ -0,0 +1,107 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs/promises';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { describe, expect, it, vi } from 'vitest';
6
+ import { createSettingsRuntime } from '../opencode/settings-runtime.js';
7
+ import { createSettingsNormalizationRuntime } from '../opencode/settings-normalization-runtime.js';
8
+ import { createProjectDirectoryRuntime } from '../opencode/project-directory-runtime.js';
9
+ import { createProjectRegistry } from './registry.js';
10
+
11
+ const setup = async () => {
12
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-registry-'));
13
+ const settingsPath = path.join(directory, 'settings.json');
14
+ const tips = vi.fn();
15
+ let failWrites = false;
16
+ const normalization = createSettingsNormalizationRuntime({ os, path, processLike: process });
17
+ const runtime = createSettingsRuntime({
18
+ fsPromises: { ...fs, rename: (...args) => failWrites ? Promise.reject(new Error('write failed')) : fs.rename(...args) },
19
+ path, crypto, SETTINGS_FILE_PATH: settingsPath, ...normalization,
20
+ sanitizeSettingsUpdate: (patch) => patch,
21
+ mergePersistedSettings: (current, patch) => ({ ...current, ...patch }),
22
+ formatSettingsResponse: (settings) => settings,
23
+ resolveDirectoryCandidate: (value) => value,
24
+ onProjectOrderChanged: tips,
25
+ });
26
+ const { validateDirectoryPath } = createProjectDirectoryRuntime({
27
+ fsPromises: fs, path, normalizeDirectoryPath: normalization.normalizeDirectoryPath,
28
+ });
29
+ const registry = createProjectRegistry({ persistSettings: runtime.persistSettings, validateDirectoryPath });
30
+ const workspace = path.join(directory, 'workspace');
31
+ await fs.mkdir(workspace);
32
+ return { directory, settingsPath, workspace, registry, runtime, tips,
33
+ failWrites: () => { failWrites = true; },
34
+ cleanup: () => fs.rm(directory, { recursive: true, force: true }),
35
+ };
36
+ };
37
+
38
+ describe('shared project registry owner', () => {
39
+ it('registers and deduplicates canonical aliases without deleting files', async () => {
40
+ const app = await setup();
41
+ try {
42
+ const first = await app.registry.register({ path: app.workspace, label: 'App' });
43
+ const alias = path.join(app.directory, 'alias');
44
+ await fs.symlink(app.workspace, alias);
45
+ const second = await app.registry.register({ path: alias });
46
+ expect(first.created).toBe(true);
47
+ expect(second).toMatchObject({ created: false, project: { id: first.project.id, label: 'App' } });
48
+ expect((await app.runtime.readSettingsFromDiskStrict()).projects).toHaveLength(1);
49
+ expect(app.tips).toHaveBeenCalledTimes(1);
50
+ expect((await fs.stat(app.workspace)).isDirectory()).toBe(true);
51
+ } finally { await app.cleanup(); }
52
+ });
53
+
54
+ it('serializes concurrent registrations against the latest settings and preserves unrelated/offline projects', async () => {
55
+ const app = await setup();
56
+ try {
57
+ const other = path.join(app.directory, 'other');
58
+ await fs.mkdir(other);
59
+ await fs.writeFile(app.settingsPath, JSON.stringify({
60
+ projects: [{ id: 'offline', path: path.join(app.directory, 'offline'), addedAt: 1, lastOpenedAt: 1 }],
61
+ theme: 'saved', activeProjectId: 'offline', lastDirectory: 'keep-this-selection',
62
+ }));
63
+ const results = await Promise.all([
64
+ app.registry.register({ path: app.workspace }), app.registry.register({ path: other }),
65
+ app.runtime.persistSettings({ theme: 'new-theme' }),
66
+ ]);
67
+ const saved = await app.runtime.readSettingsFromDiskStrict();
68
+ expect(saved.projects.map((project) => project.path)).toEqual(expect.arrayContaining([path.join(app.directory, 'offline'), await fs.realpath(app.workspace), await fs.realpath(other)]));
69
+ expect(saved.projects).toHaveLength(3);
70
+ expect(saved.projects[0].path).toBe(path.join(app.directory, 'offline'));
71
+ expect(saved.theme).toBe('new-theme');
72
+ expect(saved.activeProjectId).not.toBe(results[0].project.id);
73
+ expect(saved.lastDirectory).toBe('keep-this-selection');
74
+ const restarted = createProjectRegistry({ persistSettings: app.runtime.persistSettings,
75
+ validateDirectoryPath: async () => ({ ok: true, directory: await fs.realpath(app.workspace) }) });
76
+ expect((await restarted.register({ path: app.workspace })).created).toBe(false);
77
+ } finally { await app.cleanup(); }
78
+ });
79
+
80
+ it('rejects missing/file directories without a write or revision tip', async () => {
81
+ const app = await setup();
82
+ try {
83
+ await fs.writeFile(app.settingsPath, JSON.stringify({ theme: 'saved' }));
84
+ const before = await fs.readFile(app.settingsPath, 'utf8');
85
+ await expect(app.registry.register({ path: path.join(app.directory, 'missing') })).rejects.toMatchObject({ code: 'validation_error' });
86
+ await expect(app.registry.register({ path: app.settingsPath })).rejects.toMatchObject({ code: 'validation_error' });
87
+ expect(await fs.readFile(app.settingsPath, 'utf8')).toBe(before);
88
+ expect(app.tips).not.toHaveBeenCalled();
89
+ } finally { await app.cleanup(); }
90
+ });
91
+
92
+ it('preserves the previous committed settings on failed writes, and never overwrites corrupt settings', async () => {
93
+ const app = await setup();
94
+ try {
95
+ await fs.writeFile(app.settingsPath, JSON.stringify({ theme: 'saved' }));
96
+ app.failWrites();
97
+ await expect(app.registry.register({ path: app.workspace })).rejects.toThrow('write failed');
98
+ expect(await app.runtime.readSettingsFromDiskStrict()).toEqual({ theme: 'saved' });
99
+ expect(app.tips).not.toHaveBeenCalled();
100
+ for (const corrupt of ['{broken', '[]', 'null']) {
101
+ await fs.writeFile(app.settingsPath, corrupt);
102
+ await expect(app.registry.register({ path: app.workspace })).rejects.toThrow();
103
+ expect(await fs.readFile(app.settingsPath, 'utf8')).toBe(corrupt);
104
+ }
105
+ } finally { await app.cleanup(); }
106
+ });
107
+ });