dsh-tiddlywiki 0.28.7 → 0.28.8

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 (52) hide show
  1. package/README.md +1 -0
  2. package/docs/CHANGELOG.md +1 -0
  3. package/docs/features.md +4 -0
  4. package/docs/usage.md +13 -3
  5. package/lib/client.js +63 -27
  6. package/lib/index.js +10655 -10188
  7. package/lib/index.js.map +1 -1
  8. package/package.json +2 -2
  9. package/src/client/dom.ts +26 -0
  10. package/src/client/index.ts +14 -0
  11. package/src/client/note-widget-draft.ts +154 -0
  12. package/src/client/note-widget-tags.ts +184 -0
  13. package/src/client/note-widget-upload.ts +50 -0
  14. package/src/client/note-widget.ts +19 -348
  15. package/src/client/panel.ts +12 -3
  16. package/src/client/render-fetch.ts +11 -4
  17. package/src/client/scope-seat.ts +117 -0
  18. package/src/client/session-summary.ts +29 -7
  19. package/src/client/settings-icon-picker.ts +238 -0
  20. package/src/client/settings-page-catalog.ts +578 -0
  21. package/src/client/settings-page-config.ts +445 -0
  22. package/src/client/settings-page-runtime.ts +149 -0
  23. package/src/client/settings-page-wikis.ts +432 -0
  24. package/src/client/settings-page.ts +127 -1425
  25. package/src/client/styles.ts +36 -0
  26. package/src/client/tool-views.ts +170 -36
  27. package/src/client/wiki-icon.generated.ts +97 -0
  28. package/src/client/wiki-icon.ts +50 -15
  29. package/src/client/wiki-scope-dock.ts +56 -2
  30. package/src/client/wiki-scope.ts +98 -0
  31. package/src/host/admin-catalog.ts +488 -0
  32. package/src/host/admin-routes.ts +670 -0
  33. package/src/host/admin-secrets.ts +119 -0
  34. package/src/host/admin.ts +3 -1244
  35. package/src/host/clip-bridge.ts +24 -1
  36. package/src/host/config.ts +10 -2
  37. package/src/host/routes-session.ts +617 -0
  38. package/src/host/routes-tw-proxy.ts +390 -0
  39. package/src/host/routes.ts +77 -829
  40. package/src/host/tools-attach.ts +151 -0
  41. package/src/host/tools-git.ts +213 -0
  42. package/src/host/tools-notes.ts +672 -0
  43. package/src/host/tools-read.ts +421 -0
  44. package/src/host/tools-support.ts +513 -0
  45. package/src/host/tools.ts +33 -1814
  46. package/src/host/wiki-registry.ts +25 -4
  47. package/src/host/wiki.ts +55 -5
  48. package/src/index-clip.ts +142 -0
  49. package/src/index-git.ts +196 -0
  50. package/src/index-prompt.ts +139 -0
  51. package/src/index-wikis.ts +353 -0
  52. package/src/index.ts +89 -429
package/src/index.ts CHANGED
@@ -25,30 +25,20 @@ import { ConfigStore, DARK_PALETTE_DEFAULT, type PluginConfigShape } from './hos
25
25
  import { registerAdminRoutes, resolveTwRoot, type AdminDeps, type AdminWikisApplyResult, type AdminWikisView } from './host/admin.ts'
26
26
  import { checkAllSeeds, runSeedById, removeSeedById } from './host/seeds.ts'
27
27
  import { TiddlyWebClient, isBinaryType, TEXT_LIST_FILTER } from './host/tw-api.ts'
28
- import { ClipBridge, downloadClipImage, type BridgeConfig, type ClipImageDownload } from './host/clip-bridge.ts'
29
28
  import { WechatPublishRunner, checkWechatReady, normalizeWechatConfig } from './host/wechat-publish.ts'
30
29
  import { registerTiddlywikiTools, tiddlywikiToolSummary, type ToolsDeps, type ToolScope } from './host/tools.ts'
31
- import { describePrompt, withScopeBanner, PROMPT_SECTION_NAME, PROMPT_SECTION_ORDER, type PromptConfig } from './host/prompt.ts'
30
+ import { describePrompt, type PromptConfig } from './host/prompt.ts'
32
31
  import {
33
- clearLocationState,
34
32
  defaultLocationStateFile,
35
- expandEnvPath,
36
- listWikiCandidates,
37
33
  locationPath,
38
- normalizeLocation,
39
34
  readLocationState,
40
35
  writeLocationState,
41
36
  type WikiLocation,
42
- type WikiLocationInfo,
43
- type WikiLocationSource,
44
37
  } from './host/wiki-location.ts'
45
- import { switchWiki, type WikiSwitchResult } from './host/wiki-switch.ts'
46
38
  import { WikiInstance } from './host/wiki-instance.ts'
47
39
  import { WikiFarm, resolveAgentScope, targetRuntimeFor } from './host/wiki-farm.ts'
48
40
  import { defaultSessionScopeFile, isSafeSessionId, readSessionScopes, setSessionScope } from './host/session-scope.ts'
49
- import { RepoCommitters } from './host/repo-committers.ts'
50
41
  import { installSplitSkill } from './host/skill-install.ts'
