@yuriai/web 0.2.39 → 0.2.40-beta.4
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-BPihSrmD.js → AgentAvatar-BmT_6apW.js} +1 -1
- package/dist/assets/{AssistantConversationSurface-CjY5PL5-.js → AssistantConversationSurface-B-D-mLgs.js} +3 -3
- package/dist/assets/{AssistantConversationSurface-B60CYrok.css → AssistantConversationSurface-n9w_Av0k.css} +1 -1
- package/dist/assets/{AssistantUnreadBadge-Cqm9s7su.js → AssistantUnreadBadge-C34eOGCL.js} +1 -1
- package/dist/assets/{AssistantView-DQYpQy2m.js → AssistantView-0nXkM9VG.js} +1 -1
- package/dist/assets/{DiagramView-B0BtdArn.js → DiagramView-BU6jWxKJ.js} +1 -1
- package/dist/assets/{FadeInOnReveal-tft8IuZn.js → FadeInOnReveal-CCVdl9Vt.js} +1 -1
- package/dist/assets/{GuiPluginPage-DbRaxEMz.js → GuiPluginPage-BMt5AMqg.js} +1 -1
- package/dist/assets/{GuiPluginSurface-slfiNhjw.js → GuiPluginSurface-kxAcgmf1.js} +1 -1
- package/dist/assets/{GuiPluginWindow-CncIyWAp.js → GuiPluginWindow-BVvzrnp1.js} +1 -1
- package/dist/assets/{Icon-CGEMyGrr.js → Icon-B5nBc6dO.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-DPV84_Pj.js → ImageLoadingPlaceholder-Bv5mmf2U.js} +1 -1
- package/dist/assets/{LoadingImage-C54k9D10.js → LoadingImage-BzBw_1lI.js} +1 -1
- package/dist/assets/MarkdownRenderer-CoMohPOZ.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-QZCYT1B1.js → MarkdownRendererImpl-DoZW1UKH.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-CH0XdDB8.js → MarkstreamRendererImpl-B3zd5x2O.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-doWZ3QnX.js → MobileDetailNavigation-bEZ_NA03.js} +1 -1
- package/dist/assets/{MobileResizableSheet-DmBfNDpy.js → MobileResizableSheet-D5PcZMuI.js} +1 -1
- package/dist/assets/{MobileShareBridge-CCRDZ5at.js → MobileShareBridge-Cjukxazk.js} +1 -1
- package/dist/assets/{MobileTabPageHeader-RIJ0Tv9a.js → MobileTabPageHeader-Da1maXx-.js} +1 -1
- package/dist/assets/{MultiRunWindow-FISLdCRZ.js → MultiRunWindow-rMqP99ID.js} +1 -1
- package/dist/assets/{OnboardingScreen-D4OnZuHF.js → OnboardingScreen-CZhqHzAj.js} +1 -1
- package/dist/assets/{OverlayScrollbar-B5tpZ8bV.js → OverlayScrollbar-Byx2H3pc.js} +1 -1
- package/dist/assets/{SettingsView-B9qVD3Y-.js → SettingsView-7Bea2DvF.js} +1 -1
- package/dist/assets/{SettingsWindow-DUlTQkFw.js → SettingsWindow-U-RDDOS7.js} +1 -1
- package/dist/assets/{SetupTourDialog-Cfc1h-8p.js → SetupTourDialog-CKec5tUy.js} +1 -1
- package/dist/assets/{TerminalView-D0nGaGQc.js → TerminalView-CS1oSAuY.js} +1 -1
- package/dist/assets/{ToolOutputDialog-RBSVUj7J.js → ToolOutputDialog-BWhrFvvI.js} +1 -1
- package/dist/assets/{VoiceSettings-B6L3hyGL.js → VoiceSettings-7aFmJq9Z.js} +1 -1
- package/dist/assets/{appThemeRegistry-CvThoPJW.js → appThemeRegistry-LyWTE-mT.js} +1 -1
- package/dist/assets/{capgoAdapter-Bj8RLSP5.js → capgoAdapter-B5NImlKh.js} +1 -1
- package/dist/assets/{checkbox-CnTrXcOT.js → checkbox-Bdj4n5cI.js} +1 -1
- package/dist/assets/{collapsible-Brxkw3Ad.js → collapsible-D1JZOgJZ.js} +1 -1
- package/dist/assets/{context-menu-V40RXF6h.js → context-menu-DDX0ZFhc.js} +1 -1
- package/dist/assets/{diagram-DmtDqCEH.js → diagram-C72TQWfh.js} +1 -1
- package/dist/assets/{dialog-wNy9dklb.js → dialog-CIKJalI5.js} +1 -1
- package/dist/assets/{fileMentionTouchSelection-B35c9M1S.js → fileMentionTouchSelection-tnd9RDDh.js} +1 -1
- package/dist/assets/{gitApi-B6T5guw-.js → gitApi-BI8OG_ts.js} +1 -1
- package/dist/assets/{input-DKLf8ixL.js → input-gVHSS0EB.js} +1 -1
- package/dist/assets/{insertionBoundaries-BT7QMdXR.js → insertionBoundaries-B-yZI6iY.js} +1 -1
- package/dist/assets/{main-wQpnkA8l.js → main-BfAN93rT.js} +4 -4
- package/dist/assets/{main-Bto3lVGC.js → main-DYWwmI_W.js} +2 -2
- package/dist/assets/{markdownHeightCache-CDLGxKMx.js → markdownHeightCache-B-FoaQ1U.js} +1 -1
- package/dist/assets/{mcpQueries-W4pdjGH6.js → mcpQueries-CehWHIB1.js} +1 -1
- package/dist/assets/{miniChat-5-Hv0t6L.js → miniChat-BlkcLQBr.js} +2 -2
- package/dist/assets/{mobile-CIfJVgvD.js → mobile-I3Xe5NtO.js} +2 -2
- package/dist/assets/{mobileBackNavigation-DEYDDBvo.js → mobileBackNavigation-BFUH-c-G.js} +1 -1
- package/dist/assets/{mobileConnections-Ciduwjrk.js → mobileConnections-BFvtbJXX.js} +2 -2
- package/dist/assets/{multirun-DH5YM6eW.js → multirun-DdEjp77z.js} +1 -1
- package/dist/assets/{native-config-tZKBxKlJ.js → native-config-DqDXViVx.js} +1 -1
- package/dist/assets/{projectMeta-ByznasuE.js → projectMeta-BKgum5WN.js} +1 -1
- package/dist/assets/{pwa-6LwD5mEU.js → pwa-BvKUY4Hk.js} +1 -1
- package/dist/assets/{queue-abort-optimistic-BxQHPU5z.js → queue-abort-optimistic-BcbiNk8t.js} +1 -1
- package/dist/assets/{react-KWIP7CQs.js → react-DeB-Vc_L.js} +1 -1
- package/dist/assets/{readiness-aRoinILZ.js → readiness-CIlvQ-aQ.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-CZScT8zj.js → renderElectronMiniChatApp-DIjWdFHu.js} +2 -2
- package/dist/assets/{renderMobileApp-DuXuzELH.js → renderMobileApp-CE0QyOH0.js} +4 -4
- package/dist/assets/{runtimeConfig-D6tyDSf2.js → runtimeConfig-uhjQn4kK.js} +1 -1
- package/dist/assets/{runtimeEndpointReset-CTScNTQk.js → runtimeEndpointReset-DezNESKT.js} +3 -3
- package/dist/assets/{select-CM7BZ8sO.js → select-BwCKwnTH.js} +1 -1
- package/dist/assets/{sessionLookup-BU5wx0-q.js → sessionLookup-DzKZsy-W.js} +1 -1
- package/dist/assets/{sortable-tabs-strip-DucBEuLZ.js → sortable-tabs-strip-m5JQrTx4.js} +1 -1
- package/dist/assets/{speechSettingsQueries-BP-b2-GN.js → speechSettingsQueries-C5mPRWIv.js} +1 -1
- package/dist/assets/{src-CCKR0Tmd.css → src-HgtAe3Q4.css} +1 -1
- package/dist/assets/{textarea-C8G6xLAC.js → textarea-CaTDyZrS.js} +1 -1
- package/dist/assets/{tooltip-CeCFnNNR.js → tooltip-BvZzoiqg.js} +1 -1
- package/dist/assets/types-Bm8kDgSv.js +2 -0
- package/dist/assets/{useAppFontEffects-B2DfbicL.js → useAppFontEffects-C9IaiJgF.js} +5 -5
- package/dist/assets/{useDesktopWindowControlsLayout-CD1Nr6Ms.js → useDesktopWindowControlsLayout-C3M12PjJ.js} +1 -1
- package/dist/assets/{useEffectiveDirectory-DT950TGk.js → useEffectiveDirectory-Do4UqfZR.js} +1 -1
- package/dist/assets/{useMobileNavigationStore-CXnVqWpM.js → useMobileNavigationStore-InwdmuDX.js} +5 -5
- package/dist/assets/{usePluginsStore-DIah6ngo.js → usePluginsStore-BH4-CNcj.js} +1 -1
- package/dist/assets/{useStreamingTextThrottle-BrP3Yc-q.js → useStreamingTextThrottle-CeKHHK13.js} +1 -1
- package/dist/assets/{useWorkerHighlightedLines-tpb9bWVl.js → useWorkerHighlightedLines-0XahwAbS.js} +1 -1
- package/dist/index.html +6 -6
- package/dist/mini-chat.html +6 -6
- package/dist/mobile.html +2 -2
- package/package.json +1 -1
- package/server/lib/assistants/DOCUMENTATION.md +15 -3
- package/server/lib/assistants/builtin-skills.js +19 -0
- package/server/lib/assistants/builtin-skills.test.js +40 -0
- package/server/lib/assistants/harness.js +2 -0
- package/server/lib/assistants/harness.test.js +41 -1
- package/server/lib/assistants/service.test.js +3 -0
- package/server/lib/gui-customization/DOCUMENTATION.md +31 -1
- package/server/lib/gui-customization/projects-client.mjs +59 -0
- package/server/lib/gui-customization/projects.js +43 -0
- package/server/lib/gui-customization/projects.test.js +103 -0
- package/server/lib/gui-customization/remote-connections-client.mjs +2 -8
- package/server/lib/gui-customization/session-skill-command.mjs +8 -0
- package/server/lib/gui-customization/session-skill.js +15 -10
- package/server/lib/gui-customization/session-skill.test.js +21 -2
- package/server/lib/gui-customization/skill/SKILL.md +3 -1
- package/server/lib/gui-customization/skill/references/projects.md +63 -0
- package/server/lib/notifications/DOCUMENTATION.md +12 -0
- package/server/lib/notifications/runtime.js +20 -2
- package/server/lib/notifications/runtime.test.js +21 -0
- package/server/lib/notifications/session-unread-runtime.js +51 -13
- package/server/lib/notifications/session-unread.test.js +113 -1
- package/server/lib/opencode/core-routes.js +2 -1
- package/server/lib/opencode/feature-routes-runtime.js +6 -0
- package/server/lib/opencode/feature-routes-runtime.test.js +4 -0
- package/server/lib/projects/DOCUMENTATION.md +6 -3
- package/server/lib/scheduled-tasks/session-skill.js +2 -1
- package/server/lib/scheduled-tasks/session-skill.test.js +34 -1
- package/server/lib/session-index/DOCUMENTATION.md +4 -1
- package/server/lib/session-index/event-ingest.js +8 -0
- package/server/lib/session-index/event-ingest.test.js +16 -0
- package/server/lib/session-index/service.js +1 -0
- package/server/lib/session-index/service.test.js +3 -1
- package/server/lib/session-metadata/DOCUMENTATION.md +18 -1
- package/server/lib/session-title/DOCUMENTATION.md +3 -0
- package/server/lib/session-title/runtime.js +1 -0
- package/server/lib/session-title/runtime.test.js +2 -0
- package/dist/assets/MarkdownRenderer-DBZS1O3m.js +0 -2
- package/dist/assets/types-Zl9uYRiX.js +0 -2
|
@@ -0,0 +1,103 @@
|
|
|
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 express from 'express';
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import { createProjectRegistry } from '../projects/registry.js';
|
|
8
|
+
import { createProjectIdFromPath } from '../projects/project-id.js';
|
|
9
|
+
import { createSettingsRuntime } from '../opencode/settings-runtime.js';
|
|
10
|
+
import { createSettingsNormalizationRuntime } from '../opencode/settings-normalization-runtime.js';
|
|
11
|
+
import { createProjectDirectoryRuntime } from '../opencode/project-directory-runtime.js';
|
|
12
|
+
import { registerProjectsSkill, PROJECTS_SKILL_PATH } from './projects.js';
|
|
13
|
+
|
|
14
|
+
describe('session project registration API', () => {
|
|
15
|
+
let root, workspace, settingsPath, runtime, server, origin, getSession, binding, registerProject, shared, failWrites, tips;
|
|
16
|
+
const auth = { Authorization: `Basic ${Buffer.from('opencode:fixture').toString('base64')}` };
|
|
17
|
+
beforeEach(async () => {
|
|
18
|
+
root = await fs.mkdtemp(path.join(os.tmpdir(), 'project-skill-'));
|
|
19
|
+
workspace = path.join(root, '项目 & # 100%');
|
|
20
|
+
await fs.mkdir(workspace);
|
|
21
|
+
settingsPath = path.join(root, 'settings.json');
|
|
22
|
+
const normalization = createSettingsNormalizationRuntime({ os, path, processLike: process });
|
|
23
|
+
tips = vi.fn(); failWrites = false; shared = true;
|
|
24
|
+
runtime = createSettingsRuntime({ fsPromises: { ...fs, rename: (...args) => failWrites ? Promise.reject(new Error('private-write-error')) : fs.rename(...args) },
|
|
25
|
+
path, crypto, SETTINGS_FILE_PATH: settingsPath, ...normalization,
|
|
26
|
+
sanitizeSettingsUpdate: (patch) => patch, mergePersistedSettings: (current, patch) => ({ ...current, ...patch }),
|
|
27
|
+
formatSettingsResponse: (value) => value, resolveDirectoryCandidate: (value) => value, onProjectOrderChanged: tips,
|
|
28
|
+
});
|
|
29
|
+
const { validateDirectoryPath } = createProjectDirectoryRuntime({ fsPromises: fs, path, normalizeDirectoryPath: normalization.normalizeDirectoryPath });
|
|
30
|
+
const registry = createProjectRegistry({ persistSettings: runtime.persistSettings, validateDirectoryPath });
|
|
31
|
+
registerProject = vi.fn((input) => registry.register(input));
|
|
32
|
+
getSession = vi.fn(async () => ({ metadata: { yuri: { scheduledTaskSkill: { hostOrigin: binding } } } }));
|
|
33
|
+
const app = express();
|
|
34
|
+
registerProjectsSkill(app, { express, getIsSharedOpenCodeService: () => shared, getOpenCodeAuthHeaders: () => auth,
|
|
35
|
+
createClient: () => ({ session: { get: getSession } }), registerProject, readSettingsFromDiskStrict: runtime.readSettingsFromDiskStrict,
|
|
36
|
+
sanitizeProjects: normalization.sanitizeProjects,
|
|
37
|
+
});
|
|
38
|
+
server = await new Promise((resolve) => { const s = app.listen(0, '127.0.0.1', () => resolve(s)); });
|
|
39
|
+
origin = `http://127.0.0.1:${server.address().port}`; binding = origin;
|
|
40
|
+
});
|
|
41
|
+
afterEach(async () => { await new Promise((resolve) => server.close(resolve)); await fs.rm(root, { recursive: true, force: true }); });
|
|
42
|
+
const request = (operation, input = {}, headers = auth) => fetch(`${origin}${PROJECTS_SKILL_PATH}`, { method: 'POST',
|
|
43
|
+
headers: { 'content-type': 'application/json', ...headers }, body: JSON.stringify({ sessionID: 'ses_one', operation, input }) });
|
|
44
|
+
|
|
45
|
+
it('confirms persisted registration, deduplicates canonical paths and preserves existing selection/settings', async () => {
|
|
46
|
+
const oldPath = path.join(root, 'offline');
|
|
47
|
+
const oldId = createProjectIdFromPath(oldPath);
|
|
48
|
+
await fs.writeFile(settingsPath, JSON.stringify({ secret: 'private-settings', projects: [{ id: oldId, path: oldPath, label: 'Old' }], activeProjectId: oldId }));
|
|
49
|
+
const response = await request('add', { path: workspace, label: 'App' });
|
|
50
|
+
expect(response.status).toBe(200);
|
|
51
|
+
expect(response.headers.get('cache-control')).toBe('no-store');
|
|
52
|
+
const added = await response.json();
|
|
53
|
+
expect(added).toEqual({ created: true, project: { id: expect.any(String), path: await fs.realpath(workspace), label: 'App' } });
|
|
54
|
+
const alias = path.join(root, 'alias'); await fs.symlink(workspace, alias);
|
|
55
|
+
expect(await (await request('add', { path: alias, label: 'Do not rename' })).json()).toEqual({ ...added, created: false });
|
|
56
|
+
const persisted = await runtime.readSettingsFromDiskStrict();
|
|
57
|
+
expect(persisted.projects).toHaveLength(2);
|
|
58
|
+
expect(persisted.activeProjectId).toBe(oldId);
|
|
59
|
+
expect(persisted.secret).toBe('private-settings');
|
|
60
|
+
expect(tips).toHaveBeenCalledTimes(1);
|
|
61
|
+
const listed = await (await request('list')).json();
|
|
62
|
+
expect(listed.projects).toContainEqual(added.project);
|
|
63
|
+
expect(JSON.stringify({ added, listed })).not.toContain('private-settings');
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('rejects invalid input and nonexistent/file paths without changing saved state', async () => {
|
|
67
|
+
await fs.writeFile(settingsPath, JSON.stringify({ projects: [], secret: 'saved' }));
|
|
68
|
+
const before = await fs.readFile(settingsPath, 'utf8');
|
|
69
|
+
for (const input of [{}, [], null, { path: 'relative' }, { path: workspace, activate: true }, { path: workspace, label: '' },
|
|
70
|
+
{ path: workspace, label: 'x'.repeat(81) }, { path: workspace + '\u0000' }, { path: path.join(root, 'missing') }, { path: settingsPath }]) {
|
|
71
|
+
expect((await request('add', input)).status).toBe(400);
|
|
72
|
+
}
|
|
73
|
+
expect((await request('remove', { path: workspace })).status).toBe(400);
|
|
74
|
+
expect((await request('list', { path: workspace })).status).toBe(400);
|
|
75
|
+
expect(await fs.readFile(settingsPath, 'utf8')).toBe(before);
|
|
76
|
+
expect(tips).not.toHaveBeenCalled();
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it('requires service authentication, shared ownership and the admitted Host before registration', async () => {
|
|
80
|
+
for (const headers of [{}, { Authorization: 'Bearer browser' }, { ...auth, Origin: origin }]) expect((await request('add', { path: workspace }, headers)).status).toBe(403);
|
|
81
|
+
shared = false;
|
|
82
|
+
expect((await request('describe')).status).toBe(403);
|
|
83
|
+
expect(getSession).not.toHaveBeenCalled();
|
|
84
|
+
shared = true; binding = 'http://127.0.0.1:1';
|
|
85
|
+
for (const operation of ['describe', 'list', 'add']) expect((await request(operation, operation === 'add' ? { path: workspace } : {})).status).toBe(403);
|
|
86
|
+
expect(registerProject).not.toHaveBeenCalled();
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('never reports corrupt reads or failed persistence as successful empty or added results', async () => {
|
|
90
|
+
for (const corrupt of ['{broken', '[]', 'null', '{"projects":{}}']) {
|
|
91
|
+
await fs.writeFile(settingsPath, corrupt);
|
|
92
|
+
expect((await request('list')).status).toBe(503);
|
|
93
|
+
expect(await fs.readFile(settingsPath, 'utf8')).toBe(corrupt);
|
|
94
|
+
}
|
|
95
|
+
await fs.writeFile(settingsPath, '{"projects":[]}');
|
|
96
|
+
failWrites = true;
|
|
97
|
+
const response = await request('add', { path: workspace });
|
|
98
|
+
expect(response.status).toBe(503);
|
|
99
|
+
expect(await response.text()).not.toContain('private-write-error');
|
|
100
|
+
expect(await fs.readFile(settingsPath, 'utf8')).toBe('{"projects":[]}');
|
|
101
|
+
expect(tips).not.toHaveBeenCalled();
|
|
102
|
+
});
|
|
103
|
+
});
|
|
@@ -1,15 +1,9 @@
|
|
|
1
1
|
import { readFile } from 'node:fs/promises';
|
|
2
2
|
import { realpathSync } from 'node:fs';
|
|
3
3
|
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { sessionSkillCommand } from './session-skill-command.mjs';
|
|
4
5
|
|
|
5
|
-
export const remoteConnectionsCommand =
|
|
6
|
-
const args = [executable, script, encoded, operation];
|
|
7
|
-
const quote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
8
|
-
if (process.platform !== 'win32') return `ELECTRON_RUN_AS_NODE=1 ${args.map(quote).join(' ')}`;
|
|
9
|
-
const psQuote = (value) => `'${String(value).replaceAll("'", "''")}'`;
|
|
10
|
-
const ps = `$env:ELECTRON_RUN_AS_NODE='1'; & ${args.map(psQuote).join(' ')}`;
|
|
11
|
-
return `powershell.exe -NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${Buffer.from(ps, 'utf16le').toString('base64')}`;
|
|
12
|
-
};
|
|
6
|
+
export const remoteConnectionsCommand = sessionSkillCommand;
|
|
13
7
|
|
|
14
8
|
async function main() {
|
|
15
9
|
try {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export const sessionSkillCommand = (executable, script, encoded, operation) => {
|
|
2
|
+
const args = [executable, script, encoded, operation];
|
|
3
|
+
const quote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`;
|
|
4
|
+
if (process.platform !== 'win32') return `ELECTRON_RUN_AS_NODE=1 ${args.map(quote).join(' ')}`;
|
|
5
|
+
const psQuote = (value) => `'${String(value).replaceAll("'", "''")}'`;
|
|
6
|
+
const ps = `$env:ELECTRON_RUN_AS_NODE='1'; & ${args.map(psQuote).join(' ')}`;
|
|
7
|
+
return `powershell.exe -NoProfile -NonInteractive -WindowStyle Hidden -EncodedCommand ${Buffer.from(ps, 'utf16le').toString('base64')}`;
|
|
8
|
+
};
|
|
@@ -2,16 +2,20 @@ import { readFile, mkdir, writeFile, rename, rm } from 'node:fs/promises';
|
|
|
2
2
|
import { createHash, randomUUID } from 'node:crypto';
|
|
3
3
|
import path from 'node:path';
|
|
4
4
|
import { remoteConnectionsCommand } from './remote-connections-client.mjs';
|
|
5
|
+
import { sessionSkillCommand } from './session-skill-command.mjs';
|
|
5
6
|
|
|
6
|
-
const
|
|
7
|
+
const scripts = { 'remote-connections.mjs': './remote-connections-client.mjs', 'projects.mjs': './projects-client.mjs', 'session-skill-command.mjs': './session-skill-command.mjs' };
|
|
8
|
+
const files = ['SKILL.md', 'references/projects.md', 'references/appearance.md', 'references/ui-surfaces.md', 'references/plugin-styles.md', 'references/gui-api.md', 'references/workflow.md', 'references/global-pages.md', 'references/work-status.md', 'references/icons.md', 'references/file-previews.md', 'references/preview-exports.md', 'references/remote-connections.md', ...Object.keys(scripts)];
|
|
7
9
|
|
|
8
10
|
/** Stage immutable, shipped instructions; never edit the user's global skills/config. */
|
|
9
11
|
export function createCustomizationSkillInstaller({ yuriDataDir }) {
|
|
10
12
|
const resources = new Map();
|
|
11
|
-
const prepare = (withRemote) => {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
const
|
|
13
|
+
const prepare = (withRemote, withProjects) => {
|
|
14
|
+
const key = `${withRemote}:${withProjects}`;
|
|
15
|
+
if (!resources.has(key)) resources.set(key, (async () => {
|
|
16
|
+
const stagedFiles = files.filter((name) => (name !== 'remote-connections.mjs' || withRemote)
|
|
17
|
+
&& (name !== 'projects.mjs' || withProjects) && (name !== 'session-skill-command.mjs' || withRemote || withProjects));
|
|
18
|
+
const contents = await Promise.all(stagedFiles.map((name) => readFile(new URL(scripts[name] ?? `./skill/${name}`, import.meta.url), 'utf8')));
|
|
15
19
|
const hash = createHash('sha256').update(contents.join('\0')).digest('hex').slice(0, 16);
|
|
16
20
|
const directory = path.join(yuriDataDir, 'session-skills', `yuri-customization-${hash}`);
|
|
17
21
|
await mkdir(path.join(directory, 'references'), { recursive: true, mode: 0o700 });
|
|
@@ -22,14 +26,15 @@ export function createCustomizationSkillInstaller({ yuriDataDir }) {
|
|
|
22
26
|
finally { await rm(temporary, { force: true }); }
|
|
23
27
|
}));
|
|
24
28
|
return path.join(directory, 'SKILL.md');
|
|
25
|
-
})().catch((error) => { resources.delete(
|
|
26
|
-
return resources.get(
|
|
29
|
+
})().catch((error) => { resources.delete(key); throw error; }));
|
|
30
|
+
return resources.get(key);
|
|
27
31
|
};
|
|
28
|
-
return async (client, sessionID, remoteBinding) => {
|
|
29
|
-
const file = await prepare(Boolean(remoteBinding));
|
|
32
|
+
return async (client, sessionID, { remoteBinding, projectBinding } = {}) => {
|
|
33
|
+
const file = await prepare(Boolean(remoteBinding), Boolean(projectBinding));
|
|
34
|
+
const projects = projectBinding ? ` For project registration, read references/projects.md and run the bound project API helper.\nBound project helper: ${sessionSkillCommand(process.execPath, path.join(path.dirname(file), 'projects.mjs'), Buffer.from(JSON.stringify({ ...projectBinding, sessionID })).toString('base64url'), 'describe')}\n` : ' No bound project helper is provided; project registration is unavailable through this session skill.';
|
|
30
35
|
const remote = remoteBinding ? ` For SSH setup/config sync or Relay pairing, use only this bound helper after reading references/remote-connections.md. Bound local desktop helper: ${remoteConnectionsCommand(process.execPath, path.join(path.dirname(file), 'remote-connections.mjs'), Buffer.from(JSON.stringify({ ...remoteBinding, sessionID })).toString('base64url'), 'describe')}` : ' No bound SSH/Relay command is provided: these operations are unavailable in this session. Report that limit and stop this branch; use native Settings or a new supported local desktop session. A script or another capability\'s binding does not enable it. There is no credential/filesystem fallback for this capability.';
|
|
31
36
|
await client.session.instructions.entry.put({ sessionID, key: 'yuri.customization',
|
|
32
|
-
value: `Yuri customization: for SSH connections, configuration sync, Relay pairing, appearance (themes, CSS/layout, Logo, macOS Dock), work-status widgets, global pages/tabs, custom file parsing/previews, preview exports, or GUI panels/commands/settings, read ${JSON.stringify(file)} first. Use the matching reference and apply changes only when requested.${remote}`,
|
|
37
|
+
value: `Yuri customization: for adding a directory as a project in Yuri, SSH connections, configuration sync, Relay pairing, appearance (themes, CSS/layout, Logo, macOS Dock), work-status widgets, global pages/tabs, custom file parsing/previews, preview exports, or GUI panels/commands/settings, read ${JSON.stringify(file)} first. Use the matching reference and apply changes only when requested.${projects}${remote}`,
|
|
33
38
|
});
|
|
34
39
|
};
|
|
35
40
|
}
|
|
@@ -23,7 +23,15 @@ describe('built-in customization instructions', () => {
|
|
|
23
23
|
expect(entry.value.length).toBeLessThan(1500);
|
|
24
24
|
const file = JSON.parse(entry.value.match(/read (".*?") first/)[1]);
|
|
25
25
|
expect(await fs.readFile(file, 'utf8')).toContain('name: yuri-customization');
|
|
26
|
-
for (const name of ['appearance', 'ui-surfaces', 'plugin-styles', 'gui-api', 'workflow', 'global-pages', 'work-status', 'icons', 'file-previews', 'preview-exports', 'remote-connections']) expect((await fs.readFile(path.join(path.dirname(file), 'references', `${name}.md`), 'utf8')).length).toBeGreaterThan(500);
|
|
26
|
+
for (const name of ['projects', 'appearance', 'ui-surfaces', 'plugin-styles', 'gui-api', 'workflow', 'global-pages', 'work-status', 'icons', 'file-previews', 'preview-exports', 'remote-connections']) expect((await fs.readFile(path.join(path.dirname(file), 'references', `${name}.md`), 'utf8')).length).toBeGreaterThan(500);
|
|
27
|
+
expect(entry.value).toContain('adding a directory as a project in Yuri');
|
|
28
|
+
expect(await fs.readFile(file, 'utf8')).toContain('(references/projects.md)');
|
|
29
|
+
const projects = await fs.readFile(path.join(path.dirname(file), 'references', 'projects.md'), 'utf8');
|
|
30
|
+
expect(projects).toContain('POST /api/yuri/session-skills/projects');
|
|
31
|
+
expect(projects).toContain('commands.add');
|
|
32
|
+
expect(projects).not.toContain('open \'yuri://');
|
|
33
|
+
expect(entry.value).toContain('No bound project helper is provided');
|
|
34
|
+
await expect(fs.stat(path.join(path.dirname(file), 'projects.mjs'))).rejects.toMatchObject({ code: 'ENOENT' });
|
|
27
35
|
expect(entry.value).not.toContain('Bound local desktop helper');
|
|
28
36
|
expect(entry.value).toContain('No bound SSH/Relay command is provided');
|
|
29
37
|
expect(entry.value).toContain('There is no credential/filesystem fallback');
|
|
@@ -32,12 +40,23 @@ describe('built-in customization instructions', () => {
|
|
|
32
40
|
expect(await fs.readFile(path.join(path.dirname(file), 'references', 'global-pages.md'), 'utf8')).toContain('(icons.md)');
|
|
33
41
|
expect(await fs.readFile(path.join(path.dirname(file), 'references', 'appearance.md'), 'utf8')).toContain('yuri.branding');
|
|
34
42
|
expect(put.mock.calls[1][0].value).toBe(entry.value);
|
|
35
|
-
|
|
43
|
+
const binding = { hostOrigin: 'http://127.0.0.1:4000', upstreamOrigin: 'http://127.0.0.1:4096', registrationFile: path.join(root, 'service.json') };
|
|
44
|
+
await install(client, 'ses_bound', { remoteBinding: binding });
|
|
36
45
|
const bound = put.mock.calls[2][0].value;
|
|
37
46
|
const boundFile = JSON.parse(bound.match(/read (".*?") first/)[1]);
|
|
38
47
|
expect(boundFile).not.toBe(file);
|
|
39
48
|
expect(bound).toContain('Bound local desktop helper:');
|
|
49
|
+
expect(await fs.readFile(path.join(path.dirname(boundFile), 'references', 'projects.md'), 'utf8')).toBe(projects);
|
|
40
50
|
expect(await fs.readFile(path.join(path.dirname(boundFile), 'remote-connections.mjs'), 'utf8')).toContain('/api/yuri/session-skills/remote-connections');
|
|
51
|
+
expect(await fs.readFile(path.join(path.dirname(boundFile), 'session-skill-command.mjs'), 'utf8')).toContain('sessionSkillCommand');
|
|
52
|
+
await install(client, 'ses_project', { projectBinding: binding });
|
|
53
|
+
const projectEntry = put.mock.calls[3][0].value;
|
|
54
|
+
const projectFile = JSON.parse(projectEntry.match(/read (".*?") first/)[1]);
|
|
55
|
+
expect(projectFile).not.toBe(boundFile);
|
|
56
|
+
expect(projectEntry).toContain('Bound project helper:');
|
|
57
|
+
expect(projectEntry).toContain('No bound SSH/Relay command is provided');
|
|
58
|
+
expect(await fs.readFile(path.join(path.dirname(projectFile), 'projects.mjs'), 'utf8')).toContain('/api/yuri/session-skills/projects');
|
|
59
|
+
await expect(fs.stat(path.join(path.dirname(projectFile), 'remote-connections.mjs'))).rejects.toMatchObject({ code: 'ENOENT' });
|
|
41
60
|
});
|
|
42
61
|
it('initializes managed sessions, rolls back failures, preserves adopted sessions and skips external/shared ownership', async () => {
|
|
43
62
|
const root = await directory();
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: yuri-customization
|
|
3
|
-
description:
|
|
3
|
+
description: Add existing directories as Yuri projects through its API, configure SSH connections, configuration sync and Relay pairing, or customize its GUI through plugins for appearance, pages, widgets, previews, panels and settings.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Yuri customization
|
|
7
7
|
|
|
8
|
+
For adding an existing directory to Yuri's project list, follow [projects](references/projects.md) using this session's bound project API helper. Registration is separate from creating files, cloning or opening a conversation.
|
|
9
|
+
|
|
8
10
|
For SSH setup, configuration sync or Relay pairing, first check this session's pointer for its exact bound local desktop helper command. Without that command, report unavailable and stop this branch: a script file or another capability's binding does not enable it. With the command, follow [remote connections](references/remote-connections.md). For UI changes, use the plugin workflow below. Its GUI contracts describe Yuri's supported subset of the experimental OpenCode GUI SDK 2.2.0, not every capability in the newest upstream Desktop.
|
|
9
11
|
|
|
10
12
|
## Workflow
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# Add a project
|
|
2
|
+
|
|
3
|
+
Register an existing directory through the **bound project API helper** in this
|
|
4
|
+
session's Yuri customization pointer. This is a Host capability, not a GUI plugin
|
|
5
|
+
or a desktop deep link. Registration does not create files, clone a repository,
|
|
6
|
+
open a conversation or switch an existing active project.
|
|
7
|
+
|
|
8
|
+
## Workflow
|
|
9
|
+
|
|
10
|
+
1. Resolve the user-requested directory to an absolute path on the bound Yuri
|
|
11
|
+
Host. Reuse a known directory; directory creation/cloning is a separate action
|
|
12
|
+
requiring the user's request. Paths in JSON are literal strings, not
|
|
13
|
+
percent-encoded URL parameters.
|
|
14
|
+
2. Run this session's exact `Bound project helper` command (`describe`). It returns
|
|
15
|
+
the supported operations and ready-to-run `commands.add` and `commands.list`.
|
|
16
|
+
The helper owns authentication; no credential discovery or browser login is
|
|
17
|
+
needed. If the pointer has no bound project command, report unavailable.
|
|
18
|
+
3. Run the returned `add` command unchanged, supplying JSON on stdin:
|
|
19
|
+
|
|
20
|
+
```json
|
|
21
|
+
{"path":"/workspace/my-project","label":"My project"}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`path` is required; `label` is optional (up to 80 characters). The Host validates
|
|
25
|
+
the existing directory and canonicalizes its path, then registers it through
|
|
26
|
+
Yuri's shared project registry and serialized settings writer. Repeat calls
|
|
27
|
+
for the same canonical directory reuse the existing project and preserve its
|
|
28
|
+
name, order and metadata.
|
|
29
|
+
4. A successful result is `{"project":{"id":"…","path":"…","label":"…"},"created":true}`.
|
|
30
|
+
`created:false` means it was already registered. Both confirm the saved project;
|
|
31
|
+
use the returned canonical `project.path` and report the result briefly. The
|
|
32
|
+
`label` field can be absent. No browser check is required to prove registration.
|
|
33
|
+
|
|
34
|
+
`list` returns `{"projects":[{"id":"…","path":"…","label":"…"}]}` from the
|
|
35
|
+
authoritative settings store. After an interrupted response, list or retry add
|
|
36
|
+
with the same path: registration is idempotent. A failure is unconfirmed, never an
|
|
37
|
+
empty-success result. Missing paths, files and inaccessible directories fail
|
|
38
|
+
without implicit filesystem creation. A `terminal:true` helper error stops this
|
|
39
|
+
workflow until a new supported session's bound describe succeeds.
|
|
40
|
+
|
|
41
|
+
## Interface and scope
|
|
42
|
+
|
|
43
|
+
The helper calls `POST /api/yuri/session-skills/projects` with
|
|
44
|
+
`{sessionID, operation: "describe" | "list" | "add", input}`. It uses the same
|
|
45
|
+
loopback service authentication and admitted-session Host binding as the other
|
|
46
|
+
built-in session helpers. Only affected project metadata is returned, never full
|
|
47
|
+
settings or credentials. Use the bound command rather than reconstructing auth or
|
|
48
|
+
calling the route with browser tokens.
|
|
49
|
+
|
|
50
|
+
The existing UI API `POST /api/opencode/directory` and this bridge share
|
|
51
|
+
`projects/registry.js`; the UI API additionally activates the directory. The skill
|
|
52
|
+
registers only, preserving an existing active selection (the first project may
|
|
53
|
+
become active through normal settings initialization). Existing project-order
|
|
54
|
+
notifications distribute the saved registry to connected clients.
|
|
55
|
+
|
|
56
|
+
New shared-service sessions admitted by a Yuri Host receive the helper whether
|
|
57
|
+
the UI is Electron, web or connected mobile. The directory belongs to that Host,
|
|
58
|
+
not the phone or another machine. Private/external OpenCode, standalone VS Code,
|
|
59
|
+
old sessions and contacts without a bound command gain no API access from reading
|
|
60
|
+
this file. Contacts may instead have their own granted `yuri.projects` tools;
|
|
61
|
+
those retain their own capability contract. When the helper is unavailable, use
|
|
62
|
+
the intended Host's project UI or start a supported session. Keep desktop deep
|
|
63
|
+
links for their existing navigation purpose, not as an API authorization fallback.
|
|
@@ -12,6 +12,18 @@ delivery settings and the legacy in-memory attention/presence endpoints.
|
|
|
12
12
|
success/error (including legacy idle/error) increments attention without requiring
|
|
13
13
|
an online client. Root/system visibility uses the session-index policy and an
|
|
14
14
|
authoritative session record; child sessions do not create unread badges.
|
|
15
|
+
Explicit CLI-worker ownership (`metadata.yuri.worker.parentSessionID`) uses the
|
|
16
|
+
same exclusion as the session catalog, even if native `parentID` is absent.
|
|
17
|
+
Metadata lifecycle updates remove existing hidden attention without waiting for
|
|
18
|
+
another completion. The first unread GET after Host startup reconciles persisted
|
|
19
|
+
unread rows against current session records, with at most four identity reads in
|
|
20
|
+
flight and one shared reconciliation for concurrent clients. Already-read rows
|
|
21
|
+
are skipped and successful identities are not reread on later GETs. Failed
|
|
22
|
+
identity/cleanup writes retain that row, return retryable 503, and retry only the
|
|
23
|
+
unresolved rows; independent successful cleanup stays committed. No transcript
|
|
24
|
+
scan or title/agent-name heuristic is used. Unmarked CLI roots remain ordinary
|
|
25
|
+
conversations; verified historical workers must first receive their explicit
|
|
26
|
+
ownership marker through the metadata store.
|
|
15
27
|
Token/part/message deltas do no work. Each session serializes lifecycle boundaries
|
|
16
28
|
and independently retries failed identity reads/writes with capped backoff.
|
|
17
29
|
New execution rearms terminal deduplication and clears its previous error marker;
|
|
@@ -218,7 +218,8 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
218
218
|
);
|
|
219
219
|
|
|
220
220
|
const getCachedSessionMeta = (sessionId, directory) => {
|
|
221
|
-
const
|
|
221
|
+
const requestedKey = getSessionMetaCacheKey(sessionId, directory);
|
|
222
|
+
const cacheKey = sessionMetaCache.has(requestedKey) ? requestedKey : getSessionMetaCacheKey(sessionId, undefined);
|
|
222
223
|
const entry = sessionMetaCache.get(cacheKey);
|
|
223
224
|
if (!entry) return undefined;
|
|
224
225
|
if (Date.now() - entry.at > SESSION_META_CACHE_TTL_MS) {
|
|
@@ -232,6 +233,8 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
232
233
|
const previous = getCachedSessionMeta(sessionId, directory);
|
|
233
234
|
sessionMetaCache.set(getSessionMetaCacheKey(sessionId, directory), {
|
|
234
235
|
parentID: meta.parentID !== undefined ? meta.parentID : (previous?.parentID ?? null),
|
|
236
|
+
workerParentSessionID: meta.workerParentSessionID !== undefined
|
|
237
|
+
? meta.workerParentSessionID : (previous?.workerParentSessionID ?? null),
|
|
235
238
|
smallModelPurpose: meta.smallModelPurpose !== undefined
|
|
236
239
|
? meta.smallModelPurpose
|
|
237
240
|
: (previous?.smallModelPurpose ?? null),
|
|
@@ -254,6 +257,7 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
254
257
|
? yuri.assigned.from
|
|
255
258
|
: null;
|
|
256
259
|
return {
|
|
260
|
+
workerParentSessionID: normalizeParentID(yuri?.worker?.parentSessionID),
|
|
257
261
|
smallModelPurpose: normalizeSmallModelPurpose(yuri?.smallModel?.purpose),
|
|
258
262
|
// Throwaway LLM gateway sessions (`metadata.yuri.llm.purpose`) share
|
|
259
263
|
// the same sidebar-hidden contract as small-model system sessions.
|
|
@@ -271,6 +275,19 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
271
275
|
|
|
272
276
|
const maybeCacheSessionMetaFromPayload = (payload) => {
|
|
273
277
|
if (!payload || typeof payload !== 'object') return;
|
|
278
|
+
if (payload.type === 'session.metadata.updated') {
|
|
279
|
+
const data = payload.data ?? payload.properties;
|
|
280
|
+
if (typeof data?.sessionID === 'string' && data.metadata && typeof data.metadata === 'object') {
|
|
281
|
+
const meta = metaFromYuri(data.metadata.yuri);
|
|
282
|
+
for (const key of sessionMetaCache.keys()) {
|
|
283
|
+
if (key.endsWith(`\0${data.sessionID}`)) {
|
|
284
|
+
setCachedSessionMeta(data.sessionID, key.slice(0, -data.sessionID.length - 1), meta);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
setCachedSessionMeta(data.sessionID, undefined, meta);
|
|
288
|
+
}
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
274
291
|
if (payload.type !== 'session.created' && payload.type !== 'session.updated') return;
|
|
275
292
|
const info = payload.properties?.info;
|
|
276
293
|
if (!info || typeof info !== 'object') return;
|
|
@@ -289,7 +306,7 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
289
306
|
if (!sessionId) return undefined;
|
|
290
307
|
|
|
291
308
|
const cached = getCachedSessionMeta(sessionId, directory);
|
|
292
|
-
if (cached?.complete) return cached;
|
|
309
|
+
if (cached?.complete || isHiddenFromNavSession(cached)) return cached;
|
|
293
310
|
|
|
294
311
|
try {
|
|
295
312
|
const base = buildOpenCodeUrl(`/session/${encodeURIComponent(sessionId)}`, '');
|
|
@@ -347,6 +364,7 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
347
364
|
const isHiddenFromNavSession = (meta) => {
|
|
348
365
|
if (!meta) return false;
|
|
349
366
|
if (typeof meta.parentID === 'string' && meta.parentID.length > 0) return true;
|
|
367
|
+
if (meta.workerParentSessionID) return true;
|
|
350
368
|
if (typeof meta.smallModelPurpose === 'string' && meta.smallModelPurpose.length > 0) return true;
|
|
351
369
|
if (typeof meta.llmPurpose === 'string' && meta.llmPurpose.length > 0) return true;
|
|
352
370
|
if (typeof meta.assistantID === 'string' && meta.assistantID.length > 0 && meta.assignedFrom !== 'contact') {
|
|
@@ -368,6 +368,27 @@ describe('notification trigger runtime llm system-session suppression', () => {
|
|
|
368
368
|
expectAllOutletsSilent(outlets);
|
|
369
369
|
});
|
|
370
370
|
|
|
371
|
+
it('skips completion/error outlets for explicitly linked CLI workers without native parentID', async () => {
|
|
372
|
+
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({
|
|
373
|
+
id: 'worker', title: 'Ordinary title', metadata: { yuri: { worker: { parentSessionID: 'root' } } },
|
|
374
|
+
})));
|
|
375
|
+
const outlets = createRuntime();
|
|
376
|
+
await outlets.runtime.maybeSendPushForTrigger(completionPayload('worker'));
|
|
377
|
+
await outlets.runtime.maybeSendPushForTrigger({ type: 'session.error', properties: { sessionID: 'worker', error: 'boom' } });
|
|
378
|
+
expectAllOutletsSilent(outlets);
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
it('refreshes cached CLI-worker ownership from a native metadata-only event', async () => {
|
|
382
|
+
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ id: 'worker', metadata: {} })));
|
|
383
|
+
const outlets = createRuntime();
|
|
384
|
+
await outlets.runtime.maybeSendPushForTrigger({ type: 'session.updated', properties: { info: { id: 'worker' } } });
|
|
385
|
+
await outlets.runtime.maybeSendPushForTrigger({ type: 'session.metadata.updated', data: {
|
|
386
|
+
sessionID: 'worker', metadata: { yuri: { worker: { parentSessionID: 'root' } } },
|
|
387
|
+
} });
|
|
388
|
+
await outlets.runtime.maybeSendPushForTrigger(completionPayload('worker'));
|
|
389
|
+
expectAllOutletsSilent(outlets);
|
|
390
|
+
});
|
|
391
|
+
|
|
371
392
|
it('skips ready notifications synthesized from session.idle for llm sessions', async () => {
|
|
372
393
|
vi.stubGlobal('fetch', vi.fn(async () => llmSessionResponse()));
|
|
373
394
|
const outlets = createRuntime();
|
|
@@ -1,17 +1,22 @@
|
|
|
1
1
|
import express from 'express';
|
|
2
2
|
import { isVisibleSession } from '../session-index/service.js';
|
|
3
3
|
|
|
4
|
-
/**
|
|
4
|
+
/** Lifecycle boundaries and startup repair do work; streaming deltas never read or write. */
|
|
5
5
|
export function createSessionUnreadRuntime({ store, loadSession, hub, resolveDirectory = value => value, retryMs = 1000 }) {
|
|
6
6
|
const flights = new Map();
|
|
7
7
|
const queues = new Map();
|
|
8
|
+
const unreconciled = new Set(Object.entries(store.snapshot().sessions)
|
|
9
|
+
.filter(([, row]) => row.unreadCount > 0).map(([id]) => id));
|
|
10
|
+
let reconciliation = null;
|
|
8
11
|
let disposed = false;
|
|
9
12
|
const directoryOf = session => resolveDirectory(session.location?.directory ?? session.directory ?? '');
|
|
10
13
|
const visible = session => session && !session.parentID && isVisibleSession(session);
|
|
11
14
|
const apply = async ({ payload, id, kind }) => {
|
|
12
15
|
if (kind === 'deleted') { store.remove(id); return; }
|
|
13
16
|
const session = await loadSession(id);
|
|
14
|
-
if (disposed
|
|
17
|
+
if (disposed) return;
|
|
18
|
+
if (!visible(session)) { store.remove(id); return; }
|
|
19
|
+
if (kind === 'refresh') return;
|
|
15
20
|
store.observe({ id, directory: directoryOf(session), kind, eventAt: payload.created, sequence: payload.durable?.seq });
|
|
16
21
|
};
|
|
17
22
|
const drain = (id, queue) => {
|
|
@@ -22,7 +27,16 @@ export function createSessionUnreadRuntime({ store, loadSession, hub, resolveDir
|
|
|
22
27
|
await apply(queue.items[0]);
|
|
23
28
|
queue.items.shift().resolve();
|
|
24
29
|
queue.attempt = 0;
|
|
25
|
-
} catch {
|
|
30
|
+
} catch (error) {
|
|
31
|
+
if (queue.items[0].retry === false) {
|
|
32
|
+
queue.items.shift().reject(error);
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
queue.items = queue.items.filter(item => {
|
|
36
|
+
if (item.retry !== false) return true;
|
|
37
|
+
item.reject(error);
|
|
38
|
+
return false;
|
|
39
|
+
});
|
|
26
40
|
// Preserve the failed boundary and its following run boundaries in order.
|
|
27
41
|
// Other sessions have independent queues and can continue normally.
|
|
28
42
|
const delay = Math.min(retryMs * 2 ** Math.min(queue.attempt++, 5), 30000);
|
|
@@ -41,6 +55,35 @@ export function createSessionUnreadRuntime({ store, loadSession, hub, resolveDir
|
|
|
41
55
|
if (pending) drain(id, pending);
|
|
42
56
|
});
|
|
43
57
|
};
|
|
58
|
+
const enqueue = (payload, id, kind, retry = true) => {
|
|
59
|
+
const queue = queues.get(id) ?? { items: [], timer: null, attempt: 0 };
|
|
60
|
+
if (!retry && queue.timer) return Promise.reject(new Error('Session identity retry pending'));
|
|
61
|
+
queues.set(id, queue);
|
|
62
|
+
const completion = new Promise((resolve, reject) => {
|
|
63
|
+
queue.items.push({ payload, id, kind, retry, resolve, reject });
|
|
64
|
+
});
|
|
65
|
+
drain(id, queue);
|
|
66
|
+
return completion;
|
|
67
|
+
};
|
|
68
|
+
const reconcileStored = () => {
|
|
69
|
+
if (reconciliation) return reconciliation;
|
|
70
|
+
if (!unreconciled.size) return Promise.resolve();
|
|
71
|
+
const ids = [...unreconciled];
|
|
72
|
+
let cursor = 0;
|
|
73
|
+
let failed = false;
|
|
74
|
+
reconciliation = Promise.all(Array.from({ length: Math.min(4, ids.length) }, async () => {
|
|
75
|
+
while (!disposed && cursor < ids.length) {
|
|
76
|
+
const id = ids[cursor++];
|
|
77
|
+
try {
|
|
78
|
+
await enqueue({}, id, 'refresh', false);
|
|
79
|
+
unreconciled.delete(id);
|
|
80
|
+
} catch { failed = true; }
|
|
81
|
+
}
|
|
82
|
+
})).then(() => {
|
|
83
|
+
if (failed) throw new Error('Stored session identity unavailable');
|
|
84
|
+
}).finally(() => { reconciliation = null; });
|
|
85
|
+
return reconciliation;
|
|
86
|
+
};
|
|
44
87
|
const processEvent = (envelope) => {
|
|
45
88
|
const raw = envelope?.payload ?? envelope;
|
|
46
89
|
const payload = raw?.payload ?? raw;
|
|
@@ -51,15 +94,10 @@ export function createSessionUnreadRuntime({ store, loadSession, hub, resolveDir
|
|
|
51
94
|
const kind = type === 'session.execution.started' || (type === 'session.status' && body.status?.type === 'busy') ? 'running'
|
|
52
95
|
: type === 'session.execution.succeeded' || type === 'session.idle' ? 'complete'
|
|
53
96
|
: type === 'session.execution.failed' || type === 'session.error' ? 'error'
|
|
54
|
-
: type === 'session.deleted' ? 'deleted'
|
|
97
|
+
: type === 'session.deleted' ? 'deleted'
|
|
98
|
+
: type === 'session.metadata.updated' || type === 'session.updated' || type === 'yuri:session-metadata' ? 'refresh' : null;
|
|
55
99
|
if (!kind || disposed) return Promise.resolve();
|
|
56
|
-
|
|
57
|
-
queues.set(id, queue);
|
|
58
|
-
const completion = new Promise(resolve => {
|
|
59
|
-
queue.items.push({ payload, id, kind, resolve });
|
|
60
|
-
});
|
|
61
|
-
drain(id, queue);
|
|
62
|
-
return completion;
|
|
100
|
+
return enqueue(payload, id, kind);
|
|
63
101
|
};
|
|
64
102
|
const unsubscribe = hub?.subscribeEvent(event => {
|
|
65
103
|
void processEvent(event).catch(() => console.warn('[session-unread] lifecycle update failed'));
|
|
@@ -67,8 +105,8 @@ export function createSessionUnreadRuntime({ store, loadSession, hub, resolveDir
|
|
|
67
105
|
return {
|
|
68
106
|
processEvent,
|
|
69
107
|
registerRoutes(app) {
|
|
70
|
-
app.get('/api/yuri/session-unread', (_req, res) => {
|
|
71
|
-
try { res.json(store.snapshot()); }
|
|
108
|
+
app.get('/api/yuri/session-unread', async (_req, res) => {
|
|
109
|
+
try { await reconcileStored(); res.json(store.snapshot()); }
|
|
72
110
|
catch { res.status(503).json({ error: 'Session unread state unavailable' }); }
|
|
73
111
|
});
|
|
74
112
|
app.put('/api/yuri/session-unread/:id', express.json({ limit: '8kb' }), async (req, res) => {
|