@surfishs/dsh-prompt-enhance 0.0.9 → 0.1.1

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@surfishs/dsh-prompt-enhance",
3
3
  "description": "Prompt enhancement for the dsh web GUI: rewrite the composer draft into a well-structured prompt through the harness LLM service, preview the before/after, then fill back, copy, or undo. Original draft is always preserved.",
4
- "version": "0.0.9",
4
+ "version": "0.1.1",
5
5
  "author": "surfishs",
6
6
  "type": "module",
7
7
  "engines": {
@@ -116,6 +116,7 @@
116
116
  "format:check": "prettier --check .",
117
117
  "test": "vitest run",
118
118
  "test:watch": "vitest",
119
+ "check:host-primitives": "node scripts/check-host-primitives.mjs",
119
120
  "prepublishOnly": "npm run build && npm test"
120
121
  },
121
122
  "publishConfig": {
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Admission control for every entry that can spend a model call: a
3
+ * sliding-window rate cap, a concurrency cap, and a consecutive-failure breaker.
4
+ *
5
+ * The composer route and the `/enhance` command reach the model through the same
6
+ * host process, so they must share ONE gate. Separate gates would let the
7
+ * command plane sidestep the caps the settings page advertises.
8
+ * @module dsh-prompt-enhance/admission
9
+ */
10
+
11
+ import type { EnhanceError, EnhanceErrorCode } from './shared/protocol'
12
+
13
+ /**
14
+ * Consecutive failed calls that trip the cool-down, and how long it lasts.
15
+ *
16
+ * The sliding window counts successful calls only, so a run of timeouts never
17
+ * burns the user's quota. That leaves one hole: a deterministic upstream
18
+ * failure — a wrong API key, a mistyped provider, a model the account cannot
19
+ * reach — fails in milliseconds, and a retry loop against such a failure is
20
+ * bounded only by the concurrency cap, i.e. barely at all. Three consecutive
21
+ * failures are enough to tell "the model is flaky" from "this route cannot
22
+ * work", so the gate pauses instead of hammering the provider.
23
+ */
24
+ export const FAILURE_STREAK_LIMIT = 3
25
+ export const FAILURE_COOLDOWN_MS = 30_000
26
+
27
+ /** Caps of one admission decision, read from the live configuration. */
28
+ export interface AdmissionLimits {
29
+ rateLimitPerMinute: number
30
+ maxConcurrent: number
31
+ }
32
+
33
+ /**
34
+ * How one admitted call ended, as the gate counts it.
35
+ *
36
+ * `neutral` exists for a failure that is NOT the route's fault — no model
37
+ * configured, an effort the route refuses — because counting it would trip the
38
+ * breaker and hide the actionable error behind a cool-down that blames the
39
+ * model. It releases the slot and records nothing, like a cancellation.
40
+ */
41
+ export type AdmissionOutcome = 'success' | 'failure' | 'aborted' | 'neutral'
42
+
43
+ /**
44
+ * Wire codes that mean "this route cannot work", not "the model flaked".
45
+ *
46
+ * Both fail locally in milliseconds without any model traffic, so retrying them
47
+ * costs nothing; the useful answer is the error itself ("configure a model",
48
+ * "pick another tier"), not a cool-down.
49
+ */
50
+ const NON_BREAKER_CODES: ReadonlySet<EnhanceErrorCode> = new Set(['unconfigured', 'effort-unsupported'])
51
+
52
+ /**
53
+ * Classify one settled call for {@link AdmissionGate.settle}.
54
+ *
55
+ * Both entries (the composer route and the /enhance command) call THIS function,
56
+ * so "which failures count" is decided in one place and cannot drift apart
57
+ * between them.
58
+ * @param aborted - whether the caller went away mid-flight.
59
+ * @param code - the wire error code of the failure.
60
+ * @returns the outcome to settle with.
61
+ */
62
+ export function breakerOutcome(aborted: boolean, code: EnhanceErrorCode): AdmissionOutcome {
63
+ if (aborted) return 'aborted'
64
+ return NON_BREAKER_CODES.has(code) ? 'neutral' : 'failure'
65
+ }
66
+
67
+ /** One admission answer. */
68
+ export type AdmissionDecision = { ok: true } | { ok: false; error: EnhanceError; retryAfterSeconds?: number }
69
+
70
+ /**
71
+ * One process-wide admission gate.
72
+ *
73
+ * The rate window counts SUCCESSFUL calls only: counting attempts would burn
74
+ * the user's window on a run of timeouts or upstream errors and lock them out
75
+ * right when the model recovers. The concurrency cap still bounds in-flight
76
+ * calls regardless of outcome, and a cancellation is neither a success nor a
77
+ * failure.
78
+ */
79
+ export class AdmissionGate {
80
+ private stamps: number[] = []
81
+ private active = 0
82
+ private failures = 0
83
+ private cooldownUntil = 0
84
+
85
+ /**
86
+ * Ask for a slot.
87
+ * @param now - epoch millis of the admission attempt.
88
+ * @param limits - the live caps.
89
+ * @returns the decision; a refusal carries the wire error, plus the
90
+ * advertised wait when the gate can predict one.
91
+ */
92
+ admit(now: number, limits: AdmissionLimits): AdmissionDecision {
93
+ // Failure breaker first: a host stuck on a broken route must refuse before
94
+ // spending a window slot, and the wait is advertised so the caller can say
95
+ // when to try again.
96
+ if (now < this.cooldownUntil) {
97
+ const retryAfterSeconds = Math.max(1, Math.ceil((this.cooldownUntil - now) / 1000))
98
+ return { ok: false, error: { code: 'cooldown', params: { retryAfterSeconds, failures: FAILURE_STREAK_LIMIT } }, retryAfterSeconds }
99
+ }
100
+ // Trim the window in one splice instead of a `while (shift)` loop: with the
101
+ // configured cap at 600 the worst case drops from O(N²) array shifts to a
102
+ // single O(N) relocation.
103
+ const cut = now - 60_000
104
+ let validFrom = 0
105
+ while (validFrom < this.stamps.length && (this.stamps[validFrom] ?? cut) < cut) validFrom++
106
+ if (validFrom > 0) this.stamps.splice(0, validFrom)
107
+ if (this.stamps.length >= limits.rateLimitPerMinute) {
108
+ // The window is bounded, so the oldest surviving stamp tells exactly when
109
+ // a slot frees up — advertise it instead of making the caller guess.
110
+ const oldest = this.stamps[0] ?? now
111
+ const retryAfterSeconds = Math.max(1, Math.ceil((60_000 - (now - oldest)) / 1000))
112
+ return { ok: false, error: { code: 'rate-limit', params: { limit: limits.rateLimitPerMinute, retryAfterSeconds } }, retryAfterSeconds }
113
+ }
114
+ // No retry-after here: a busy slot frees whenever some in-flight call
115
+ // settles, which is not a delay this gate can predict.
116
+ if (this.active >= limits.maxConcurrent) {
117
+ return { ok: false, error: { code: 'concurrency-limit', params: { max: limits.maxConcurrent } } }
118
+ }
119
+ this.active += 1
120
+ return { ok: true }
121
+ }
122
+
123
+ /**
124
+ * Release the slot one admitted call held and record how it ended.
125
+ * @param outcome - success, failure, or neither (a cancellation, or a neutral
126
+ * failure that is not the route's fault).
127
+ * @param now - epoch millis when the call settled.
128
+ */
129
+ settle(outcome: AdmissionOutcome, now: number): void {
130
+ if (this.active > 0) this.active -= 1
131
+ if (outcome === 'success') {
132
+ // Stamped at completion, not admission: a slow success still counts as
133
+ // one call, and failures never consume the window.
134
+ this.stamps.push(now)
135
+ this.failures = 0
136
+ return
137
+ }
138
+ if (outcome === 'failure') {
139
+ this.failures += 1
140
+ if (this.failures >= FAILURE_STREAK_LIMIT) {
141
+ this.cooldownUntil = now + FAILURE_COOLDOWN_MS
142
+ this.failures = 0
143
+ }
144
+ }
145
+ }
146
+ }
@@ -24,24 +24,30 @@ import { useSessionKey, serverSessionId } from './session-key'
24
24
  /** Props of the input.right entry: the InputZone owner share + session kit + locale seat. */
25
25
  export type EnhanceButtonProps = PropsRuntime<'conversation.input.right'> & PropsLocale<'dsh-prompt-enhance'>
26
26
 
27
+ /** Sentinel of {@link occurrenceCountOf} for a host that exposes no chip view. */
28
+ const OCCURRENCES_UNKNOWN = -1
29
+
27
30
  /**
28
- * Read the length of an optional array-shaped field out of the host's input
29
- * state.
31
+ * Read the composer's reference-chip count, or {@link OCCURRENCES_UNKNOWN} when
32
+ * the host state cannot answer.
33
+ *
34
+ * Why this is not a plain `Array.isArray(x) ? x.length : 0`: applying a result
35
+ * happens through `inputActions.setDraft`, which replaces the editor document
36
+ * with plain text. A command or file-reference chip is not text, so that write
37
+ * destroys it — irreversibly, and with no undo entry covering the chip. "The
38
+ * host did not tell us" is therefore not the same answer as "there are none":
39
+ * the guard below fails CLOSED on it.
30
40
  *
31
- * Attachment ids are part of the conversation input snapshot in the dsh lines
32
- * this plugin targets, but the field was RENAMED between generations
33
- * (`imageIds` on the 0.1.x line, `attachmentIds` from 0.2.0 on) and a slot host
34
- * is not obliged to expose either. Reading `.length` off a missing field throws
35
- * *during render* — which React answers by unmounting the whole slot entry
36
- * behind its error boundary, so the composer loses the button and the console
37
- * fills with a stack trace instead of a usable feature. Reading defensively
38
- * turns an absent or malformed field into "no such count", which only disables
39
- * the corresponding advisory guard; the enhancement itself still runs.
41
+ * Reading `.length` off a missing field was the original bug class here: it
42
+ * threw DURING RENDER and React unmounted the whole slot entry behind its error
43
+ * boundary. This reader keeps the defensive shape (never throws, never assumes
44
+ * a type) but hands the uncertainty to the guard instead of silently answering
45
+ * "zero".
40
46
  * @param value - the untrusted field.
41
- * @returns the array length, or 0 when the field is absent/not an array.
47
+ * @returns the chip count, or {@link OCCURRENCES_UNKNOWN} when unreadable.
42
48
  */
43
- function countOf(value: unknown): number {
44
- return Array.isArray(value) ? value.length : 0
49
+ function occurrenceCountOf(value: unknown): number {
50
+ return Array.isArray(value) ? value.length : OCCURRENCES_UNKNOWN
45
51
  }
46
52
 
47
53
  /**
@@ -65,7 +71,7 @@ export function EnhanceButton(props: EnhanceButtonProps): ReactNode {
65
71
  const wireId = serverSessionId(sessionId)
66
72
  const draft = useInput((state: InputState) => stringOf((state as { draft?: unknown }).draft))
67
73
  const phase = useInput((state: InputState) => (state as { phase?: unknown }).phase)
68
- const occurrenceCount = useInput((state: InputState) => countOf((state as { occurrences?: unknown }).occurrences))
74
+ const occurrenceCount = useInput((state: InputState) => occurrenceCountOf((state as { occurrences?: unknown }).occurrences))
69
75
  const settings = useSyncExternalStore(subscribeClientSettings, getClientSettings)
70
76
  const panel = useSyncExternalStore(ui.subscribe, ui.getPanel)
71
77
  const rootRef = useRef<HTMLButtonElement | null>(null)
@@ -100,6 +106,15 @@ export function EnhanceButton(props: EnhanceButtonProps): ReactNode {
100
106
  ui.openError(uiKey, source, { code: 'rejected', localized: message })
101
107
  return
102
108
  }
109
+ // Fail CLOSED on an unreadable chip view (see occurrenceCountOf): the
110
+ // fill-back writes plain text over the editor document, so a chip we
111
+ // cannot see is a chip we would destroy. Refusing is recoverable; the
112
+ // destroyed reference is not.
113
+ if (occurrenceCount === OCCURRENCES_UNKNOWN) {
114
+ const unknown = t('error.chipsUnknown')
115
+ ui.openError(uiKey, source, { code: 'rejected', localized: unknown })
116
+ return
117
+ }
103
118
  if (occurrenceCount > 0) {
104
119
  const occurrences = t('error.occurrences')
105
120
  ui.openError(uiKey, source, { code: 'rejected', localized: occurrences })
@@ -166,6 +181,10 @@ export function EnhanceButton(props: EnhanceButtonProps): ReactNode {
166
181
  <button
167
182
  ref={rootRef}
168
183
  type="button"
184
+ // Session anchor for the dock entries this plugin renders: the composer
185
+ // card has to be found per session, and this button lives inside it.
186
+ // Read by useDockAlignment (same attribute constant).
187
+ data-dsh-pe-key={uiKey}
169
188
  className={`dsh-pe-btn${busy ? ' is-busy' : ''}${otherBusy && !empty ? ' is-blocked' : ''}${empty && !busy ? ' is-empty' : ''}`}
170
189
  title={busy ? t('button.busy') : otherBusy ? t('button.otherBusy') : empty ? t('button.emptyTitle') : t('button.title')}
171
190
  aria-label={busy ? t('button.busy') : otherBusy ? t('button.otherBusy') : empty ? t('button.emptyTitle') : t('button.title')}
@@ -18,6 +18,14 @@ import { useDockAlignment } from './useDockAlignment'
18
18
  /** Props of the input.dock entry: the InputZone owner share + session kit + locale seat. */
19
19
  export type ResultDockProps = PropsRuntime<'conversation.input.dock'> & PropsLocale<'dsh-prompt-enhance'>
20
20
 
21
+ /**
22
+ * How long the regenerate button keeps the "regenerated" label.
23
+ *
24
+ * Matches the copy confirmation's window (`ResultPanel`'s copy handler uses the
25
+ * same 2500ms) so both transient confirmations feel like one system.
26
+ */
27
+ const REGENERATED_NOTICE_MS = 2500
28
+
21
29
  /** One session's enhancement card, docked above its composer. */
22
30
  export function ResultDock(props: ResultDockProps): ReactNode {
23
31
  const { t, sessionId, useInput, inputActions } = props
@@ -25,11 +33,7 @@ export function ResultDock(props: ResultDockProps): ReactNode {
25
33
  // host id for UI keying when present, else a stable per-mount fallback.
26
34
  const uiKey = useSessionKey(sessionId, inputActions)
27
35
  const panel = useSyncExternalStore(ui.subscribe, ui.getPanel)
28
- const rootRef = useDockAlignment(panel !== undefined && panel.sessionId === uiKey)
29
- const [undone, setUndone] = useState(false)
30
- const [regenerated, setRegenerated] = useState(false)
31
- const [pendingRegenerate, setPendingRegenerate] = useState(false)
32
- const previousResultRef = useRef<unknown>(undefined)
36
+ const rootRef = useDockAlignment(panel !== undefined && panel.sessionId === uiKey, uiKey)
33
37
  const draft = useInput((state) => {
34
38
  const value = (state as { draft?: unknown }).draft
35
39
  return typeof value === 'string' ? value : ''
@@ -63,12 +67,22 @@ export function ResultDock(props: ResultDockProps): ReactNode {
63
67
  : // eslint-disable-next-line react-hooks/rules-of-hooks
64
68
  Number(useSession((state) => (state as { queue?: unknown[] }).queue?.length ?? 0))
65
69
 
66
- // The applied chip is derived from the undo stack: it is true exactly while
70
+ // The applied state is derived from the undo stack: it is true exactly while
67
71
  // the composer still holds the applied text, and drops itself when the user
68
- // edits (the UndoBar drops the stale entry in the same situation).
72
+ // edits (the UndoBar drops the stale entry in the same situation). It drives
73
+ // the footer button (fill vs undo); the header shows no status chip.
69
74
  const entry = ui.peekUndo(uiKey)
70
75
  const applied = entry !== undefined && entry.applied === draft
71
76
 
77
+ // The regenerate button is HIDDEN while the next round streams, so its
78
+ // confirmation has to be a completion signal: it turns on only after a result
79
+ // that differs from the one the click captured arrives, and clears itself
80
+ // after REGENERATED_NOTICE_MS. A failure or a closed panel only drops the
81
+ // pending flag — there is no button to relabel in those states.
82
+ const [regeneratedNotice, setRegeneratedNotice] = useState(false)
83
+ const pendingRegenerate = useRef(false)
84
+ const previousResultRef = useRef<unknown>(undefined)
85
+
72
86
  // Sending the draft dismisses the card; the undo row can still take over.
73
87
  // The phase is checked where the host provides it; the session transition
74
88
  // (running false→true, or a new queued turn) is the fallback for hosts that
@@ -95,45 +109,27 @@ export function ResultDock(props: ResultDockProps): ReactNode {
95
109
  return () => document.removeEventListener('keydown', onKeyDown)
96
110
  }, [panel, uiKey])
97
111
 
98
- // The "undone" chip is transient: it confirms the undo for a moment, then
99
- // clears without needing another state change.
112
+ // Turn the completion signal into the transient label, and clear it on time.
113
+ // The two effects are separate on purpose: the first only watches the panel
114
+ // settling, the second only owns the timer, so a re-render of the panel cannot
115
+ // restart the countdown.
100
116
  useEffect(() => {
101
- if (!undone) return
102
- const timer = setTimeout(() => setUndone(false), 2500)
103
- return () => clearTimeout(timer)
104
- }, [undone])
105
-
106
- // "Regenerated" is a completion signal, not a click signal: wait until the
107
- // panel settles with a different result object, then show the chip briefly.
108
- useEffect(() => {
109
- if (!pendingRegenerate) return
110
- if (panel === undefined || panel.sessionId !== uiKey) {
111
- setPendingRegenerate(false)
112
- return
113
- }
114
- if (panel.phase === 'error') {
115
- setPendingRegenerate(false)
117
+ if (!pendingRegenerate.current) return
118
+ if (panel === undefined || panel.sessionId !== uiKey || panel.phase === 'error') {
119
+ pendingRegenerate.current = false
116
120
  return
117
121
  }
118
122
  if (panel.phase === 'result' && panel.result !== previousResultRef.current) {
119
- setPendingRegenerate(false)
120
- setRegenerated(true)
123
+ pendingRegenerate.current = false
124
+ setRegeneratedNotice(true)
121
125
  }
122
- }, [panel, pendingRegenerate, uiKey])
123
-
124
- useEffect(() => {
125
- if (!regenerated) return
126
- const timer = setTimeout(() => setRegenerated(false), 2500)
127
- return () => clearTimeout(timer)
128
- }, [regenerated])
126
+ }, [panel, uiKey])
129
127
 
130
- // A regenerate click on an empty draft is a no-op; do not leave the pending
131
- // flag stuck forever in that case.
132
128
  useEffect(() => {
133
- if (!pendingRegenerate) return
134
- const timer = setTimeout(() => setPendingRegenerate(false), 15000)
129
+ if (!regeneratedNotice) return
130
+ const timer = setTimeout(() => setRegeneratedNotice(false), REGENERATED_NOTICE_MS)
135
131
  return () => clearTimeout(timer)
136
- }, [pendingRegenerate])
132
+ }, [regeneratedNotice])
137
133
 
138
134
  if (panel === undefined || panel.sessionId !== uiKey) return null
139
135
 
@@ -145,23 +141,22 @@ export function ResultDock(props: ResultDockProps): ReactNode {
145
141
  // closing it falls back to the standalone undo row.
146
142
  ui.pushUndo(uiKey, { original: draft, applied: panel.result.text })
147
143
  inputActions.setDraft(panel.result.text)
148
- setUndone(false)
149
- setRegenerated(false)
150
144
  }
151
145
 
152
146
  const undo = (): void => {
153
147
  if (entry === undefined) return
154
148
  inputActions.setDraft(entry.original)
155
149
  ui.popUndo(uiKey)
156
- setUndone(true)
157
- setRegenerated(false)
158
150
  }
159
151
 
160
152
  const regenerate = (): void => {
161
153
  if (panel.phase !== 'result') return
154
+ // A click during the notice window starts a fresh round: drop the label now
155
+ // so the button shows its normal text before it disappears, and remember
156
+ // which result this round has to replace.
157
+ setRegeneratedNotice(false)
162
158
  previousResultRef.current = panel.result
163
- setRegenerated(false)
164
- setPendingRegenerate(true)
159
+ pendingRegenerate.current = true
165
160
  ui.runSession(uiKey)
166
161
  }
167
162
 
@@ -171,8 +166,7 @@ export function ResultDock(props: ResultDockProps): ReactNode {
171
166
  state={panel}
172
167
  t={t}
173
168
  applied={applied}
174
- undone={undone}
175
- regenerated={regenerated}
169
+ regenerated={regeneratedNotice}
176
170
  onApply={apply}
177
171
  onUndo={undo}
178
172
  onRegenerate={regenerate}
@@ -30,9 +30,7 @@ export interface ResultPanelProps {
30
30
  onUndo?: () => void
31
31
  /** Run the same source prompt through the model again. */
32
32
  onRegenerate?: () => void
33
- /** Show the transient 'undone' chip after an undo. */
34
- undone?: boolean
35
- /** Show the transient 'regenerated' chip after a regenerate request settles. */
33
+ /** Show the transient "regenerated" label on that button instead of its normal text. */
36
34
  regenerated?: boolean
37
35
  }
38
36
 
@@ -165,7 +163,7 @@ function totalTokensOf(usage: EnhanceUsage): number {
165
163
 
166
164
  /** One enhancement result card. */
167
165
  export function ResultPanel(props: ResultPanelProps): ReactNode {
168
- const { state, t, onApply, onCancel, onRetry, applied = false, onUndo, onRegenerate, undone = false, regenerated = false } = props
166
+ const { state, t, onApply, onCancel, onRetry, applied = false, onUndo, onRegenerate, regenerated = false } = props
169
167
  const [copied, setCopied] = useState<'idle' | 'ok' | 'failed'>('idle')
170
168
 
171
169
  const copy = useCallback((): void => {
@@ -205,6 +203,24 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
205
203
  return parts.join(' · ')
206
204
  }
207
205
 
206
+ /**
207
+ * One label of a swap group.
208
+ *
209
+ * Every label of the group sits in the same `.dsh-pe-swap` grid cell, so the
210
+ * widest label of the active language defines the button width and swapping
211
+ * the visible one cannot resize the button or shift the footer. Only the
212
+ * active label is painted; `aria-hidden` keeps the inert ones out of the
213
+ * accessibility tree even before the stylesheet applies.
214
+ * @param active - whether this label is the one currently shown.
215
+ * @param text - the label text.
216
+ * @returns the label element.
217
+ */
218
+ const swapLabel = (active: boolean, text: string): ReactNode => (
219
+ <span className={active ? 'on' : undefined} aria-hidden={active ? undefined : true}>
220
+ {text}
221
+ </span>
222
+ )
223
+
208
224
  return (
209
225
  <section className="dsh-pe-panel" role="region" aria-label={t('panel.title')}>
210
226
  <header className="dsh-pe-head">
@@ -224,15 +240,6 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
224
240
  )}
225
241
  </span>
226
242
  )}
227
- {copied === 'ok' ? (
228
- <span className="dsh-pe-applied">{t('panel.copiedShort')}</span>
229
- ) : regenerated ? (
230
- <span className="dsh-pe-applied">{t('panel.regeneratedShort')}</span>
231
- ) : applied ? (
232
- <span className="dsh-pe-applied">{t('panel.appliedShort')}</span>
233
- ) : undone ? (
234
- <span className="dsh-pe-applied">{t('panel.undoneShort')}</span>
235
- ) : null}
236
243
  <button type="button" className="dsh-pe-close" aria-label={t('panel.close')} onClick={onCancel}>
237
244
  ✕
238
245
  </button>
@@ -285,9 +292,12 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
285
292
  <footer className="dsh-pe-foot">
286
293
  <span className="dsh-pe-grow" />
287
294
  {state.phase === 'result' && (
288
- <button type="button" className="dsh-pe-btn-action plain" onClick={onRegenerate} disabled={onRegenerate === undefined}>
295
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-swap" onClick={onRegenerate} disabled={onRegenerate === undefined}>
289
296
  <RegenerateIcon />
290
- {t('panel.regenerate')}
297
+ <span className="dsh-pe-swap">
298
+ {swapLabel(!regenerated, t('panel.regenerate'))}
299
+ {swapLabel(regenerated, t('panel.regenerated'))}
300
+ </span>
291
301
  </button>
292
302
  )}
293
303
  {state.phase === 'error' && (
@@ -306,19 +316,31 @@ export function ResultPanel(props: ResultPanelProps): ReactNode {
306
316
  )}
307
317
  {state.phase === 'result' && (
308
318
  <>
309
- <button type="button" className="dsh-pe-btn-action plain dsh-pe-copy" onClick={copy}>
319
+ <button type="button" className="dsh-pe-btn-action plain dsh-pe-btn-swap" onClick={copy}>
310
320
  <CopyIcon />
311
- {copied === 'ok' ? t('panel.copied') : copied === 'failed' ? t('panel.copyFailed') : t('panel.copy')}
321
+ <span className="dsh-pe-swap">
322
+ {swapLabel(copied === 'idle', t('panel.copy'))}
323
+ {swapLabel(copied === 'ok', t('panel.copied'))}
324
+ {swapLabel(copied === 'failed', t('panel.copyFailed'))}
325
+ </span>
312
326
  </button>
313
327
  {applied ? (
314
- <button type="button" className="dsh-pe-btn-action primary" onClick={onUndo} disabled={onUndo === undefined}>
328
+ <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-swap" onClick={onUndo} disabled={onUndo === undefined}>
315
329
  <UndoIcon />
316
- {t('undo.undo')}
330
+ {/* The undo label reserves the width of the fill label it replaces,
331
+ so switching between the two does not resize the footer. */}
332
+ <span className="dsh-pe-swap">
333
+ {swapLabel(true, t('undo.undo'))}
334
+ {swapLabel(false, t('panel.apply'))}
335
+ </span>
317
336
  </button>
318
337
  ) : (
319
- <button type="button" className="dsh-pe-btn-action primary" onClick={onApply}>
338
+ <button type="button" className="dsh-pe-btn-action primary dsh-pe-btn-swap" onClick={onApply}>
320
339
  <FillIcon />
321
- {t('panel.apply')}
340
+ <span className="dsh-pe-swap">
341
+ {swapLabel(true, t('panel.apply'))}
342
+ {swapLabel(false, t('undo.undo'))}
343
+ </span>
322
344
  </button>
323
345
  )}
324
346
  </>
@@ -43,7 +43,7 @@ export function UndoBar(props: UndoBarProps): ReactNode {
43
43
  // row takes over only after the card is closed.
44
44
  const panel = ui.getPanel()
45
45
  const visible = (panel === undefined || panel.sessionId !== uiKey) && entry !== undefined && entry.applied === draft
46
- const rootRef = useDockAlignment(visible)
46
+ const rootRef = useDockAlignment(visible, uiKey)
47
47
  if (!visible) return null
48
48
 
49
49
  const undo = (): void => {
@@ -103,6 +103,12 @@ function parseResult(value: unknown): EnhanceResult {
103
103
  model: record.model,
104
104
  elapsedMs: record.elapsedMs,
105
105
  ...(usage === undefined ? {} : { usage }),
106
+ // Carried explicitly, not optional-by-accident: the panel's "output hit
107
+ // the token cap" warning is driven by this flag alone, so rebuilding the
108
+ // object without it left the host setting it, the wire carrying it, and
109
+ // the UI never seeing it. Only `true` is ever normalized in, matching the
110
+ // host, which sets the field solely on a capped finish.
111
+ ...(record.truncated === true ? { truncated: true } : {}),
106
112
  }
107
113
  }
108
114
  throw new EnhanceClientError({ code: 'internal', params: { reason: 'malformed' } })
@@ -11,3 +11,6 @@
11
11
 
12
12
  /** Plugin version injected by the client build; `typeof`-guarded at use. */
13
13
  declare const __PLUGIN_VERSION__: string
14
+
15
+ /** Package name injected by the client build; `typeof`-guarded at use. */
16
+ declare const __PLUGIN_NAME__: string
@@ -19,10 +19,7 @@ export const zh = {
19
19
  'panel.enhanced': '增强结果',
20
20
  'panel.apply': '回填到输入框',
21
21
  'panel.regenerate': '重新生成',
22
- 'panel.appliedShort': '已替换 ✓',
23
- 'panel.undoneShort': '已撤销 ✓',
24
- 'panel.regeneratedShort': '已重新生成 ✓',
25
- 'panel.copiedShort': '已复制 ✓',
22
+ 'panel.regenerated': '已重新生成',
26
23
  'panel.copy': '复制结果',
27
24
  'panel.copied': '已复制',
28
25
  'panel.copyFailed': '复制失败',
@@ -42,8 +39,8 @@ export const zh = {
42
39
  'undo.dismiss': '关闭提示',
43
40
  'error.empty': '输入框为空,请先输入要增强的提示词。',
44
41
  'error.tooLong': '内容共 {count} 个字符,超过 {max} 个字符上限(按 Unicode 字符数统计,不是 token 数)。为避免改变原意不会自动截断,请精简后再试。',
45
- 'error.attachmentsOnly': '输入框只附加了附件(图片或文件),请补充要增强的文本。',
46
42
  'error.occurrences': '输入内容包含命令或文件引用,暂不支持增强;请先移除后再试。',
43
+ 'error.chipsUnknown': '无法读取输入框的引用状态(宿主未提供引用信息)。为避免覆盖已添加的命令或文件引用,本次增强已阻止;请清空输入框后输入纯文本草稿,或升级 DSH 后重试。',
47
44
  'error.phase': '当前输入正被占用(提交中),请稍后再试。',
48
45
  'error.disabled': '提示词增强已在插件设置中关闭。',
49
46
  'error.rejected': '增强请求被拒绝。',
@@ -141,7 +138,7 @@ export const zh = {
141
138
  'settings.strategy.extend': '追加在内置策略后',
142
139
  'settings.reasoning.inherit': '提供方默认',
143
140
  'settings.reasoning.loading': '正在读取该模型的档位…',
144
- 'settings.reasoning.unavailable': '无法读取该模型的档位,仅可跟随提供方默认。',
141
+ 'settings.reasoning.unavailable': '无法读取该模型的档位列表;已保存的档位仍会照常发送。',
145
142
  'settings.reasoning.noTiers': '该模型未声明推理档位,调用时将跟随提供方默认。',
146
143
  'settings.reasoning.unsupported': '当前值「{effort}」不在该模型支持的档位中。',
147
144
  'settings.reasoning.current': '当前值:{value}',
@@ -170,10 +167,7 @@ export const en: Record<PromptEnhanceKey, string> = {
170
167
  'panel.enhanced': 'Enhanced result',
171
168
  'panel.apply': 'Fill into input box',
172
169
  'panel.regenerate': 'Regenerate',
173
- 'panel.appliedShort': 'Replaced ✓',
174
- 'panel.undoneShort': 'Undone ✓',
175
- 'panel.regeneratedShort': 'Regenerated ✓',
176
- 'panel.copiedShort': 'Copied ✓',
170
+ 'panel.regenerated': 'Regenerated',
177
171
  'panel.copy': 'Copy result',
178
172
  'panel.copied': 'Copied',
179
173
  'panel.copyFailed': 'Copy failed',
@@ -193,8 +187,9 @@ export const en: Record<PromptEnhanceKey, string> = {
193
187
  'undo.dismiss': 'Dismiss',
194
188
  'error.empty': 'The input box is empty — type a prompt to enhance first.',
195
189
  'error.tooLong': 'The draft is {count} characters, above the {max} cap (Unicode characters, not tokens). It is never auto-truncated (that would change your meaning) — please shorten it.',
196
- 'error.attachmentsOnly': 'The composer only has attachments; add the text you want enhanced.',
197
190
  'error.occurrences': 'The draft contains commands or file references, which are not supported yet — remove them first.',
191
+ 'error.chipsUnknown':
192
+ 'The composer reference state could not be read on this host, so the enhancement was blocked to avoid overwriting a command or file reference. Clear the input box and type plain text, or update DSH, then retry.',
198
193
  'error.phase': 'The input box is busy (submitting) — try again in a moment.',
199
194
  'error.disabled': 'Prompt enhance is disabled in the plugin settings.',
200
195
  'error.rejected': 'The enhance request was rejected.',
@@ -296,7 +291,7 @@ export const en: Record<PromptEnhanceKey, string> = {
296
291
  'settings.strategy.extend': 'Append after the built-in strategy',
297
292
  'settings.reasoning.inherit': 'Provider default',
298
293
  'settings.reasoning.loading': 'Reading this model’s tiers…',
299
- 'settings.reasoning.unavailable': 'Could not read this model’s tiers; only “follow provider default” is available.',
294
+ 'settings.reasoning.unavailable': 'Could not read this model’s tier list; your saved tier is still sent.',
300
295
  'settings.reasoning.noTiers': 'This model declares no reasoning tiers; calls follow the provider default.',
301
296
  'settings.reasoning.unsupported': 'The current value “{effort}” is not one of this model’s tiers.',
302
297
  'settings.reasoning.current': 'Current value: {value}',
@@ -39,7 +39,15 @@ export const SETTINGS_ROW_CONFIG_SLOT = 'plugins.row.config'
39
39
  export const SETTINGS_NAMESPACE = 'dsh-prompt-enhance'
40
40
 
41
41
  /** The bundle whose patch declares the row, and that row's id. */
42
- export const SETTINGS_BUNDLE = '@surfishs/dsh-prompt-enhance'
42
+ /**
43
+ * Package name of this bundle, injected by the client build from
44
+ * `package.json.name` (see `scripts/build.mjs`), exactly like the version.
45
+ * It must not be a literal: the plugin manager keys a row's config page as
46
+ * `<package name>#<row id>`, so a fork that renames the package would silently
47
+ * lose that page. The fallback is the shipped name, for environments that
48
+ * execute the source without the build (unit tests).
49
+ */
50
+ export const SETTINGS_BUNDLE = typeof __PLUGIN_NAME__ === 'string' ? __PLUGIN_NAME__ : '@surfishs/dsh-prompt-enhance'
43
51
  export const SETTINGS_ROW_ID = 'dsh-prompt-enhance'
44
52
 
45
53
  /**