@yuriai/web 0.2.0-beta.1 → 0.2.0-beta.2

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 (87) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{AssistantView-CKSBN9HQ.js → AssistantView-8ju42ZTW.js} +3 -3
  3. package/dist/assets/{DiagramView-RmE0gXVx.js → DiagramView-rw0YYQMb.js} +1 -1
  4. package/dist/assets/{GuiPluginSurface-DWGYdQLr.js → GuiPluginSurface-CZyG8VSt.js} +1 -1
  5. package/dist/assets/{GuiPluginWindow-CLgceKTX.js → GuiPluginWindow-BHbqKl7P.js} +1 -1
  6. package/dist/assets/{MarkdownRenderer-7zj1J9EY.js → MarkdownRenderer-CtlVSzEr.js} +2 -2
  7. package/dist/assets/{MarkdownRendererImpl-lXwdc-kG.js → MarkdownRendererImpl-wN873oJ5.js} +1 -1
  8. package/dist/assets/{MarkstreamRendererImpl-B5or38qI.js → MarkstreamRendererImpl-Bh0SBb3A.js} +1 -1
  9. package/dist/assets/{MobileDetailNavigation-K8AyOZUE.js → MobileDetailNavigation-BmVdW83D.js} +1 -1
  10. package/dist/assets/{MobileShareBridge-9RP7ni2F.js → MobileShareBridge-DsEPHal0.js} +1 -1
  11. package/dist/assets/{MobileTabPageHeader-ZZTO3phT.js → MobileTabPageHeader-C3XsN5mD.js} +1 -1
  12. package/dist/assets/{MultiRunWindow-CLGnrnLn.js → MultiRunWindow-E69FtA8j.js} +1 -1
  13. package/dist/assets/{SettingsView-BlruenEQ.js → SettingsView-cAxZUqrO.js} +1 -1
  14. package/dist/assets/{SettingsWindow-B-z25PVS.js → SettingsWindow-lAKvVEKw.js} +1 -1
  15. package/dist/assets/{TerminalView-CRyh7cpp.js → TerminalView-Dk4wVZaD.js} +1 -1
  16. package/dist/assets/{ToolOutputDialog-CMiPmx7q.js → ToolOutputDialog-USJ-ZgXn.js} +1 -1
  17. package/dist/assets/{appThemeRegistry-e1zU7R2C.js → appThemeRegistry-LtxIx7El.js} +1 -1
  18. package/dist/assets/{capgoAdapter-CEzjhZ15.js → capgoAdapter-DCIeVZw_.js} +1 -1
  19. package/dist/assets/{device-CCFr0Aht.js → device-B-trKdcC.js} +1 -1
  20. package/dist/assets/{dropdown-menu.styles-4tACRbYU.js → dropdown-menu.styles-B-E_v3QZ.js} +1 -1
  21. package/dist/assets/{fileMentionTouchSelection-BCTXha9_.js → fileMentionTouchSelection-CRlBHcv1.js} +1 -1
  22. package/dist/assets/{fileReferenceActions-B0iaTe0c.js → fileReferenceActions-ZQ5--HF8.js} +1 -1
  23. package/dist/assets/{gitApi-DIwsfb2k.js → gitApi-BKjA7Bpe.js} +1 -1
  24. package/dist/assets/gui-DpIvy9qB.js +1 -0
  25. package/dist/assets/host-u2MH0QSP.js +1 -0
  26. package/dist/assets/{insertionBoundaries-CFDcBxaK.js → insertionBoundaries-D_wrLY-Q.js} +1 -1
  27. package/dist/assets/{main-XMhFdW0K.js → main-C4Zc7_s8.js} +2 -2
  28. package/dist/assets/{main-DBJ19laz.js → main-CkA5yk63.js} +4 -4
  29. package/dist/assets/{mcpQueries-f0cDQQKu.js → mcpQueries-s9QcLjGw.js} +1 -1
  30. package/dist/assets/{miniChat-BVTtOggs.js → miniChat-C_wwveSN.js} +2 -2
  31. package/dist/assets/{mobile-0X6dYZAB.js → mobile-TuU7P2PX.js} +2 -2
  32. package/dist/assets/{mobileBackNavigation-htjL23a2.js → mobileBackNavigation-C6OcBTbS.js} +1 -1
  33. package/dist/assets/{multirun-mBD1Y3Eb.js → multirun-cZcReWkT.js} +1 -1
  34. package/dist/assets/{native-config-B9V18QgV.js → native-config-DnQvXgu6.js} +1 -1
  35. package/dist/assets/{platform-HIkm-CHn.js → platform-CxNhofMC.js} +3 -3
  36. package/dist/assets/{projectMeta-tXx77gZG.js → projectMeta-DXlpoXd3.js} +1 -1
  37. package/dist/assets/{readiness-Da7jHHss.js → readiness-m2mD0fyj.js} +1 -1
  38. package/dist/assets/{renderElectronMiniChatApp-DwIydDUm.js → renderElectronMiniChatApp-COXM_nk2.js} +2 -2
  39. package/dist/assets/{renderMobileApp-TNkNM5Zx.js → renderMobileApp-CbU3BLr6.js} +4 -4
  40. package/dist/assets/{runtimeConfig-ChR1FQv1.js → runtimeConfig-jHTvOptz.js} +1 -1
  41. package/dist/assets/{runtimeEndpointReset-CxMEqgDx.js → runtimeEndpointReset-BOuzWhtp.js} +3 -3
  42. package/dist/assets/{scheduledTaskNavigation-B71VHwFK.js → scheduledTaskNavigation-CE4sIXxf.js} +1 -1
  43. package/dist/assets/{sessionChangeSummary-DDbB-N5p.js → sessionChangeSummary-C7Y5e238.js} +1 -1
  44. package/dist/assets/{sessionLookup-CsJ8Vrq8.js → sessionLookup-BscEQpqH.js} +1 -1
  45. package/dist/assets/{sortable-tabs-strip-CnaQoAAB.js → sortable-tabs-strip-dKp0SH4C.js} +1 -1
  46. package/dist/assets/{speechSettingsQueries-X0jStYkm.js → speechSettingsQueries-DVKcuOEf.js} +1 -1
  47. package/dist/assets/{terminalApi-DVZUO2Uv.js → terminalApi-Bs5skvIp.js} +1 -1
  48. package/dist/assets/{types-Dfj_Rn0L.js → types-eQY4TOgr.js} +1 -1
  49. package/dist/assets/{useAppFontEffects-DDdQeaoM.js → useAppFontEffects-DOp_gxxk.js} +5 -5
  50. package/dist/assets/{useDesktopWindowControlsLayout-BFyKfmUX.js → useDesktopWindowControlsLayout-CPqgnywT.js} +1 -1
  51. package/dist/assets/{useEffectiveDirectory-CST6AXTm.js → useEffectiveDirectory-9Efzl9IZ.js} +1 -1
  52. package/dist/assets/{useFontPreferences-D-XYUHOV.js → useFontPreferences-n13Q1-rH.js} +1 -1
  53. package/dist/assets/{useMobileNavigationStore-BdWv0Da4.js → useMobileNavigationStore-Cwk7wARY.js} +5 -5
  54. package/dist/assets/{useWorkerHighlightedLines-OsRfq7LD.js → useWorkerHighlightedLines-ClwAu-Q3.js} +1 -1
  55. package/dist/assets/vendor-opencode-client-BcpAhe9I.js +12 -0
  56. package/dist/assets/{vendor-opencode-plugin-DhwD3Tat.js → vendor-opencode-plugin-BglYYlJt.js} +1 -1
  57. package/dist/assets/vendor-solid-js-B2FO7pdm.js +1 -0
  58. package/dist/index.html +8 -8
  59. package/dist/mini-chat.html +8 -8
  60. package/dist/mobile.html +8 -8
  61. package/package.json +3 -3
  62. package/server/lib/opencode/DOCUMENTATION.md +9 -9
  63. package/server/lib/opencode/ensure-cli.js +12 -14
  64. package/server/lib/opencode/ensure-cli.test.js +8 -8
  65. package/server/lib/opencode/env-runtime.test.js +1 -1
  66. package/server/lib/opencode/opencode2-pin.js +3 -4
  67. package/server/lib/opencode/opencode2-pin.test.js +5 -4
  68. package/server/lib/opencode/owned-runtime-upgrade.js +4 -11
  69. package/server/lib/opencode/owned-runtime-upgrade.test.js +4 -0
  70. package/server/lib/opencode/routes.js +2 -1
  71. package/server/lib/opencode/routes.test.js +1 -1
  72. package/server/lib/opencode/runtime-contract.js +3 -4
  73. package/server/lib/opencode/session-directory-runtime.js +2 -13
  74. package/server/lib/opencode/session-directory-runtime.test.js +69 -4
  75. package/server/lib/opencode/upgrade-screen.js +9 -5
  76. package/server/lib/opencode/upgrade-screen.test.js +20 -0
  77. package/server/lib/opencode/version-alignment.test.js +6 -6
  78. package/server/lib/session-index/DOCUMENTATION.md +18 -8
  79. package/server/lib/session-index/routes.js +3 -1
  80. package/server/lib/session-index/routes.test.js +2 -0
  81. package/server/lib/session-index/service.js +23 -0
  82. package/server/lib/session-index/sync-runtime.js +75 -20
  83. package/server/lib/session-index/sync-runtime.test.js +5 -5
  84. package/dist/assets/gui-CTnzY_cr.js +0 -1
  85. package/dist/assets/host-CEMl6ZlP.js +0 -1
  86. package/dist/assets/vendor-opencode-client-Eb-_7KbZ.js +0 -23
  87. package/dist/assets/vendor-solid-js-CXSXbuQO.js +0 -1
@@ -24,6 +24,71 @@ const session = (id, directory, updated = 1) => ({ id, title: id, location: { di
24
24
  const json = (value, status = 200) => new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } });
25
25
 