51
- import { isInsidePath, pathComparisonKey } from './host/path-key.ts'
52
42
  import {
53
43
  DEFAULT_WIKI_ID,
54
44
  DEFAULT_WIKI_MODE,
@@ -58,7 +48,6 @@ import {
58
48
  entryPath,
59
49
  readRegistry,
60
50
  singleEntryRegistry,
61
- validateRegistry,
62
51
  writeRegistry,
63
52
  type WikiEntry,
64
53
  type WikiRegistry,
@@ -66,6 +55,13 @@ import {
66
55
  import { READY_TIMEOUT_DEFAULT_MS } from './host/ready-policy.ts'
67
56
  import { ANON_USERNAME, PATH_PREFIX, TW_PROXY_PATH, TW_PROXY_PREFIX, WikiServer, proxyBaseFor } from './host/wiki.ts'
68
57
  import { dshHomePath, defineTool } from './sdk.ts'
58
+ // v0.28.8:apply() 太大,按「自洽的子面」拆到 index-*.ts(模块族,readFamily 读取,
59
+ // 守门脚本因此不必钉单个文件名)。index.ts 仍是唯一的插件入口,也仍然拥有全部
60
+ // 可变状态(farm / 控制文件缓存 / switching / disposed),子模块只拿到显式的 deps。
61
+ import { createWikiViews, proxyBaseForEntry, restartAffectedWikis, resolveWikiRoot } from './index-wikis.ts'
62
+ import { createGitLayer } from './index-git.ts'
63
+ import { createPromptSurface, createServerTuning } from './index-prompt.ts'
64
+ import { createClipSurface } from './index-clip.ts'
69
65
 
70
66
  /** Cordis plugin name (also the client loader id / profile row id). */
71
67
  export const name = 'dsh-tiddlywiki'
@@ -246,6 +242,9 @@ export type { PluginConfigShape } from './host/config.ts'
246
242
  export type { GitStatusView } from './host/git.ts'
247
243
  export type { Tiddler } from './host/tw-api.ts'
248
244
  export type { WikiServerOptions, WikiStatusView } from './host/wiki.ts'
245
+ // 桌面加固(v0.28.8):TW 子进程用哪个 node 起。导出是为了能被守门脚本直接断言
246
+ // (打包版 Electron 宿主下 process.execPath 是 Electron 二进制,起不了 TW)。
247
+ export { resolveNodeExecutable } from './host/wiki.ts'
249
248
 
250
249
  /** Plugin config (design doc §13). Defaults are applied in apply().
251
250
  * Mirrors PluginConfigShape (src/host/config.ts) — the cordis `config:` block;
@@ -307,7 +306,7 @@ interface ResolvedConfig {
307
306
  port: number
308
307
  git: { autoCommit: boolean; debounceMs: number; remote: string; branch: string }
309
308
  note: { tag: string; workspaceMark: boolean }
310
- bridge: { enabled: boolean; port: number; token: string; tag: string }
309
+ bridge: { enabled: boolean; port: number; token: string; tag: string; wiki: string }
311
310
  ui: { showQuickNote: boolean; showQuickNoteDock: boolean; quickNoteMode: 'native' | 'card'; sidebarLabel: string; showPanelStatus: boolean; showSyncButton: boolean; followDshTheme: boolean; darkPalette: string; tabLabel: string; showSessionTab: boolean; showRightbarTab: boolean; sendToAgent: { enabled: boolean; endpoint?: string; token?: string }; allArticles: { pageSize: number } }
312
311
  startup: { readyTimeoutMs: number }
313
312
  /**
@@ -339,7 +338,7 @@ const DEFAULTS: ResolvedConfig = {
339
338
  port: 0,
340
339
  git: { autoCommit: true, debounceMs: 60_000, remote: '', branch: 'main' },
341
340
  note: { tag: 'inbox', workspaceMark: true },
342
- bridge: { enabled: false, port: CLIP_BRIDGE_DEFAULT_PORT, token: '', tag: 'clip' },
341
+ bridge: { enabled: false, port: CLIP_BRIDGE_DEFAULT_PORT, token: '', tag: 'clip', wiki: '' },
343
342
  ui: { showQuickNote: true, showQuickNoteDock: true, quickNoteMode: 'native', sidebarLabel: 'TiddlyWiki', showPanelStatus: true, showSyncButton: true, followDshTheme: true, darkPalette: DARK_PALETTE_DEFAULT, tabLabel: '知识库', showSessionTab: true, showRightbarTab: true, sendToAgent: { enabled: true }, allArticles: { pageSize: 10 } },
344
343
  startup: { readyTimeoutMs: READY_TIMEOUT_DEFAULT_MS },
345
344
  // 可选功能默认关闭(v0.23.0):需额外安装 opencli + 浏览器扩展才可用。
@@ -368,13 +367,12 @@ export { TW_WEB_HOST_TIDDLER, TW_WEB_HOST_DEFAULT } from './host/config.ts'
368
367
  * Resolve the DEFAULT wikiRoot: explicit config (env-expanded) else
369
368
  * $DSH_HOME/tiddlywiki. The runtime pointer file can override it — see
370
369
  * `readLocationState()` in host/wiki-location.ts.
370
+ *
371
+ * v0.28.8: the implementation moved to `index-wikis.ts` together with the rest
372
+ * of the location surface; the re-export keeps the barrel (lib/index.js) and
373
+ * this module's own callers unchanged.
371
374
  */
372
- function resolveWikiRoot(config: TiddlywikiConfig): string {
373
- if (config.wikiRoot !== undefined && config.wikiRoot.trim().length > 0) {
374
- return expandEnvPath(config.wikiRoot.trim())
375
- }
376
- return dshHomePath('tiddlywiki')
377
- }
375
+ export { resolveWikiRoot }
378
376
 
379
377
  /*
380
378
  * `MANAGED_GITIGNORE_LINES` / `writeGitignore()` / `watchWiki()` moved to
@@ -428,50 +426,28 @@ export function apply(ctx: HostCtx, rawConfig: TiddlywikiConfig = {}): void {
428
426
  /** The cordis-level default location (last resort in the registry chain). */
429
427
  const defaultLocation: WikiLocation = { root: config.wikiRoot, name: config.wiki }
430
428
  const git = new GitFace()
431
- /**
432
- * Auto-commit is keyed by REPOSITORY, not by wiki (v0.28.0): several knowledge
433
- * bases may be subfolders of one repository, and only one `git add -A` per
434
- * repository may run (see host/repo-committers.ts).
435
- */
436
- const repos = new RepoCommitters({
437
- git,
438
- /**
439
- * Per REPOSITORY (v0.28.0): several knowledge bases may share one repository,
440
- * so the setting is resolved from the first wiki INSIDE that repository (in
441
- * list order — deterministic), falling back to the default wiki and then to
442
- * the cordis base.
443
- *
444
- * Wikis in one repository disagreeing about `git.*` is almost always a
445
- * mistake (a repository has ONE remote, ONE branch, ONE index), so it is
446
- * called out rather than silently resolved.
447
- */
448
- settings: (repoRoot) => {
449
- const members = (farm?.registry.wikis ?? []).filter((entry) => entryIsInRepo(entry, repoRoot))
450
- const chosen = members[0]
451
- const runtimeConfig = (entry: WikiEntry | undefined): PluginConfigShape | undefined =>
452
- entry === undefined ? undefined : farm?.runtime(entry.id)?.eff()
453
- const g = (runtimeConfig(chosen) ?? eff()).git ?? {}
454
- if (members.length > 1) {
455
- const fingerprints = new Set(members.map((entry) => JSON.stringify(runtimeConfig(entry)?.git ?? {})))
456
- if (fingerprints.size > 1) {
457
- console.warn(`[dsh-tiddlywiki] 知识库 ${members.map((entry) => entry.id).join('、')} 共用同一个仓库(${repoRoot}),但各自配了不同的 git.* —— 一个仓库只有一份 git 设置,本次以「${chosen?.id ?? '默认库'}」为准`)
458
- }
459
- }
460
- return {
461
- autoCommit: g.autoCommit ?? config.git.autoCommit,
462
- debounceMs: g.debounceMs ?? config.git.debounceMs,
463
- }
464
- },
465
- message: () => `wiki autocommit ${new Date().toISOString()}`,
466
- log: (message) => console.warn('[dsh-tiddlywiki]', message),
467
- })
468
429
  /** Created by the startup task, once the control file has been read. */
469
430
  let farm: WikiFarm<WikiInstance> | undefined
470
431
  /** The runtime legacy/agent traffic falls back to (undefined = nothing up). */
471
432
  const defaultInstance = (): WikiInstance | undefined => farm?.defaultRuntime()
472
- const eff = (): PluginConfigShape => defaultInstance()?.eff() ?? baseShape
473
- const effectiveWorkspaceMark = (): boolean => defaultInstance()?.workspaceMark() ?? config.note.workspaceMark
474
- const effectiveBridge = (): BridgeConfig => defaultInstance()?.bridgeConfig() ?? config.bridge
433
+ /**
434
+ * Auto-commit is keyed by REPOSITORY, not by wiki (v0.28.0), and the four
435
+ * "effective config" accessors below all read through the DEFAULT runtime —
436
+ * v0.28.8 moved that whole layer into index-git.ts (see its module note) and
437
+ * this is the state it resolves against.
438
+ */
439
+ const gitLayer = createGitLayer({
440
+ git,
441
+ farm: () => farm,
442
+ defaultInstance,
443
+ baseShape: () => baseShape,
444
+ gitConfig: () => config.git,
445
+ noteConfig: () => config.note,
446
+ defaultPath: () => wikiViews.defaultPath(),
447
+ registryFile: () => registryFile,
448
+ isDisposed: () => disposed,
449
+ })
450
+ const { repos, teardownCommitter, reapplyGitConfig, effectiveWorkspaceMark, effectiveBridge, effectiveWechat } = gitLayer
475
451
 
476
452
  /** sessionId → wikiId (v0.28.0). Loaded at boot, written by the GUI selector. */
477
453
  let sessionScopes: Record<string, string> = {}
@@ -504,16 +480,6 @@ export function apply(ctx: HostCtx, rawConfig: TiddlywikiConfig = {}): void {
504
480
  for (const dispose of disposers.splice(0)) dispose()
505
481
  }
506
482
 
507
- /**
508
- * Effective 公众号发布 config (cordis base + settings-page overlay), read PER
509
- * REQUEST: enabling the feature, switching the adapter or rotating the token
510
- * applies without a dsh web restart. `normalizeWechatConfig` is the single
511
- * place that turns the loose config-tiddler JSON into the typed shape — a
512
- * garbage `adapter`/`command` falls back to the defaults instead of reaching
513
- * the spawned command line.
514
- */
515
- const effectiveWechat = (): ReturnType<typeof normalizeWechatConfig> => normalizeWechatConfig(eff().wechat)
516
-
517
483
  /**
518
484
  * WeChat publish runner (v0.23.3): owns the opencli child process behind the
519
485
  * TW toolbar button. Construction spawns nothing (the CLI is resolved per
@@ -538,69 +504,14 @@ export function apply(ctx: HostCtx, rawConfig: TiddlywikiConfig = {}): void {
538
504
  // has been loaded, and (b) after every settings-page save (admin route →
539
505
  // `onConfigChanged`). Re-registration is skipped when the built text is
540
506
  // unchanged, so saving an unrelated setting never churns the prompt.
541
- let disposePromptSection: (() => void) | undefined
542
- let currentPromptText: string | undefined
543
- /**
544
- * The prompt section's text for ONE session.
545
- *
546
- * It is a FUNCTION (v0.28.0): the section is registered once, but the text is
547
- * evaluated per assembly with that assembly's agent, so a session scoped to
548
- * wiki B is told it is working on wiki B. Single-wiki installs get exactly the
549
- * previous text — the scope line appears only when more than one knowledge
550
- * base is visible.
551
- *
552
- * Per-wiki `prompt.*` is honoured too: the config read is the SCOPE wiki's, so
553
- * the 「每库定制提示词」decision from the design doc actually takes effect.
554
- */
555
- const promptTextFor = (sessionId: string | undefined): string => {
556
- const scope = toolScope(sessionId)
557
- const cfg = resolveAgentScope(farm, sessionScopes, sessionId).runtime?.eff() ?? baseShape
558
- // `wechat.enabled` (v0.23.0) is NOT a `prompt.*` field but it gates the
559
- // publish rule, and the feature is opt-in + separately installed — users who
560
- // never enabled it must see no publishing text.
561
- const built = withScopeBanner(describePrompt(
562
- { ...((cfg.prompt ?? {}) as PromptConfig), wechat: (cfg.wechat ?? {}).enabled === true },
563
- tiddlywikiToolSummary(),
564
- ).text, scope)
565
- return built
566
- }
567
-
568
- /**
569
- * Built text for the DEFAULT scope (also the saved-state preview / the
570
- * re-registration key). The signature catalogue for `full` mode comes from the
571
- * live tool registry, never from hand-written prose (v0.21.0 — the old copy had
572
- * drifted).
573
- */
574
- const promptText = (): string => promptTextFor(undefined)
575
-
576
- /**
577
- * (Re-)register the section. The text is a function, so a scope change needs
578
- * no re-registration at all; this still runs on config saves so the
579
- * `system-prompt/change` signal (and the history re-render) fires, and the
580
- * skip-if-unchanged check keeps an unrelated save from churning anything.
581
- */
582
- const applyPrompt = (): void => {
583
- const next = promptText()
584
- if (next === currentPromptText) return
585
- currentPromptText = next
586
- disposePromptSection?.()
587
- disposePromptSection = undefined
588
- if (next.length === 0) return
589
- disposePromptSection = ctx.systemPrompt.section({
590
- name: PROMPT_SECTION_NAME,
591
- order: PROMPT_SECTION_ORDER,
592
- text: (context: unknown) => {
593
- // `AssembleContext.scope` IS the agent (see assembleContextFor in
594
- // @deepseek-ai/dsh-agent), and Agent.id is the session id — the documented
595
- // way a section learns whose prompt it is building.
596
- const agent = (context as { scope?: { id?: unknown } } | undefined)?.scope
597
- return promptTextFor(typeof agent?.id === 'string' ? agent.id : undefined)
598
- },
599
- })
600
- }
601
- disposers.push(() => {
602
- disposePromptSection?.()
603
- disposePromptSection = undefined
507
+ // v0.28.8: the whole wiring (the per-assembly text + the registration) lives
508
+ // in index-prompt.ts; the disposer list stays here because teardown order is
509
+ // the plugin's business.
510
+ const { applyPrompt } = createPromptSurface({
511
+ ctx,
512
+ effectiveConfigFor: (sessionId) => resolveAgentScope(farm, sessionScopes, sessionId).runtime?.eff() ?? baseShape,
513
+ toolScope,
514
+ pushDisposer: (dispose) => disposers.push(dispose),
604
515
  })
605
516
 
606
517
  /**
@@ -609,111 +520,30 @@ export function apply(ctx: HostCtx, rawConfig: TiddlywikiConfig = {}): void {
609
520
  * wiki — it takes effect on the next start()/restart() without a dsh web
610
521
  * restart. Values are clamped by host/ready-policy.ts.
611
522
  */
612
- const applyServerTuning = (): void => {
613
- for (const runtime of farm?.allRuntimes() ?? []) runtime.applyServerTuning()
614
- }
523
+ const applyServerTuning = createServerTuning({ farm: () => farm })
615
524
 
616
525
  /**
617
- * Lazy TW client. host/wiki-instance.ts owns both the port-change invalidation
618
- * (a crash before readiness makes the child re-probe a free port, so a cached
619
- * client must not stay pinned to a dead one) and the preemptive Basic
620
- * credentials (`auth.username` puts the child behind `readers`/`writers`, so
621
- * EVERY request — reads included — needs auth).
526
+ * The same-origin proxy base a wiki's TW frontend must use (v0.28.0).
527
+ * The rule itself lives in host/wiki.ts (`proxyBaseFor`) so the harness and the
528
+ * host cannot disagree about it — see that function for why it matters.
622
529
  */
623
- const client = (): TiddlyWebClient | undefined => defaultInstance()?.client()
624
-
625
- // 本地剪藏桥(书签小工具后端):只监听 127.0.0.1,per-request 读 effective
626
- // config —— enabled/token/tag 在设置页保存后立即生效;port 只在启动时绑定
627
- // 一次(改端口需重启 dsh web,seed 文档已说明)。写入走唯一的 TiddlyWebClient
628
- // 通道(D1),不存在第二条写路径。
629
- const clipBridge = new ClipBridge({
630
- getConfig: effectiveBridge,
631
- write: async (tiddler) => {
632
- const c = client()
633
- if (c === undefined) throw new Error('wiki not ready')
634
- await c.put(tiddler)
635
- },
636
- exists: async (title) => {
637
- const c = client()
638
- if (c === undefined) throw new Error('wiki not ready')
639
- return (await c.get(title)) !== undefined
640
- },
641
- // Server-side image download: no browser CORS; a browser-ish UA + the clip
642
- // source page as Referer get past most hotlink-protected CDNs. The whole
643
- // SSRF posture (public http(s) only, per-hop validation with the resolved
644
- // address PINNED so DNS cannot rebind between check and connect, manual
645
- // redirects, streaming 15MB cap, no transparent decompression) lives in
646
- // downloadClipImage (v0.19.0).
647
- download: async (imageUrl, referer): Promise<ClipImageDownload> => {
648
- const result = await downloadClipImage(imageUrl, referer)
649
- return { buffer: result.buffer, type: result.type ?? null }
650
- },
651
- log: (m) => console.info('[dsh-tiddlywiki] clip bridge:', m),
530
+ const proxyBase = (entry: WikiEntry): string => proxyBaseForEntry(() => farm, entry)
531
+ // 本地剪藏桥(v0.28.8:整块接线搬到 index-clip.ts —— 它解释「一次剪藏落到哪个
532
+ // 库」的唯一实现,见那里的 clipTarget 文档)。
533
+ const { clipBridge } = createClipSurface({
534
+ farm: () => farm,
535
+ defaultInstance,
536
+ effectiveBridge,
537
+ effect: (fn, label) => ctx.effect(fn, label),
652
538
  })
653
- ctx.effect(() => () => clipBridge.stop(), 'dsh-tiddlywiki: clip bridge')
654
539
 
655
540
  // Auto-committer + filesystem watcher live on the instance (v0.28.0). They are
656
541
  // still set up/torn down SEPARATELY: a runtime wiki switch has to release both
657
542
  // (they hold the OLD folder) and re-arm them for the new one. The teardown is
658
543
  // registered exactly ONCE below — a per-switch `disposers.push()` would leak a
659
544
  // disposer per switch.
660
- /**
661
- * Release every running wiki's fs watcher AND flush every repository's pending
662
- * commit (plugin teardown / a wiki switch). The COMMITTERS themselves are
663
- * plugin-wide — one per repository — so they are NOT dropped here: a switch
664
- * must not throw away the debounce window of unrelated wikis that share the
665
- * same repository.
666
- */
667
- const teardownCommitter = async (): Promise<void> => {
668
- for (const runtime of farm?.allRuntimes() ?? []) await runtime.teardownExtras()
669
- await repos.flush()
670
- }
671
545
  disposers.push(() => { void teardownCommitter() })
672
546
 
673
- /**
674
- * Re-apply the EFFECTIVE git config to the running instance (v0.25.0).
675
- *
676
- * Until then, `git.*` was read ONCE: `AutoCommitter` snapshots
677
- * `enabled`/`debounceMs` into immutable options at construction, and the remote
678
- * only reached the repo through `bootstrapGit()` at startup. The settings page
679
- * happily saved + echoed new values that changed nothing until a dsh web
680
- * restart — turning 自动提交 off kept committing, changing the remote kept
681
- * pushing to the old one. Rebuilding the committer closes that gap; the guard
682
- * flag (plus teardownExtras' own idempotence) keeps a burst of saves from
683
- * leaving two committers or a dangling fs watcher.
684
- *
685
- * Not covered on purpose: an already-initialised repository keeps its branch
686
- * (`git.branch` is only consulted by `git.init`), and clearing the remote
687
- * field does not delete `origin` (that is a destructive repo change the UI
688
- * never promised). Both are documented in the settings page + README.
689
- */
690
- const reapplyGitConfig = async (): Promise<void> => {
691
- await teardownCommitter()
692
- const g = eff().git ?? {}
693
- const remote = (typeof g.remote === 'string' && g.remote.trim().length > 0 ? g.remote : config.git.remote).trim()
694
- if (remote.length > 0) {
695
- // Repo-level operation: running it inside any wiki folder of that
696
- // repository sets the repository's `origin` (there is only one).
697
- const ensured = await git.ensureRemote(defaultPath(), remote)
698
- if (!ensured.ok) console.warn('[dsh-tiddlywiki] git remote update:', ensured.message)
699
- }
700
- repos.rebuild()
701
- for (const runtime of farm?.allRuntimes() ?? []) runtime.setupExtras()
702
- }
703
-
704
- /**
705
- * The same-origin proxy base a wiki's TW frontend must use (v0.28.0).
706
- * The rule itself lives in host/wiki.ts (`proxyBaseFor`) so the harness and the
707
- * host cannot disagree about it — see that function for why it matters.
708
- */
709
- const proxyBaseForEntry = (entry: WikiEntry): string => proxyBaseFor((farm?.registry.mode ?? 'single'), entry.id)
710
-
711
- /** Does this wiki live inside that repository (or is it the repository root)? */
712
- const entryIsInRepo = (entry: WikiEntry, repoRoot: string): boolean => {
713
- const path = entryPath(entry)
714
- return pathComparisonKey(path) === pathComparisonKey(repoRoot) || isInsidePath(repoRoot, path)
715
- }
716
-
717
547
  // Tools (works even while the wiki is down; the scope resolves lazily).
718
548
  const toolsDeps: ToolsDeps = {
719
549
  // Per SESSION (v0.28.0): the session's scope decides which knowledge base a
@@ -731,7 +561,7 @@ export function apply(ctx: HostCtx, rawConfig: TiddlywikiConfig = {}): void {
731
561
  // restart (rule #1); here we only pick the right targets — several knowledge
732
562
  // bases may share one repository, so "something changed" is NOT the same
733
563
  // question as "this wiki is stale".
734
- restartAffected: async (dir: string, changedFiles: readonly string[]) => restartAffectedWikis(dir, changedFiles),
564
+ restartAffected: async (dir: string, changedFiles: readonly string[]) => restartAffectedWikis({ farm: () => farm, repoRootOf: (d) => repos.repoRootOf(d) }, dir, changedFiles),
735
565
  // Workspace (project) marking for agent-created notes (v0.24.0): a tool call
736
566
  // carries its session id, and the session header carries the cwd — so the
737
567
  // plugin can tag new notes with the project all by itself instead of asking
@@ -757,6 +587,12 @@ export function apply(ctx: HostCtx, rawConfig: TiddlywikiConfig = {}): void {
757
587
  // an orphan process and a leaked listener. Every await below is followed by a
758
588
  // `disposed` check, and the task stops the child itself when it notices.
759
589
  let disposed = false
590
+ /**
591
+ * Single-flight guard: two concurrent switches would fight over the child.
592
+ * Declared here (next to `disposed`) because the whole switch surface moved to
593
+ * index-wikis.ts and takes both as getters — see createWikiViews below.
594
+ */
595
+ let switching = false
760
596
 
761
597
  /** single 模式的位置:旧指针文件 > cordis 默认(v0.22.0 的优先级,逐字保留)。 */
762
598
  const singleModeLocation = async (): Promise<WikiLocation> => {
@@ -832,7 +668,7 @@ export function apply(ctx: HostCtx, rawConfig: TiddlywikiConfig = {}): void {
832
668
  twRoot: resolveTwRoot,
833
669
  touchCommit: (dir) => { void repos.touch(dir) },
834
670
  flushCommits: (dir) => repos.flush(dir),
835
- proxyBase: () => proxyBaseForEntry(entry),
671
+ proxyBase: () => proxyBase(entry),
836
672
  }),
837
673
  log: (message) => console.warn('[dsh-tiddlywiki]', message),
838
674
  })
@@ -867,209 +703,33 @@ export function apply(ctx: HostCtx, rawConfig: TiddlywikiConfig = {}): void {
867
703
  }
868
704
  })()
869
705
 
870
- // ── Runtime wiki location (v0.22.0, extended v0.28.0) ──────────────────────
871
- // TWO paths, because the two modes genuinely differ:
872
- // single → legacy behaviour, verbatim: a pointer file OUTSIDE every wiki
873
- // records the choice and `switchWiki()` moves the ONE running wiki
874
- // with rollback (stop → repoint → start → bootstrap, and restore the
875
- // old folder on failure). Covered by verify-wiki-switch.mjs.
876
- // multi → "move the DEFAULT wiki's folder": edit the registry and let the
877
- // farm reconcile (stop → recycle → start). No whole-plugin rollback
878
- // is needed there — the other knowledge bases keep serving.
879
- /** The folder the default wiki occupies, running or not. */
880
- const defaultPath = (): string => {
881
- const running = defaultInstance()
882
- if (running !== undefined) return running.path
883
- const entry = farm === undefined ? undefined : defaultEntry(farm.registry)
884
- return entry === undefined ? locationPath(defaultLocation) : entryPath(entry)
885
- }
886
- /** The `{root,name}` the default wiki currently occupies (running or not). */
887
- const defaultCurrentLocation = (): WikiLocation => {
888
- const running = defaultInstance()
889
- if (running !== undefined) return running.server.currentLocation
890
- const entry = farm === undefined ? undefined : defaultEntry(farm.registry)
891
- return entry === undefined ? defaultLocation : { root: entry.root, name: entry.name }
892
- }
893
- /** Source of the CURRENT location, for the settings page. */
894
- const locationSource = async (): Promise<WikiLocationSource> => {
895
- const state = await readLocationState(locationStateFile)
896
- if (state.active !== undefined && locationPath(state.active) === defaultPath()) return 'state'
897
- return typeof rawConfig.wikiRoot === 'string' && rawConfig.wikiRoot.trim().length > 0 ? 'config' : 'default'
898
- }
899
- const locationInfo = async (): Promise<WikiLocationInfo> => {
900
- const state = await readLocationState(locationStateFile)
901
- const current = defaultCurrentLocation()
902
- return {
903
- current: { ...current, path: defaultPath(), source: await locationSource() },
904
- default: { ...defaultLocation, path: locationPath(defaultLocation) },
905
- stateFile: locationStateFile,
906
- candidates: await listWikiCandidates(current.root),
907
- ...(state.error !== undefined ? { error: state.error } : {}),
908
- }
909
- }
910
- /** Single-flight guard: two concurrent switches would fight over the child. */
911
- let switching = false
912
- /** SINGLE mode: the legacy orchestrator, on the farm's default runtime. */
913
- const runSwitch = async (target: { root?: unknown; name?: unknown }, persist: (t: WikiLocation) => Promise<void>): Promise<WikiSwitchResult> => {
914
- if (switching) return { ok: false, error: '正在切换知识库,请稍候再试', rolledBack: true }
915
- // A switch in flight while the plugin is being disposed (hot reload / dsh web
916
- // shutdown) would re-arm the committer + fs watcher AFTER teardown ran, and
917
- // could even spawn a fresh TW child after `stop()` (v0.23.5).
918
- if (disposed) return { ok: false, error: '插件正在卸载,已取消切换', rolledBack: false }
919
- const runtime = defaultInstance()
920
- if (runtime === undefined) return { ok: false, error: '默认知识库当前没有运行,无法切换位置', rolledBack: false }
921
- switching = true
922
- try {
923
- const result = await switchWiki({
924
- currentLocation: () => runtime.server.currentLocation,
925
- currentPath: () => runtime.path,
926
- // v0.24.1: ironclad rule #1 lists the knowledge-base switch as a path
927
- // that MUST drain first; writes still in the OLD wiki's syncer queue were
928
- // otherwise killed with the child. `drainThenStop` is the shared primitive
929
- // (owned by the instance since v0.28.0); the rollback path reuses it, and a
930
- // missing client (child already down) is a no-op.
931
- stopServer: async () => { await runtime.drainStop() },
932
- applyLocation: (nextLocation) => {
933
- // Repoints the server AND drops the cached REST client (whose 2s list
934
- // cache belongs to the OLD wiki).
935
- runtime.updateEntry({ ...runtime.entry, root: nextLocation.root, name: nextLocation.name })
936
- },
937
- startServer: async () => { await runtime.server.start() },
938
- teardownExtras: () => runtime.teardownExtras(),
939
- setupExtras: () => { runtime.setupExtras() },
940
- reloadConfig: async () => {
941
- await runtime.config.load(runtime.client())
942
- // The new wiki carries its own config tiddler → its own prompt.*.
943
- applyPrompt()
944
- },
945
- bootstrap: async () => {
946
- await runtime.bootstrapWiki()
947
- await runtime.bootstrapGit()
948
- },
949
- savePointer: persist,
950
- log: (message) => console.warn('[dsh-tiddlywiki]', message),
951
- }, target)
952
- // Teardown may have run while the switch was awaiting: the switch itself
953
- // succeeded, but the extras it re-armed must be released again so we do not
954
- // leak a committer/watcher past dispose (v0.23.5).
955
- if (disposed) await runtime.teardownExtras()
956
- // The farm must agree with the runtime the orchestrator just moved — its
957
- // registry is what a later `apply()` (add/remove an entry) diffs against.
958
- if (result.ok && farm !== undefined) {
959
- const moved = runtime.entry
960
- farm.syncRegistry({ ...farm.registry, wikis: farm.registry.wikis.map((entry) => (entry.id === moved.id ? moved : entry)) })
961
- }
962
- return result
963
- } finally {
964
- switching = false
965
- }
966
- }
967
- /**
968
- * MULTI mode: move the DEFAULT wiki to another folder. The farm's reconcile
969
- * stops the old child, recycles the runtime and starts it on the new folder;
970
- * the registry is persisted LAST (a failed write costs restart-survival, not
971
- * the running wiki — same trade-off the pointer file already makes).
972
- */
973
- const repointDefault = async (target: { root?: unknown; name?: unknown }): Promise<WikiSwitchResult> => {
974
- if (disposed) return { ok: false, error: '插件正在卸载,已取消切换', rolledBack: false }
975
- if (farm === undefined) return { ok: false, error: '插件尚未就绪,请稍后再试', rolledBack: true }
976
- if (switching) return { ok: false, error: '正在切换知识库,请稍候再试', rolledBack: true }
977
- const normalized = normalizeLocation(target)
978
- if (normalized.location === undefined) return { ok: false, error: normalized.error ?? '位置非法', rolledBack: true }
979
- const next = normalized.location
980
- const current = defaultEntry(farm.registry)
981
- if (current === undefined) return { ok: false, error: '清单里没有默认知识库', rolledBack: true }
982
- const moved: WikiEntry = { ...current, root: next.root, name: next.name }
983
- const nextRegistry: WikiRegistry = { ...farm.registry, wikis: farm.registry.wikis.map((entry) => (entry.id === moved.id ? moved : entry)) }
984
- // Re-validate: moving a folder can collide with (or nest inside) another
985
- // registered wiki, and those rules are the whole point of the registry.
986
- const validated = validateRegistry(nextRegistry)
987
- if (validated.registry === undefined) return { ok: false, error: validated.fatal.join(';'), rolledBack: true }
988
- switching = true
989
- try {
990
- await farm.apply(validated.registry)
991
- const applied: WikiSwitchResult = { ok: true, location: { root: moved.root, name: moved.name }, path: entryPath(moved) }
992
- try {
993
- await writeRegistry(validated.registry, registryFile)
994
- } catch (err) {
995
- return { ...applied, warning: `位置已切换,但清单写入失败(重启 dsh web 后会回到原位置):${err instanceof Error ? err.message : String(err)}` }
996
- }
997
- return applied
998
- } finally {
999
- switching = false
1000
- }
1001
- }
1002
- /** Switch the DEFAULT wiki to another folder and remember the choice. */
1003
- const switchWikiLocation = (target: { root?: unknown; name?: unknown }): Promise<WikiSwitchResult> => {
1004
- if (farm?.registry.mode === 'multi') return repointDefault(target)
1005
- return runSwitch(target, async (t) => { await writeLocationState(t, locationStateFile) })
1006
- }
1007
- /**
1008
- * 「恢复为配置默认」: single mode drops the pointer and goes back to the cordis
1009
- * default (cleared EVEN when the current folder already IS the default, or the
1010
- * stale pointer wins again after the next restart); multi mode moves the
1011
- * default wiki back to the configured location.
1012
- */
1013
- const resetWikiLocation = async (): Promise<WikiSwitchResult> => {
1014
- if (farm?.registry.mode === 'multi') return repointDefault(defaultLocation)
1015
- if (locationPath(defaultLocation) === defaultPath()) {
1016
- await clearLocationState(locationStateFile)
1017
- return { ok: true, location: defaultLocation, path: defaultPath() }
1018
- }
1019
- return runSwitch(defaultLocation, async () => { await clearLocationState(locationStateFile) })
1020
- }
1021
-
1022
- /** The control file's view for the settings page (see controlRegistryNow). */
1023
- const buildWikisView = (): AdminWikisView => {
1024
- const registry = controlRegistryNow()
1025
- return {
1026
- mode: registry.mode,
1027
- defaultId: registry.defaultId,
1028
- source: controlSource,
1029
- registryFile,
1030
- ...(controlError !== undefined ? { error: controlError } : {}),
1031
- warnings: controlWarnings,
1032
- wikis: registry.wikis.map((entry) => {
1033
- const runtime = farm?.runtime(entry.id)
1034
- return {
1035
- id: entry.id,
1036
- label: entry.label,
1037
- root: entry.root,
1038
- name: entry.name,
1039
- path: entryPath(entry),
1040
- agentVisible: entry.agentVisible,
1041
- autostart: entry.autostart,
1042
- running: runtime !== undefined,
1043
- status: runtime?.server.status().status ?? 'stopped',
1044
- }
1045
- }),
1046
- }
1047
- }
1048
-
1049
706
  /**
1050
- * Restart the RUNNING wikis whose content a pull just changed (v0.28.0).
707
+ * The folder the default wiki occupies, running or not.
1051
708
  *
1052
- * Shared by the agent tool and the browser `/sync` route so the two cannot
1053
- * drift. `dir` is where the pull ran (the repository is resolved from it) and
1054
- * `changedFiles` are repository-relative — which is what makes this correct
1055
- * when several knowledge bases share one repository.
709
+ * v0.28.8: the location/view sub-surface lives in index-wikis.ts — it owns the
710
+ * `{root,name}` bookkeeping, the single/multi switch orchestration and the
711
+ * settings-page registry view. The mutable state it resolves against stays
712
+ * HERE (farm / control-file cache / switching / disposed), which is why every
713
+ * hop below is an accessor: `disposed` is declared just above, and the
714
+ * `switching` flag it owns is passed as a getter/setter pair.
1056
715
  */
1057
- const restartAffectedWikis = async (dir: string, changedFiles: readonly string[]): Promise<{ restarted: string[]; failed: Array<{ id: string; message: string }> }> => {
1058
- if (farm === undefined) return { restarted: [], failed: [] }
1059
- const repoRoot = (await repos.repoRootOf(dir)) ?? dir
1060
- const restarted: string[] = []
1061
- const failed: Array<{ id: string; message: string }> = []
1062
- for (const runtime of farm.affectedBy(repoRoot, changedFiles)) {
1063
- try {
1064
- // `WikiInstance.restart()` drains the syncer queue first (rule #1).
1065
- await runtime.restart()
1066
- restarted.push(runtime.entry.id)
1067
- } catch (err) {
1068
- failed.push({ id: runtime.entry.id, message: err instanceof Error ? err.message : String(err) })
1069
- }
1070
- }
1071
- return { restarted, failed }
1072
- }
716
+ const wikiViews = createWikiViews({
717
+ rawConfig: () => rawConfig,
718
+ defaultLocation: () => defaultLocation,
719
+ locationStateFile: () => locationStateFile,
720
+ registryFile: () => registryFile,
721
+ farm: () => farm,
722
+ defaultInstance,
723
+ controlRegistryNow,
724
+ controlSource: () => controlSource,
725
+ controlWarnings: () => controlWarnings,
726
+ controlError: () => controlError,
727
+ isSwitching: () => switching,
728
+ setSwitching: (value) => { switching = value },
729
+ isDisposed: () => disposed,
730
+ applyPrompt,
731
+ })
732
+ const { defaultPath, defaultCurrentLocation, locationInfo, switchWikiLocation, resetWikiLocation, buildWikisView } = wikiViews
1073
733
 
1074
734
  // Routes + settings-panel admin surface (lazy webServer).
1075
735
  ctx.inject(['webServer'], (webCtx: HostCtx) => {
@@ -1153,7 +813,7 @@ export function apply(ctx: HostCtx, rawConfig: TiddlywikiConfig = {}): void {
1153
813
  getWikiPath: (req) => target(req)?.path ?? defaultPath(),
1154
814
  // Same helper as the agent tool (one implementation, two callers): a pull
1155
815
  // can change several knowledge bases that share one repository.
1156
- restartAffected: (_req, dir, changedFiles) => restartAffectedWikis(dir, changedFiles),
816
+ restartAffected: (_req, dir, changedFiles) => restartAffectedWikis({ farm: () => farm, repoRootOf: (d) => repos.repoRootOf(d) }, dir, changedFiles),
1157
817
  // The composer's per-session selector (v0.28.0). Reading is a Map lookup;
1158
818
  // writing persists to session-scope.ts AND starts the wiki on demand — the
1159
819
  // tools resolve the scope SYNCHRONOUSLY and never start anything, so the