@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,12 +1,14 @@
1
1
  <script setup lang="ts">
2
2
  import { uiLocale, t } from '../../i18n/i18n';
3
- import { computed, ref, watch } from 'vue';
4
- import { pluginCacheLimit, pluginPackageLimit, type WorkspacePersonalPluginPolicy } from '@tano/protocol';
5
- import PluginRepositoryStorage from './PluginRepositoryStorage.vue';
3
+ import { computed, inject, ref, watch } from 'vue';
4
+ import { pluginCacheLimit, pluginPackageLimit } from '@tano/protocol';
5
+ import { workbenchPrefsKey } from '../../shell/workbench-context';
6
6
  import { useWorkspaceStore } from '../../stores/workspace';
7
7
  import { PluginPackageCache } from '../packages';
8
8
  import type { PluginCacheEntry } from '../cache-storage';
9
- const props = defineProps<{ id: string }>();
9
+ const props = defineProps<{ id: string; developerMode?: boolean }>();
10
+ const workbench = inject(workbenchPrefsKey, null);
11
+ const isDeveloperMode = computed(() => props.developerMode ?? Boolean(workbench?.developerMode));
10
12
  const store = useWorkspaceStore(), cache = new PluginPackageCache();
11
13
  const entries = ref<PluginCacheEntry[]>([]), pending = ref(false), error = ref(''), status = ref('');
12
14
  const developmentUrl = ref(''), trustBuilds = ref(false);
@@ -47,38 +49,7 @@ async function run(action: () => Promise<unknown>, message: string) {
47
49
  <p v-if="runtime?.message" :role="runtime.status === 'error' ? 'alert' : 'status'">{{ runtime.message }}</p>
48
50
  <p v-if="error" role="alert">{{ error }}</p><p v-if="status" role="status">{{ status }}</p>
49
51
  <button :disabled="pending || !installation?.enabled" @click="run(() => store.restartPlugin(id, store.workspace!.id), t('已重新加载当前版本'))">{{ t('重新加载当前版本') }}</button>
50
- <div v-if="store.canManagePlugins && store.workspace" class="personal-policy-control">
51
- <label
52
- >{{ t('本工作区对个人代码插件的策略') }}
53
- <select
54
- :value="store.personalCodePluginPolicy"
55
- :disabled="pending"
56
- :aria-label="t('本工作区对个人代码插件的策略')"
57
- @change="run(() => store.changePlugin({ personalCodePlugins: ($event.target as HTMLSelectElement).value as WorkspacePersonalPluginPolicy }, store.workspace!.id), t('已更新工作区个人代码插件策略'))"
58
- >
59
- <option value="allow">{{ t('允许运行(遵循个人授权)') }}</option>
60
- <option value="read-only">{{ t('仅允许只读访问(禁止写入)') }}</option>
61
- <option value="block">{{ t('禁止个人代码插件访问本工作区') }}</option>
62
- </select>
63
- </label>
64
- </div>
65
- <p>{{ t('单包上限') }} {{ size(pluginPackageLimit) }} {{ t('· 设备代码缓存') }} {{ size(used) }} / {{ size(pluginCacheLimit) }}</p>
66
- <p>{{ t('此插件本机状态') }} {{ size(state.used) }} / {{ size(state.limit) }}{{ t('。缓存清理不会删除工作区内容。') }}</p>
67
- <PluginRepositoryStorage v-if="installation?.scope !== 'user'" :plugin-id="id" />
68
- <details v-if="installation?.scope !== 'user'">
69
- <summary>{{ t('开发模式') }}</summary>
70
- <p>{{ t('先安装并授权一个初始构建,然后运行:') }}</p>
71
- <pre>npm run plugin -- watch ./my-plugin --origin {{ appOrigin }}</pre>
72
- <p>{{ t('新构建会更新当前工作区的共享插件规则,请使用测试工作区。权限声明变化时停止自动应用。') }}</p>
73
- <label>{{ t('本机开发地址') }}<input v-model="developmentUrl" type="url" :aria-label="t('插件开发地址')" :placeholder="t('http://127.0.0.1:端口/…/package.json')" /></label>
74
- <label><input v-model="trustBuilds" type="checkbox" />{{ t('信任此开发会话中权限不变的新构建') }}</label>
75
- <button :disabled="!trustBuilds || !installation?.authorized || !installation?.enabled || !store.canManagePlugins" @click="startDevelopment">{{ t('开始自动重载') }}</button>
76
- <template v-if="store.pluginDevelopment.pluginId === id">
77
- <p role="status">{{ store.pluginDevelopment.message }}</p>
78
- <button v-if="store.pluginDevelopment.active" @click="store.stopPluginDevelopment()">{{ t('停止自动重载') }}</button>
79
- </template>
80
- </details>
81
- <details v-if="installation?.scope !== 'user'">
52
+ <details v-if="installation?.scope !== 'user' && (installation?.rule?.history?.length || isDeveloperMode)">
82
53
  <summary>{{ t('历史版本(') }}{{ installation?.rule?.history?.length ?? 0 }})</summary>