26
26
  describe('physical session directory identity', () => {
27
+ it('backfills only 30 days once per runtime, resumes failed pages, and never boots locations', async () => {
28
+ const { real } = fixture();
29
+ const dbPath = path.join(real, 'index.sqlite');
30
+ const now = 100 * 24 * 60 * 60 * 1000;
31
+ let fail = true;
32
+ let runtimeKey = 'http://localhost:4000';
33
+ const requests = [];
34
+ const fetchFn = vi.fn(async (input) => {
35
+ const url = new URL(input);
36
+ requests.push(url);
37
+ expect(url.pathname).toBe('/api/session');
38
+ expect(url.searchParams.has('directory')).toBe(false);
39
+ expect(url.searchParams.has('location[directory]')).toBe(false);
40
+ if (!url.searchParams.has('cursor')) return json({ data: [session('recent', real, now)], cursor: { next: 'second' } });
41
+ if (fail) return json({}, 503);
42
+ return json({ data: [session('older', real, now - 31 * 24 * 60 * 60 * 1000)], cursor: { next: 'never-read' } });
43
+ });
44
+ const open = () => {
45
+ const service = createSessionIndexService({ dbPath, getRuntimeConfig: () => ({ apiBaseUrl: runtimeKey }) });
46
+ const sync = createSessionIndexSyncRuntime({ sessionIndexService: service, now: () => now,
47
+ buildOpenCodeUrl: (route) => `http://localhost/api${route}`, getOpenCodeAuthHeaders: () => ({}), fetchFn });
48
+ return { service, sync };
49
+ };
50
+ let { service, sync } = open();
51
+ try {
52
+ sync.enqueue(Array.from({ length: 31 }, (_, i) => `/unused/${i}`), { startup: true });
53
+ sync.enqueue([], { startup: true });
54
+ await vi.waitFor(() => expect(sync.snapshot().sync.active).toBe(false));
55
+ expect(fetchFn).toHaveBeenCalledTimes(2);
56
+ expect(service.getHistoryBackfill()).toMatchObject({ cursor: 'second', complete: false });
57
+ expect(service.findBySessionId('recent')).toBeTruthy();
58
+ sync.stop(); service.close();
59
+ ({ service, sync } = open());
60
+ fail = false;
61
+ sync.enqueue([], { startup: true });
62
+ await vi.waitFor(() => expect(sync.snapshot().sync.active).toBe(false));
63
+ expect(fetchFn).toHaveBeenCalledTimes(3);
64
+ expect(requests[2].searchParams.get('cursor')).toBe('second');
65
+ expect(service.getHistoryBackfill().complete).toBe(true);
66
+ expect(service.findBySessionId('older')).toBeNull();
67
+ sync.stop(); service.close();
68
+ ({ service, sync } = open());
69
+ sync.enqueue([], { startup: true });
70
+ expect(sync.snapshot().sync.active).toBe(false);
71
+ expect(fetchFn).toHaveBeenCalledTimes(3);
72
+ runtimeKey = 'https://other.example';
73
+ expect(service.getHistoryBackfill()).toBeNull();
74
+ } finally { sync.stop(); service.close(); }
75
+ });
76
+
77
+ it('records an empty backfill as complete and preserves spaces in session directories', async () => {
78
+ const service = createSessionIndexService({ dbPath: ':memory:' });
79
+ const fetchFn = vi.fn(async () => json({ data: [], cursor: {} }));
80
+ const sync = createSessionIndexSyncRuntime({ sessionIndexService: service,
81
+ buildOpenCodeUrl: (route) => `http://localhost/api${route}`, getOpenCodeAuthHeaders: () => ({}), fetchFn });
82
+ try {
83
+ sync.enqueue([], { startup: true });
84
+ await vi.waitFor(() => expect(sync.snapshot().sync.active).toBe(false));
85
+ sync.enqueue([], { startup: true });
86
+ expect(fetchFn).toHaveBeenCalledTimes(1);
87
+ service.upsert(session('spaces', '/home/example/Library/Mobile Documents/project', Date.now()));
88
+ expect(service.findBySessionId('spaces').directory).toBe('/home/example/Library/Mobile Documents/project');
89
+ } finally { sync.stop(); service.close(); }
90
+ });
91
+
27
92
  it('checks deletion only on the owning local runtime and preserves uncertain failures', async () => {
28
93
  let url = 'http://127.0.0.1:4000';
29
94
  const stat = vi.fn(async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); });
@@ -67,6 +132,7 @@ describe('physical session directory identity', () => {
67
132
  fetchFn,
68
133
  });
69
134
  try {
135
+ runtime.enqueue([missing]);
70
136
  await vi.waitFor(() => expect(service.snapshot().directories.map(x => x.directory)).not.toContain(missing));
71
137
  expect(service.snapshot().directories.map(x => x.directory)).toEqual(expect.arrayContaining([real, history, partial, child]));
72
138
  runtime.enqueue([missing, history, partial, child]);
@@ -95,10 +161,10 @@ describe('physical session directory identity', () => {
95
161
  requests.push(url);
96
162
  expect(init.signal).toBe(controller.signal);
97
163
  expect(init.headers).toEqual({ Authorization: 'test-only' });
98
- if (url.pathname === '/api/location') return json({ project: { id: 'project-repo' } });
164
+ expect(url.pathname).toBe('/api/session');
99
165
  expect(url.searchParams.has('directory')).toBe(false);
100
166
  if (!url.searchParams.has('cursor')) {
101
- expect(url.searchParams.get('project')).toBe('project-repo');
167
+ expect(url.searchParams.has('project')).toBe(false);
102
168
  return json({ data: [session('other', other, 30)], cursor: { next: 'page-2' } });
103
169
  }
104
170
  return json({ data: [session('old-alias', alias, 20), session('real', real, 10)], cursor: { next: 'page-3' } });
@@ -117,8 +183,7 @@ describe('physical session directory identity', () => {
117
183
  expect(payload.data.map((row) => row.id)).toEqual(['old-alias', 'real']);
118
184
  expect(payload.data.every((row) => row.directory === real && row.location.directory === real)).toBe(true);
119
185
  expect(payload.cursor.next).toBe('page-3');
120
- expect(requests).toHaveLength(3);
121
- expect(requests[0].searchParams.get('location[directory]')).toBe(real);
186
+ expect(requests).toHaveLength(2);
122
187
  });
123
188
 
124
189
  it('uses the same physical directory for cold sync and later native live events', async () => {
@@ -8,13 +8,15 @@
8
8
  */
9
9
 
10
10
  import {
11
- PINNED_OPENCODE2_VERSION,
12
11
  MINIMUM_OPENCODE2_VERSION,
13
12
  isAcceptableOpenCode2HealthVersion,
14
13
  isOpenCode1xVersion,
15
14
  isOpenCode2VersionAtLeast,
16
15
  npmPackageForOpenCode2,
17
16
  } from './opencode2-pin.js';
17
+ import { createOpenCodeUpdateDiscovery } from './update-discovery.js';
18
+
19
+ const discoverLatestVersion = createOpenCodeUpdateDiscovery();
18
20
 
19
21
  /** Oldest OpenCode this Yuri build will enter a session against. */
20
22
  export const REQUIRED_OPENCODE_VERSION = MINIMUM_OPENCODE2_VERSION;
@@ -26,11 +28,10 @@ const normalizeVersion = (value) => {
26
28
  };
27
29
 
28
30
  /**
29
- * Install target is the pin when the pin already satisfies the screen, otherwise
30
- * the screen minimum. A pin still at 2.0.12 must not be what this screen installs.
31
+ * Describe the minimum until an installation resolves its remote stable target.
31
32
  * @param {string} [pin]
32
33
  */
33
- export function resolveUpgradeScreenTarget(pin = PINNED_OPENCODE2_VERSION) {
34
+ export function resolveUpgradeScreenTarget(pin = REQUIRED_OPENCODE_VERSION) {
34
35
  if (isOpenCode2VersionAtLeast(pin, REQUIRED_OPENCODE_VERSION)) return pin;
35
36
  return REQUIRED_OPENCODE_VERSION;
36
37
  }
@@ -181,7 +182,10 @@ export async function installRequiredOpenCode(deps) {
181
182
  409,
182
183
  );
183
184
  }
184
- const target = status.targetVersion;
185
+ const target = await (deps.resolveLatestVersion || discoverLatestVersion)();
186
+ if (!/^2\.\d+\.\d+$/.test(target) || !isUpgradeScreenSatisfied(target)) {
187
+ throw failure('No compatible stable OpenCode release was found.', 'UPGRADE_TARGET_INVALID');
188
+ }
185
189
  const previousBinary = typeof deps.getResolvedBinary === 'function' ? deps.getResolvedBinary() : null;
186
190
  const previousSource = typeof deps.getResolvedBinarySource === 'function' ? deps.getResolvedBinarySource() : null;
187
191
  const ownership = typeof deps.resolveOwnership === 'function' ? await deps.resolveOwnership() : null;
@@ -108,12 +108,31 @@ describe('installRequiredOpenCode', () => {
108
108
  calls.push('ready');
109
109
  }),
110
110
  readConfiguredBinary: async () => null,
111
+ resolveLatestVersion: async () => '2.0.23',
111
112
  isSharedService: () => false,
112
113
  ...overrides,
113
114
  };
114
115
  return { deps, calls };
115
116
  };
116
117
 
118
+ it('resolves a newer stable release instead of installing a compiled-in pin', async () => {
119
+ const { deps } = createDeps({
120
+ resolveLatestVersion: vi.fn(async () => '2.2.0'),
121
+ readBinaryVersion: () => '2.2.0',
122
+ readServeVersion: vi.fn().mockResolvedValueOnce('2.0.14').mockResolvedValueOnce('2.2.0'),
123
+ });
124
+ await expect(installRequiredOpenCode(deps)).resolves.toMatchObject({ upgraded: true, version: '2.2.0' });
125
+ expect(deps.install).toHaveBeenCalledWith({ version: '2.2.0' });
126
+ });
127
+
128
+ it('does not mutate installation or selection when release discovery fails', async () => {
129
+ const { deps } = createDeps({ resolveLatestVersion: async () => { throw new Error('offline'); } });
130
+ await expect(installRequiredOpenCode(deps)).rejects.toThrow('offline');
131
+ expect(deps.install).not.toHaveBeenCalled();
132
+ expect(deps.persistBinary).not.toHaveBeenCalled();
133
+ expect(deps.restart).not.toHaveBeenCalled();
134
+ });
135
+
117
136
  it('installs 2.0.23 and only succeeds after the running serve is verified', async () => {
118
137
  const { deps, calls } = createDeps({
119
138
  readServeVersion: vi.fn()
@@ -190,6 +209,7 @@ describe('upgrade screen routes', () => {
190
209
  resolveOwnership: async () => ({ ownership: 'owned-cache', guidance: null }),
191
210
  readServeVersion,
192
211
  readCliVersion: () => '2.0.12',
212
+ resolveLatestVersion: async () => '2.0.23',
193
213
  platformCanInstall: true,
194
214
  install: vi.fn(async () => {
195
215
  throw new Error('registry unreachable');
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
- import { MINIMUM_OPENCODE2_VERSION, PINNED_OPENCODE2_VERSION } from './opencode2-pin.js';
2
+ import { MINIMUM_OPENCODE2_VERSION } from './opencode2-pin.js';
3
3
  import { evaluateRuntimeContract } from './runtime-contract.js';
4
4
  import { describeUpgradeScreen, installRequiredOpenCode, resolveUpgradeScreenTarget } from './upgrade-screen.js';
5
5
  import { ensurePinnedOpenCode2Cli } from './ensure-cli.js';
@@ -13,24 +13,24 @@ describe('v2 version alignment', () => {
13
13
  expect(evaluateRuntimeContract({ serveVersion: version, cliVersion: '2.0.15', reachable: true, authenticated: true })).toMatchObject({ executionAllowed: true, versionMismatch: true, minVerifiedVersion: '2.0.20' });
14
14
  expect(describeUpgradeScreen({ version }).state).toBe('compatible');
15
15
  });
16
- it('installs the audited pin on first install and preserves newer discovered CLIs', async () => {
16
+ it('installs the discovered stable release and preserves existing CLIs', async () => {
17
17
  expect(MINIMUM_OPENCODE2_VERSION).toBe('2.0.20');
18
- expect(PINNED_OPENCODE2_VERSION).toBe('2.0.23');
19
- expect(resolveUpgradeScreenTarget()).toBe('2.0.23');
18
+ expect(resolveUpgradeScreenTarget()).toBe(MINIMUM_OPENCODE2_VERSION);
20
19
  const install = vi.fn(async () => '/owned/opencode');
21
- await expect(ensurePinnedOpenCode2Cli({ readVersion: (path) => path === '/owned/opencode' ? '2.0.23' : '', install })).resolves.toMatchObject({ version: '2.0.23', installed: true });
20
+ await expect(ensurePinnedOpenCode2Cli({ resolveLatestVersion: async () => '2.0.23', readVersion: (path) => path === '/owned/opencode' ? '2.0.23' : '', install })).resolves.toMatchObject({ version: '2.0.23', installed: true });
22
21
  expect(install).toHaveBeenCalledWith(expect.objectContaining({ version: '2.0.23' }));
23
22
  install.mockClear();
24
23
  await expect(ensurePinnedOpenCode2Cli({ discoveredPath: '/global/opencode', readVersion: () => '2.1.0', install })).resolves.toMatchObject({ version: '2.1.0', installed: false });
25
24
  expect(install).not.toHaveBeenCalled();
26
25
  });
27
26
  it('does not infer a successful installation from an unreadable binary', async () => {
28
- await expect(ensurePinnedOpenCode2Cli({ readVersion: () => '', install: async () => '/owned/opencode' })).rejects.toThrow('got unknown');
27
+ await expect(ensurePinnedOpenCode2Cli({ resolveLatestVersion: async () => '2.2.0', readVersion: () => '', install: async () => '/owned/opencode' })).rejects.toThrow('got unknown');
29
28
  });
30
29
  it('verifies the live service after explicit install, and rolls selection back on failure', async () => {
31
30
  const persistBinary = vi.fn();
32
31
  const restart = vi.fn();
33
32
  const deps = { resolveOwnership: async () => ({ ownership: 'shared-service', binaryOwnership: 'owned-cache' }), readServeVersion: vi.fn().mockResolvedValueOnce('2.0.19').mockResolvedValueOnce('2.0.23'), readCliVersion: () => '2.0.23', platformCanInstall: true, install: async () => '/owned/opencode', readBinaryVersion: () => '2.0.23', persistBinary, restart, isSharedService: () => true };
33
+ deps.resolveLatestVersion = async () => '2.0.23';
34
34
  await expect(installRequiredOpenCode(deps)).resolves.toMatchObject({ upgraded: true, version: '2.0.23' });
35
35
  expect(restart).toHaveBeenCalledWith({ binaryPath: '/owned/opencode' });
36
36
  deps.readServeVersion.mockResolvedValue('2.0.19');
@@ -8,15 +8,15 @@ with an empty result. Remote upstreams never use the Host filesystem as evidence
8
8
  permission and I/O errors are not deletion. Checks are not negatively cached, so
9
9
  a recreated directory participates in the next requested sync.
10
10
 
11
- Once at startup, the sync runtime checks empty, exhausted indexed
12
- directories. It removes only directory shells with no summary rows, no child rows,
11
+ Startup does not probe indexed directories. An explicitly requested directory
12
+ refresh removes only missing directory shells with no summary rows, no child rows,
13
13
  and no more pages, using one conditional SQLite deletion. Session history and pins
14
14
  are preserved. This maintenance does not touch code files or upstream projects.
15
15
  Runtime switches and shutdown discard pending checks; successful cleanup publishes
16
16
  a revision tip. Snapshot GETs do not perform filesystem scans. Old project paths
17
17
  may still be submitted by clients, but pre-scan checks prevent recreating empty
18
18
  shells for missing paths. App or external worktree deletion is picked up by the
19
- next requested sync or startup pass; there is no periodic filesystem polling.
19
+ next requested sync; there is no startup or periodic filesystem polling.
20
20
 
21
21
  ## Physical directory identity
22
22
 
@@ -33,8 +33,8 @@ child membership follows the directory, and the merged head stays bounded to 20.
33
33
  Reconciliation failure rolls back the entire index conversion. Rechecking on reads
34
34
  also recovers paths unavailable during startup.
35
35
 
36
- Directory lists resolve the upstream location/project, fetch project-scoped pages
37
- and retain only records whose physical directory matches the requested directory.
36
+ Explicit directory lists fetch session pages without initializing an upstream
37
+ Location and retain only records whose physical directory matches the request.
38
38
  This discovers old aliases outside the index without admitting sibling worktrees.
39
39
  Opaque next/previous cursors stay upstream-owned; filtered short/empty pages with
40
40
  a continuation are partial, not exhausted. The existing five-page sync budget and
@@ -121,9 +121,19 @@ Repeated session summary events whose bounded root summary or child membership
121
121
  is unchanged leave directory recency and the public revision unchanged. Root
122
122
  events that remain outside the newest-20 bound follow the same no-op path.
123
123
 
124
- `sync-runtime.js` owns cold-start synchronization. The renderer submits all
125
- known project directories once to `POST /api/yuri/session-index/sync`.
126
- The runtime processes them sequentially. OpenCode 2.x list is cursor-only (no
124
+ `sync-runtime.js` owns cold-start synchronization. The renderer sends
125
+ `{ startup: true }` to `POST /api/yuri/session-index/sync`, without project paths.
126
+ The Host backfills sessions updated within the last 30 days using a single global
127
+ descending session-list cursor, stopping at the time boundary. It never requests
128
+ Location/config/plugin APIs or probes project paths. Each page and its cursor are
129
+ committed atomically in SQLite under the runtime key; empty success also records
130
+ completion. Subsequent launches perform no upstream history reads after completion.
131
+ Failure/shutdown preserves the last committed cursor for retry. Existing summaries
132
+ win over backfill, and normal create/update/archive/delete events maintain the index.
133
+ Existing databases without this marker receive one bounded backfill without being
134
+ cleared. Manual directory refresh remains a separate explicit operation.
135
+
136
+ The runtime processes explicit directory refreshes sequentially. OpenCode 2.x list is cursor-only (no
127
137
  `start` incremental); each directory fetches active-only pages (`limit=20`)
128
138
  after optional Host `projectSessions` overlay. Consecutive archived rows may
129
139
  consume further pages within a small page budget so the newest-20 **active**
@@ -55,7 +55,9 @@ export const registerSessionIndexRoutes = (app, {
55
55
  app.post('/api/yuri/session-index/sync', async (req, res) => {
56
56
  if (!sessionIndexSyncRuntime) return unsupported(res);
57
57
  const directories = Array.isArray(req.body?.directories) ? req.body.directories : [];
58
- const base = sessionIndexSyncRuntime.enqueue(directories);
58
+ const base = req.body?.startup === true
59
+ ? sessionIndexSyncRuntime.enqueue([], { startup: true })
60
+ : sessionIndexSyncRuntime.enqueue(directories);
59
61
  if (!hostStoreWired) return res.status(202).json(base);
60
62
  // Clients apply this body as a snapshot: same Host archive gate as GET.
61
63
  const host = await readHostMap();
@@ -79,6 +79,8 @@ describe('session index routes', () => {
79
79
  expect(res.statusCode).toBe(202);
80
80
  expect(enqueue).toHaveBeenCalledWith(['/repo/a', '/repo/b']);
81
81
  expect(res.body).toMatchObject({ revision: 1, sync: { active: true } });
82
+ route('POST', '/api/yuri/session-index/sync')({ body: { startup: true, directories: ['/ignored'] } }, res);
83
+ expect(enqueue).toHaveBeenLastCalledWith([], { startup: true });
82
84
  });
83
85
 
84
86
  it('does not register a long-poll changes route', () => {
@@ -688,7 +688,30 @@ export const createSessionIndexService = ({ dbPath, getRuntimeConfig = () => nul
688
688
  `).run(runtimeKey(), directory).changes > 0;
689
689
 
690
690
  try { reconcileDirectoryAliases(runtimeKey()); } catch (error) { db.close(); throw error; }
691
+ const historyKey = () => `history_backfill:${runtimeKey()}`;
692
+ const getHistoryBackfill = () => {
693
+ const row = db.prepare('SELECT value FROM session_index_meta WHERE key = ?').get(historyKey());
694
+ return row ? JSON.parse(row.value) : null;
695
+ };
696
+ const commitHistoryPage = db.transaction(({ sessions, progress, expectedRuntimeKey }) => {
697
+ if (expectedRuntimeKey !== runtimeKey()) return false;
698
+ for (const session of sessions) {
699
+ // Live events and already indexed summaries win over historical reads.
700
+ if (!findBySessionId(session.id)) {
701
+ upsert(session);
702
+ const directory = normalizeDirectory(session?.location?.directory ?? session?.directory);
703
+ // The bounded 30-day import is not proof that older history is empty.
704
+ db.prepare('UPDATE runtime_directory SET has_more = 1 WHERE runtime_key = ? AND directory = ? AND last_full_synced_at = 0')
705
+ .run(expectedRuntimeKey, directory);
706
+ }
707
+ }
708
+ db.prepare('INSERT OR REPLACE INTO session_index_meta(key, value) VALUES (?, ?)')
709
+ .run(historyKey(), JSON.stringify(progress));
710
+ return true;
711
+ });
691
712
  return {
713
+ getHistoryBackfill,
714
+ commitHistoryPage,
692
715
  replaceDirectory,
693
716
  removeEmptyDirectory,
694
717
  replaceDirectories,
@@ -106,6 +106,7 @@ export const createSessionIndexSyncRuntime = ({
106
106
  const waiters = new Set();
107
107
  let batchDirectories = new Set();
108
108
  let revisionTipTimer;
109
+ let historyQueued = false;
109
110
 
110
111
  const syncState = () => ({
111
112
  active: !stopped && (running || queue.length > 0),
@@ -331,6 +332,52 @@ export const createSessionIndexSyncRuntime = ({
331
332
  }
332
333
  };
333
334
 
335
+ const fetchHistory = async (task) => {
336
+ if (stopped || task.runtimeKey !== sessionIndexService.getRuntimeKey()) return 'discarded';
337
+ const progress = sessionIndexService.getHistoryBackfill() ?? {
338
+ cutoff: now() - 30 * 24 * 60 * 60 * 1000, cursor: null, complete: false,
339
+ };
340
+ if (progress.complete) return 'completed';
341
+ const controller = new AbortController();
342
+ currentController = controller;
343
+ currentWasPreempted = false;
344
+ const timeout = setTimer(() => controller.abort(), FETCH_TIMEOUT_MS);
345
+ try {
346
+ const url = new URL(buildOpenCodeUrl('/session'));
347
+ url.searchParams.set('limit', '100');
348
+ url.searchParams.set('order', 'desc');
349
+ if (progress.cursor) url.searchParams.set('cursor', progress.cursor);
350
+ const response = await fetchFn(url, {
351
+ headers: { Accept: 'application/json', ...getOpenCodeAuthHeaders() }, signal: controller.signal,
352
+ });
353
+ if (!response.ok) throw new Error(`OpenCode history list failed (${response.status})`);
354
+ const payload = await response.json();
355
+ if (!Array.isArray(payload?.data)) throw new Error('Invalid OpenCode history page');
356
+ if (stopped || task.runtimeKey !== sessionIndexService.getRuntimeKey()) return 'discarded';
357
+ if (payload.data.some((session) => !session?.id || updatedAt(session) <= 0)) {
358
+ throw new Error('Invalid OpenCode history session');
359
+ }
360
+ const recent = payload.data.filter((session) => updatedAt(session) >= progress.cutoff);
361
+ const cursor = extractSessionListCursorToken(payload.cursor);
362
+ const complete = recent.length !== payload.data.length || !cursor || payload.data.length === 0;
363
+ if (!complete && cursor === progress.cursor) throw new Error('Repeated OpenCode history cursor');
364
+ const sessions = typeof projectSessions === 'function' ? projectSessions(recent) : recent;
365
+ if (!Array.isArray(sessions)) throw new Error('Invalid history projection');
366
+ sessionIndexService.commitHistoryPage({
367
+ sessions, progress: { ...progress, cursor, complete }, expectedRuntimeKey: task.runtimeKey,
368
+ });
369
+ return complete ? 'completed' : 'more';
370
+ } catch (error) {
371
+ if (stopped || task.runtimeKey !== sessionIndexService.getRuntimeKey()) return 'discarded';
372
+ if (currentWasPreempted) return 'preempted';
373
+ throw error;
374
+ } finally {
375
+ clearTimer(timeout);
376
+ if (currentController === controller) currentController = null;
377
+ currentWasPreempted = false;
378
+ }
379
+ };
380
+
334
381
  const fetchChildFlag = async (task) => {
335
382
  if (isDirectoryMissing && await isDirectoryMissing(task.directory)) return 'discarded';
336
383
  if (stopped || task.runtimeKey !== sessionIndexService.getRuntimeKey()) return 'discarded';
@@ -419,16 +466,32 @@ export const createSessionIndexSyncRuntime = ({
419
466
  const task = queue.shift();
420
467
  if (!task) break;
421
468
  try {
422
- const result = await fetchDirectory(task);
469
+ const result = task.history ? await fetchHistory(task) : await fetchDirectory(task);
470
+ if (result === 'more') {
471
+ queue.push(task);
472
+ notify();
473
+ continue;
474
+ }
423
475
  if (result === 'preempted') {
424
476
  queue.unshift(task);
425
477
  await delay(Math.max(0, interactiveUntil - now()));
426
478
  continue;
427
479
  }
428
480
  if (result === 'discarded' || stopped) continue;
481
+ if (task.history) {
482
+ historyQueued = false;
483
+ notify();
484
+ continue;
485
+ }
429
486
  queuedDirectories.delete(task.directory);
430
487
  completedDirectories.add(task.directory);
431
488
  } catch (error) {
489
+ if (task.history) {
490
+ historyQueued = false;
491
+ console.warn('[SessionIndex] History backfill paused:', error);
492
+ notify();
493
+ continue;
494
+ }
432
495
  queuedDirectories.delete(task.directory);
433
496
  failedDirectories.add(task.directory);
434
497
  console.warn(`[SessionIndex] Background sync failed for ${task.directory}:`, error);
@@ -437,6 +500,7 @@ export const createSessionIndexSyncRuntime = ({
437
500
  }
438
501
  } catch (error) {
439
502
  for (const task of queue.splice(0)) {
503
+ if (task.history) { historyQueued = false; continue; }
440
504
  queuedDirectories.delete(task.directory);
441
505
  failedDirectories.add(task.directory);
442
506
  }
@@ -450,7 +514,7 @@ export const createSessionIndexSyncRuntime = ({
450
514
  }
451
515
  };
452
516
 
453
- const enqueue = (directories) => {
517
+ const enqueue = (directories, { startup = false } = {}) => {
454
518
  if (stopped) return snapshot();
455
519
  const nextRuntimeKey = sessionIndexService.getRuntimeKey();
456
520
  if (nextRuntimeKey !== runtimeKey) {
@@ -464,6 +528,15 @@ export const createSessionIndexSyncRuntime = ({
464
528
  completedDirectories.clear();
465
529
  failedDirectories.clear();
466
530
  batchDirectories = new Set();
531
+ historyQueued = false;
532
+ }
533
+ if (startup) {
534
+ if (!historyQueued && !sessionIndexService.getHistoryBackfill()?.complete) {
535
+ historyQueued = true;
536
+ queue.push({ history: true, runtimeKey });
537
+ void run();
538
+ }
539
+ return snapshot();
467
540
  }
468
541
  const newBatch = !running && queue.length === 0;
469
542
  if (newBatch) {
@@ -532,23 +605,5 @@ export const createSessionIndexSyncRuntime = ({
532
605
  notify(true);
533
606
  };
534
607
 
535
- const cleanupMissingDirectories = async () => {
536
- const key = sessionIndexService.getRuntimeKey();
537
- let changed = false;
538
- try {
539
- for (const entry of sessionIndexService.snapshot().directories) {
540
- if (stopped || key !== sessionIndexService.getRuntimeKey()) break;
541
- if (entry.sessions.length || entry.hasMore) continue;
542
- const missing = await isDirectoryMissing(entry.directory);
543
- if (stopped || key !== sessionIndexService.getRuntimeKey()) break;
544
- if (missing) changed = sessionIndexService.removeEmptyDirectory(entry.directory) || changed;
545
- }
546
- if (changed && !stopped && key === sessionIndexService.getRuntimeKey()) notify(true);
547
- } catch (error) {
548
- console.warn('[SessionIndex] Directory cleanup failed:', error);
549
- }
550
- };
551
- if (isDirectoryMissing) void cleanupMissingDirectories();
552
-
553
608
  return { enqueue, noteInteractiveRequest, publishChange, snapshot, waitForChange, stop };
554
609
  };
@@ -41,7 +41,7 @@ const isFullyIdle = (runtime) => (
41
41
  );
42
42
 
43
43
  describe('session index background sync runtime', () => {
44
- it('cleans missing directories once at startup without scheduling a poll', async () => {
44
+ it('does not probe indexed directories at startup', async () => {
45
45
  const service = createService([{ directory: '/repo', sessions: [], hasMore: false }]);
46
46
  service.removeEmptyDirectory = vi.fn(() => true);
47
47
  const isDirectoryMissing = vi.fn(async () => true);
@@ -53,11 +53,11 @@ describe('session index background sync runtime', () => {
53
53
  setTimer: (fn, ms) => { const timer = { fn, ms }; timers.push(timer); return timer; },
54
54
  clearTimer,
55
55
  });
56
- await waitUntil(() => runtime.snapshot().revision === 1);
57
- expect(service.removeEmptyDirectory).toHaveBeenCalledWith('/repo');
58
- expect(runtime.snapshot().revision).toBe(1);
56
+ await Promise.resolve();
57
+ expect(service.removeEmptyDirectory).not.toHaveBeenCalled();
58
+ expect(runtime.snapshot().revision).toBe(0);
59
59
  runtime.stop();
60
- expect(isDirectoryMissing).toHaveBeenCalledTimes(1);
60
+ expect(isDirectoryMissing).not.toHaveBeenCalled();
61
61
  expect(timers).toHaveLength(0);
62
62
  });
63
63
 
@@ -1 +0,0 @@
1
- import{f as e,i as t,n}from"./runtime-switch-CAZiOV2G.js";import{n as r}from"./runtime-fetch-BAN5Gnnp.js";import{i}from"./vendor-opencode-client-Eb-_7KbZ.js";function a(a){let o=t(),s=n();return i.make({baseUrl:new URL(e().api(`/`),window.location.href).href,fetch:(i,c)=>{if(a.aborted||o!==t()||s!==n())return Promise.reject(new DOMException(`Plugin runtime ended`,`AbortError`));let l=new URL(i instanceof Request?i.url:i.toString()),u=new URL(e().api(`${l.pathname}${l.search}`),window.location.href),d=new Request(u,i instanceof Request?i:c);return r(d,{...c,signal:AbortSignal.any([a,d.signal,...c?.signal?[c.signal]:[]])})}})}export{a as createGuiClient};
@@ -1 +0,0 @@
1
- import{C as e,D as t,I as n,L as r,M as i,O as a,P as o,S as s,T as c,_ as l,a as u,c as d,j as f,n as p,o as m,r as h,s as g,t as _,v,w as y,y as b}from"./vendor-opencode-client-Eb-_7KbZ.js";import{i as x}from"./vendor-tanstack-query-core-BWz0ose6.js";import{c as S,l as ee,o as te}from"./path-utils-QNmCUIdP.js";import{n as ne}from"./pathNormalization-ewtPqJWn.js";import{i as re,o as ie}from"./fileReferenceParser-D6pFtXag.js";import{n as ae,t as oe}from"./vendor-solid-js-CXSXbuQO.js";import{a as se,c as ce,d as C,f as w,h as le,i as T,l as E,m as D,n as ue,o as O,p as de,r as fe,s as pe,t as k,u as A}from"./vendor-opencode-plugin-DhwD3Tat.js";import{ft as j,pt as M,wt as N,y as P}from"./vendor-effect-DXlObQuU.js";var F={"@opencode/plugin/gui":O,"@opencode/plugin/gui/main":O,"@opencode/plugin/gui/file":se,"@opencode/plugin/gui/review":T,"@opencode/plugin/gui/browser":fe,"@opencode/plugin/rpc":k,"@opencode/schema/rpc":ue,"@opencode/client":h,"@opencode/client/effect":p,"@opencode/client/solid":_,effect:P,"solid-js":o,"solid-js/web":ae,"solid-js/store":g},I=new Set(`assert assert/strict async_hooks buffer child_process cluster console constants crypto dgram diagnostics_channel dns dns/promises domain events fs fs/promises http http2 https inspector inspector/promises module net os path path/posix path/win32 perf_hooks process punycode querystring readline readline/promises repl stream stream/consumers stream/promises stream/web string_decoder sys timers timers/promises tls trace_events tty url util util/types v8 vm wasi worker_threads zlib`.split(` `));function L(){let e=new Proxy(function(){},{get:(t,n)=>n===`then`?void 0:n===Symbol.hasInstance?()=>!1:n===Symbol.toPrimitive||n===`toString`?()=>`[main-only module]`:e,apply:()=>e,construct:()=>e,set:()=>!0});return e}function R(e){if(e.length>16777216)throw Error(`GUI bundle exceeds 16 MiB`);let t={exports:{}};Function(`require`,`module`,`exports`,e)(e=>{if(Object.hasOwn(F,e))return F[e];if(e===`electron`||e.startsWith(`node:`)||I.has(e))return L();throw Error(`Unsupported GUI shared module: ${e}`)},t,t.exports);let n=t.exports,r=n&&typeof n==`object`&&`default`in n?n.default:n;if(!r||typeof r!=`object`)throw Error(`GUI bundle must default-export Plugin.define`);if(!(`setup`in r)||typeof r.setup!=`function`)throw Error(`This host requires a window setup; main-only plugins are unsupported`);if(`os`in r&&r.os!==void 0)throw Error(`OS-restricted plugins require the native GUI host`);if(`main`in r&&r.main!==void 0&&typeof r.main!=`function`)throw Error(`Invalid GUI main entry`);if(`stores`in r&&r.stores!==void 0){if(!r.stores||typeof r.stores!=`object`||Array.isArray(r.stores))throw Error(`Invalid GUI stores`);for(let e of Object.values(r.stores))if(!e||typeof e!=`object`||!(`schema`in e)||!N(e.schema)||!(`scope`in e)||![`global`,`session`].includes(String(e.scope))||!(`initial`in e))throw Error(`Invalid GUI store declaration`)}if(`i18n`in r&&r.i18n!==void 0){if(!r.i18n||typeof r.i18n!=`object`||Array.isArray(r.i18n))throw Error(`Invalid GUI locale catalog`);for(let e of Object.values(r.i18n))if(!e||typeof e!=`object`||Array.isArray(e)||Object.values(e).some(e=>typeof e!=`string`))throw Error(`GUI locales must be inline string dictionaries`)}return r}function z(e){let t=e;if(/^file:/i.test(t)){let e=new URL(t);t=`${e.hostname&&e.hostname!==`localhost`?`//${e.hostname}`:``}${decodeURIComponent(e.pathname)}`,/^\/[a-z]:\//i.test(t)&&(t=t.slice(1))}let n=ne(t)??``;return n===`.`?``:n}var B=e=>/^(?:\/|[a-z]:\/)/i.test(e),V=()=>{throw Error(`Unsupported GUI file API: tree`)},H=class extends Error{},U=e=>new TextEncoder().encode(e).byteLength,me=class{files;query;transport;root;api;ended=!1;states=new Map;inflight=new Map;watches=new Map;apiLeases=new Map;registeredOwners=new WeakSet;endedOwners=new WeakSet;leaseCount=0;rerun=new Set;selections=new Map;scrolls=new Map;subscriptions=new Map;constructor(e,t,n,r){this.files=e,this.query=t,this.transport=n,this.root=r,this.root=z(r),this.api={root:this.root,ready:()=>!this.ended,resolve:e=>this.resolve(e),absolute:B,get:e=>{let t=this.track(e,`file`);return this.states.get(t)},missing:e=>{let t=this.track(e,`missing`);return this.states.get(t)?.notFound===!0},sync:(e,t)=>{let n=a();return this.ended||n&&this.endedOwners.has(n)?Promise.resolve():(this.acquireApiLease(e),this.sync(e,t?.force))},unwatch:e=>this.releaseApiLease(a(),this.resolve(e)),exists:async e=>{try{if(this.files.statFile)return(await this.query.fetchQuery(this.statOptions(e))).isFile;let t=this.full(e);return(await this.files.listDirectory(t.slice(0,t.lastIndexOf(`/`)))).entries.some(e=>!e.isDirectory&&z(e.path)===t)}catch{return!1}},search:async(e,t)=>{if(t?.kind===`any`)throw Error(`Unsupported GUI file search: directories`);t?.signal?.throwIfAborted();let r=await this.query.fetchQuery({queryKey:[`gui-plugin-files`,n,this.root,`search`,e,t?.limit],gcTime:3e4,queryFn:async({signal:n})=>(n.throwIfAborted(),this.files.search({directory:this.root,query:e,maxResults:t?.limit??100}))});if(t?.signal?.throwIfAborted(),this.ended)throw new DOMException(`GUI file model was disposed`,`AbortError`);return r.map(e=>this.resolve(e.path))},selection:{get:e=>this.selections.get(this.track(e,`selection`)),set:(e,t)=>{let n=this.resolve(e),r=this.selections.get(n);r===t||r&&t&&r.start===t.start&&r.end===t.end&&r.side===t.side&&r.endSide===t.endSide||(this.selections.set(n,t),this.trim(this.selections,`selection`),this.changed(n,`selection`))}},scroll:{get:e=>this.scrolls.get(this.track(e,`scroll`))??{},set:(e,t)=>{let n=this.resolve(e),r=this.scrolls.get(n),i={...r,...t};(r?.top!==i.top||r?.left!==i.left)&&(this.scrolls.set(n,i),this.trim(this.scrolls,`scroll`),this.changed(n,`scroll`))}},tree:{list:V,state:V,sync:V,expand:V,collapse:V}}}resolve(e){let t=z(e);if(!B(t))return t;if(t===this.root)return``;let n=this.root.endsWith(`/`)?this.root:`${this.root}/`;return t.startsWith(n)?t.slice(n.length):t}full(e){let t=this.resolve(e);return B(t)?t:z(`${this.root}/${t}`)}input(e){return{scopeDirectory:this.root,path:this.full(e),options:{directory:this.root}}}statOptions(e){return{...ee(this.files,this.input(e),this.transport),gcTime:3e4}}track(e,n){let r=this.resolve(e),a=t();if(!a||this.ended)return r;let o=`${n}:${r}`,s=this.subscriptions.get(o);s||(s={revision:c(0),listeners:new Set},this.subscriptions.set(o,s));let l=s;return l.listeners.has(a)||(l.listeners.add(a),i(a,()=>f(()=>{l.listeners.delete(a),!l.listeners.size&&this.subscriptions.get(o)===l&&this.subscriptions.delete(o)}))),l.revision[0](),r}changed(e,t){this.ended||this.subscriptions.get(`${t}:${e}`)?.revision[1](e=>e+1)}trim(e,t){for(;e.size>64;){let n=e.keys().next().value;e.delete(n),this.changed(n,t)}}setState(e,t){let n=this.states.get(e);n?.content?.content===t.content?.content&&n?.content?.type===t.content?.type&&(t.content=n?.content),!(n&&n.loaded===t.loaded&&n.loading===t.loading&&n.error===t.error&&n.notFound===t.notFound&&n.content===t.content)&&(this.states.set(e,t),l(()=>{this.changed(e,`file`),n?.notFound===!0!=(t.notFound===!0)&&this.changed(e,`missing`)}))}acquireApiLease(e){let t=a();if(this.ended||t&&this.endedOwners.has(t)||!this.files.statFile)return;let n=this.resolve(e),r=this.apiLeases.get(t);if(r?.has(n))return;if(this.leaseCount>=256)throw Error(`GUI file consumer limit exceeded`);let i=this.watch(n);r||(r=new Map,this.apiLeases.set(t,r)),r.set(n,i),this.leaseCount++,t&&!this.registeredOwners.has(t)&&(this.registeredOwners.add(t),f(()=>{`fn`in t||this.endedOwners.add(t),this.registeredOwners.delete(t);for(let e of[...this.apiLeases.get(t)?.keys()??[]])this.releaseApiLease(t,e)}))}releaseApiLease(e,t){let n=this.apiLeases.get(e),r=n?.get(t);r&&(n.delete(t),this.leaseCount--,n.size||this.apiLeases.delete(e),r())}reserve(e){if(!this.states.has(e)){if(this.states.size>=64){let e=[...this.states.keys()].find(e=>!this.watches.has(e)&&!this.inflight.has(e));if(!e)throw Error(`GUI file cache limit exceeded`);let t=this.states.get(e)?.notFound===!0;this.states.delete(e),l(()=>{this.changed(e,`file`),t&&this.changed(e,`missing`)})}this.states.set(e,{path:e,name:e.split(`/`).at(-1)??e})}}async sync(e,t=!1){if(this.ended)return;let n=this.resolve(e);if(this.inflight.has(n))return t&&this.rerun.add(n),this.inflight.get(n);if(!t&&this.states.get(n)?.loaded&&!this.states.get(n)?.error)return;this.reserve(n);let r=this.states.get(n);this.setState(n,{...r,path:n,name:n.split(`/`).at(-1)??n,loading:!r?.loaded&&!this.watches.get(n)?.failed});let i=(async()=>{try{do{this.rerun.delete(n);let e=this.watches.get(n),r=e?.epoch;try{let i=S(this.files,this.input(n),this.transport),a=await this.query.fetchQuery({...i,gcTime:3e4,staleTime:t?0:3e4,queryFn:async()=>{if(!this.files.readFile)throw Error(`File content reads are unavailable in this runtime`);let e=await this.files.readFile(this.full(n),{directory:this.root});if(e.exists===!1)throw new H(`File does not exist`);let t=e.content;if(U(t)>131072)throw Error(`GUI file preview exceeds 128 KiB`);return t}});if(this.ended)return;if(U(a)>131072)throw Error(`GUI file preview exceeds 128 KiB`);(!e||e.epoch===r&&!e.failed)&&this.setState(n,{path:n,name:n.split(`/`).at(-1)??n,loaded:!0,loading:!1,content:{type:`text`,content:a}})}catch(t){if(this.ended)return;if((!e||e.epoch===r&&!e.failed)&&this.setState(n,{...this.states.get(n),loading:!1,...t instanceof H?{notFound:!0}:{},error:String(t)}),!this.rerun.has(n))throw t}t=!0}while(!this.ended&&this.rerun.has(n))}finally{this.inflight.delete(n),this.rerun.delete(n)}})();return this.inflight.set(n,i),i}watch(e){if(this.ended||!this.files.statFile)return()=>{};let t=this.resolve(e),n=this.watches.get(t);if(!n){if(this.watches.size>=64)throw Error(`GUI file watch limit exceeded`);this.reserve(t),n={count:0,epoch:0,failed:!1,stop:()=>{}};let e=n;this.watches.set(t,e);let r,i=new x(this.query,{...this.statOptions(t),refetchInterval:2e3,refetchIntervalInBackground:!1}),a=i.subscribe(n=>{if(this.ended||this.watches.get(t)!==e||n.isFetching)return;if(n.isError||n.isSuccess&&!n.data.isFile){e.failed=!0,e.epoch++,this.setState(t,{...this.states.get(t),loading:!1,notFound:n.isSuccess?!0:this.states.get(t)?.notFound,error:n.isError?String(n.error):`File does not exist`});return}if(!n.data||!n.isSuccess)return;let i=`${n.data.size}:${n.data.mtimeMs??``}`,a=e.failed||r!==void 0&&i!==r;e.failed=!1,r=i,a&&(e.epoch++,this.sync(t,!0).catch(()=>{}))});e.stop=()=>{a(),i.destroy()}}n.count++;let r=!0;return()=>{r&&(r=!1,--n.count===0&&this.watches.get(t)===n&&this.stopWatch(t))}}stopWatch(e){this.watches.get(e)?.stop(),this.watches.delete(e)}dispose(){this.ended=!0;for(let e of this.watches.values())e.stop();this.watches.clear(),this.apiLeases.clear(),this.leaseCount=0,this.rerun.clear(),this.states.clear(),this.inflight.clear(),this.selections.clear(),this.scrolls.clear(),this.subscriptions.clear()}},W=256,G=2097152,K=e=>structuredClone(d(e)),he=class{backend;transport;memory=new Map;resets=new Map;constructor(e,t){this.backend=e,this.transport=t}forPlugin(e,t){let n=(t,n=`global`)=>{if(typeof n==`object`&&`session`in n&&!n.session.location)throw Error(`Unsupported GUI storage: session location is unknown`);let r=n===`global`?n:`session`in n?[n.session.server.id,n.session.id,n.session.location]:[n.server,n.directory];return`yuri.gui-plugin.${JSON.stringify([this.transport,e,r,t])}`},r=e=>{if(t.aborted)throw Error(`GUI plugin has been disposed`);if(e!==void 0)throw Error(`Unsupported GUI storage migration: from`)},i=new Map;return{store:(e,a)=>{r(a.from);let o=n(e,a.scope),s=i.get(o);if(s)return s;if(i.size>=W)throw Error(`GUI plugin store limit exceeded`);let l=j(a.schema),u=M(a.schema),d=l(u(K(a.initial)));if(JSON.stringify(u(d)).length>G)throw Error(`GUI plugin store exceeds 2 MiB`);let f=d,p=this.backend.getItem(o);if(p!==null&&p.length<=G)try{f=l(JSON.parse(p))}catch{f=d}let[m,h]=c(f),g=e=>{r();let t=JSON.stringify(u(K(e)));if(t.length>G)throw Error(`GUI plugin store exceeds 2 MiB`);let n=l(JSON.parse(t));this.backend.setItem(o,t),h(()=>n)},_={get value(){return m()},ready:()=>!0,set:g,update:e=>{let t=K(m());if(e(t)!==void 0)throw Error(`Store update must not return a replacement`);g(t)}},v=()=>h(()=>K(d)),y=this.resets.get(o)??new Set;return y.add(v),this.resets.set(o,y),t.addEventListener(`abort`,()=>{y.delete(v),y.size||this.resets.delete(o),i.clear()},{once:!0}),i.set(o,_),_},memory:(e,t)=>{r();let i=n(e),a=this.memory.get(i);if(a)return[a[0],e=>{r(),a[1](e)}];if(this.memory.size>=W)throw Error(`GUI plugin memory store limit exceeded`);if(JSON.stringify(t.initial).length>G)throw Error(`GUI plugin memory exceeds 2 MiB`);let[o,s]=u(K(t.initial)),c=[o,e=>{r();let t=K(d(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>G)throw Error(`GUI plugin memory exceeds 2 MiB`);s(m(t))}];return this.memory.set(i,[o,e=>{let t=K(d(o));if(e(t)!==void 0)throw Error(`Memory update must not return a replacement`);if(JSON.stringify(t).length>G)throw Error(`GUI plugin memory exceeds 2 MiB`);s(m(t))}]),c},remove:(e,t)=>{r(t?.from);let i=n(e,t?.scope);this.backend.removeItem(i);for(let e of this.resets.get(i)??[])e()}}}dispose(){this.memory.clear(),this.resets.clear()}},ge=`yuri.file-icon`,q=`http://www.w3.org/2000/svg`,_e=new Set([`svg`,`g`,`path`,`rect`,`circle`,`ellipse`,`line`,`polyline`,`polygon`,`defs`,`linearGradient`,`radialGradient`,`stop`,`clipPath`,`mask`,`use`,`title`,`desc`]),J=e=>e.trim().replace(/^\./,``).toLowerCase();function Y(e,t){if(typeof e!=`string`)throw Error(`GUI file icon requires SVG text`);let n=t.get(e);if(n)return n;if(e.length>16384)throw Error(`GUI file icon SVG exceeds 16 KiB`);let r=new TextEncoder().encode(e).byteLength;if(r>16384)throw Error(`GUI file icon SVG exceeds 16 KiB`);if(!/^\s*<svg[\s>]/.test(e)||/<!|<\?/.test(e))throw Error(`Invalid GUI file icon SVG`);let i=new DOMParser().parseFromString(e,`image/svg+xml`),a=i.documentElement;if(a?.localName!==`svg`||a.namespaceURI!==q||i.querySelector(`parsererror`))throw Error(`Invalid GUI file icon SVG`);for(let e of[a,...a.querySelectorAll(`*`)]){if(e.namespaceURI!==q||!_e.has(e.localName))throw Error(`Unsupported GUI file icon SVG element`);for(let t of e.attributes){let e=t.name.toLowerCase(),n=t.value.trim();if(e.startsWith(`on`)||e===`style`||e===`xml:base`||n.includes(`\\`)||Array.from(n).some(e=>e.charCodeAt(0)<32)||(e===`href`||e.endsWith(`:href`))&&!/^#[\w.-]+$/.test(n)||/url\s*\(/i.test(n)&&!/^url\(\s*#[\w.-]+\s*\)$/.test(n))throw Error(`Unsupported GUI file icon SVG reference or attribute`)}}let o={source:e,bytes:r,uri:`data:image/svg+xml,${encodeURIComponent(e)}`};return t.set(e,o),o}var ve=class{plugins=new Map;index=new Map;listeners=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});get(e,t){if(t?.isDirectory)return;let n=e.split(/[\\/]/).at(-1)??``,r=t?.extension??(n.includes(`.`)?n.slice(n.lastIndexOf(`.`)+1):``),i=this.index.get(J(r));return t?.themeVariant===`light`?i?.light.uri:i?.dark.uri}replace(e,t){if(t.length>64)throw Error(`GUI file icon per-plugin limit exceeded`);if(!t.length){this.remove(e);return}let n=new Map;for(let t of this.plugins.get(e)??[])for(let e of[t.dark,t.light])n.set(e.source,e);let r=new Set,i=t.map(e=>{if(!e||typeof e!=`object`||!(`id`in e)||typeof e.id!=`string`||!e.id.trim()||e.id.length>128||r.has(e.id))throw Error(`Invalid or duplicate GUI file icon id`);if(r.add(e.id),!(`extensions`in e)||!Array.isArray(e.extensions)||!e.extensions.length||e.extensions.length>64)throw Error(`GUI file icon requires 1–64 extensions`);let t=e.extensions.map(e=>{if(typeof e!=`string`)throw Error(`Invalid GUI file icon extension`);let t=J(e);if(!/^[a-z0-9][a-z0-9_+-]{0,63}$/.test(t))throw Error(`Invalid GUI file icon extension`);return t}),i=Y(`svg`in e?e.svg:void 0,n),a=`lightSvg`in e&&e.lightSvg!==void 0?Y(e.lightSvg,n):i;return{id:e.id,extensions:[...new Set(t)],dark:i,light:a}}),a=i.length,o=i.reduce((e,t)=>e+t.dark.bytes+t.light.bytes,0);for(let[t,n]of this.plugins)t!==e&&(a+=n.length,o+=n.reduce((e,t)=>e+t.dark.bytes+t.light.bytes,0));if(a>512||o>8388608)throw Error(`GUI file icon total limit exceeded`);this.plugins.set(e,i),this.publish()}remove(e){this.plugins.delete(e)&&this.publish()}dispose(){this.plugins.clear(),this.publish(),this.listeners.clear()}publish(){let e=new Map;for(let t of this.plugins.values())for(let n of t)for(let t of n.extensions)e.set(t,n);let t=e.size!==this.index.size||[...e].some(([e,t])=>{let n=this.index.get(e);return n?.dark.uri!==t.dark.uri||n?.light.uri!==t.light.uri});if(this.index=e,t)for(let e of this.listeners)e()}},X=e=>{throw Error(`Unsupported GUI host API: ${e}`)};function Z(e,t){return new Proxy(t,{get:(t,n)=>n in t?Reflect.get(t,n):X(`${e}.${String(n)}`)})}var Q=e=>Object.freeze(e.map(e=>Object.freeze(e)));function $(e,t){if(e){for(let n of e.owned??[])$(n,t);e.cleanups&&=e.cleanups.map(e=>()=>{try{Promise.resolve(e()).catch(t)}catch(e){t(e)}})}}var ye=class{options;fileIcons=new ve;instances=new Map;listeners=new Set;panelMounts=new Set;fileViews=new Map;changes=c(0);views=c(0);session=c();appearance;layouts=new Map;files;storage;ended=!1;contracts=new Map;snapshot=Object.freeze({plugins:Object.freeze([]),commands:Object.freeze([]),panels:Object.freeze([]),settings:Object.freeze([]),menuItems:Object.freeze([]),activePanel:null});screen;constructor(e){this.options=e,this.appearance=c({locale:e.locale,mode:e.mode,narrow:e.narrow}),this.storage=new he(e.storage,e.transport);let t=()=>(this.session[0](),this.files?.api??X(`screen.file without a session`));this.screen=Z(`screen`,{get file(){return t()}})}subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;changed(){this.changes[1](e=>e+1)}setSession(e){if(this.ended)return;let t=this.session[0]();if(t?.id===e?.id&&t?.directory===e?.directory)return;if(!e)for(let e of[...this.panelMounts])e();this.files?.dispose(),this.files=e?new me(this.options.files,this.options.queryClient,this.options.transport,e.directory):void 0;let n=Z(`session.server`,{id:this.options.transport,name:this.options.transport,client:this.options.client}),r=e?Object.freeze(Z(`session`,{id:e.id,directory:e.directory,key:`${this.options.transport}\n${e.id}`,tab:e.id,server:n,pending:!1,visit:{},location:{directory:e.directory}})):void 0;this.session[1](r),this.publish()}setAppearance(e){if(this.ended)return;let t=this.appearance[0]();(t.locale!==e.locale||t.mode!==e.mode||t.narrow!==e.narrow)&&this.appearance[1]({...e})}install(t,r){let o=this.instances.get(t);if(this.ended||o?.status===`active`&&o.revision===r.revision)return;o&&(this.instances.delete(t),this.release(o));let s={id:t,revision:r.revision,controller:new AbortController,status:`active`,cleanups:new Set,contributions:new Set,iconChanges:c(0),commands:[],panels:[],settings:[],menus:[]};this.instances.set(t,s);try{let t=R(r.code);y(o=>{s.dispose=o,s.root=a(),v(()=>b(D.Provider,{value:s.context=this.context(s,t,r.options),get children(){s.owner=a();let e=n(()=>t.setup(s.context));if(typeof e==`function`)s.cleanups.add(()=>{Promise.resolve(e()).catch(e=>{s.error=String(e)})});else if(e!==void 0)throw e&&typeof e==`object`&&`then`in e&&Promise.resolve(e).catch(()=>{}),Error(`GUI setup must be synchronous and return only cleanup`);return null}}),e=>this.fail(s,e)),s.controller.signal.aborted||i(s.owner,()=>e(()=>{if(s.iconChanges[0](),!s.controller.signal.aborted)try{let e=[...s.contributions].filter(e=>e.registry===ge).map(e=>e.read()).filter(e=>e!==void 0);this.fileIcons.replace(s.id,e)}catch(e){n(()=>this.fail(s,e))}})),s.controller.signal.aborted||i(s.owner,()=>e(()=>{this.changes[0](),this.session[0](),this.appearance[0]();try{this.derive(s)}catch(e){n(()=>this.fail(s,e))}n(()=>this.publish())}))})}catch(e){this.fail(s,e)}this.changed(),this.publish()}release(e){e.controller.abort();for(let t of[...e.cleanups])try{t()}catch(t){e.error??=String(t)}e.cleanups.clear(),$(e.root,t=>{e.error??=String(t)});try{e.dispose?.()}catch(t){e.error??=String(t)}e.contributions.clear(),e.commands=[],e.panels=[],e.settings=[],e.menus=[],this.fileIcons.remove(e.id);for(let t of this.contracts.values())t.provider===e&&(t.provider=void 0,t.live[1]({status:`inactive`,reason:e.status===`failed`?`failed`:`disabled`}))}fail(e,t){e.status!==`failed`&&this.instances.get(e.id)===e&&(e.status=`failed`,e.error=t instanceof Error?t.message:String(t),this.release(e),this.publish())}uninstall(e){let t=this.instances.get(e);if(t){this.instances.delete(e),this.release(t);for(let t of this.layouts.values())t.open=t.open.filter(t=>!t.startsWith(`${e}:`)),t.active?.startsWith(`${e}:`)&&(t.active=null);this.changed(),this.publish()}}dispose(){this.ended||(this.ended=!0,l(()=>{for(let e of[...this.instances.keys()])this.uninstall(e)}),this.files?.dispose(),this.fileIcons.dispose(),this.storage.dispose(),this.layouts.clear(),this.fileViews.clear(),this.contracts.clear(),this.listeners.clear())}own(e,t){let n=!0,i=()=>{n&&(n=!1,e.cleanups.delete(i),t())};return e.controller.signal.aborted||r(w)?.ended?(i(),i):(e.cleanups.add(i),a()&&f(i),i)}list(e){this.changes[0]();let t=[];for(let n of this.instances.values())if(n.status===`active`){for(let r of n.contributions)if(r.registry===e.id){let e=r.read();e!==void 0&&t.push(e)}}return t}context(t,i,o){let c=this.storage.forPlugin(t.id,t.controller.signal),l=Object.fromEntries(Object.entries(i.stores??{}).map(([e,t])=>[e,t.scope===`global`?c.store(e,{...t,scope:`global`}):n=>c.store(e,{...t,scope:{session:n}})])),u=(e,t)=>{let n=this.appearance[0]().locale;return(i.i18n?.[n]?.[e]??i.i18n?.[n.split(`-`)[0]]?.[e]??i.i18n?.en?.[e]??e).replace(/\{\{(\w+)\}\}/g,(e,n)=>String(t?.[n]??e))},d=Z(`layout`,{narrow:()=>this.appearance[0]().narrow,ready:()=>!!this.session[0](),open:(e,n,r)=>{t.controller.signal.aborted||this.openPanel(e,n,r)},close:(e,n)=>{t.controller.signal.aborted||this.closeFor(e,n)},toggle:(e,t)=>d.state(e,t)===`visible`?d.close(e,t):d.open(e,t),hide:(e,n)=>{if(t.controller.signal.aborted)return;let r=this.layout(n);r.active===e&&r.shown&&(r.shown=!1,this.changed())},state:(e,t)=>{this.changes[0]();let n=this.layout(t);return n.active===e?n.shown?`visible`:`active`:n.open.includes(e)?`open`:`closed`},stored:e=>(this.changes[0](),this.layout(e).open.filter(e=>e.startsWith(`${t.id}:`)).map(e=>e.slice(t.id.length+1))),side:{opened:e=>(this.changes[0](),this.layout(e).shown),toggle:e=>{if(t.controller.signal.aborted)return;let n=this.layout(e);n.shown=!n.shown,this.changed()},menu:()=>this.list(E).filter(e=>e.menu===`session.panel`).sort((e,t)=>(e.order??0)-(t.order??0))},scroll:{get:(e,t)=>(this.changes[0](),this.layout(e).scroll.get(t)),set:(e,n,r)=>{if(t.controller.signal.aborted)return;let i=this.layout(e).scroll;if(!i.has(n)&&i.size>=128)throw Error(`GUI layout scroll limit exceeded`);i.set(n,{...r}),this.changed()}}});return Z(`ctx`,{id:t.id,options:o,signal:t.controller.signal,client:this.options.client,storage:c,stores:l,app:{name:`yuri`,version:``,channel:`local`,platform:`web`,packaged:!1},desktop:void 0,t:u,plural:(e,t,n)=>{let r=`${e}.${new Intl.PluralRules(this.appearance[0]().locale).select(t)}`;return u(r,{...n,count:t})===r?u(`${e}.other`,{...n,count:t}):u(r,{...n,count:t})},add:(i,o)=>{if(t.controller.signal.aborted||r(w)?.ended)return()=>{};if([`server`,`titlebar-item`,`composer-pill`,`slot`,`file.viewer`,`menubar-item`].includes(i.id)&&X(`registry.${i.id}`),t.contributions.size>=256)throw Error(`GUI contribution limit exceeded`);let c=()=>{},l,u=y(t=>{c=t,l=a();let n=s(()=>typeof o==`function`?o():o);if(i.id===`style`){let t=document.createElement(`style`);document.head.append(t),f(()=>t.remove()),e(()=>{let e=n();t.textContent=e===void 0?``:String(e)})}return{registry:i.id,read:n}},a()??t.owner);t.contributions.add(u);let d=()=>{i.id===`yuri.file-icon`&&t.iconChanges[1](e=>e+1)};return n(d),n(()=>this.changed()),this.own(t,()=>{$(l,e=>{t.error??=String(e)}),c(),t.contributions.delete(u),n(d),n(()=>this.changed())})},list:e=>this.list(e),provide:(e,n)=>{if(t.controller.signal.aborted||r(w)?.ended)return()=>{};if(e.kind!==`contract`||!(e.id===t.id||e.id.startsWith(`${t.id}.`)))throw Error(`Contract must belong to the providing plugin`);let i=this.contract(e.id);if(i.provider)throw Error(`Contract already provided: ${e.id}`);return i.provider=t,i.live[1]({status:`active`,value:n,generation:++i.generation}),this.own(t,()=>{i.provider===t&&(i.provider=void 0,i.live[1]({status:`inactive`,reason:t.status===`failed`?`failed`:`disabled`}))})},use:e=>this.contract(e.id,e.kind===`ipc`).live[0],main:e=>{if(!(e.id===t.id||e.id.startsWith(`${t.id}.`)))throw Error(`IPC must belong to the plugin`);return new Proxy({state:()=>void 0},{get:(e,t)=>t===`state`?e.state:t===`on`?()=>X(`native IPC events`):()=>Promise.reject(Error(`Unsupported GUI host API: native IPC`))})},sessions:{current:this.session[0],list:()=>{let e=this.session[0]();return e?[e]:[]}},screen:{current:()=>this.session[0]()?this.screen:void 0},layout:d,appearance:{mode:()=>this.appearance[0]().mode,font:()=>getComputedStyle(document.documentElement).getPropertyValue(`--font-mono`).trim()||`monospace`},locale:{locale:()=>this.appearance[0]().locale,direction:()=>/^(ar|fa|he|ur)(-|$)/i.test(this.appearance[0]().locale)?`rtl`:`ltr`},system:{copy:e=>navigator.clipboard.writeText(e),openExternal:e=>{let t=new URL(e);[`https:`,`http:`,`mailto:`].includes(t.protocol)||X(`system.openExternal protocol`),window.open(e,`_blank`,`noopener,noreferrer`)},save:async e=>{let t=URL.createObjectURL(new Blob([e.content],{type:`text/plain`}));try{let n=document.createElement(`a`);return n.href=t,n.download=e.name,n.click(),!0}finally{setTimeout(()=>URL.revokeObjectURL(t),0)}}},commands:{run:e=>t.controller.signal.aborted||!this.command(e)?!1:(this.runCommand(e),!0)},links:{open:e=>!t.controller.signal.aborted&&this.navigateLink(t,e),exists:e=>n(()=>{if(t.controller.signal.aborted)return!1;let n=this.linkHandler(e);try{return Promise.resolve(n?.value.exists?.(e)??!1).catch(()=>!1)}catch{return!1}})}})}contract(e,t=!1){let n=this.contracts.get(e);if(!n){if(this.contracts.size>=256)throw Error(`GUI contract limit exceeded`);let t=c({status:`inactive`,reason:`disabled`});n={live:[le(t[0]),t[1]],generation:0},this.contracts.set(e,n)}return t&&n.provider&&X(`IPC contract collision`),n}derive(e){if(e.status!==`active`)return;let t=[],r=[],i=[],a=[],o=this.session[0]();for(let n of e.contributions){if(n.registry===`yuri.file-icon`)continue;let s=n.read();if(s!==void 0){if(n.registry===pe.id){let n=s;n.enabled!==!1&&t.push({key:`${e.id}.${n.id}`,title:n.title,description:n.description,bind:n.bind,hidden:n.hidden,run:()=>this.invoke(e,()=>n.run())})}else if(n.registry===A.id&&o){let t=s,n=`${e.id}:`,i=this.layout(o).open.filter(e=>e.startsWith(n)).map(e=>e.slice(n.length));for(let n of t.list({session:o,screen:this.screen,open:i}))r.push({plugin:e,panel:t,tab:n})}else if(n.registry===C.id){let e=s;(e.page||e.section)&&X(`SettingsPage host sections`),e.title,i.push(e)}else if(n.registry===E.id){let e=s;e.menu===`session.panel`?(e.title,a.push(e)):X(`MenuItem.${e.menu}`)}}}for(let e of r)e.tab.title;e.commands=t,e.panels=r,e.settings=i,e.menus=a,n(()=>this.views[1](e=>e+1))}publish(){let e=n(this.session[0]),t=e?this.layouts.get(e.key):void 0,r=[...this.instances.values()],i=r.filter(e=>e.status===`active`),a=i.flatMap(e=>e.panels.map(({tab:n})=>{let r=n.file?this.filePath(n.file):void 0;return{key:`${e.id}:${n.id}`,pluginId:e.id,title:n.title,file:r,inline:!!(r&&this.fileViews.has(r)),active:t?.shown===!0&&t.active===`${e.id}:${n.id}`}}));this.snapshot=Object.freeze({plugins:Q(r.map(({id:e,revision:t,status:n,error:r})=>({id:e,revision:t,status:n,error:r}))),commands:Q(i.flatMap(e=>e.commands.filter(e=>!e.hidden))),panels:Q(a),settings:Q(i.flatMap(e=>e.settings.map(t=>({key:`${e.id}:${t.id}`,pluginId:e.id,title:t.title})))),menuItems:Q(i.flatMap(e=>e.menus.map(t=>({key:`${e.id}:${t.id}`,title:t.title,description:t.description,run:()=>{this.invoke(e,()=>t.run())}})))),activePanel:t?.shown&&a.some(e=>e.key===t.active)?t.active:null,sessionKey:e?.key});for(let e of this.listeners)e()}invoke(e,t){if(!e.controller.signal.aborted)try{let n=i(e.owner??null,t);if(n instanceof Promise)return n.catch(t=>this.fail(e,t))}catch(t){this.fail(e,t)}}command(e){return[...this.instances.values()].flatMap(e=>e.commands).find(t=>t.key===e)}runCommand(e){return this.command(e)?.run()}linkHandler(e){let t=[];for(let e of this.instances.values())for(let n of e.contributions)if(n.registry===ce.id){let r=n.read();r&&t.push({instance:e,value:r})}for(let n of t.sort((e,t)=>(t.value.priority??0)-(e.value.priority??0)))try{if(n.value.match(e))return n}catch(e){this.fail(n.instance,e)}}navigateLink(e,t){if(this.ended)return!1;let n=ie(t.href);if(!n||!re(n.path))return this.openLink(t);let r=this.session[0]();if(!r||t.session&&(t.session.key!==r.key||t.session.server.id!==r.server.id))return!1;if(!this.options.focusFile)return this.openLink(t);let i=te(t.base??r.directory,n.path),a=n.line===void 0?``:`:${n.line}${n.column===void 0?``:`:${n.column}`}`;return this.invoke(e,()=>this.options.focusFile(i+a,r.directory)),!0}openLink(e){if(this.ended)return!1;let t={...e,session:e.session??this.session[0]()},n=this.linkHandler(t);return n?(this.invoke(n.instance,()=>n.value.open(t)),!0):!1}filePath(e,t=this.session[0]()?.directory){let n=z(e);return/^(?:\/|[a-z]:\/)/i.test(n)||!t?n:z(`${t}/${n}`)}registerFileView(e,t){if(this.ended)return()=>{};let n=this.filePath(e,t),r=this.fileViews.get(n)??0;this.fileViews.set(n,r+1),r===0&&(this.changed(),this.publish());let i=!1;return()=>{if(i||this.ended)return;i=!0;let e=(this.fileViews.get(n)??1)-1;if(e){this.fileViews.set(n,e);return}{let e=this.session[0](),t=e&&this.layouts.get(e.key);t?.active&&this.snapshot.panels.some(e=>e.key===t.active&&e.file===n)&&(t.shown=!1),this.fileViews.delete(n)}this.changed(),this.publish()}}filePanel(e,t){let n=this.filePath(e,t);return this.snapshot.panels.find(e=>e.file===n&&e.inline)}panelVisible(e){let t=this.session[0]();if(!t)return!1;let n=this.panel(e)?.tab.file;if(n&&this.fileViews.has(this.filePath(n)))return!0;let r=this.layouts.get(t.key);return!!(r?.shown&&r.active===e)}layout(e){let t=this.layouts.get(e.key);if(!t){if(this.layouts.size>=128)throw Error(`GUI session layout limit exceeded`);t={open:[],active:null,shown:!1,scroll:new Map},this.layouts.set(e.key,t)}return t}openPanel(e,t,n){if(this.ended)return;let r=this.layout(t),i=r.active,a=r.shown,o=r.open.length;if(!r.open.includes(e)){if(r.open.length>=64)throw Error(`GUI panel tab limit exceeded`);r.open=[...r.open,e]}n?.tab!==`append`&&(r.active=e,r.shown=!(this.appearance[0]().narrow&&n?.background)),(i!==r.active||a!==r.shown||o!==r.open.length)&&(this.changed(),this.publish());let s=this.panel(e);t.key===this.session[0]()?.key&&s&&n?.tab!==`append`&&this.invoke(s.plugin,()=>s.panel.focus?.({...this.props(e),restored:!1}))}selectPanel(e){let t=this.session[0]();t&&this.openPanel(e,t)}closeFor(e,t){let n=this.layout(t),r=t.key===this.session[0]()?.key?this.panel(e):void 0;if(!n.open.includes(e)||r?.tab.pinned||r?.tab.closable===!1)return;let i=this.session[0](),a=r&&i?{tab:r.tab,session:i,screen:this.screen}:void 0;n.open=n.open.filter(t=>t!==e),n.active===e&&(n.active=n.open.at(-1)??null),this.changed(),this.publish(),r&&a&&this.invoke(r.plugin,()=>r.panel.close?.(a))}closePanel(e){let t=this.session[0]();t&&this.closeFor(e,t)}hidePanel(){let e=this.session[0]();if(!e)return;let t=this.layout(e);t.shown&&(t.shown=!1,this.changed(),this.publish())}panel(e){return[...this.instances.values()].flatMap(e=>e.panels).find(t=>`${t.plugin.id}:${t.tab.id}`===e)}props(e){let t=this.panel(e)?.tab,n=()=>(this.views[0](),this.panel(e)?.tab??t??X(`panel no longer listed`)),r=()=>this.session[0]()??X(`panel without session`);return{get tab(){return n()},get session(){return r()},screen:this.screen}}mountPanel(t,r){let i=this.panel(t);if(!i)return()=>{};let a=()=>{let r=s(()=>{this.session[0](),this.changes[0](),this.views[0]();let e=this.panel(t)?.tab.file;return e&&this.files&&this.panelVisible(t)?{model:this.files,file:e}:void 0},void 0,{equals:(e,t)=>e?.model===t?.model&&e?.file===t?.file});return e(()=>{let e=r();e&&(f(e.model.watch(e.file)),e.model.sync(e.file).catch(()=>{}))}),n(()=>i.panel.render(this.props(t)))},o=this.mount(i.plugin,r,()=>b(de.Provider,{value:{visible:()=>(this.changes[0](),this.panelVisible(t)),present:()=>(this.changes[0](),this.panelVisible(t)),placement:()=>this.appearance[0]().narrow?`mobile`:`side`,reserve:()=>!1,animate:()=>!1,sidebar:Z(`panel.sidebar`,{}),open:()=>{let e=this.session[0]();return e?i.plugin.context.layout.stored(e):[]}},get children(){return a()}})),c=()=>{this.panelMounts.delete(c),o()};return this.panelMounts.add(c),this.own(i.plugin,c)}mountSettings(e,t){for(let n of this.instances.values()){let r=n.settings.find(t=>`${n.id}:${t.id}`===e);if(r)return this.mount(n,t,()=>r.render({}))}return()=>{}}mount(e,t,r){if(e.controller.signal.aborted)return()=>{};let i=()=>{},o,s=t=>{queueMicrotask(()=>this.fail(e,t))};try{i=oe(()=>b(D.Provider,{value:e.context,get children(){return o=a(),v(()=>n(r),s)}}),t)}catch(t){this.fail(e,t)}return this.own(e,()=>{$(o,t=>{e.error??=String(t)}),i(),t.replaceChildren()})}};export{ye as GuiPluginHost};