@huanlin/dsh-plugin-input-history 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","names":["capacity: number","parsed: unknown","historyStore: HistoryStore | null","en: Record<InputHistoryKey, string>","zh: Record<InputHistoryKey, string>","navCursor: number | null","savedDraft: string | null"],"sources":["../src/client/history.ts","../src/client/HistoryDock.tsx","../src/client/ime.ts","../src/client/dom.ts","../src/client/locales.ts","../src/client/index.ts"],"sourcesContent":["/**\n * Prompt history store — pure functions over a string array.\n *\n * The store is a FIFO list of unique prompt strings, persisted to\n * `localStorage`. Newest entries are at the end of the array. The\n * navigation cursor walks backwards from the end (ArrowUp = older,\n * ArrowDown = newer).\n *\n * The functions in this module are pure (no `localStorage` access) so\n * they can be unit-tested without jsdom. The `HistoryStore` class below\n * wires them to `localStorage` with try/catch containment — a quota\n * exception or a disabled storage (private mode) degrades gracefully to\n * an in-memory list that lives for the page lifetime.\n *\n * @module @huanlin/dsh-plugin-input-history/client/history\n */\n\n/** localStorage key (versioned; bump on schema changes to start fresh). */\nexport const STORAGE_KEY = 'dsh-plugin-input-history:v1'\n\n/** Default capacity when none is configured. */\nexport const DEFAULT_CAPACITY = 500\n\n/**\n * Append a prompt to the history.\n *\n * Rules:\n * - Empty / whitespace-only strings are ignored (the InputBar already\n * rejects them at submit, but defensive).\n * - When the new entry equals the most recent one, it is a no-op\n * (avoids stacking duplicates from rapid resends).\n * - When the new entry already exists earlier in the history, that\n * earlier occurrence is removed (recency wins; the prompt moves to\n * the end). This mirrors terminal shell behaviour.\n * - When the array would exceed `capacity`, the oldest entries are\n * dropped from the front (FIFO).\n *\n * @param history - the current history array (newest at end).\n * @param prompt - the prompt to append.\n * @param capacity - the maximum number of entries to retain.\n * @returns the new history array (may be the same reference if no-op).\n */\nexport function appendHistory(\n history: readonly string[],\n prompt: string,\n capacity: number = DEFAULT_CAPACITY,\n): string[] {\n const trimmed = prompt.trim()\n if (trimmed === '') return history as string[]\n // Latest-equal with no earlier duplicate: true no-op (same reference).\n // When an earlier duplicate exists, the filter below removes it so the\n // entry moves to the end (recency wins).\n const lastIndex = history.lastIndexOf(trimmed)\n if (lastIndex !== -1 && lastIndex === history.length - 1 && history.indexOf(trimmed) === lastIndex) {\n return history as string[]\n }\n // Remove any earlier occurrence (recency wins).\n const filtered = history.filter(item => item !== trimmed)\n filtered.push(trimmed)\n // FIFO: drop oldest entries from the front.\n const cap = Math.max(1, capacity)\n if (filtered.length > cap) {\n return filtered.slice(filtered.length - cap)\n }\n return filtered\n}\n\n/**\n * Navigation cursor for walking the history.\n *\n * The cursor is `null` when the user is not navigating (i.e. they are\n * typing a fresh draft). ArrowUp sets it to the last index, then\n * decrements; ArrowDown increments; when it would exceed `history.length\n * - 1`, it returns to `null` (meaning \"restore the in-progress draft\").\n *\n * @param current - the current cursor (null = not navigating).\n * @param total - the total number of history entries.\n * @param dir - `'up'` (older) or `'down'` (newer).\n * @returns the next cursor, or `null` when navigation falls off the\n * newest end (caller should restore the saved draft).\n */\nexport function nextIndex(\n current: number | null,\n total: number,\n dir: 'up' | 'down',\n): number | null {\n if (total === 0) return null\n if (dir === 'up') {\n if (current === null) return total - 1\n if (current <= 0) return 0\n return current - 1\n }\n // dir === 'down'\n if (current === null) return null\n if (current >= total - 1) return null\n return current + 1\n}\n\n/**\n * Read the history entry at a cursor, or `null` when the cursor is null.\n *\n * @param history - the history array.\n * @param cursor - the navigation cursor.\n * @returns the prompt at the cursor, or `null`.\n */\nexport function entryAt(\n history: readonly string[],\n cursor: number | null,\n): string | null {\n if (cursor === null) return null\n if (cursor < 0 || cursor >= history.length) return null\n return history[cursor] ?? null\n}\n\n/**\n * History store bound to `localStorage`.\n *\n * The store reads once on construction (or on `reload()`) and keeps an\n * in-memory copy. Writes go to both memory and `localStorage` inside a\n * try/catch — a quota exception leaves the in-memory copy authoritative\n * for the rest of the page lifetime. This trades cross-tab consistency\n * for resilience: the store never throws on a write, and the worst case\n * is that a tab keeps its own view until refresh.\n *\n * Cross-tab sync is intentionally NOT implemented: prompt history is\n * append-mostly and a stale read across tabs is harmless (the next\n * append corrects it). Listening to the `storage` event would add\n * reactivity that the navigation UI does not need.\n */\nexport class HistoryStore {\n private items: string[]\n private readonly storage: Storage | null\n private readonly key: string\n\n /**\n * @param capacity - maximum entries to retain (FIFO).\n * @param storage - the storage backend (defaults to `localStorage` when available).\n * @param key - the storage key (defaults to {@link STORAGE_KEY}).\n */\n constructor(\n private readonly capacity: number = DEFAULT_CAPACITY,\n storage?: Storage | null,\n key: string = STORAGE_KEY,\n ) {\n this.storage = storage ?? safeLocalStorage()\n this.key = key\n this.items = this.readFromStorage()\n }\n\n /** Current history snapshot (newest at end). */\n get list(): readonly string[] {\n return this.items\n }\n\n /** Number of entries currently stored. */\n get length(): number {\n return this.items.length\n }\n\n /** Reload from storage (e.g. after a suspected external edit). Truncates to the current capacity. */\n reload(): void {\n const loaded = this.readFromStorage()\n const cap = Math.max(1, this.capacity)\n this.items = loaded.length > cap ? loaded.slice(loaded.length - cap) : loaded\n }\n\n /**\n * Append a prompt and persist. See {@link appendHistory} for rules.\n * @returns the new history snapshot.\n */\n append(prompt: string): readonly string[] {\n this.items = appendHistory(this.items, prompt, this.capacity)\n this.writeToStorage()\n return this.items\n }\n\n /** Clear all history (used by tests and a future \"clear\" UI). */\n clear(): void {\n this.items = []\n this.writeToStorage()\n }\n\n private readFromStorage(): string[] {\n if (this.storage === null) return []\n try {\n const raw = this.storage.getItem(this.key)\n if (raw === null) return []\n const parsed: unknown = JSON.parse(raw)\n if (!Array.isArray(parsed)) return []\n return parsed.filter((item): item is string => typeof item === 'string')\n } catch {\n return []\n }\n }\n\n private writeToStorage(): void {\n if (this.storage === null) return\n try {\n this.storage.setItem(this.key, JSON.stringify(this.items))\n } catch {\n // Quota exceeded, private mode, or disabled storage: keep the\n // in-memory copy authoritative for the rest of the page lifetime.\n }\n }\n}\n\n/** Safe accessor for `localStorage` that returns null on any failure. */\nfunction safeLocalStorage(): Storage | null {\n try {\n if (typeof localStorage === 'undefined') return null\n return localStorage\n } catch {\n return null\n }\n}\n","/**\n * HistoryDock — invisible dock entry that collects prompt history.\n *\n * Registers as a `conversation.composer.dock` list entry and renders an\n * `aria-hidden` anchor (zero layout footprint). The dock's only job is\n * history collection: every render reads `props.session.nodes` and\n * appends new user/steering text to the module-scope `HistoryStore`.\n *\n * The keydown listener that drives navigation lives in `apply` (module\n * scope), NOT in this dock — because the dock is session-scoped and\n * DSH treats blank sessions as \"hero\" (ConversationRoot.tsx:79-80),\n * which suppresses the dock entirely (`!hero` guard at line 156).\n * Moving the listener to `apply` ensures it is always attached,\n * regardless of hero/blank/active session state.\n *\n * @module @huanlin/dsh-plugin-input-history/client/HistoryDock\n */\n\nimport { useRef } from 'react'\nimport type { PropsRuntime, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'\n// Type-only: SlotMap merge for 'conversation.composer.dock' + SessionStandardProps.\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { HistoryStore, DEFAULT_CAPACITY } from './history.ts'\n\n/** Full props: dock runtime share + locale seat. */\ntype HistoryDockProps = PropsRuntime<'conversation.composer.dock'> & PropsLocale<'dsh-plugin-input-history'>\n\n/**\n * Module-scope history store, initialized once on first dock mount.\n * Shared with the keydown listener in `apply` via `getHistoryStore()`.\n */\nlet historyStore: HistoryStore | null = null\n\n/** Get the shared history store (initializes lazily on first call). */\nexport function getHistoryStore(): HistoryStore {\n if (historyStore === null) {\n historyStore = new HistoryStore(DEFAULT_CAPACITY)\n }\n return historyStore\n}\n\n/**\n * Render the invisible history-collection dock entry.\n *\n * @param props - dock runtime share (InputZone owner + session kit) + locale seat.\n * @returns an `aria-hidden` anchor with zero layout footprint.\n */\nexport function HistoryDock({ session }: HistoryDockProps) {\n const store = getHistoryStore()\n\n // History collection: diff the last user/steering text against the\n // previously-seen tail and append on change. Runs every render (cheap:\n // O(n) over the tail nodes, breaks early once a user/steering node is\n // found). The store dedupes internally, so re-appends are no-ops.\n const lastSeenTextRef = useRef<string | null>(null)\n const lastText = latestUserOrSteeringText(session.nodes)\n if (lastText !== null && lastText !== lastSeenTextRef.current) {\n lastSeenTextRef.current = lastText\n store.append(lastText)\n }\n\n // `display: none` keeps the anchor out of layout and out of the\n // a11y tree. The dock is purely a lifecycle anchor for history\n // collection; the keydown listener lives in `apply`.\n return <div aria-hidden style={{ display: 'none' }} data-dsh-plugin-input-history=\"\" />\n}\n\n/**\n * Extract the text of the latest `user` or `steering` node from a\n * conversation snapshot's nodes list.\n *\n * Returns the concatenated text of all `type: 'text'` content blocks.\n * Returns `null` when no user/steering node is present (e.g. a fresh\n * session with only a system/context message).\n *\n * @param nodes - the conversation snapshot's `nodes` array.\n */\nfunction latestUserOrSteeringText(\n nodes: ReadonlyArray<{\n kind: string\n content?: ReadonlyArray<{ type: string; text?: string }>\n }>,\n): string | null {\n for (let i = nodes.length - 1; i >= 0; i--) {\n const node = nodes[i]!\n if (node.kind !== 'user' && node.kind !== 'steering') continue\n const content = node.content\n if (content === undefined) continue\n let text = ''\n for (const block of content) {\n if (block.type === 'text' && typeof block.text === 'string') {\n text += block.text\n }\n }\n return text\n }\n return null\n}\n","/**\n * IME-composition key guard.\n *\n * While a Chinese/Japanese/Korean input method is composing (the user is\n * picking a candidate from the IME window), every pressed key BELONGS to\n * the input method: arrows move the candidate highlight, Enter/Space\n * confirm the composition, Escape cancels it. Page code must not process\n * those keys — a history-navigation handler that calls `preventDefault()`\n * on ArrowUp/ArrowDown during composition would silently break the IME:\n * candidates stop responding, the composition gets torn apart, and only\n * bare letters come out.\n *\n * The composition signal follows the DSH core convention (InputBar's IME\n * guard, issue #535): `isComposing` for modern engines, keyCode 229 as\n * the legacy signal engines emit without isComposing.\n *\n * @module @huanlin/dsh-plugin-input-history/client/ime\n */\n\n/** The pure decision: is this keyboard event part of an IME composition? */\nexport function isImeComposition(event: { isComposing: boolean; keyCode: number }): boolean {\n return event.isComposing || event.keyCode === 229\n}\n","/**\n * DOM helpers for the composer textarea.\n *\n * The DSH InputBar's textarea is not exposed through any public API —\n * plugins cannot obtain a React ref or a slot-currency handle to it.\n * The two operations this plugin needs (locate the textarea, decide\n * whether the caret is on the first/last line of a multi-line draft) are\n * pure functions over DOM and string state, kept here for unit testing.\n *\n * The locator queries the stable (but undocumented) `data-composer-card`\n * attribute on the composer card root (`InputBar.tsx:629`) and returns\n * the descendant `<textarea>`. The attribute is internal to\n * `@deepseek-ai/dsh-client-ui-conversation` and may change across\n * upstream versions; the locator is the single point to update.\n *\n * @module @huanlin/dsh-plugin-input-history/client/dom\n */\n\n/** Caret line information for a multi-line textarea value. */\nexport interface CursorLineInfo {\n /** 0-based index of the line the caret is on. */\n readonly currentLine: number\n /** Total number of lines in the value (>= 1). */\n readonly totalLines: number\n /** True when the caret is collapsed and on the first line. */\n readonly atFirstLine: boolean\n /** True when the caret is collapsed and on the last line. */\n readonly atLastLine: boolean\n}\n\n/**\n * Compute the caret's line position in a textarea value.\n *\n * Lines are split on `\\n` (the textarea's own line break character). The\n * caret must be collapsed (`selectionStart === selectionEnd`) for the\n * `atFirstLine` / `atLastLine` flags to be true — a non-collapsed\n * selection spanning multiple lines should not trigger history navigation.\n *\n * @param value - the textarea's current value.\n * @param selectionStart - the textarea's `selectionStart`.\n * @param selectionEnd - the textarea's `selectionEnd` (defaults to `selectionStart`).\n * @returns the caret's line information.\n */\nexport function cursorLineInfo(\n value: string,\n selectionStart: number,\n selectionEnd: number = selectionStart,\n): CursorLineInfo {\n // Swap if reversed (the browser allows selectionStart > selectionEnd when\n // the user drags upwards); clamp to value bounds.\n const rawStart = Math.min(selectionStart, selectionEnd)\n const rawEnd = Math.max(selectionStart, selectionEnd)\n const clampedStart = Math.max(0, Math.min(rawStart, value.length))\n const clampedEnd = Math.max(clampedStart, Math.min(rawEnd, value.length))\n const collapsed = clampedStart === clampedEnd\n const lines = value.split('\\n')\n const totalLines = lines.length\n let currentLine = 0\n let runningLength = 0\n for (let i = 0; i < totalLines; i++) {\n const line = lines[i]!\n // The caret at position `p` belongs to line `i` if `p` is in\n // [runningLength, runningLength + line.length + 1) — the `+1` covers\n // the position immediately after the line's last character, which is\n // still on this line (right before the `\\n`). The very end of the\n // value (after the last line's last char) belongs to the last line.\n const lineEnd = runningLength + line.length\n const isLastLine = i === totalLines - 1\n const upperBound = isLastLine ? lineEnd + 1 : lineEnd + 1 // include the `\\n` position\n if (clampedStart >= runningLength && clampedStart < upperBound) {\n currentLine = i\n break\n }\n runningLength = lineEnd + 1 // +1 for the `\\n`\n }\n return {\n currentLine,\n totalLines,\n atFirstLine: collapsed && currentLine === 0,\n atLastLine: collapsed && currentLine === totalLines - 1,\n }\n}\n\n/**\n * Locate the DSH composer textarea in the current document.\n *\n * Walks from the event target up to find the closest `[data-composer-card]`\n * ancestor, then queries the descendant `<textarea>` inside it. Returns\n * `null` when the target is not inside the composer card (e.g. the user\n * is typing in another input or the textarea is momentarily absent).\n *\n * When called without an event target, falls back to a document-wide\n * query — used in tests and ad-hoc probing.\n *\n * @param from - the event target (or any node inside the composer card).\n * @returns the textarea element, or `null` when not found.\n */\nexport function findComposerTextarea(from?: EventTarget | null): HTMLTextAreaElement | null {\n if (typeof document === 'undefined') return null\n if (from === undefined) {\n // No argument: document-wide query.\n return document.querySelector<HTMLTextAreaElement>('[data-composer-card] textarea')\n }\n // `null` or an actual target: do NOT fall back to document-wide query.\n if (from === null) return null\n // `closest` is on Element; EventTarget may be a Text node or other\n // non-Element node. Narrow with an instanceof check.\n const card = from instanceof Element ? from.closest('[data-composer-card]') : null\n if (card !== null) {\n const ta = card.querySelector<HTMLTextAreaElement>('textarea')\n if (ta !== null) return ta\n }\n return null\n}\n","/**\n * Locale dictionaries for dsh-plugin-input-history.\n *\n * The plugin renders nothing visible — the only user-facing copy is the\n * `aria-label` on the invisible dock anchor (for screen readers) and a\n * future settings row label.\n *\n * @module @huanlin/dsh-plugin-input-history/client/locales\n */\n\n/** All copy keys for the dsh-plugin-input-history namespace. */\nexport type InputHistoryKey =\n | 'ariaLabel'\n | 'restoredDraft'\n | 'noHistory'\n\n/** Locale namespace id (matches the cordis.patch.yml plugin id). */\nexport const NS = 'dsh-plugin-input-history'\n\n/** English dictionary. */\nexport const en: Record<InputHistoryKey, string> = {\n ariaLabel: 'Prompt history navigation (ArrowUp/ArrowDown)',\n restoredDraft: 'Restored in-progress draft',\n noHistory: 'No prompt history yet',\n}\n\n/** Chinese dictionary. */\nexport const zh: Record<InputHistoryKey, string> = {\n ariaLabel: '提示词历史导航(上/下方向键)',\n restoredDraft: '已恢复正在编辑的草稿',\n noHistory: '暂无提示词历史',\n}\n","/**\n * dsh-plugin-input-history — browser half.\n *\n * Two registrations:\n * - `conversation.composer.dock` list slot (id `dsh-plugin-input-history`,\n * order 100) — renders an invisible anchor that collects history from\n * `session.nodes` every render. The dock is session-scoped; DSH treats\n * blank sessions as \"hero\" and suppresses the dock, so history\n * collection only runs in active sessions. That is fine: the first\n * message in a blank session is collected after the session becomes\n * active (the message makes it non-blank).\n * - A document-level `keydown` listener attached in `apply` (NOT in the\n * dock component) — this ensures the listener is always active,\n * including in hero/blank mode where the dock is suppressed. The\n * listener uses the native `value` setter + `dispatchEvent('input')`\n * to feed history text into the textarea, which triggers InputBar's\n * `onChange` → `keyboard.setDraft` — the same path the user's typing\n * takes.\n *\n * History is collected from `user` and `steering` conversation nodes as\n * they appear in any session's `ConversationSnapshot`, persisted to\n * `localStorage` (FIFO, 500 entries), and shared across all sessions\n * in the same browser profile.\n *\n * @module @huanlin/dsh-plugin-input-history/client\n */\n\nimport type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'\n// Type-only: pulls the locale plugin's Context merge (ctx.locale).\nimport type {} from '@deepseek-ai/dsh-client-locale/client'\n// Type-only: pulls the shell's SlotMap merge (conversation.composer.dock)\n// + SessionStandardProps (useInput, inputActions).\nimport type {} from '@deepseek-ai/dsh-client-ui-conversation/client'\nimport { HistoryDock, getHistoryStore } from './HistoryDock.tsx'\nimport { isImeComposition } from './ime.ts'\nimport { cursorLineInfo, findComposerTextarea } from './dom.ts'\nimport { nextIndex, entryAt } from './history.ts'\nimport { en, NS, zh, type InputHistoryKey } from './locales.ts'\n\ndeclare module '@deepseek-ai/dsh-client-ui-slots' {\n interface LocaleNamespaceMap {\n /** The dock's aria-label + future settings row copy. */\n 'dsh-plugin-input-history': InputHistoryKey\n }\n}\n\n/** Required services: slots + locale. */\nexport const inject = ['slots', 'locale']\n\n/**\n * Navigation cursor + saved draft for the keydown listener. Module-scoped\n * because the listener is attached once in `apply` and must persist across\n * dock mount/unmount cycles.\n */\nlet navCursor: number | null = null\nlet savedDraft: string | null = null\n\n/**\n * Client plugin body: register the dock + attach the keydown listener.\n *\n * @param ctx - client root context.\n */\nexport function apply(ctx: ClientContext): void {\n ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-plugin-input-history: dictionaries')\n\n // The dock collects history from session.nodes. It is session-scoped;\n // in hero/blank mode it is suppressed, but the keydown listener below\n // still works (it reads from the module-scope HistoryStore, which\n // persists across dock mount/unmount cycles via localStorage).\n ctx.slots.inject('conversation.composer.dock', () =>\n ctx.slots.register(\n {\n name: 'conversation.composer.dock',\n id: 'dsh-plugin-input-history',\n order: 100,\n locale: NS,\n },\n HistoryDock,\n ),\n )\n\n // Attach the document-level keydown listener. This lives in `apply`\n // (not in the dock component) so it stays active even when the dock is\n // suppressed (hero/blank sessions — ConversationRoot.tsx:79-80 treats\n // blank sessions as hero, and line 156 skips the dock render).\n ctx.effect(() => {\n if (typeof document === 'undefined') return () => {}\n const handler = (event: KeyboardEvent): void => {\n if (event.key !== 'ArrowUp' && event.key !== 'ArrowDown') return\n if (isImeComposition(event)) return\n if (event.defaultPrevented) return\n const textarea = findComposerTextarea(event.target)\n if (textarea === null) return\n if (event.target !== textarea) return\n // Skip if the textarea is readOnly or disabled — hero mode's\n // workspace-picker trigger, or a submitting machine phase.\n if (textarea.readOnly || textarea.disabled) return\n\n const store = getHistoryStore()\n const history = store.list\n\n // Multi-line boundary check.\n const info = cursorLineInfo(textarea.value, textarea.selectionStart, textarea.selectionEnd)\n if (event.key === 'ArrowUp' && !info.atFirstLine) return\n if (event.key === 'ArrowDown' && !info.atLastLine) return\n\n const dir = event.key === 'ArrowUp' ? 'up' : 'down'\n const next = nextIndex(navCursor, history.length, dir)\n\n // Down off the newest end: restore the saved draft (if any).\n if (next === null) {\n const saved = savedDraft\n navCursor = null\n if (saved !== null) {\n setNativeTextareaValue(textarea, saved)\n savedDraft = null\n }\n event.preventDefault()\n return\n }\n\n // Entering history: save the current draft the first time we\n // navigate away from \"not navigating\".\n if (navCursor === null && savedDraft === null) {\n savedDraft = textarea.value\n }\n\n const entry = entryAt(history, next)\n if (entry === null) return\n navCursor = next\n setNativeTextareaValue(textarea, entry)\n event.preventDefault()\n }\n document.addEventListener('keydown', handler, false)\n return () => {\n document.removeEventListener('keydown', handler, false)\n }\n }, 'dsh-plugin-input-history: keydown listener')\n}\n\n/**\n * Set the textarea value via the native prototype setter and dispatch an\n * `input` event so React's controlled-component onChange fires.\n *\n * React 18 tracks the textarea's value internally; directly assigning\n * `textarea.value = x` does NOT trigger React's onChange because React's\n * value tracker compares against its last-seen value. Using the native\n * prototype setter bypasses React's tracker, and the dispatched `input`\n * event makes React detect the change and run InputBar's `onChange` →\n * `keyboard.setDraft(next)`. This is the same technique used by\n * browser automation libraries (Playwright, Testing Library) to simulate\n * user typing in React controlled inputs.\n *\n * @param textarea - the target textarea element.\n * @param value - the new value to set.\n */\nfunction setNativeTextareaValue(textarea: HTMLTextAreaElement, value: string): void {\n const proto = window.HTMLTextAreaElement.prototype\n const descriptor = Object.getOwnPropertyDescriptor(proto, 'value')\n if (descriptor === undefined || descriptor.set === undefined) {\n // Fallback: direct assignment (may not trigger React onChange in\n // all browsers, but better than nothing).\n textarea.value = value\n return\n }\n descriptor.set.call(textarea, value)\n textarea.dispatchEvent(new Event('input', { bubbles: true }))\n}\n"],"mappings":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,WAAW,SAAU;AAG/B,OAAI,SAAS,YAAY,SAAS,SAAU;GAG5C,MAAM,UADQ,iBAAiB,CACT;GAGtB,MAAM,OAAO,eAAe,SAAS,OAAO,SAAS,gBAAgB,SAAS,aAAa;AAC3F,OAAI,MAAM,QAAQ,aAAa,CAAC,KAAK,YAAa;AAClD,OAAI,MAAM,QAAQ,eAAe,CAAC,KAAK,WAAY;GAEnD,MAAM,MAAM,MAAM,QAAQ,YAAY,OAAO;GAC7C,MAAM,OAAO,UAAU,WAAW,QAAQ,QAAQ,IAAI;AAGtD,OAAI,SAAS,MAAM;IACjB,MAAM,QAAQ;AACd,gBAAY;AACZ,QAAI,UAAU,MAAM;AAClB,4BAAuB,UAAU,MAAM;AACvC,kBAAa;;AAEf,UAAM,gBAAgB;AACtB;;AAKF,OAAI,cAAc,QAAQ,eAAe,KACvC,cAAa,SAAS;GAGxB,MAAM,QAAQ,QAAQ,SAAS,KAAK;AACpC,OAAI,UAAU,KAAM;AACpB,eAAY;AACZ,0BAAuB,UAAU,MAAM;AACvC,SAAM,gBAAgB;;AAExB,WAAS,iBAAiB,WAAW,SAAS,MAAM;AACpD,eAAa;AACX,YAAS,oBAAoB,WAAW,SAAS,MAAM;;IAExD,6CAA6C;;;;;;;;;;;;;;;;;;AAmBlD,SAAS,uBAAuB,UAA+B,OAAqB;CAClF,MAAM,QAAQ,OAAO,oBAAoB;CACzC,MAAM,aAAa,OAAO,yBAAyB,OAAO,QAAQ;AAClE,KAAI,eAAe,UAAa,WAAW,QAAQ,QAAW;AAG5D,WAAS,QAAQ;AACjB;;AAEF,YAAW,IAAI,KAAK,UAAU,MAAM;AACpC,UAAS,cAAc,IAAI,MAAM,SAAS,EAAE,SAAS,MAAM,CAAC,CAAC"}
package/lib/index.js ADDED
@@ -0,0 +1,12 @@
1
+ //#region src/index.ts
2
+ const name = "dsh-plugin-input-history";
3
+ const inject = [];
4
+ /**
5
+ * Host apply — no-op. The history navigation is a pure client-side UI
6
+ * contribution; no host-side resources are used.
7
+ * @param _ctx - host context (unused).
8
+ */
9
+ function apply(_ctx) {}
10
+
11
+ //#endregion
12
+ export { apply, inject, name };
@@ -0,0 +1,24 @@
1
+ //#region src/invariant.ts
2
+ const PACKAGE_NAME = "@huanlin/dsh-plugin-input-history";
3
+ /** Cordis companion plugin name. */
4
+ const name = "dsh-plugin-input-history-invariant";
5
+ /** Service required before the companion can reserve package ownership. */
6
+ const inject = ["invariants"];
7
+ /**
8
+ * No runtime invariant: the single `conversation.composer.dock` slot
9
+ * registration is a registry-owned contribution whose disposal is proven
10
+ * by the HMR-safety spec. The plugin's only mutable state is the
11
+ * localStorage-backed history array, whose lifecycle is bounded by the
12
+ * browser profile (not the cordis fiber) and whose write path is
13
+ * last-writer-wins with try/catch containment.
14
+ */
15
+ const install = () => {};
16
+ /**
17
+ * Register this package's invariant companion.
18
+ * @param ctx - Cordis context carrying the invariant service.
19
+ * @returns the installed registration's disposer after setup succeeds.
20
+ */
21
+ const apply = (ctx) => Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install));
22
+
23
+ //#endregion
24
+ export { apply, inject, name };
@@ -0,0 +1,31 @@
1
+ /**
2
+ * HistoryDock — invisible dock entry that collects prompt history.
3
+ *
4
+ * Registers as a `conversation.composer.dock` list entry and renders an
5
+ * `aria-hidden` anchor (zero layout footprint). The dock's only job is
6
+ * history collection: every render reads `props.session.nodes` and
7
+ * appends new user/steering text to the module-scope `HistoryStore`.
8
+ *
9
+ * The keydown listener that drives navigation lives in `apply` (module
10
+ * scope), NOT in this dock — because the dock is session-scoped and
11
+ * DSH treats blank sessions as "hero" (ConversationRoot.tsx:79-80),
12
+ * which suppresses the dock entirely (`!hero` guard at line 156).
13
+ * Moving the listener to `apply` ensures it is always attached,
14
+ * regardless of hero/blank/active session state.
15
+ *
16
+ * @module @huanlin/dsh-plugin-input-history/client/HistoryDock
17
+ */
18
+ import type { PropsRuntime, PropsLocale } from '@deepseek-ai/dsh-client-ui-slots';
19
+ import { HistoryStore } from './history.ts';
20
+ /** Full props: dock runtime share + locale seat. */
21
+ type HistoryDockProps = PropsRuntime<'conversation.composer.dock'> & PropsLocale<'dsh-plugin-input-history'>;
22
+ /** Get the shared history store (initializes lazily on first call). */
23
+ export declare function getHistoryStore(): HistoryStore;
24
+ /**
25
+ * Render the invisible history-collection dock entry.
26
+ *
27
+ * @param props - dock runtime share (InputZone owner + session kit) + locale seat.
28
+ * @returns an `aria-hidden` anchor with zero layout footprint.
29
+ */
30
+ export declare function HistoryDock({ session }: HistoryDockProps): import("react").JSX.Element;
31
+ export {};
@@ -0,0 +1,83 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * HistoryDock — invisible dock entry that collects prompt history.
4
+ *
5
+ * Registers as a `conversation.composer.dock` list entry and renders an
6
+ * `aria-hidden` anchor (zero layout footprint). The dock's only job is
7
+ * history collection: every render reads `props.session.nodes` and
8
+ * appends new user/steering text to the module-scope `HistoryStore`.
9
+ *
10
+ * The keydown listener that drives navigation lives in `apply` (module
11
+ * scope), NOT in this dock — because the dock is session-scoped and
12
+ * DSH treats blank sessions as "hero" (ConversationRoot.tsx:79-80),
13
+ * which suppresses the dock entirely (`!hero` guard at line 156).
14
+ * Moving the listener to `apply` ensures it is always attached,
15
+ * regardless of hero/blank/active session state.
16
+ *
17
+ * @module @huanlin/dsh-plugin-input-history/client/HistoryDock
18
+ */
19
+ import { useRef } from 'react';
20
+ import { HistoryStore, DEFAULT_CAPACITY } from "./history.js";
21
+ /**
22
+ * Module-scope history store, initialized once on first dock mount.
23
+ * Shared with the keydown listener in `apply` via `getHistoryStore()`.
24
+ */
25
+ let historyStore = null;
26
+ /** Get the shared history store (initializes lazily on first call). */
27
+ export function getHistoryStore() {
28
+ if (historyStore === null) {
29
+ historyStore = new HistoryStore(DEFAULT_CAPACITY);
30
+ }
31
+ return historyStore;
32
+ }
33
+ /**
34
+ * Render the invisible history-collection dock entry.
35
+ *
36
+ * @param props - dock runtime share (InputZone owner + session kit) + locale seat.
37
+ * @returns an `aria-hidden` anchor with zero layout footprint.
38
+ */
39
+ export function HistoryDock({ session }) {
40
+ const store = getHistoryStore();
41
+ // History collection: diff the last user/steering text against the
42
+ // previously-seen tail and append on change. Runs every render (cheap:
43
+ // O(n) over the tail nodes, breaks early once a user/steering node is
44
+ // found). The store dedupes internally, so re-appends are no-ops.
45
+ const lastSeenTextRef = useRef(null);
46
+ const lastText = latestUserOrSteeringText(session.nodes);
47
+ if (lastText !== null && lastText !== lastSeenTextRef.current) {
48
+ lastSeenTextRef.current = lastText;
49
+ store.append(lastText);
50
+ }
51
+ // `display: none` keeps the anchor out of layout and out of the
52
+ // a11y tree. The dock is purely a lifecycle anchor for history
53
+ // collection; the keydown listener lives in `apply`.
54
+ return _jsx("div", { "aria-hidden": true, style: { display: 'none' }, "data-dsh-plugin-input-history": "" });
55
+ }
56
+ /**
57
+ * Extract the text of the latest `user` or `steering` node from a
58
+ * conversation snapshot's nodes list.
59
+ *
60
+ * Returns the concatenated text of all `type: 'text'` content blocks.
61
+ * Returns `null` when no user/steering node is present (e.g. a fresh
62
+ * session with only a system/context message).
63
+ *
64
+ * @param nodes - the conversation snapshot's `nodes` array.
65
+ */
66
+ function latestUserOrSteeringText(nodes) {
67
+ for (let i = nodes.length - 1; i >= 0; i--) {
68
+ const node = nodes[i];
69
+ if (node.kind !== 'user' && node.kind !== 'steering')
70
+ continue;
71
+ const content = node.content;
72
+ if (content === undefined)
73
+ continue;
74
+ let text = '';
75
+ for (const block of content) {
76
+ if (block.type === 'text' && typeof block.text === 'string') {
77
+ text += block.text;
78
+ }
79
+ }
80
+ return text;
81
+ }
82
+ return null;
83
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * DOM helpers for the composer textarea.
3
+ *
4
+ * The DSH InputBar's textarea is not exposed through any public API —
5
+ * plugins cannot obtain a React ref or a slot-currency handle to it.
6
+ * The two operations this plugin needs (locate the textarea, decide
7
+ * whether the caret is on the first/last line of a multi-line draft) are
8
+ * pure functions over DOM and string state, kept here for unit testing.
9
+ *
10
+ * The locator queries the stable (but undocumented) `data-composer-card`
11
+ * attribute on the composer card root (`InputBar.tsx:629`) and returns
12
+ * the descendant `<textarea>`. The attribute is internal to
13
+ * `@deepseek-ai/dsh-client-ui-conversation` and may change across
14
+ * upstream versions; the locator is the single point to update.
15
+ *
16
+ * @module @huanlin/dsh-plugin-input-history/client/dom
17
+ */
18
+ /** Caret line information for a multi-line textarea value. */
19
+ export interface CursorLineInfo {
20
+ /** 0-based index of the line the caret is on. */
21
+ readonly currentLine: number;
22
+ /** Total number of lines in the value (>= 1). */
23
+ readonly totalLines: number;
24
+ /** True when the caret is collapsed and on the first line. */
25
+ readonly atFirstLine: boolean;
26
+ /** True when the caret is collapsed and on the last line. */
27
+ readonly atLastLine: boolean;
28
+ }
29
+ /**
30
+ * Compute the caret's line position in a textarea value.
31
+ *
32
+ * Lines are split on `\n` (the textarea's own line break character). The
33
+ * caret must be collapsed (`selectionStart === selectionEnd`) for the
34
+ * `atFirstLine` / `atLastLine` flags to be true — a non-collapsed
35
+ * selection spanning multiple lines should not trigger history navigation.
36
+ *
37
+ * @param value - the textarea's current value.
38
+ * @param selectionStart - the textarea's `selectionStart`.
39
+ * @param selectionEnd - the textarea's `selectionEnd` (defaults to `selectionStart`).
40
+ * @returns the caret's line information.
41
+ */
42
+ export declare function cursorLineInfo(value: string, selectionStart: number, selectionEnd?: number): CursorLineInfo;
43
+ /**
44
+ * Locate the DSH composer textarea in the current document.
45
+ *
46
+ * Walks from the event target up to find the closest `[data-composer-card]`
47
+ * ancestor, then queries the descendant `<textarea>` inside it. Returns
48
+ * `null` when the target is not inside the composer card (e.g. the user
49
+ * is typing in another input or the textarea is momentarily absent).
50
+ *
51
+ * When called without an event target, falls back to a document-wide
52
+ * query — used in tests and ad-hoc probing.
53
+ *
54
+ * @param from - the event target (or any node inside the composer card).
55
+ * @returns the textarea element, or `null` when not found.
56
+ */
57
+ export declare function findComposerTextarea(from?: EventTarget | null): HTMLTextAreaElement | null;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * DOM helpers for the composer textarea.
3
+ *
4
+ * The DSH InputBar's textarea is not exposed through any public API —
5
+ * plugins cannot obtain a React ref or a slot-currency handle to it.
6
+ * The two operations this plugin needs (locate the textarea, decide
7
+ * whether the caret is on the first/last line of a multi-line draft) are
8
+ * pure functions over DOM and string state, kept here for unit testing.
9
+ *
10
+ * The locator queries the stable (but undocumented) `data-composer-card`
11
+ * attribute on the composer card root (`InputBar.tsx:629`) and returns
12
+ * the descendant `<textarea>`. The attribute is internal to
13
+ * `@deepseek-ai/dsh-client-ui-conversation` and may change across
14
+ * upstream versions; the locator is the single point to update.
15
+ *
16
+ * @module @huanlin/dsh-plugin-input-history/client/dom
17
+ */
18
+ /**
19
+ * Compute the caret's line position in a textarea value.
20
+ *
21
+ * Lines are split on `\n` (the textarea's own line break character). The
22
+ * caret must be collapsed (`selectionStart === selectionEnd`) for the
23
+ * `atFirstLine` / `atLastLine` flags to be true — a non-collapsed
24
+ * selection spanning multiple lines should not trigger history navigation.
25
+ *
26
+ * @param value - the textarea's current value.
27
+ * @param selectionStart - the textarea's `selectionStart`.
28
+ * @param selectionEnd - the textarea's `selectionEnd` (defaults to `selectionStart`).
29
+ * @returns the caret's line information.
30
+ */
31
+ export function cursorLineInfo(value, selectionStart, selectionEnd = selectionStart) {
32
+ // Swap if reversed (the browser allows selectionStart > selectionEnd when
33
+ // the user drags upwards); clamp to value bounds.
34
+ const rawStart = Math.min(selectionStart, selectionEnd);
35
+ const rawEnd = Math.max(selectionStart, selectionEnd);
36
+ const clampedStart = Math.max(0, Math.min(rawStart, value.length));
37
+ const clampedEnd = Math.max(clampedStart, Math.min(rawEnd, value.length));
38
+ const collapsed = clampedStart === clampedEnd;
39
+ const lines = value.split('\n');
40
+ const totalLines = lines.length;
41
+ let currentLine = 0;
42
+ let runningLength = 0;
43
+ for (let i = 0; i < totalLines; i++) {
44
+ const line = lines[i];
45
+ // The caret at position `p` belongs to line `i` if `p` is in
46
+ // [runningLength, runningLength + line.length + 1) — the `+1` covers
47
+ // the position immediately after the line's last character, which is
48
+ // still on this line (right before the `\n`). The very end of the
49
+ // value (after the last line's last char) belongs to the last line.
50
+ const lineEnd = runningLength + line.length;
51
+ const isLastLine = i === totalLines - 1;
52
+ const upperBound = isLastLine ? lineEnd + 1 : lineEnd + 1; // include the `\n` position
53
+ if (clampedStart >= runningLength && clampedStart < upperBound) {
54
+ currentLine = i;
55
+ break;
56
+ }
57
+ runningLength = lineEnd + 1; // +1 for the `\n`
58
+ }
59
+ return {
60
+ currentLine,
61
+ totalLines,
62
+ atFirstLine: collapsed && currentLine === 0,
63
+ atLastLine: collapsed && currentLine === totalLines - 1,
64
+ };
65
+ }
66
+ /**
67
+ * Locate the DSH composer textarea in the current document.
68
+ *
69
+ * Walks from the event target up to find the closest `[data-composer-card]`
70
+ * ancestor, then queries the descendant `<textarea>` inside it. Returns
71
+ * `null` when the target is not inside the composer card (e.g. the user
72
+ * is typing in another input or the textarea is momentarily absent).
73
+ *
74
+ * When called without an event target, falls back to a document-wide
75
+ * query — used in tests and ad-hoc probing.
76
+ *
77
+ * @param from - the event target (or any node inside the composer card).
78
+ * @returns the textarea element, or `null` when not found.
79
+ */
80
+ export function findComposerTextarea(from) {
81
+ if (typeof document === 'undefined')
82
+ return null;
83
+ if (from === undefined) {
84
+ // No argument: document-wide query.
85
+ return document.querySelector('[data-composer-card] textarea');
86
+ }
87
+ // `null` or an actual target: do NOT fall back to document-wide query.
88
+ if (from === null)
89
+ return null;
90
+ // `closest` is on Element; EventTarget may be a Text node or other
91
+ // non-Element node. Narrow with an instanceof check.
92
+ const card = from instanceof Element ? from.closest('[data-composer-card]') : null;
93
+ if (card !== null) {
94
+ const ta = card.querySelector('textarea');
95
+ if (ta !== null)
96
+ return ta;
97
+ }
98
+ return null;
99
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Prompt history store — pure functions over a string array.
3
+ *
4
+ * The store is a FIFO list of unique prompt strings, persisted to
5
+ * `localStorage`. Newest entries are at the end of the array. The
6
+ * navigation cursor walks backwards from the end (ArrowUp = older,
7
+ * ArrowDown = newer).
8
+ *
9
+ * The functions in this module are pure (no `localStorage` access) so
10
+ * they can be unit-tested without jsdom. The `HistoryStore` class below
11
+ * wires them to `localStorage` with try/catch containment — a quota
12
+ * exception or a disabled storage (private mode) degrades gracefully to
13
+ * an in-memory list that lives for the page lifetime.
14
+ *
15
+ * @module @huanlin/dsh-plugin-input-history/client/history
16
+ */
17
+ /** localStorage key (versioned; bump on schema changes to start fresh). */
18
+ export declare const STORAGE_KEY = "dsh-plugin-input-history:v1";
19
+ /** Default capacity when none is configured. */
20
+ export declare const DEFAULT_CAPACITY = 500;
21
+ /**
22
+ * Append a prompt to the history.
23
+ *
24
+ * Rules:
25
+ * - Empty / whitespace-only strings are ignored (the InputBar already
26
+ * rejects them at submit, but defensive).
27
+ * - When the new entry equals the most recent one, it is a no-op
28
+ * (avoids stacking duplicates from rapid resends).
29
+ * - When the new entry already exists earlier in the history, that
30
+ * earlier occurrence is removed (recency wins; the prompt moves to
31
+ * the end). This mirrors terminal shell behaviour.
32
+ * - When the array would exceed `capacity`, the oldest entries are
33
+ * dropped from the front (FIFO).
34
+ *
35
+ * @param history - the current history array (newest at end).
36
+ * @param prompt - the prompt to append.
37
+ * @param capacity - the maximum number of entries to retain.
38
+ * @returns the new history array (may be the same reference if no-op).
39
+ */
40
+ export declare function appendHistory(history: readonly string[], prompt: string, capacity?: number): string[];
41
+ /**
42
+ * Navigation cursor for walking the history.
43
+ *
44
+ * The cursor is `null` when the user is not navigating (i.e. they are
45
+ * typing a fresh draft). ArrowUp sets it to the last index, then
46
+ * decrements; ArrowDown increments; when it would exceed `history.length
47
+ * - 1`, it returns to `null` (meaning "restore the in-progress draft").
48
+ *
49
+ * @param current - the current cursor (null = not navigating).
50
+ * @param total - the total number of history entries.
51
+ * @param dir - `'up'` (older) or `'down'` (newer).
52
+ * @returns the next cursor, or `null` when navigation falls off the
53
+ * newest end (caller should restore the saved draft).
54
+ */
55
+ export declare function nextIndex(current: number | null, total: number, dir: 'up' | 'down'): number | null;
56
+ /**
57
+ * Read the history entry at a cursor, or `null` when the cursor is null.
58
+ *
59
+ * @param history - the history array.
60
+ * @param cursor - the navigation cursor.
61
+ * @returns the prompt at the cursor, or `null`.
62
+ */
63
+ export declare function entryAt(history: readonly string[], cursor: number | null): string | null;
64
+ /**
65
+ * History store bound to `localStorage`.
66
+ *
67
+ * The store reads once on construction (or on `reload()`) and keeps an
68
+ * in-memory copy. Writes go to both memory and `localStorage` inside a
69
+ * try/catch — a quota exception leaves the in-memory copy authoritative
70
+ * for the rest of the page lifetime. This trades cross-tab consistency
71
+ * for resilience: the store never throws on a write, and the worst case
72
+ * is that a tab keeps its own view until refresh.
73
+ *
74
+ * Cross-tab sync is intentionally NOT implemented: prompt history is
75
+ * append-mostly and a stale read across tabs is harmless (the next
76
+ * append corrects it). Listening to the `storage` event would add
77
+ * reactivity that the navigation UI does not need.
78
+ */
79
+ export declare class HistoryStore {
80
+ private readonly capacity;
81
+ private items;
82
+ private readonly storage;
83
+ private readonly key;
84
+ /**
85
+ * @param capacity - maximum entries to retain (FIFO).
86
+ * @param storage - the storage backend (defaults to `localStorage` when available).
87
+ * @param key - the storage key (defaults to {@link STORAGE_KEY}).
88
+ */
89
+ constructor(capacity?: number, storage?: Storage | null, key?: string);
90
+ /** Current history snapshot (newest at end). */
91
+ get list(): readonly string[];
92
+ /** Number of entries currently stored. */
93
+ get length(): number;
94
+ /** Reload from storage (e.g. after a suspected external edit). Truncates to the current capacity. */
95
+ reload(): void;
96
+ /**
97
+ * Append a prompt and persist. See {@link appendHistory} for rules.
98
+ * @returns the new history snapshot.
99
+ */
100
+ append(prompt: string): readonly string[];
101
+ /** Clear all history (used by tests and a future "clear" UI). */
102
+ clear(): void;
103
+ private readFromStorage;
104
+ private writeToStorage;
105
+ }