83
54
  <p>{{ t('保留最近 10 个版本引用。移除引用后,该版本不再受云端回收保护,日后恢复需重新导入。回滚沿用当前共享设置,运行前仍需核对并授权版本。') }}</p>
84
55
  <ul>
@@ -91,19 +62,36 @@ async function run(action: () => Promise<unknown>, message: string) {
91
62
  </li>
92
63
  </ul>
93
64
  </details>
94
- <details>
95
- <summary>{{ t('此插件的设备缓存(') }}{{ localEntries.length }})</summary>
96
- <ul><li v-for="entry in localEntries" :key="entry.integrity">{{ entry.version }} · {{ size(entry.bytes) }} · <code>{{ entry.integrity.slice(0, 12) }}</code>
97
- <button :disabled="pending || entry.integrity === installation?.rule?.integrity || store.userPluginIntegrities().has(entry.integrity)" @click="run(() => cache.remove(entry.integrity), t('已清理所选代码缓存'))">{{ t('清理缓存') }}</button>
98
- </li></ul>
99
- <p>{{ t('清理旧缓存后,回滚可能需要联网下载或重新导入对应包。') }}</p>
100
- </details>
101
- <details>
102
- <summary>{{ t('运行日志(') }}{{ runtime?.logs?.length ?? 0 }})</summary>
103
- <p>{{ t('仅保留本次工作区会话最近 100 条,重新加载插件后仍可查看。') }}</p>
104
- <button @click="store.clearPluginLogs(id)">{{ t('清空日志') }}</button>
105
- <ol class="plugin-logs"><li v-for="(log, index) in runtime?.logs" :key="index"><time>{{ new Date(log.time).toLocaleTimeString(uiLocale) }}</time> {{ log.level }} <pre>{{ log.message }}</pre></li></ol>
106
- </details>
65
+ <template v-if="isDeveloperMode">
66
+ <p>{{ t('单包上限') }} {{ size(pluginPackageLimit) }} {{ t('· 设备代码缓存') }} {{ size(used) }} / {{ size(pluginCacheLimit) }}</p>
67
+ <p>{{ t('此插件本机状态') }} {{ size(state.used) }} / {{ size(state.limit) }}{{ t('。缓存清理不会删除工作区内容。') }}</p>
68
+ <details v-if="installation?.scope !== 'user'">
69
+ <summary>{{ t('开发模式') }}</summary>
70
+ <p>{{ t('先安装并授权一个初始构建,然后运行:') }}</p>
71
+ <pre>npm run plugin -- watch ./my-plugin --origin {{ appOrigin }}</pre>
72
+ <p>{{ t('新构建会更新当前工作区的共享插件规则,请使用测试工作区。权限声明变化时停止自动应用。') }}</p>
73
+ <label>{{ t('本机开发地址') }}<input v-model="developmentUrl" type="url" :aria-label="t('插件开发地址')" :placeholder="t('http://127.0.0.1:端口/…/package.json')" /></label>
74
+ <label><input v-model="trustBuilds" type="checkbox" />{{ t('信任此开发会话中权限不变的新构建') }}</label>
75
+ <button :disabled="!trustBuilds || !installation?.authorized || !installation?.enabled || !store.canManagePlugins" @click="startDevelopment">{{ t('开始自动重载') }}</button>
76
+ <template v-if="store.pluginDevelopment.pluginId === id">
77
+ <p role="status">{{ store.pluginDevelopment.message }}</p>
78
+ <button v-if="store.pluginDevelopment.active" @click="store.stopPluginDevelopment()">{{ t('停止自动重载') }}</button>
79
+ </template>
80
+ </details>
81
+ <details>
82
+ <summary>{{ t('此插件的设备缓存(') }}{{ localEntries.length }})</summary>
83
+ <ul><li v-for="entry in localEntries" :key="entry.integrity">{{ entry.version }} · {{ size(entry.bytes) }} · <code>{{ entry.integrity.slice(0, 12) }}</code>
84
+ <button :disabled="pending || entry.integrity === installation?.rule?.integrity || store.userPluginIntegrities().has(entry.integrity)" @click="run(() => cache.remove(entry.integrity), t('已清理所选代码缓存'))">{{ t('清理缓存') }}</button>
85
+ </li></ul>
86
+ <p>{{ t('清理旧缓存后,回滚可能需要联网下载或重新导入对应包。') }}</p>
87
+ </details>
88
+ <details>
89
+ <summary>{{ t('运行日志(') }}{{ runtime?.logs?.length ?? 0 }})</summary>
90
+ <p>{{ t('仅保留本次工作区会话最近 100 条,重新加载插件后仍可查看。') }}</p>
91
+ <button @click="store.clearPluginLogs(id)">{{ t('清空日志') }}</button>
92
+ <ol class="plugin-logs"><li v-for="(log, index) in runtime?.logs" :key="index"><time>{{ new Date(log.time).toLocaleTimeString(uiLocale) }}</time> {{ log.level }} <pre>{{ log.message }}</pre></li></ol>
93
+ </details>
94
+ </template>
107
95
  </section>
