@tano.page/workbench 0.15.0 → 0.16.0

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 (118) hide show
  1. package/package.json +35 -14
  2. package/src/App.vue +68 -797
  3. package/src/assistant/agent-identities.ts +1 -97
  4. package/src/assistant/agent-task-context.ts +1 -54
  5. package/src/assistant/attachments.ts +1 -1
  6. package/src/assistant/completion.ts +1 -61
  7. package/src/assistant/components/AssistantPanel.vue +1 -1
  8. package/src/assistant/connection-actions.ts +237 -0
  9. package/src/assistant/document-mentions.ts +1 -33
  10. package/src/assistant/engine.ts +1 -585
  11. package/src/assistant/execution.ts +6 -33
  12. package/src/assistant/hash.ts +1 -4
  13. package/src/assistant/language.ts +10 -37
  14. package/src/assistant/plugin-bridge-builder.ts +146 -0
  15. package/src/assistant/prompts.ts +1 -65
  16. package/src/assistant/proposal-actions.ts +336 -0
  17. package/src/assistant/store.ts +87 -554
  18. package/src/assistant/structures.ts +1 -157
  19. package/src/assistant/tasks.ts +8 -94
  20. package/src/assistant/tool-rules.ts +1 -7
  21. package/src/composables/use-workbench-help.ts +177 -0
  22. package/src/composables/use-workbench-lifecycle.ts +249 -0
  23. package/src/composables/use-workbench-settings.ts +185 -0
  24. package/src/composables/use-workbench-shortcuts.ts +37 -1022
  25. package/src/composables/use-workbench-views.ts +325 -0
  26. package/src/documents/components/DocumentActionMenu.vue +279 -0
  27. package/src/documents/components/DocumentInspector.vue +168 -0
  28. package/src/documents/components/DocumentPane.vue +482 -0
  29. package/src/documents/description-merge.ts +1 -9
  30. package/src/files/components/FileMetadataPanel.vue +49 -15
  31. package/src/i18n/locale-catalogs.ts +7 -6
  32. package/src/i18n/locale-registry.ts +8 -6
  33. package/src/i18n/locales/de-DE.json +23 -1
  34. package/src/i18n/locales/en-US.json +23 -1
  35. package/src/i18n/locales/es-ES.json +23 -1
  36. package/src/i18n/locales/ja-JP.json +23 -1
  37. package/src/i18n/locales/zh-TW.json +23 -1
  38. package/src/mail/components/MailAccountDialog.vue +1 -0
  39. package/src/mail/components/MailComposerDialog.vue +1 -0
  40. package/src/mail/components/MailWorkspaceView.vue +1 -0
  41. package/src/mail/components/SidebarMail.vue +1 -0
  42. package/src/objects/content-references.ts +6 -56
  43. package/src/objects/wiki-links.ts +1 -48
  44. package/src/objects/workspace-objects.ts +2 -3
  45. package/src/plans/calendar.ts +2 -2
  46. package/src/plans/components/CalendarAgendaView.vue +165 -0
  47. package/src/plans/components/CalendarFilterBar.vue +128 -0
  48. package/src/plans/components/CalendarMonthView.vue +224 -0
  49. package/src/plans/components/CalendarQuickCreateDialog.vue +269 -0
  50. package/src/plans/components/CalendarTimelineView.vue +517 -0
  51. package/src/plans/components/CalendarTopbarControls.vue +101 -0
  52. package/src/plans/components/CalendarView.vue +162 -2106
  53. package/src/plans/components/CalendarYearView.vue +138 -0
  54. package/src/plans/components/PlanConnectionsDialog.vue +1 -1
  55. package/src/plans/components/calendar-shared.css +192 -0
  56. package/src/plans/composables/use-calendar-interactions.ts +396 -0
  57. package/src/plans/composables/use-calendar-scroll.ts +420 -0
  58. package/src/plugins/components/PluginDetailPage.vue +10 -6
  59. package/src/plugins/components/PluginDeveloperArea.vue +192 -0
  60. package/src/plugins/components/PluginExplorer.vue +6 -4
  61. package/src/plugins/components/PluginImportDialog.vue +1 -1
  62. package/src/plugins/components/PluginInstaller.vue +269 -178
  63. package/src/plugins/components/PluginMaintenance.vue +37 -49
  64. package/src/plugins/components/PluginRepositoryStorage.vue +4 -2
  65. package/src/plugins/components/PluginSettingsForm.vue +2 -1
  66. package/src/plugins/components/PluginsTabPage.vue +61 -0
  67. package/src/plugins/components/plugin-center.css +5 -0
  68. package/src/plugins/data.ts +9 -86
  69. package/src/plugins/editor-plugin-adapters.ts +169 -0
  70. package/src/plugins/plugin-data.ts +2 -3
  71. package/src/plugins/plugin-rpc-router.ts +558 -0
  72. package/src/plugins/plugin-sdk.ts +1 -260
  73. package/src/plugins/plugin-ui-dialogs.ts +167 -0
  74. package/src/plugins/queries.ts +1 -75
  75. package/src/plugins/view-header.ts +2 -7
  76. package/src/runtime.ts +3 -2
  77. package/src/settings/components/SettingsPanel.vue +8 -3
  78. package/src/settings/components/WorkbenchSettings.vue +20 -7
  79. package/src/settings/components/settings-context.ts +1 -1
  80. package/src/settings/settings-tab.ts +1 -0
  81. package/src/shell/command-palette.ts +3 -3
  82. package/src/shell/components/EditorToolbar.vue +8 -9
  83. package/src/shell/components/EditorTools.vue +1 -5
  84. package/src/shell/components/PaneTopbar.vue +393 -0
  85. package/src/shell/components/SelectionToolbar.vue +0 -2
  86. package/src/shell/components/WorkbenchContextMenus.vue +37 -26
  87. package/src/shell/components/WorkbenchModals.vue +22 -18
  88. package/src/shell/components/WorkbenchPanes.vue +358 -1512
  89. package/src/shell/components/WorkbenchSidebar.vue +486 -0
  90. package/src/shell/pane-registry.ts +69 -0
  91. package/src/shell/use-surface-dismissal.ts +219 -0
  92. package/src/shell/use-workbench-commands.ts +599 -0
  93. package/src/shell/use-workbench-keybindings.ts +337 -0
  94. package/src/shell/use-workbench.ts +488 -1081
  95. package/src/shell/workbench-context.ts +30 -3
  96. package/src/stores/workspace-document-io.ts +807 -0
  97. package/src/stores/workspace-file-ops.ts +1 -1
  98. package/src/stores/workspace-knowledge.ts +1 -1
  99. package/src/stores/workspace-lifecycle.ts +459 -0
  100. package/src/stores/workspace-plugins-state.ts +71 -599
  101. package/src/stores/workspace-session.ts +287 -0
  102. package/src/stores/workspace-tabs-layout.ts +1 -1
  103. package/src/stores/workspace-types.ts +50 -0
  104. package/src/stores/workspace.ts +163 -1345
  105. package/src/styles.css +0 -1
  106. package/src/tabs/components/DesktopTabs.vue +19 -11
  107. package/src/windows/AuxiliaryWindows.vue +2 -2
  108. package/src/windows/use-window-event-bridge.ts +152 -0
  109. package/src/workspace/components/TemplateLibrary.vue +1 -1
  110. package/src/workspace/components/WorkspaceIconPicker.vue +5 -4
  111. package/src/workspace/components/WorkspacePickerMenu.vue +317 -0
  112. package/src/assistant/locales/de-DE.json +0 -129
  113. package/src/assistant/locales/en-US.json +0 -129
  114. package/src/assistant/locales/es-ES.json +0 -129
  115. package/src/assistant/locales/ja-JP.json +0 -129
  116. package/src/assistant/locales/zh-CN.json +0 -129
  117. package/src/assistant/locales/zh-TW.json +0 -129
  118. package/src/assistant/task-prompts.json +0 -39
