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
@@ -24,16 +24,24 @@
24
24
  * Save posts to /dsh-tiddlywiki/note → an independent tiddler (title & tags
25
25
  * editable; defaults: timestamp title + config tag, usually "inbox").
26
26
  *
27
+ * v0.28.8 split: this file is the card's ASSEMBLY POINT — the state machine and
28
+ * the whole DOM build. Its sub-parts live next door and are re-exported at the
29
+ * bottom so the public surface (index.ts, quick-note-dock.ts) is unchanged:
30
+ * - note-widget-draft.ts draft persistence + pure helpers
31
+ * - note-widget-tags.ts the multi-tag chip editor
32
+ * - note-widget-upload.ts attachment upload (and MAX_UPLOAD_BYTES)
33
+ *
27
34
  * @module dsh-tiddlywiki/client/note-widget
28
35
  */
29
36
  import { toast } from './toast.ts'
30
37
  import { openEditorPopup, isEditorPopupOpen, isEditorPopupBlank } from './editor-popup.ts'
31
38
  import { buildMarkdownEditor, type MarkdownEditor } from './markdown-editor.ts'
32
- import { EDIT_ENDPOINT, GET_ENDPOINT, NOTE_ENDPOINT, RECENT_ENDPOINT, TAGS_ENDPOINT, UPLOAD_ENDPOINT, resolveTwUrl, twProxyFor, withWikiQuery } from './endpoints.ts'
39
+ import { EDIT_ENDPOINT, GET_ENDPOINT, NOTE_ENDPOINT, RECENT_ENDPOINT, resolveTwUrl, twProxyFor, withWikiQuery } from './endpoints.ts'
33
40
  import { fetchStatus } from './status-cache.ts'
34
41
  import { resolveFocusWiki, subscribeFocusWiki } from './wiki-focus.ts'
35
-
36
- const MAX_UPLOAD_BYTES = 64 * 1024 * 1024
42
+ import { buildTagEditor } from './note-widget-tags.ts'
43
+ import { uploadInto } from './note-widget-upload.ts'
44
+ import { DRAFT_DEBOUNCE_MS, adoptDraft, clearDraft, draftSignature, fetchDefaultTag, loadDraft, persistDraft, relativeTime, timestampTitle } from './note-widget-draft.ts'
37
45
 
38
46
  /**
39
47
  * Broadcast by the card on open/close (detail: { open }). The input-dock quick-
@@ -41,316 +49,6 @@ const MAX_UPLOAD_BYTES = 64 * 1024 * 1024
41
49
  */
42
50
  export const NOTE_STATE_EVENT = 'dsh-tw-note-state'
43
51
 