108
96
  </template>
109
97
  <style scoped>
@@ -5,6 +5,7 @@ import type { PluginPackageUsage } from '@tano/protocol';
5
5
  import { useWorkspaceStore } from '../../stores/workspace';
6
6
  const props = defineProps<{ pluginId?: string }>();
7
7
  const store = useWorkspaceStore(), usage = ref<PluginPackageUsage>(), pending = ref(false), error = ref(''), status = ref('');
8
+ const opened = ref(false);
8
9
  const entries = computed(() => usage.value?.entries.filter(entry => !props.pluginId || entry.pluginId === props.pluginId) ?? []);
9
10
  const size = (bytes: number) => bytes >= 1024 * 1024 ? `${(bytes / 1024 / 1024).toFixed(1)} MiB` : `${(bytes / 1024).toFixed(1)} KiB`;
10
11
  let generation = 0;
@@ -14,9 +15,10 @@ async function load(current: number) {
14
15
  const result = await store.loadPluginPackageUsage(store.workspace.id);
15
16
  if (current === generation) usage.value = result;
16
17
  }
17
- watch([() => props.pluginId, () => store.workspace?.id, () => store.canManagePlugins,
18
+ watch([opened, () => props.pluginId, () => store.workspace?.id, () => store.canManagePlugins,
18
19
  () => JSON.stringify(store.installedPlugins.map(plugin => plugin.rule))], async (_current, _previous, cleanup) => {
19
20
  const current = ++generation; cleanup(() => { generation++; }); usage.value = undefined; error.value = ''; status.value = ''; pending.value = false;
21
+ if (!opened.value) return;
20
22
  try { await load(current); } catch (cause) { if (current === generation) error.value = String(cause); }
21
23
  }, { immediate: true });
22
24
  async function run(integrity?: string) {
@@ -31,7 +33,7 @@ async function run(integrity?: string) {
31
33
  }
32
34
  </script>
33
35
  <template>
34
- <details v-if="store.pluginRepositoryAvailable && store.canManagePlugins" class="plugin-repository-storage">
36
+ <details v-if="store.pluginRepositoryAvailable && store.canManagePlugins" class="plugin-repository-storage" @toggle="opened = ($event.target as HTMLDetailsElement).open">
35
37
  <summary>{{ t('工作区云端包存储') }}</summary>
36
38
  <p v-if="error" role="alert">{{ error }}</p><p v-if="status" role="status">{{ status }}</p>
37
39
  <button :disabled="pending" @click="run()">{{ t('刷新云端容量') }}</button>
@@ -7,6 +7,7 @@ const props = defineProps<{
7
7
  schema: readonly PluginSettingField[];
8
8
  modelValue: string;
9
9
  disabled?: boolean;
10
+ developerMode?: boolean;
10
11
  }>();
11
12
  const emit = defineEmits<{ 'update:modelValue': [value: string] }>();
12
13
 
@@ -85,7 +86,7 @@ function updateNumber(field: PluginSettingField, raw: string) {
85
86
  </label>
86
87
  <p v-if="field.description" class="setting-description">{{ field.description }}</p>
87
88
  </div>
88
- <details class="setting-raw">
89
+ <details v-if="developerMode" class="setting-raw">
89
90
  <summary>{{ t('高级 JSON 视图') }}</summary>
90
91
  <textarea
91
92
  :value="modelValue"
@@ -0,0 +1,61 @@
1
+ <script setup lang="ts">
2
+ import type { Workspace } from '@tano/protocol';
3
+ import { t } from '../../i18n/i18n';
4
+ import type { WorkbenchActions, WorkbenchExtensions } from '../../runtime';
5
+ import { PluginInstaller } from '../../shell/workbench-async-components';
6
+
7
+ defineProps<{
8
+ workspace: Workspace;
9
+ objectReferencesEnabled: boolean;
10
+ developerMode: boolean;
11
+ extensions: WorkbenchExtensions;
12
+ extensionActions: WorkbenchActions;
13
+ }>();
14
+
15
+ const emit = defineEmits<{
16
+ 'enable-developer-mode': [];
17
+ 'create-object': [type: string];
18
+ }>();
19
+ </script>
20
+
21
+ <template>
22
+ <main class="plugins-tab-page">
23
+ <div class="plugins-tab-content">
24
+ <p v-if="!objectReferencesEnabled" class="tool-level-notice">
25
+ {{ t('「工作区对象与引用」已关闭,插件对象和关系暂时只读。可在工作区设置中重新启用。') }}
26
+ </p>
27
+ <p v-else-if="workspace.readOnly" class="tool-level-notice">
28
+ {{ t('此工作区为只读,无法修改对象和关系。') }}
29
+ </p>
30
+ <PluginInstaller
31
+ :developer-mode="developerMode"
32
+ @enable-developer-mode="emit('enable-developer-mode')"
33
+ @create-object="emit('create-object', $event)"
34
+ >
35
+ <template v-if="extensions.regions['plugin-customize']" #customize="{ developerMode: devMode }">
36
+ <component
37
+ :is="extensions.regions['plugin-customize']"
38
+ :actions="extensionActions"
39
+ :developer-mode="devMode"
40
+ />
41
+ </template>
42
+ <template v-if="extensions.regions['plugin-forge']" #forge="{ canPublish, openPublishing, developerMode: devMode }">
43
+ <component
44
+ :is="extensions.regions['plugin-forge']"
45
+ :actions="extensionActions"
46
+ :can-publish="canPublish"
47
+ :developer-mode="devMode"
48
+ @open-publishing="openPublishing"
49
+ />
50
+ </template>
51
+ <template v-if="extensions.regions['plugin-publishing']" #publishing="{ developerMode: devMode }">
52
+ <component
53
+ :is="extensions.regions['plugin-publishing']"
54
+ :actions="extensionActions"
55
+ :developer-mode="devMode"
56
+ />
57
+ </template>
58
+ </PluginInstaller>
59
+ </div>
60
+ </main>
61
+ </template>
@@ -581,3 +581,8 @@
581
581
  .plugin-policy { display: grid; gap: 12px; }
582
582
  .plugin-policy label { display: grid; gap: 6px; font-size: 12px; color: var(--muted); }
583
583
  .plugin-policy select, .plugin-policy input, .plugin-policy textarea { padding: 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--surface); color: var(--text); font: inherit; }
584
+ .workspace-plugin-policy { margin: 16px 0; padding: 12px 14px; border: 1px solid var(--line); border-radius: 8px; background: var(--surface); }
585
+ .workspace-plugin-policy label { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; font-size: 12.5px; color: var(--muted); }
586
+ .workspace-plugin-policy select { padding: 6px 10px; border: 1px solid var(--line); border-radius: 6px; background: var(--paper); color: var(--text); font: inherit; font-size: 12.5px; }
587
+ .dev-optin-link { display: inline-flex; align-items: center; gap: 6px; border: 0; background: transparent; color: var(--muted); font: inherit; font-size: 12px; cursor: pointer; padding: 4px 6px; border-radius: 6px; }
588
+ .dev-optin-link:hover { color: var(--text); background: var(--hover); }
@@ -1,86 +1,9 @@
1
- import { canonicalPluginJson, pluginRecord } from '@tano/protocol';
2
- import type { PluginPage, PluginPageOptions, PluginTextEdit, PluginEvent } from './plugin-sdk';
3
- import { assistantHash } from '../assistant/hash';
4
-
5
- export function pluginQueryOptions(value: unknown, allowed: readonly string[]) {
6
- const options = value === undefined ? {} : value;
7
- if (!pluginRecord(options) || Object.keys(options).some(key => ![...allowed, 'limit', 'cursor', 'direction'].includes(key))) throw new Error('查询参数无效');
8
- if (options.limit !== undefined && (!Number.isInteger(options.limit) || Number(options.limit) < 1 || Number(options.limit) > 100)) throw new Error('每页数量必须为 1 至 100');
9
- if (options.cursor !== undefined && (typeof options.cursor !== 'string' || options.cursor.length > 100)) throw new Error('分页游标无效');
10
- if (options.direction !== undefined && !['asc', 'desc'].includes(String(options.direction))) throw new Error('查询排序方向无效');
11
- return options;
12
- }
13
- export function queryText(value: unknown, limit = 200): string | undefined {
14
- if (value === undefined) return undefined;
15
- if (typeof value !== 'string' || value.length > limit) throw new Error('查询文本无效');
16
- return value;
17
- }
18
- export function queryBoolean(value: unknown): boolean | undefined {
19
- if (value !== undefined && typeof value !== 'boolean') throw new Error('查询条件必须为布尔值');
20
- return value as boolean | undefined;
21
- }
22
- export const compareQueryText = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0;
23
-
24
- /** Cursors never contain workspace data and are bound to an execution instance and query revision. */
25
- export class PluginQueryPager {
26
- private cursors = new Map<string, { scope: string; signature: string; offset: number; expires: number }>();
27
- clear() { this.cursors.clear(); }
28
- async page<T, R = T>(scope: string, method: string, options: PluginPageOptions, revision: unknown, rows: T[],
29
- project: (row: T) => Promise<R | undefined> = async row => row as unknown as R,
30
- assertCurrent: () => void = () => {}, scanLimit = Number.POSITIVE_INFINITY): Promise<PluginPage<R>> {
31
- const { cursor, ...query } = options;
32
- const signature = await assistantHash(canonicalPluginJson([method, query, revision]));
33
- assertCurrent();
34
- for (const [key, value] of this.cursors) if (value.expires < Date.now()) this.cursors.delete(key);
35
- const previous = cursor ? this.cursors.get(cursor) : undefined;
36
- if (cursor && (!previous || previous.scope !== scope || previous.signature !== signature)) throw new Error('查询结果已变化或分页已过期,请从第一页重新查询');
37
- let offset = previous?.offset ?? 0, scanned = 0, bytes = 0;
38
- const items: R[] = [], limit = options.limit ?? 50;
39
- while (offset < rows.length && items.length < limit && scanned < scanLimit) {
40
- assertCurrent();
41
- const item = await project(rows[offset]!);
42
- assertCurrent();
43
- if (item !== undefined) {
44
- const size = new TextEncoder().encode(JSON.stringify(item)).length;
45
- if (size > 256 * 1024) throw new Error('单条查询结果超过 256 KB,请缩小对象内容');
46
- if (bytes + size > 256 * 1024) break;
47
- items.push(item); bytes += size;
48
- }
49
- offset++; scanned++;
50
- }
51
- const result: PluginPage<R> = { items };
52
- if (scanLimit === Number.POSITIVE_INFINITY) result.total = rows.length;
53
- if (offset < rows.length) {
54
- result.nextCursor = crypto.randomUUID();
55
- this.cursors.set(result.nextCursor, { scope, signature, offset, expires: Date.now() + 60_000 });
56
- if (this.cursors.size > 128) this.cursors.delete(this.cursors.keys().next().value!);
57
- }
58
- return result;
59
- }
60
- }
61
-
62
- export function applyPluginTextEdits(content: string, value: unknown): string {
63
- if (!Array.isArray(value) || !value.length || value.length > 100) throw new Error('编辑事务需要 1 至 100 个修改');
64
- const edits: PluginTextEdit[] = value.map(edit => {
65
- if (!pluginRecord(edit) || Object.keys(edit).some(key => !['from', 'to', 'insert'].includes(key)) ||
66
- !Number.isInteger(edit.from) || !Number.isInteger(edit.to) || Number(edit.from) < 0 || Number(edit.to) < Number(edit.from) ||
67
- Number(edit.to) > content.length || typeof edit.insert !== 'string') throw new Error('编辑范围无效');
68
- const splitsSurrogate = (offset: number) => /[\uD800-\uDBFF]/.test(content[offset - 1] ?? '') && /[\uDC00-\uDFFF]/.test(content[offset] ?? '');
69
- if (splitsSurrogate(Number(edit.from)) || splitsSurrogate(Number(edit.to))) throw new Error('编辑范围不能拆分 Unicode 字符');
70
- return edit as unknown as PluginTextEdit;
71
- }).sort((a, b) => a.from - b.from || a.to - b.to);
72
- for (let i = 1; i < edits.length; i++) if (edits[i]!.from < edits[i - 1]!.to || edits[i]!.from === edits[i - 1]!.from) throw new Error('编辑范围不能重叠');
73
- let next = content;
74
- for (const edit of edits.reverse()) next = next.slice(0, edit.from) + edit.insert + next.slice(edit.to);
75
- if (next.length > 512000) throw new Error('编辑后的文档超过大小限制');
76
- return next;
77
- }
78
-
79
- /** Deltas expose identities only; permission checks occur again before delivery in the host. */
80
- export function pluginChanges(type: Exclude<PluginEvent['type'], 'workspace.changed'>, before: Map<string, string>, after: Map<string, string>): PluginEvent | undefined {
81
- const changes: { id: string; kind: 'created' | 'updated' | 'deleted' }[] = [];
82
- for (const [id, stamp] of after) if (before.get(id) !== stamp) changes.push({ id, kind: before.has(id) ? 'updated' : 'created' });
83
- for (const id of before.keys()) if (!after.has(id)) changes.push({ id, kind: 'deleted' });
84
- if (!changes.length) return;
85
- return changes.length > 100 ? { type, changes: [], reset: true } : { type, changes };
86
- }
1
+ export {
2
+ applyPluginTextEdits,
3
+ compareQueryText,
4
+ pluginChanges,
5
+ PluginQueryPager,
6
+ pluginQueryOptions,
7
+ queryBoolean,
8
+ queryText,
9
+ } from '@tano/protocol/plugin-data';
@@ -0,0 +1,169 @@
1
+ import {
2
+ pluginRecord,
3
+ type Workspace,
4
+ } from '@tano/protocol';
5
+ import type { ExternalSlashCommand } from '@tano/editor/slash-commands';
6
+ import type {
7
+ ExternalCodeBlockRenderer,
8
+ ExternalEditorDecoration,
9
+ } from '@tano/editor/external-decorations';
10
+ import { createPluginUiSandbox } from './ui-sandbox';
11
+ import type { useWorkspaceStore } from '../stores/workspace';
12
+
13
+ export function createEditorPluginAdapters(
14
+ getStore: () => ReturnType<typeof useWorkspaceStore>,
15
+ getWorkspace: () => Workspace | null,
16
+ ) {
17
+ const codeBlockRendererCache = new Map<
18
+ string,
19
+ { source: readonly unknown[]; list: ExternalCodeBlockRenderer[] }
20
+ >();
21
+
22
+ function editorPluginSlashCommands(fileId: string): ExternalSlashCommand[] {
23
+ const ws = getWorkspace();
24
+ const store = getStore();
25
+ if (!ws) return [];
26
+ return store.pluginSlashCommands.map((cmd) => ({
27
+ id: cmd.key,
28
+ label: cmd.label,
29
+ marker: cmd.pluginName,
30
+ keywords: [...(cmd.keywords ?? []), cmd.pluginName, cmd.id].join(' '),
31
+ description: cmd.description,
32
+ execute: () => {
33
+ void store
34
+ .interactWithPlugin({
35
+ workspaceId: ws.id,
36
+ pluginId: cmd.pluginId,
37
+ instanceId: cmd.instanceId,
38
+ kind: 'command',
39
+ name: cmd.command,
40
+ payload: { workspaceId: ws.id, fileId, source: 'slash' },
41
+ })
42
+ .catch((error) => store.report(String(error)));
43
+ },
44
+ }));
45
+ }
46
+
47
+ function editorPluginDecorations(fileId: string): ExternalEditorDecoration[] {
48
+ const ws = getWorkspace();
49
+ const store = getStore();
50
+ if (!ws) return [];
51
+ return store.pluginDecorationsFor(fileId).map((item) => ({
52
+ key: item.key,
53
+ from: item.from,
54
+ to: item.to,
55
+ tone: item.tone,
56
+ badge: item.badge,
57
+ tooltip: item.tooltip,
58
+ ...(item.command
59
+ ? {
60
+ onClick: () => {
61
+ void store
62
+ .interactWithPlugin({
63
+ workspaceId: ws.id,
64
+ pluginId: item.pluginId,
65
+ instanceId: item.instanceId,
66
+ kind: 'command',
67
+ name: item.command!,
68
+ payload: {
69
+ workspaceId: ws.id,
70
+ fileId,
71
+ source: 'decoration',
72
+ decorationId: item.id,
73
+ from: item.from,
74
+ to: item.to,
75
+ },
76
+ })
77
+ .catch((error) => store.report(String(error)));
78
+ },
79
+ }
80
+ : {}),
81
+ }));
82
+ }
83
+
84
+ function editorPluginCodeBlockRenderers(fileId: string): ExternalCodeBlockRenderer[] {
85
+ const ws = getWorkspace();
86
+ const store = getStore();
87
+ const source = store.pluginCodeBlockRenderers;
88
+ if (!ws || !source.length) return [];
89
+ const cacheKey = `${ws.id}:${fileId}`;
90
+ const cached = codeBlockRendererCache.get(cacheKey);
91
+ if (cached && cached.source === source) return cached.list;
92
+ const list: ExternalCodeBlockRenderer[] = source.map((renderer) => ({
93
+ id: `${renderer.key}:${renderer.instanceId}`,
94
+ languages: renderer.languages,
95
+ label: renderer.label ?? renderer.pluginName,
96
+ height: renderer.height,
97
+ mount(container, context) {
98
+ const workspaceId = ws.id;
99
+ const diagnostic = (level: string, message: string) => {
100
+ void store
101
+ .interactWithPlugin({
102
+ workspaceId,
103
+ pluginId: renderer.pluginId,
104
+ instanceId: renderer.instanceId,
105
+ name: renderer.view,
106
+ kind: 'diagnostic',
107
+ payload: { level, message },
108
+ })
109
+ .catch(() => {});
110
+ };
111
+ const buildState = (ctx: { language: string; source: string; readonly: boolean }) => ({
112
+ kind: 'codeBlock',
113
+ fileId,
114
+ language: ctx.language,
115
+ source: ctx.source,
116
+ readonly: ctx.readonly,
117
+ });
118
+ const sandbox = createPluginUiSandbox(
119
+ container,
120
+ renderer.bundle,
121
+ buildState(context),
122
+ async (payload) => {
123
+ if (
124
+ pluginRecord(payload) &&
125
+ payload.type === 'codeBlock.updateSource' &&
126
+ typeof payload.source === 'string' &&
127
+ payload.source.length <= 200 * 1024 &&
128
+ !context.readonly
129
+ ) {
130
+ context.updateSource(payload.source);
131
+ return;
132
+ }
133
+ await store.interactWithPlugin({
134
+ workspaceId,
135
+ pluginId: renderer.pluginId,
136
+ instanceId: renderer.instanceId,
137
+ name: renderer.view,
138
+ kind: 'message',
139
+ payload: { fileId, language: context.language, payload },
140
+ });
141
+ },
142
+ (cause) => {
143
+ diagnostic('error', cause);
144
+ },
145
+ diagnostic,
146
+ );
147
+ return {
148
+ update(nextContext) {
149
+ sandbox.update(buildState(nextContext));
150
+ },
151
+ dispose() {
152
+ sandbox.dispose();
153
+ },
154
+ };
155
+ },
156
+ }));
157
+ codeBlockRendererCache.set(cacheKey, { source, list });
158
+ if (codeBlockRendererCache.size > 32) {
159
+ codeBlockRendererCache.delete(codeBlockRendererCache.keys().next().value!);
160
+ }
161
+ return list;
162
+ }
163
+
164
+ return {
165
+ editorPluginSlashCommands,
166
+ editorPluginDecorations,
167
+ editorPluginCodeBlockRenderers,
168
+ };
169
+ }
@@ -1,4 +1,3 @@
1
1
  /** Host-side pure data helpers shared by foreground and server plugin runtimes. */
2
- export { applyPluginTextEdits, PluginQueryPager } from './data';
3
- export { queryPluginData, type PluginQueryContext } from './queries';
4
- export { mergeObject } from '../objects/workspace-objects';
2
+ export { applyPluginTextEdits, PluginQueryPager, queryPluginData, type PluginQueryContext } from '@tano/protocol/plugin-data';
3
+ export { mergeObject } from '@tano/editor/workspace-objects';