@@ -1,29 +1,15 @@
1
1
  import { computed, onScopeDispose, ref, shallowRef, watch, type Ref } from 'vue';
2
2
  import type { WorkspaceCapabilities } from '@tano/editor/runtime';
3
- import { mergeMarkdown } from '@tano/markdown';
4
3
  import {
5
4
  FileRegistry,
6
5
  isMarkdown,
7
6
  isWorkspaceInternalPath,
8
- matchesPluginPathScopes,
9
- objectDirectory,
10
- parseObject,
11
- parsePluginAttachmentWrite,
12
7
  parsePluginConnectionInput,
13
- pluginRecord,
14
- referenceKey,
15
- validateObjectProperties,
16
- validatePath,
17
- validateRelation,
18
8
  type FileEntry,
19
9
  type FileSnapshot,
20
10
  type PluginConnectionInput,
21
11
  type PluginHostEnvironment,
22
12
  type PluginOAuthInput,
23
- type PluginUiConfirmOptions,
24
- type PluginUiPickOptions,
25
- type PluginUiPromptOptions,
26
- type PluginUiTone,
27
13
  type ReferenceTarget,
28
14
  type RelationTypeDefinition,
29
15
  type Workspace,
@@ -32,24 +18,25 @@ import {
32
18
  type WorkspaceRelation,
33
19
  } from '@tano/protocol';
34
20
  import workbenchPackage from '../../package.json';
35
- import { assistantHash } from '../assistant/hash';
36
- import { nativeAttachments } from '../files/attachments';
37
21
  import type { useDocumentIndex } from '../documents/document-index';
38
- import { documentDirty as dirty, type OpenDocument } from '../documents/document-session';
22
+ import type { OpenDocument } from '../documents/document-session';
39
23
  import { t } from '../i18n/i18n';
40
24
  import { PluginAttachmentReader } from '../plugins/attachment-reader';
41
25
  import { listActivePluginContextProviders } from '../plugins/assistant-bridge';
42
- import type {
43
- PluginAiCompleteRequest,
44
- PluginAiCompleteResult,
45
- PluginAiStructuredRequest,
46
- PluginAiStructuredResult,
47
- } from '@tano/protocol';
48
26
  import { PluginQueryPager, pluginChanges } from '../plugins/data';
49
27
  import type { PluginDevelopmentState } from '../plugins/development';
50
28
  import type { PluginRuntimeState } from '../plugins/host';
51
29
  import { canManageWorkspacePlugins } from '../plugins/policy';
52
- import { queryPluginData } from '../plugins/queries';
30
+ import {
31
+ dispatchPluginRpcCall,
32
+ type PluginAiRunner,
33
+ type PluginEditorBridge,
34
+ } from '../plugins/plugin-rpc-router';
35
+ import {
36
+ createPluginUiDialogs,
37
+ type PluginUiDialogRequest,
38
+ type PluginUiToastItem,
39
+ } from '../plugins/plugin-ui-dialogs';
53
40
  import {
54
41
  pluginViewKey,
55
42
  pluginWorkbenchCodeBlockRenderers,
@@ -62,54 +49,11 @@ import {
62
49
  type PluginInteraction,
63
50
  } from '../plugins/workbench';
64
51
  import { resolveOverlayExtension, type WorkbenchOverlaySnapshot, type WorkbenchRuntime } from '../runtime';
65
- import { mergeObject, saveObject, type ObjectRecord } from '../objects/workspace-objects';
52
+ import type { ObjectRecord } from '../objects/workspace-objects';
66
53
  import { WorkspacePluginRuntime } from '../plugins/workspace-plugin-runtime';
67
54
  import { PLUGINS_TAB_ID, type InstalledObjectPlugin } from '../plugins/workspace-plugins';
68
- import { saveRelationChange } from '../objects/workspace-relations';
69
-
70
- export type PluginUiDialogRequest =
71
- | {
72
- id: string;
73
- kind: 'pick';
74
- pluginId: string;
75
- pluginName: string;
76
- options: PluginUiPickOptions;
77
- }
78
- | {
79
- id: string;
80
- kind: 'prompt';
81
- pluginId: string;
82
- pluginName: string;
83
- options: PluginUiPromptOptions;
84
- }
85
- | {
86
- id: string;
87
- kind: 'confirm';
88
- pluginId: string;
89
- pluginName: string;
90
- options: PluginUiConfirmOptions;
91
- };
92
55
 
93
- export interface PluginUiToastItem {
94
- id: string;
95
- pluginId: string;
96
- pluginName: string;
97
- message: string;
98
- tone: PluginUiTone;
99
- }
100
-
101
- export interface PluginEditorBridge {
102
- applyEdit(id: string, before: string, after: string): Promise<boolean>;
103
- activeEditor?(): {
104
- fileId: string;
105
- mode: 'rich' | 'source';
106
- readOnly: boolean;
107
- selection: { from: number; to: number; empty: boolean };
108
- selectedText: string;
109
- blockType?: string;
110
- } | null;
111
- applySelectionEdit?(id: string, text: string, mode: 'insert' | 'replace'): Promise<boolean>;
112
- }
56
+ export type { PluginUiDialogRequest, PluginUiToastItem, PluginEditorBridge };
113
57
 
114
58
  export interface WorkspacePluginsStateDeps {
115
59
  adapter: WorkspaceAdapter;
@@ -170,6 +114,7 @@ export function createWorkspacePluginsState(deps: WorkspacePluginsStateDeps) {
170
114
 
171
115
  const pluginAttachmentReader = new PluginAttachmentReader();
172
116
  let pluginEditorBridge: PluginEditorBridge | undefined;
117
+ let pluginAiRunner: PluginAiRunner | undefined;
173
118
  const pluginRuntime = shallowRef<PluginRuntimeState[]>([]);
174
119
  watch(
175
120
  [
@@ -201,14 +146,6 @@ export function createWorkspacePluginsState(deps: WorkspacePluginsStateDeps) {
201
146
  const overlaySnapshot = computed<WorkbenchOverlaySnapshot>(
202
147
  () => overlayExtension()?.snapshot ?? { safeMode: false },
203
148
  );
204
- type PluginAiRunner = (options: {
205
- pluginId: string;
206
- pluginName: string;
207
- structured: boolean;
208
- request: PluginAiCompleteRequest | PluginAiStructuredRequest;
209
- signal: AbortSignal;
210
- }) => Promise<PluginAiCompleteResult | PluginAiStructuredResult>;
211
- let pluginAiRunner: PluginAiRunner | undefined;
212
149
  const pluginDevelopment = shallowRef<PluginDevelopmentState>({
213
150
  pluginId: '',
214
151
  active: false,
@@ -224,6 +161,59 @@ export function createWorkspacePluginsState(deps: WorkspacePluginsStateDeps) {
224
161
  ? 'desktop-online'
225
162
  : 'web',
226
163
  };
164
+
165
+ const uiDialogs = createPluginUiDialogs();
166
+ const {
167
+ activePluginDialog,
168
+ pluginToasts,
169
+ cancelActivePluginDialog,
170
+ resolvePluginDialog,
171
+ dismissPluginToast,
172
+ clearPluginToasts,
173
+ showPluginToast,
174
+ openPluginDialog,
175
+ } = uiDialogs;
176
+
177
+ const pluginCall = (
178
+ method: string,
179
+ params: Record<string, unknown>,
180
+ assertInstance: () => void,
181
+ ) =>
182
+ dispatchPluginRpcCall(
183
+ {
184
+ adapter,
185
+ runtime,
186
+ workspace,
187
+ fileRegistry,
188
+ documents,
189
+ documentIndex,
190
+ capabilities,
191
+ objects,
192
+ relations,
193
+ relationError,
194
+ getRelationBase,
195
+ relationDefinitions,
196
+ referenceTargets,
197
+ pluginAttachmentReader,
198
+ pluginQueryPager,
199
+ getPluginEditorBridge: () => pluginEditorBridge,
200
+ getPluginAiRunner: () => pluginAiRunner,
201
+ openPluginDialog,
202
+ showPluginToast,
203
+ openPluginView,
204
+ serial,
205
+ writable,
206
+ refreshObjects,
207
+ openInternal,
208
+ saveInternal,
209
+ ensureTabNavigation,
210
+ touchNavigation,
211
+ },
212
+ method,
213
+ params,
214
+ assertInstance,
215
+ );
216
+
227
217
  const pluginServices = new WorkspacePluginRuntime({
228
218
  adapter,
229
219
  services: {
@@ -264,109 +254,6 @@ export function createWorkspacePluginsState(deps: WorkspacePluginsStateDeps) {
264
254
  pluginWorkbenchDecorations(pluginRuntime.value, fileId);
265
255
  const pluginStatusBarItems = computed(() => pluginWorkbenchStatusBarItems(pluginRuntime.value));
266
256
  const activeDocumentPluginSidebar = ref('');
267
- const activePluginDialog = shallowRef<PluginUiDialogRequest | null>(null);
268
- const pluginToasts = shallowRef<PluginUiToastItem[]>([]);
269
- const toastTimers = new Map<string, ReturnType<typeof setTimeout>>();
270
- let activeDialogControl: {
271
- id: string;
272
- resolve: (value: string | boolean | null) => void;
273
- reject: (error: Error) => void;
274
- cleanup: () => void;
275
- } | null = null;
276
- function cancelActivePluginDialog(reason = '插件交互已取消') {
277
- const current = activeDialogControl;
278
- if (!current) return;
279
- activeDialogControl = null;
280
- activePluginDialog.value = null;
281
- current.cleanup();
282
- current.reject(new Error(reason));
283
- }
284
- function resolvePluginDialog(id: string, value: string | boolean | null) {
285
- const current = activeDialogControl;
286
- if (!current || current.id !== id) return;
287
- activeDialogControl = null;
288
- activePluginDialog.value = null;
289
- current.cleanup();
290
- current.resolve(value);
291
- }
292
- function dismissPluginToast(id: string) {
293
- const timer = toastTimers.get(id);
294
- if (timer) {
295
- clearTimeout(timer);
296
- toastTimers.delete(id);
297
- }
298
- pluginToasts.value = pluginToasts.value.filter((item) => item.id !== id);
299
- }
300
- function showPluginToast(params: Record<string, unknown>) {
301
- const id = crypto.randomUUID();
302
- const item: PluginUiToastItem = {
303
- id,
304
- pluginId: String(params.pluginId ?? ''),
305
- pluginName: String(params.pluginName ?? ''),
306
- message: String(params.message ?? ''),
307
- tone: (params.tone as PluginUiTone | undefined) ?? 'info',
308
- };
309
- const next = [...pluginToasts.value, item];
310
- while (next.length > 3) {
311
- const removed = next.shift();
312
- if (removed) {
313
- const timer = toastTimers.get(removed.id);
314
- if (timer) {
315
- clearTimeout(timer);
316
- toastTimers.delete(removed.id);
317
- }
318
- }
319
- }
320
- pluginToasts.value = next;
321
- toastTimers.set(
322
- id,
323
- setTimeout(() => dismissPluginToast(id), 4500),
324
- );
325
- }
326
- function openPluginDialog(
327
- method: 'ui.pick' | 'ui.prompt' | 'ui.confirm',
328
- params: Record<string, unknown>,
329
- ): Promise<string | boolean | null> {
330
- if (activeDialogControl) {
331
- return Promise.reject(new Error('当前已有插件交互弹窗正在等待响应,请稍后重试'));
332
- }
333
- const id = crypto.randomUUID();
334
- const signal = params.signal instanceof AbortSignal ? params.signal : undefined;
335
- if (signal?.aborted) return Promise.reject(new Error('插件已停止'));
336
- return new Promise<string | boolean | null>((resolve, reject) => {
337
- const onAbort = () => cancelActivePluginDialog('插件已停止');
338
- signal?.addEventListener('abort', onAbort, { once: true });
339
- const cleanup = () => signal?.removeEventListener('abort', onAbort);
340
- activeDialogControl = { id, resolve, reject, cleanup };
341
- const pluginId = String(params.pluginId ?? '');
342
- const pluginName = String(params.pluginName ?? '');
343
- if (method === 'ui.pick') {
344
- activePluginDialog.value = {
345
- id,
346
- kind: 'pick',
347
- pluginId,
348
- pluginName,
349
- options: params.options as PluginUiPickOptions,
350
- };
351
- } else if (method === 'ui.prompt') {
352
- activePluginDialog.value = {
353
- id,
354
- kind: 'prompt',
355
- pluginId,
356
- pluginName,
357
- options: params.options as PluginUiPromptOptions,
358
- };
359
- } else {
360
- activePluginDialog.value = {
361
- id,
362
- kind: 'confirm',
363
- pluginId,
364
- pluginName,
365
- options: params.options as PluginUiConfirmOptions,
366
- };
367
- }
368
- });
369
- }
370
257
  const pluginSettingsRequest = shallowRef<{ key: string; sequence: number }>();
371
258
  const pluginSettingsPages = computed(() =>
372
259
  pluginViews.value
@@ -386,9 +273,7 @@ export function createWorkspacePluginsState(deps: WorkspacePluginsStateDeps) {
386
273
  activeDocumentPluginSidebar.value = '';
387
274
  pluginSettingsRequest.value = undefined;
388
275
  cancelActivePluginDialog('工作区已切换');
389
- for (const timer of toastTimers.values()) clearTimeout(timer);
390
- toastTimers.clear();
391
- pluginToasts.value = [];
276
+ clearPluginToasts();
392
277
  },
393
278
  );
394
279
  watch(pluginViews, (views) => {
@@ -577,6 +462,7 @@ export function createWorkspacePluginsState(deps: WorkspacePluginsStateDeps) {
577
462
  }
578
463
  return pluginViews.value.find((view) => view.location === 'newTab') ?? null;
579
464
  });
465
+
580
466
  function invokePluginAssistantTool(pluginId: string, toolName: string, args: Record<string, unknown>) {
581
467
  if (!workspace.value) return Promise.reject(new Error('请先打开工作区'));
582
468
  const entry = activeId.value ? fileRegistry.value?.get(activeId.value) : undefined;
@@ -586,6 +472,7 @@ export function createWorkspacePluginsState(deps: WorkspacePluginsStateDeps) {
586
472
  ...(activeFileId ? { activeFileId } : {}),
587
473
  });
588
474
  }
475
+
589
476
  function queryPluginAssistantContext(pluginId: string, providerId: string, query: string) {
590
477
  if (!workspace.value) return Promise.reject(new Error('请先打开工作区'));
591
478
  const entry = activeId.value ? fileRegistry.value?.get(activeId.value) : undefined;
@@ -608,419 +495,6 @@ export function createWorkspacePluginsState(deps: WorkspacePluginsStateDeps) {
608
495
  );
609
496
  }
610
497
 
611
- async function pluginCall(
612
- method: string,
613
- params: Record<string, unknown>,
614
- assertInstance: () => void,
615
- ): Promise<unknown> {
616
- const expected = workspace.value?.id;
617
- if (method === 'ui.pick' || method === 'ui.prompt' || method === 'ui.confirm') {
618
- assertInstance();
619
- if (!expected || workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
620
- return openPluginDialog(method, params);
621
- }
622
- if (method === 'ui.toast') {
623
- assertInstance();
624
- if (!expected || workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
625
- showPluginToast(params);
626
- return null;
627
- }
628
- if (method === 'ai.complete' || method === 'ai.structured') {
629
- assertInstance();
630
- if (!expected || workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
631
- if (!pluginAiRunner) throw new Error('当前环境尚未配置同页助手模型连接');
632
- const signal = params.signal instanceof AbortSignal ? params.signal : new AbortController().signal;
633
- return pluginAiRunner({
634
- pluginId: String(params.pluginId ?? ''),
635
- pluginName: String(params.pluginName ?? ''),
636
- structured: method === 'ai.structured',
637
- request: params.request as PluginAiCompleteRequest | PluginAiStructuredRequest,
638
- signal,
639
- });
640
- }
641
- const pathScopes = Array.isArray(params.pathScopes) ? (params.pathScopes as string[]) : undefined;
642
- if (method === 'editor.active') {
643
- assertInstance();
644
- if (!expected || workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
645
- const snapshot = pluginEditorBridge?.activeEditor?.();
646
- if (!snapshot) return null;
647
- const entry = fileRegistry.value?.get(snapshot.fileId);
648
- if (!entry || !isMarkdown(entry.path) || isWorkspaceInternalPath(entry.path)) return null;
649
- if (!matchesPluginPathScopes(entry.path, pathScopes)) return null;
650
- const doc = documentIndex.byId.value.get(entry.id);
651
- const content = doc ? doc.content : (await adapter.read(entry.path)).content;
652
- assertInstance();
653
- return {
654
- fileId: entry.id,
655
- path: entry.path,
656
- mode: snapshot.mode,
657
- readOnly: !!(workspace.value?.readOnly || entry.readOnly || snapshot.readOnly),
658
- selection: snapshot.selection,
659
- selectedText: snapshot.selectedText,
660
- ...(snapshot.blockType ? { blockType: snapshot.blockType } : {}),
661
- hash: await assistantHash(content),
662
- };
663
- }
664
- if (method === 'editor.insert' || method === 'editor.replaceSelection') {
665
- return serial(async () => {
666
- assertInstance();
667
- if (!expected || workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
668
- writable();
669
- const snapshot = pluginEditorBridge?.activeEditor?.();
670
- if (!snapshot || !pluginEditorBridge?.applySelectionEdit)
671
- throw new Error('当前没有可编辑的活动文档');
672
- const entry = fileRegistry.value?.get(snapshot.fileId);
673
- if (!entry || !isMarkdown(entry.path) || isWorkspaceInternalPath(entry.path))
674
- throw new Error('当前没有可编辑的活动文档');
675
- if (!matchesPluginPathScopes(entry.path, pathScopes))
676
- throw new Error('文档路径不在插件授权目录范围内');
677
- if (entry.readOnly || snapshot.readOnly) throw new Error('你对这篇文档只有阅读权限');
678
- const doc = documentIndex.byId.value.get(entry.id);
679
- if (doc?.conflict || doc?.missing) throw new Error('请先处理文档已有冲突');
680
- const editing = runtime.extensions?.()?.editing;
681
- if (editing?.isManaging(entry.id)) {
682
- throw new Error('当前协作会话暂不支持直接插入选区,请使用 documents.edit');
683
- }
684
- const ok = await pluginEditorBridge.applySelectionEdit(
685
- entry.id,
686
- String(params.text ?? ''),
687
- method === 'editor.insert' ? 'insert' : 'replace',
688
- );
689
- if (!ok) throw new Error('当前编辑器无法应用选区修改');
690
- assertInstance();
691
- const updated = documentIndex.byId.value.get(entry.id);
692
- const content = updated ? updated.content : (await adapter.read(entry.path)).content;
693
- return {
694
- fileId: entry.id,
695
- hash: await assistantHash(content),
696
- status: 'applied',
697
- };
698
- });
699
- }
700
- return serial(async () => {
701
- const assertCurrent = () => {
702
- assertInstance();
703
- if (!expected || workspace.value?.id !== expected) throw new Error(t('工作区已切换'));
704
- };
705
- assertCurrent();
706
- const attachmentService =
707
- runtime.attachments ??
708
- (runtime.native && adapter.mode === 'desktop' ? nativeAttachments : undefined);
709
- if (method === 'attachments.read')
710
- return pluginAttachmentReader.read(
711
- workspace.value!,
712
- params,
713
- attachmentService,
714
- assertCurrent,
715
- );
716
- if (method === 'attachments.write') {
717
- writable();
718
- if (!attachmentService?.importAttachment)
719
- throw new Error('当前宿主不支持写入附件');
720
- const parsed = parsePluginAttachmentWrite(params.request);
721
- const targetDocPath = parsed.documentPath || (pathScopes?.length ? `${pathScopes[0]!}note.md` : '');
722
- if (pathScopes?.length && !matchesPluginPathScopes(targetDocPath, pathScopes))
723
- throw new Error('附件目标目录不在插件授权目录范围内');
724
- const fileBytes = new Uint8Array(parsed.bytes);
725
- const uploadFile = new File([fileBytes], parsed.name, { type: parsed.mimeType });
726
- assertCurrent();
727
- const imported = await attachmentService.importAttachment(
728
- workspace.value!.id,
729
- targetDocPath,
730
- uploadFile,
731
- parsed.image,
732
- );
733
- assertCurrent();
734
- workspace.value = await adapter.refresh();
735
- return imported;
736
- }
737
- workspace.value = await adapter.refresh();
738
- await refreshObjects();
739
- assertCurrent();
740
- const current = workspace.value!;
741
- if (method === 'views.open') {
742
- await openPluginView(String(params.pluginId), String(params.viewId));
743
- return null;
744
- }
745
- if (method.endsWith('.query') || method === 'documents.search')
746
- return queryPluginData(method, params, pluginQueryPager, {
747
- workspace: current,
748
- objects: objects.value,
749
- relations: relations.value,
750
- drafts: documents.value,
751
- read: (path) => adapter.read(path),
752
- assertCurrent,
753
- });
754
- const file = () => {
755
- const entry = fileRegistry.value?.get(String(params.fileId));
756
- if (!entry || !isMarkdown(entry.path) || isWorkspaceInternalPath(entry.path))
757
- throw new Error('文档不存在或不可访问');
758
- if (!matchesPluginPathScopes(entry.path, pathScopes))
759
- throw new Error('文档路径不在插件授权目录范围内');
760
- return entry;
761
- };
762
- const text = (value: unknown) => {
763
- if (typeof value !== 'string' || value.length > 512000)
764
- throw new Error('插件文档内容无效或过大');
765
- return value;
766
- };
767
- if (method === 'documents.list')
768
- return current.files
769
- .filter(
770
- (row) =>
771
- row.kind === 'file' &&
772
- isMarkdown(row.path) &&
773
- !isWorkspaceInternalPath(row.path) &&
774
- matchesPluginPathScopes(row.path, pathScopes),
775
- )
776
- .map(({ id, path, name, readOnly }) => ({
777
- id,
778
- path,
779
- name,
780
- readOnly: current.readOnly || readOnly || false,
781
- }));
782
- if (method === 'documents.read') {
783
- const entry = file();
784
- const disk = await adapter.read(entry.path);
785
- const doc = documentIndex.byId.value.get(entry.id);
786
- if (doc?.conflict || doc?.missing) throw new Error('文档存在冲突,请先处理');
787
- const content = text(doc?.content ?? disk.content);
788
- return { id: entry.id, path: entry.path, content, hash: await assistantHash(content) };
789
- }
790
- if (method === 'documents.open') {
791
- await openInternal(file());
792
- ensureTabNavigation(String(params.fileId), String(params.fileId));
793
- touchNavigation();
794
- return null;
795
- }
796
- if (method === 'objects.list')
797
- return objects.value.map((record) => ({
798
- id: record.object.id,
799
- object: JSON.parse(JSON.stringify(record.object)),
800
- hash: record.snapshot.hash,
801
- }));
802
- if (method === 'objects.read') {
803
- const record = objects.value.find((row) => row.object.id === params.objectId);
804
- if (!record) throw new Error('对象不存在或不可访问');
805
- return {
806
- id: record.object.id,
807
- object: JSON.parse(JSON.stringify(record.object)),
808
- hash: record.snapshot.hash,
809
- };
810
- }
811
- if (method === 'relations.list') return JSON.parse(JSON.stringify(relations.value));
812
- writable();
813
- if (method === 'documents.create') {
814
- const path = text(params.path);
815
- if (!isMarkdown(path) || validatePath(path)) throw new Error('新文档路径无效');
816
- if (!matchesPluginPathScopes(path, pathScopes))
817
- throw new Error('新文档路径不在插件授权目录范围内');
818
- assertCurrent();
819
- await adapter.create(path, text(params.content));
820
- workspace.value = await adapter.refresh();
821
- const entry = fileRegistry.value?.at(path)!;
822
- return { id: entry.id, path };
823
- }
824
- if (method === 'documents.move') {
825
- const entry = file();
826
- if (entry.readOnly) throw new Error('你对这篇文档只有阅读权限');
827
- const destination = text(params.destination);
828
- if (!isMarkdown(destination) || validatePath(destination) || isWorkspaceInternalPath(destination))
829
- throw new Error('目标文档路径无效');
830
- if (!matchesPluginPathScopes(destination, pathScopes))
831
- throw new Error('目标路径不在插件授权目录范围内');
832
- if (destination === entry.path) return { id: entry.id, path: entry.path };
833
- if (current.files.some((row) => row.path === destination))
834
- throw new Error('目标路径已存在同名文件');
835
- if (!pluginRecord(params.base) || params.base.id !== entry.id || typeof params.base.content !== 'string')
836
- throw new Error('文档版本无效');
837
- const doc = documentIndex.byId.value.get(entry.id);
838
- if (doc?.conflict || doc?.missing) throw new Error('请先处理文档已有冲突');
839
- if (doc && dirty(doc)) throw new Error('文档存在未保存修改,请先保存后再移动');
840
- const disk = await adapter.read(entry.path);
841
- if (disk.content !== params.base.content)
842
- throw new Error('文档内容已变化,请重新读取后再移动');
843
- assertCurrent();
844
- if (adapter.changeFile) {
845
- const result = await adapter.changeFile({
846
- workspaceId: current.id,
847
- fileId: entry.id,
848
- path: entry.path,
849
- expectedHash: disk.hash,
850
- destination,
851
- });
852
- if (result.status !== 'saved') throw new Error('文档内容已变化或不存在,请重新读取后再移动');
853
- } else {
854
- await adapter.move(entry.path, destination, 'file');
855
- }
856
- assertCurrent();
857
- workspace.value = await adapter.refresh();
858
- if (doc) doc.path = destination;
859
- return { id: entry.id, path: destination };
860
- }
861
- if (method === 'documents.trash') {
862
- const entry = file();
863
- if (entry.readOnly) throw new Error('你对这篇文档只有阅读权限');
864
- if (!pluginRecord(params.base) || params.base.id !== entry.id || typeof params.base.content !== 'string')
865
- throw new Error('文档版本无效');
866
- const doc = documentIndex.byId.value.get(entry.id);
867
- if (doc?.conflict || doc?.missing) throw new Error('请先处理文档已有冲突');
868
- if (doc && dirty(doc)) throw new Error('文档存在未保存修改,请先保存后再移入回收站');
869
- const disk = await adapter.read(entry.path);
870
- if (disk.content !== params.base.content)
871
- throw new Error('文档内容已变化,请重新读取后再移入回收站');
872
- assertCurrent();
873
- if (adapter.changeFile) {
874
- const result = await adapter.changeFile({
875
- workspaceId: current.id,
876
- fileId: entry.id,
877
- path: entry.path,
878
- expectedHash: disk.hash,
879
- });
880
- if (result.status !== 'saved') throw new Error('文档内容已变化或不存在,请重新读取后再移入回收站');
881
- } else {
882
- await adapter.remove(entry.path);
883
- }
884
- assertCurrent();
885
- workspace.value = await adapter.refresh();
886
- if (doc) doc.missing = true;
887
- return { id: entry.id, path: entry.path, trashed: true };
888
- }
889
- if (method === 'documents.write') {
890
- const entry = file();
891
- if (entry.readOnly) throw new Error('你对这篇文档只有阅读权限');
892
- if (!pluginRecord(params.base) || params.base.id !== entry.id)
893
- throw new Error('文档版本无效');
894
- const base = text(params.base.content);
895
- const desired = text(params.content);
896
- const disk = await adapter.read(entry.path);
897
- const doc = documentIndex.byId.value.get(entry.id);
898
- if (doc?.conflict || doc?.missing) throw new Error('请先处理文档已有冲突');
899
- const live = doc
900
- ? mergeMarkdown(doc.base.content, doc.content, disk.content)
901
- : { clean: true, content: disk.content };
902
- const merged = mergeMarkdown(base, desired, live.content);
903
- if (!live.clean || !merged.clean) {
904
- const copyPath = entry.path.replace(
905
- /\.(md|markdown)$/i,
906
- `.plugin-conflict-${crypto.randomUUID().slice(0, 8)}.md`,
907
- );
908
- assertCurrent();
909
- await adapter.create(copyPath, desired);
910
- throw new Error(t('文档有重叠修改,插件版本已保存在 {0}', [copyPath]));
911
- }
912
- const editing = runtime.extensions?.()?.editing;
913
- if (editing?.isManaging(entry.id)) {
914
- if (!editing.applyPluginEdit)
915
- throw new Error('当前协作会话不支持插件编辑,请退出协作后重试');
916
- assertCurrent();
917
- const applied = await editing.applyPluginEdit(entry.id, live.content, merged.content);
918
- assertCurrent();
919
- return {
920
- id: entry.id,
921
- hash: await assistantHash(applied ?? merged.content),
922
- status: 'applied',
923
- };
924
- }
925
- if (doc && pluginEditorBridge && (await pluginEditorBridge.applyEdit(entry.id, doc.content, merged.content))) {
926
- return { id: entry.id, hash: await assistantHash(doc.content), status: 'applied' };
927
- }
928
- if (doc) {
929
- // The editor observes this value and applies a transaction through its existing bridge.
930
- doc.content = merged.content;
931
- doc.base = disk;
932
- assertCurrent();
933
- await saveInternal(doc);
934
- if (doc.error || doc.conflict || dirty(doc))
935
- throw new Error(doc.error ?? '插件修改已保留为草稿,请处理冲突后保存');
936
- return { id: entry.id, hash: await assistantHash(doc.content), status: 'saved' };
937
- }
938
- assertCurrent();
939
- const result = await adapter.write(entry.path, merged.content, disk.hash);
940
- if (result.status !== 'saved') {
941
- const copyPath = entry.path.replace(
942
- /\.(md|markdown)$/i,
943
- `.plugin-conflict-${crypto.randomUUID().slice(0, 8)}.md`,
944
- );
945
- await adapter.create(copyPath, desired);
946
- throw new Error(t('保存时文件发生变化,插件版本已保存在 {0}', [copyPath]));
947
- }
948
- return { id: entry.id, hash: await assistantHash(result.snapshot.content), status: 'saved' };
949
- }
950
- if (!capabilities.value.features.objectReferences) throw new Error('工作区对象功能已关闭');
951
- if (method === 'objects.create' || method === 'objects.update') {
952
- if (!pluginRecord(params.object)) throw new Error('对象无效');
953
- const draft = JSON.parse(JSON.stringify(params.object));
954
- if (method === 'objects.create') {
955
- if (!adapter.reserveObjectId) throw new Error('存储适配器不支持对象身份分配');
956
- const id = await adapter.reserveObjectId(objects.value.map((row) => row.object.id));
957
- const object = parseObject(JSON.stringify({ ...draft, version: 1, id }));
958
- validateObjectProperties(object.type, object.properties);
959
- assertCurrent();
960
- await adapter.create(
961
- `${objectDirectory}/${id}.tano.json`,
962
- JSON.stringify(object, null, 2) + '\n',
963
- );
964
- workspace.value = await adapter.refresh();
965
- await refreshObjects();
966
- return object;
967
- }
968
- if (!pluginRecord(params.base) || !pluginRecord(params.base.object))
969
- throw new Error('对象版本无效');
970
- const record = objects.value.find((row) => row.object.id === draft.id);
971
- if (!record) throw new Error('对象不存在');
972
- if (current.files.find((row) => row.path === record.path)?.readOnly)
973
- throw new Error('对象只读');
974
- const object = parseObject(JSON.stringify(draft));
975
- validateObjectProperties(object.type, object.properties);
976
- const merged = mergeObject(
977
- parseObject(JSON.stringify(params.base.object)),
978
- object,
979
- record.object,
980
- );
981
- const preserve = async () => {
982
- const path = `.tano/conflicts/plugin-object-${crypto.randomUUID()}.json`;
983
- assertCurrent();
984
- await adapter.create(
985
- path,
986
- JSON.stringify({ version: 1, pluginProposal: object, base: params.base }, null, 2) + '\n',
987
- );
988
- return path;
989
- };
990
- if (!merged)
991
- throw new Error(t('对象已有重叠修改,插件版本已保存在 {0}', [await preserve()]));
992
- let saved: ObjectRecord;
993
- try {
994
- assertCurrent();
995
- saved = await saveObject(adapter, record, merged);
996
- } catch (error) {
997
- throw new Error(t('{0} 插件版本已保存在 {1}', [String(error), await preserve()]));
998
- }
999
- workspace.value = await adapter.refresh();
1000
- await refreshObjects();
1001
- return saved.object;
1002
- }
1003
- if (method === 'relations.add' || method === 'relations.remove') {
1004
- if (relationError.value) throw new Error(relationError.value);
1005
- const relation = params.relation as WorkspaceRelation;
1006
- validateRelation(relation, relationDefinitions.value);
1007
- for (const endpoint of [relation.source, relation.target])
1008
- if (!referenceTargets.value.some((target) => referenceKey(target) === referenceKey(endpoint)))
1009
- throw new Error('关系端点不存在或不可访问');
1010
- assertCurrent();
1011
- await saveRelationChange(
1012
- adapter,
1013
- getRelationBase(),
1014
- method === 'relations.add' ? { add: relation } : { remove: relation },
1015
- );
1016
- workspace.value = await adapter.refresh();
1017
- await refreshObjects();
1018
- return null;
1019
- }
1020
- throw new Error('不支持此插件 API');
1021
- });
1022
- }
1023
-
1024
498
  // OAuth, connections & package repository helpers
1025
499
  async function startPluginOAuth(
1026
500
  workspaceId: string,
@@ -1117,9 +591,7 @@ export function createWorkspacePluginsState(deps: WorkspacePluginsStateDeps) {
1117
591
 
1118
592
  function disposePlugins() {
1119
593
  cancelActivePluginDialog('工作区已关闭');
1120
- for (const timer of toastTimers.values()) clearTimeout(timer);
1121
- toastTimers.clear();
1122
- pluginToasts.value = [];
594
+ clearPluginToasts();
1123
595
  pluginAttachmentReader.clear();
1124
596
  clearTimeout(pluginEventTimer);
1125
597
  overlayExtension()?.dispose?.();