44
- /**
45
- * 旧版全局草稿 key(v0.18.0 及以前)。多标签页会互相覆盖,现在只作为一次性
46
- * 迁移来源读取:读到且本窗口还没有草稿 → 迁移到本窗口的 key 并删除它。
47
- */
48
- const LEGACY_DRAFT_KEY = 'dsh-tw-note-draft-v1'
49
- /** 本窗口草稿 key 前缀(`<前缀><窗口 id>`),窗口之间互不覆盖。 */
50
- const DRAFT_KEY_PREFIX = 'dsh-tw-note-draft-v1:'
51
- /** sessionStorage 里保存本标签页窗口 id 的 key(刷新后仍是同一个窗口)。 */
52
- const DRAFT_WINDOW_ID_KEY = 'dsh-tw-note-window-id'
53
- /** Draft auto-save debounce. */
54
- const DRAFT_DEBOUNCE_MS = 500
55
-
56
- /**
57
- * 本窗口的草稿命名空间 id:优先取 sessionStorage 里的随机 id(同一标签页刷新后
58
- * 仍是同一个窗口 → 自己的草稿静默恢复);sessionStorage 不可用时退化为「本次
59
- * 加载一个随机 id」(刷新后会被当成「其它窗口的草稿」,恢复时给出提示而不是
60
- * 静默覆盖)。
61
- */
62
- const DRAFT_WINDOW_ID: string = (() => {
63
- try {
64
- const existing = sessionStorage.getItem(DRAFT_WINDOW_ID_KEY)
65
- if (existing !== null && existing.length > 0) return existing
66
- const created = Math.random().toString(36).slice(2, 10)
67
- sessionStorage.setItem(DRAFT_WINDOW_ID_KEY, created)
68
- return created
69
- } catch {
70
- return Math.random().toString(36).slice(2, 10)
71
- }
72
- })()
73
-
74
- interface Draft { text: string; title: string; tags: string[]; savedAt: number; windowId?: string }
75
-
76
- /** 读取结果:draft = 草稿本体;foreign = 不是本窗口写的(迁移/跨窗口)。 */
77
- interface DraftHit { draft: Draft; foreign: boolean }
78
-
79
- function draftKey(): string {
80
- return `${DRAFT_KEY_PREFIX}${DRAFT_WINDOW_ID}`
81
- }
82
-
83
- function parseDraft(raw: string | null): Draft | null {
84
- if (raw === null) return null
85
- try {
86
- const parsed = JSON.parse(raw) as Partial<Draft>
87
- if (typeof parsed.text !== 'string' || typeof parsed.title !== 'string') return null
88
- return {
89
- text: parsed.text,
90
- title: parsed.title,
91
- tags: Array.isArray(parsed.tags) ? parsed.tags.filter((t): t is string => typeof t === 'string') : [],
92
- savedAt: typeof parsed.savedAt === 'number' ? parsed.savedAt : 0,
93
- windowId: typeof parsed.windowId === 'string' ? parsed.windowId : undefined,
94
- }
95
- } catch {
96
- return null
97
- }
98
- }
99
-
100
- function readDraftFrom(key: string): Draft | null {
101
- try {
102
- return parseDraft(localStorage.getItem(key))
103
- } catch {
104
- return null
105
- }
106
- }
107
-
108
- /**
109
- * 读取本窗口草稿。本窗口 key 为空时尝试迁移旧全局 key(一次性:迁移后删除旧
110
- * key)。返回 null = 没有任何草稿;foreign=true = 草稿来源不是本窗口(旧 key
111
- * 迁移过来,或 sessionStorage 不可用时窗口 id 变了),调用方需要给出可见提示。
112
- */
113
- function loadDraft(): DraftHit | null {
114
- const own = readDraftFrom(draftKey())
115
- if (own !== null) {
116
- return { draft: own, foreign: own.windowId !== undefined && own.windowId !== DRAFT_WINDOW_ID }
117
- }
118
- const legacy = readDraftFrom(LEGACY_DRAFT_KEY)
119
- if (legacy === null) return null
120
- // 旧 key 一次性迁移:补上本窗口标记写进本窗口 key,然后删除旧 key。
121
- const migrated: Draft = { ...legacy, windowId: DRAFT_WINDOW_ID }
122
- persistDraft(migrated)
123
- try { localStorage.removeItem(LEGACY_DRAFT_KEY) } catch { /* ignore */ }
124
- return { draft: migrated, foreign: true }
125
- }
126
-
127
- /** 采纳草稿(标记为本窗口所有),避免每次打开都重复提示「来自其它窗口」。 */
128
- function adoptDraft(draft: Draft): void {
129
- persistDraft({ ...draft, windowId: DRAFT_WINDOW_ID })
130
- }
131
-
132
- function persistDraft(draft: Draft): void {
133
- try { localStorage.setItem(draftKey(), JSON.stringify({ ...draft, windowId: DRAFT_WINDOW_ID })) } catch { /* storage unavailable */ }
134
- }
135
-
136
- function clearDraft(): void {
137
- try { localStorage.removeItem(draftKey()) } catch { /* ignore */ }
138
- }
139
-
140
- /**
141
- * 内容签名(标题 + 正文 + 标签):用来判断「这份内容是不是已经写进 wiki 了」。
142
- * 只做相等比较,不是哈希——不做安全用途(v0.19.1)。
143
- */
144
- function draftSignature(title: string, text: string, tags: string[]): string {
145
- return `${title}\u0000${text}\u0000${tags.join('\u0001')}`
146
- }
147
-
148
- function pad(n: number): string {
149
- return n < 10 ? `0${n}` : String(n)
150
- }
151
-
152
- /** Default note title: `YYYY-MM-DD HH:mm`. */
153
- function timestampTitle(date = new Date()): string {
154
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
155
- }
156
-
157
- /** Compact Chinese relative time for the recent picker (e.g. "3小时前"). */
158
- function relativeTime(iso: string | null): string {
159
- if (iso === null) return ''
160
- const ms = new Date(iso).getTime()
161
- if (Number.isNaN(ms)) return ''
162
- const diff = Date.now() - ms
163
- const min = Math.floor(diff / 60_000)
164
- if (min < 1) return '刚刚'
165
- if (min < 60) return `${min}分钟前`
166
- const hr = Math.floor(min / 60)
167
- if (hr < 24) return `${hr}小时前`
168
- const day = Math.floor(hr / 24)
169
- if (day < 30) return `${day}天前`
170
- return new Date(ms).toLocaleDateString('zh-CN')
171
- }
172
-
173
- /** The default tag for a new note (settings `note.tag`).
174
- *
175
- * Reads the shared, TTL-cached `/status` projection rather than a private copy
176
- * of the `ui.*` shape (v0.22.8 — this was one of three duplicates). */
177
- async function fetchDefaultTag(): Promise<string> {
178
- const status = await fetchStatus()
179
- return typeof status?.note?.tag === 'string' && status.note.tag.length > 0 ? status.note.tag : 'inbox'
180
- }
181
-
182
- /** Multi-tag chip editor with autocomplete from the wiki's existing tags. */
183
- function buildTagEditor(opts: { onChange?: () => void; wikiQuery?: (url: string) => string } = {}): {
184
- el: HTMLDivElement
185
- /** Commits any pending input first, then returns the chips (user actions). */
186
- getTags: () => string[]
187
- /** Pure read of the committed chips — never commits pending input. */
188
- peekTags: () => string[]
189
- setDefault: (tag: string) => void
190
- setTags: (tags: string[]) => void
191
- /** Remove the document-level outside-click listener (unmount must not leak). */
192
- dispose: () => void
193
- } {
194
- const wrap = document.createElement('div')
195
- wrap.className = 'dsh-tw-note-tags'
196
-
197
- const chipWrap = document.createElement('div')
198
- chipWrap.className = 'dsh-tw-note-chips'
199
- const input = document.createElement('input')
200
- input.className = 'dsh-tw-note-taginput'
201
- input.placeholder = 'tag(可多选,自动补全)'
202
- const suggest = document.createElement('div')
203
- suggest.className = 'dsh-tw-note-tagsuggest'
204
- suggest.hidden = true
205
- wrap.append(chipWrap, input, suggest)
206
-
207
- const chips: string[] = []
208
- const hideSuggest = (): void => { suggest.hidden = true }
209
-
210
- const emit = (): void => { opts.onChange?.() }
211
-
212
- const renderChips = (): void => {
213
- chipWrap.replaceChildren()
214
- for (const tag of chips) {
215
- const chip = document.createElement('span')
216
- chip.className = 'dsh-tw-note-tagchip'
217
- chip.textContent = tag
218
- const x = document.createElement('span')
219
- x.className = 'dsh-tw-note-tagchip-x'
220
- x.textContent = '×'
221
- x.title = `移除 tag「${tag}」`
222
- x.addEventListener('click', (event) => {
223
- event.stopPropagation()
224
- const i = chips.indexOf(tag)
225
- if (i >= 0) {
226
- chips.splice(i, 1)
227
- renderChips()
228
- emit()
229
- }
230
- })
231
- chip.append(x)
232
- chipWrap.append(chip)
233
- }
234
- }
235
-
236
- const addTag = (tag: string): void => {
237
- const t = tag.trim()
238
- if (t.length === 0 || chips.includes(t)) return
239
- chips.push(t)
240
- input.value = ''
241
- renderChips()
242
- hideSuggest()
243
- input.focus()
244
- emit()
245
- }
246
-
247
- const commitInput = (): void => {
248
- for (const raw of input.value.split(/\s+/)) addTag(raw)
249
- }
250
-
251
- // Existing tags, fetched lazily once per widget lifetime — PER TARGET WIKI
252
- // (v0.28.0): the card can be pointed at another knowledge base, and its tag
253
- // suggestions must come from the same one the note is written to. The memo is
254
- // keyed by the resolved URL, so switching the target re-reads automatically
255
- // (no reset call, nothing to forget).
256
- let knownTags: string[] = []
257
- let tagsPromise: Promise<string[]> | undefined
258
- let tagsPromiseKey: string | undefined
259
- const ensureTags = (): Promise<string[]> => {
260
- const url = opts.wikiQuery?.(TAGS_ENDPOINT) ?? TAGS_ENDPOINT
261
- if (tagsPromise === undefined || tagsPromiseKey !== url) {
262
- tagsPromiseKey = url
263
- tagsPromise = fetch(url, { signal: AbortSignal.timeout(5_000) })
264
- .then((r) => (r.ok ? (r.json() as Promise<{ tags?: string[] }>) : Promise.resolve<{ tags?: string[] }>({})))
265
- .then((p) => [...(p.tags ?? [])].sort((a, b) => a.localeCompare(b, 'zh')))
266
- .catch(() => [])
267
- void tagsPromise.then((list) => { knownTags = list })
268
- }
269
- return tagsPromise
270
- }
271
-
272
- const showSuggest = (): void => {
273
- const q = input.value.trim().toLowerCase()
274
- const matches = knownTags
275
- .filter((t) => !chips.includes(t) && (q.length === 0 || t.toLowerCase().includes(q)))
276
- .slice(0, 8)
277
- suggest.replaceChildren()
278
- for (const tag of matches) {
279
- const item = document.createElement('div')
280
- item.className = 'dsh-tw-note-tagsuggest-item'
281
- item.textContent = tag
282
- // 键盘可达:div + mousedown 对键盘用户不可用,补 role/tabIndex/Enter·Space。
283
- item.setAttribute('role', 'button')
284
- item.tabIndex = 0
285
- item.setAttribute('aria-label', `添加标签「${tag}」`)
286
- item.addEventListener('mousedown', (event) => {
287
- event.preventDefault()
288
- addTag(tag)
289
- })
290
- item.addEventListener('keydown', (event) => {
291
- if (event.key === 'Enter' || event.key === ' ') {
292
- event.preventDefault()
293
- addTag(tag)
294
- }
295
- })
296
- suggest.append(item)
297
- }
298
- suggest.hidden = matches.length === 0
299
- }
300
-
301
- input.addEventListener('focus', () => { void ensureTags().then(showSuggest) })
302
- input.addEventListener('input', () => {
303
- if (knownTags.length === 0) void ensureTags().then(showSuggest)
304
- else showSuggest()
305
- })
306
- input.addEventListener('keydown', (event) => {
307
- if (event.key === 'Enter' || event.key === ',') {
308
- event.preventDefault()
309
- commitInput()
310
- } else if (event.key === 'Backspace' && input.value.length === 0 && chips.length > 0) {
311
- chips.pop()
312
- renderChips()
313
- emit()
314
- } else if (event.key === 'Escape') {
315
- hideSuggest()
316
- }
317
- })
318
- const onDocClick = (event: Event): void => {
319
- if (!wrap.contains(event.target as Node)) hideSuggest()
320
- }
321
- document.addEventListener('click', onDocClick, true)
322
-
323
- return {
324
- el: wrap,
325
- getTags: () => {
326
- commitInput()
327
- return [...chips]
328
- },
329
- peekTags: () => [...chips],
330
- setDefault: (tag: string) => {
331
- // Only pre-fill when nothing is chosen yet; never steal focus.
332
- if (chips.length === 0) {
333
- const t = tag.trim()
334
- if (t.length > 0) {
335
- chips.push(t)
336
- renderChips()
337
- }
338
- }
339
- },
340
- setTags: (tags: string[]) => {
341
- chips.length = 0
342
- for (const tag of Array.isArray(tags) ? tags : []) {
343
- const t = typeof tag === 'string' ? tag.trim() : ''
344
- if (t.length > 0 && !chips.includes(t)) chips.push(t)
345
- }
346
- input.value = ''
347
- renderChips()
348
- hideSuggest()
349
- },
350
- dispose: () => document.removeEventListener('click', onDocClick, true),
351
- }
352
- }
353
-
354
52
  /** All DOM refs created by build(); undefined until the first open. */
355
53
  interface BuiltUi {
356
54
  root: HTMLDivElement
@@ -366,41 +64,6 @@ interface BuiltUi {
366
64
  recentWrap: HTMLDivElement
367
65
  }
368
66
 
369
- /**
370
- * Upload one file to the wiki (raw body, name in ?name=), then insert a
371
- * Markdown image/link line at the caret of the given editor.
372
- *
373
- * `wikiQuery` scopes the upload to the CARD's target knowledge base (v0.28.0):
374
- * an attachment must land in the same wiki as the note that references it.
375
- */
376
- async function uploadInto(file: File, editor: MarkdownEditor, wikiQuery: (url: string) => string = (url) => url): Promise<void> {
377
- if (file.size > MAX_UPLOAD_BYTES) {
378
- toast(`文件过大(≤ ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)}MB)`)
379
- return
380
- }
381
- try {
382
- const res = await fetch(wikiQuery(`${UPLOAD_ENDPOINT}?name=${encodeURIComponent(file.name)}`), {
383
- method: 'POST',
384
- headers: { 'content-type': file.type || 'application/octet-stream' },
385
- body: file,
386
- signal: AbortSignal.timeout(120_000),
387
- })
388
- const payload = (await res.json().catch(() => null)) as { ok?: boolean; name?: string; url?: string; error?: string } | null
389
- if (!res.ok || payload?.ok !== true) {
390
- toast(`上传失败:${payload?.error ?? `HTTP ${res.status}`}`)
391
- return
392
- }
393
- const name = payload.name ?? file.name
394
- const markdown = file.type.startsWith('image/')
395
- ? `![${name}](${payload.url})`
396
- : `[${name}](${payload.url})`
397
- editor.insertAtCaret(markdown)
398
- toast(`已上传「${name}」并插入链接`)
399
- } catch (err) {
400
- toast(`上传失败:${err instanceof Error ? err.message : String(err)}`)
401
- }
402
- }
403
-
404
67
  interface RecentItem { title: string; tags: string[]; modified: string | null; snippet: string }
405
68
 
406
69
  /** The quick-note card handle the FAB drives. */
@@ -1243,3 +906,11 @@ export function createNoteWidget(): NoteWidgetHandle {
1243
906
 
1244
907
  // (The FAB owns the trigger since v0.5 — there is deliberately no standalone
1245
908
  // mount export here; index.ts wires createNoteWidget into mountKnowledgeFab.)
909
+
910
+ // ── public surface of the note-widget family (v0.28.8 split) ───────────────
911
+ // The sub-modules above were extracted out of THIS file; re-export their parts
912
+ // so every existing import path (`./note-widget.ts`) keeps working unchanged.
913
+ export { DRAFT_DEBOUNCE_MS, adoptDraft, clearDraft, draftSignature, fetchDefaultTag, loadDraft, persistDraft, relativeTime, timestampTitle } from './note-widget-draft.ts'
914
+ export type { Draft, DraftHit } from './note-widget-draft.ts'
915
+ export { buildTagEditor } from './note-widget-tags.ts'
916
+ export { MAX_UPLOAD_BYTES, uploadInto } from './note-widget-upload.ts'
@@ -86,11 +86,20 @@ const PANEL_SKIN: TwFrameSkin = {
86
86
  */
87
87
  const OPEN_TIDDLER_EVENT = 'dsh-tw-open-tiddler'
88
88
 
89
- /** Ask the mounted panel to open `title` in the TW native page. */
90
- export function openTiddler(title: string): void {
89
+ /**
90
+ * Ask the mounted panel to open `title` in the TW native page.
91
+ *
92
+ * `wikiId` (v0.28.8) names the knowledge base the link belongs to. In multi
93
+ * mode the panel must load `/tw/<id>/` and focus that wiki — without it the
94
+ * panel would show the default wiki while the card came from another one. Omit
95
+ * for the default wiki (single-wiki installs: every call, as before).
96
+ */
97
+ export function openTiddler(title: string, wikiId?: string): void {
91
98
  if (typeof document === 'undefined') return
92
99
  if (typeof title !== 'string' || title.length === 0) return
93
- document.dispatchEvent(new CustomEvent(OPEN_TIDDLER_EVENT, { detail: { title } }))
100
+ document.dispatchEvent(new CustomEvent(OPEN_TIDDLER_EVENT, {
101
+ detail: typeof wikiId === 'string' && wikiId.length > 0 ? { title, wikiId } : { title },
102
+ }))
94
103
  }
95
104
 
96
105
  /**
@@ -21,12 +21,19 @@
21
21
  *
22
22
  * @module dsh-tiddlywiki/client/render-fetch
23
23
  */
24
- import { RENDER_ENDPOINT } from './endpoints.ts'
24
+ import { RENDER_ENDPOINT, withWikiQuery } from './endpoints.ts'
25
25
 
26
- /** Render one tiddler by title through the host's sanitizing render route. */
27
- export async function fetchRenderFragment(title: string, timeoutMs = 15_000): Promise<string | null> {
26
+ /**
27
+ * Render one tiddler by title through the host's sanitizing render route.
28
+ *
29
+ * `wikiId` (v0.28.8) targets a specific knowledge base. Omit it for the default
30
+ * wiki — and note that omitting it is NOT the same as "whatever the user is
31
+ * looking at": the host falls back to the farm default, so a multi-wiki caller
32
+ * that forgets this renders ANOTHER wiki's identically-titled tiddler.
33
+ */
34
+ export async function fetchRenderFragment(title: string, timeoutMs = 15_000, wikiId?: string): Promise<string | null> {
28
35
  try {
29
- const res = await fetch(RENDER_ENDPOINT, {
36
+ const res = await fetch(withWikiQuery(RENDER_ENDPOINT, wikiId), {
30
37
  method: 'POST',
31
38
  headers: { 'content-type': 'application/json', 'x-requested-with': 'TiddlyWiki' },
32
39
  body: JSON.stringify({ title }),
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Where the per-session knowledge-base selector is MOUNTED (v0.28.8).
3
+ *
4
+ * WHY THIS MODULE EXISTS
5
+ * ----------------------
6
+ * The selector needs two different homes, because "pick a wiki" happens in two
7
+ * different places:
8
+ *
9
+ * 1. **A blank (new) session** — the user is choosing a mode/preset before any
10
+ * message exists. The right seat is the input-selector context row, next to
11
+ * the mode picker: `conversation.input.selector.context`. The author asked
12
+ * for exactly this ("像 dsh-client-ui-git-graph 在模式选择后面增加个知识库选择",
13
+ * feedback item 9), and that plugin is the reference implementation for how
14
+ * to reach it.
15
+ * 2. **An active session** — the selector must keep working where v0.28.0 put
16
+ * it, inside the quick-note row (`conversation.input.dock`), because the
17
+ * context row does not exist for an active session.
18
+ *
19
+ * The context seat is declared by SOME shells and not others: the running
20
+ * `dsh web` shell renders it, while the published SDK cohort dropped the hole
21
+ * (git-graph carries the same note). Registering into an undeclared slot THROWS,
22
+ * so both seats go through `slots.inject(...)` — the declaration-aware path —
23
+ * rather than a bare `register()`. We additionally verify this shell's live slot
24
+ * tree at runtime: `cordis_inspect_query` on the running DSH reports
25
+ * `conversation.input.selector.context` as `available: false` on the version
26
+ * installed here, which is why the fallback is the COMMON path today and must
27
+ * stay correct rather than being a rarely-exercised contingency.
28
+ *
29
+ * @module dsh-tiddlywiki/client/scope-seat
30
+ */
31
+
32
+ /** Structural face of the two seats we mount into (kept local: no SDK types). */
33
+ export interface ScopeSeatSlots {
34
+ inject(name: string, register: () => unknown): (() => void) | undefined
35
+ register(opts: { name: string; id: string; order?: number; label?: string }, component: unknown): () => void
36
+ }
37
+
38
+ /** The blank-session input-selector context row (the mode picker's neighbour). */
39
+ export const SELECTOR_CONTEXT_SLOT = 'conversation.input.selector.context'
40
+
41
+ /** The full-width dock above the composer (where the selector lives since v0.28.0). */
42
+ export const INPUT_DOCK_SLOT = 'conversation.input.dock'
43
+
44
+ /**
45
+ * How long to wait for the selector-context declaration before assuming this
46
+ * shell does not have it. Covers the shell's first render of the input selector
47
+ * row after the conversation service is up (mirrors git-graph's 2000ms).
48
+ */
49
+ export const CONTEXT_FALLBACK_MS = 2000
50
+
51
+ /**
52
+ * Register the knowledge-base chip into the best available seat.
53
+ *
54
+ * Returns a disposer that tears down BOTH the winning registration and any
55
+ * still-pending wait, so a disposal during the fallback window cannot leak a
56
+ * timer or double-mount.
57
+ *
58
+ * @param slots - the client slots registry.
59
+ * @param chip - factory for the chip component (receives the slot props).
60
+ */
61
+ export function mountScopeSeat(slots: ScopeSeatSlots, chip: unknown): () => void {
62
+ let disposed = false
63
+ let mounted = false
64
+ let fallbackTimer: number | undefined
65
+ const removers: Array<() => void> = []
66
+
67
+ /** Give up on the context seat and use the dock instead (exactly once). */
68
+ const fallbackToDock = (): void => {
69
+ if (disposed || mounted) return
70
+ const remove = slots.inject(INPUT_DOCK_SLOT, () => {
71
+ if (disposed) return () => {}
72
+ return slots.register(
73
+ { name: INPUT_DOCK_SLOT, id: 'wiki-scope', order: 9, label: '知识库' },
74
+ chip,
75
+ )
76
+ })
77
+ if (remove !== undefined) removers.push(remove)
78
+ }
79
+
80
+ const disposeContextWait = slots.inject(SELECTOR_CONTEXT_SLOT, () => {
81
+ if (disposed) return () => {}
82
+ mounted = true
83
+ // The declaration arrived, so the dock fallback must never also mount.
84
+ if (fallbackTimer !== undefined) {
85
+ window.clearTimeout(fallbackTimer)
86
+ fallbackTimer = undefined
87
+ }
88
+ try {
89
+ return slots.register(
90
+ { name: SELECTOR_CONTEXT_SLOT, id: 'wiki-scope', order: 9, label: '知识库' },
91
+ chip,
92
+ )
93
+ } catch {
94
+ // The slot was declared but this shell still refuses it (an older SDK
95
+ // whose SlotCore rejects undeclared names): fall back rather than losing
96
+ // the selector entirely.
97
+ mounted = false
98
+ fallbackToDock()
99
+ return () => {}
100
+ }
101
+ })
102
+ if (disposeContextWait !== undefined) removers.push(disposeContextWait)
103
+
104
+ fallbackTimer = window.setTimeout(() => {
105
+ fallbackTimer = undefined
106
+ fallbackToDock()
107
+ }, CONTEXT_FALLBACK_MS)
108
+
109
+ return () => {
110
+ disposed = true
111
+ if (fallbackTimer !== undefined) {
112
+ window.clearTimeout(fallbackTimer)
113
+ fallbackTimer = undefined
114
+ }
115
+ for (const remove of removers.splice(0)) remove()
116
+ }
117
+ }
@@ -38,10 +38,13 @@
38
38
  * @module dsh-tiddlywiki/client/session-summary
39
39
  */
40
40
  import * as React from 'react'
41
- import { GET_ENDPOINT, SESSION_SUMMARY_ENDPOINT as SUMMARY_ENDPOINT } from './endpoints.ts'
41
+ import { GET_ENDPOINT, SESSION_SUMMARY_ENDPOINT as SUMMARY_ENDPOINT, withWikiQuery } from './endpoints.ts'
42
42
  // The render call lives in ONE place (render-fetch.ts) — this module and
43
43
  // tool-views.ts used to carry near-identical copies (v0.22.8).
44
44
  import { fetchRenderFragment } from './render-fetch.ts'
45
+ // 本会话作用域的知识库(v0.28.8):汇总必须落在同一个库,否则标题条目在库里、
46
+ // 渲染却去默认库找 → 一直「条目不存在」(见 wiki-scope.ts)。
47
+ import { resolveSessionWikiId } from './wiki-scope.ts'
45
48
  import { getTabLabel, setTabLabel } from './tw-frame.ts'
46
49
 
47
50
  /** conversation.view 槽位注册 id(模块私有,v0.22.8:只有本文件的 mount 用)。 */
@@ -81,9 +84,9 @@ interface SessionSummaryViewProps {
81
84
  * `notFound` interpretation used to be written out a second time in the
82
85
  * interval, and the two disagreed on what a transport error means.
83
86
  */
84
- async function tiddlerExists(title: string): Promise<'yes' | 'no' | 'unknown'> {
87
+ async function tiddlerExists(title: string, wikiId?: string): Promise<'yes' | 'no' | 'unknown'> {
85
88
  try {
86
- const res = await fetch(`${GET_ENDPOINT}?title=${encodeURIComponent(title)}`, { signal: AbortSignal.timeout(8_000) })
89
+ const res = await fetch(withWikiQuery(`${GET_ENDPOINT}?title=${encodeURIComponent(title)}`, wikiId), { signal: AbortSignal.timeout(8_000) })
87
90
  if (res.status === 404) return 'no'
88
91
  // 非 2xx(500/503…)不是「条目还在」的证据:拿不到确定答案就报未知,别猜。
89
92
  if (!res.ok) return 'unknown'
@@ -104,6 +107,20 @@ function SessionSummaryView(props: SessionSummaryViewProps): React.ReactElement
104
107
  const [error, setError] = React.useState('')
105
108
  /** 降级提示(探测状态未知 / 后台刷新失败):不清掉已渲染的旧内容,只加一行说明。 */
106
109
  const [probeUnknown, setProbeUnknown] = React.useState(false)
110
+ /**
111
+ * 本会话作用域的知识库(v0.28.8)。`undefined` = 默认库,此时下面每一处请求
112
+ * 都与加这个功能之前逐字相同(`withWikiQuery` 对空值不改 URL)。
113
+ *
114
+ * 为什么必须有:汇总条目由 host 写进**该库**,渲染/探测若不带 `?wiki=` 就会去
115
+ * 默认库找同一个标题 —— 表现为一直「条目不存在」并反复重建。
116
+ */
117
+ const [wikiId, setWikiId] = React.useState<string | undefined>(undefined)
118
+ /**
119
+ * 自愈 tick 是长驻闭包,读不到最新 state;用 ref 让它探测的是**当前**库
120
+ * (否则切库后自愈会一直去旧库找汇总条目,误判成「条目被清」并反复重建)。
121
+ */
122
+ const wikiIdRef = React.useRef<string | undefined>(undefined)
123
+ wikiIdRef.current = wikiId
107
124
  const genRef = React.useRef(0)
108
125
  /**
109
126
  * 卸载守卫(v0.22.3):genRef 只能识别「被更新的一次 generate 取代」,覆盖不到
@@ -158,7 +175,12 @@ function SessionSummaryView(props: SessionSummaryViewProps): React.ReactElement
158
175
  return
159
176
  }
160
177
  try {
161
- const res = await fetch(SUMMARY_ENDPOINT, {
178
+ // 汇总也按库作用域(v0.28.8):host 的 /session/summary 会读该库自己的
179
+ // 笔记集合,不传就会拿默认库的数据生成一份"看起来对、其实来自别的库"的汇总。
180
+ const scoped = await resolveSessionWikiId(sessionId)
181
+ if (!mountedRef.current || gen !== genRef.current) return
182
+ setWikiId(scoped)
183
+ const res = await fetch(withWikiQuery(SUMMARY_ENDPOINT, scoped), {
162
184
  method: 'POST',
163
185
  headers: { 'content-type': 'application/json' },
164
186
  body: JSON.stringify({ session: sessionId }),
@@ -177,12 +199,12 @@ function SessionSummaryView(props: SessionSummaryViewProps): React.ReactElement
177
199
  setSummaryTitle(data.title)
178
200
  // 原生渲染:wikitext → HTML 片段(块解析,标题/表格/列表/引用齐全,
179
201
  // 链接已重写为 /dsh-tiddlywiki/tw/#标题,点击由全局拦截器接管)。
180
- const fragment = await fetchRenderFragment(data.title)
202
+ const fragment = await fetchRenderFragment(data.title, 15_000, scoped)
181
203
  if (!mountedRef.current || gen !== genRef.current) return
182
204
  if (fragment === null) {
183
205
  // 区分「条目被清(TW 重启把 $:/temp 冲掉了)」与「渲染服务不可用」:
184
206
  // 前者自动重建(受 MAX_MISSES 约束,有界),后者直接报错交还手动重试。
185
- const exists = await tiddlerExists(data.title)
207
+ const exists = await tiddlerExists(data.title, scoped)
186
208
  if (!mountedRef.current || gen !== genRef.current) return
187
209
  if (exists === 'no') {
188
210
  failuresRef.current++
@@ -252,7 +274,7 @@ function SessionSummaryView(props: SessionSummaryViewProps): React.ReactElement
252
274
  if (typeof document !== 'undefined' && document.hidden) return
253
275
  // Reuse the shared interpretation rather than a second copy of the
254
276
  // 404/`notFound` logic (v0.22.8) — three-valued since v0.24.x.
255
- const serverHas = await tiddlerExists(summaryTitle)
277
+ const serverHas = await tiddlerExists(summaryTitle, wikiIdRef.current)
256
278
  if (!alive) return
257
279
  if (serverHas === 'unknown') {
258
280
  // 探测失败:不计失败(TW 重启期间会被瞬间烧完额度),也不清零(不能把