@qthinker/opencode-deepseek-search 0.3.0 → 0.3.2

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.
@@ -1,7 +1,7 @@
1
1
  // Pure view model for the sidebar card. No renderer, no runtime dependency:
2
2
  // the card and the tests both derive their text from here.
3
3
  import { format, pack, t } from "./i18n/index.ts"
4
- import type { SearchStatus, UsageCounts, Language } from "./rpc.ts"
4
+ import type { BalanceStatus, SearchStatus, UsageCounts, Language } from "./rpc.ts"
5
5
 
6
6
  export interface SidebarInput {
7
7
  readonly status: SearchStatus | undefined
@@ -41,7 +41,12 @@ export interface SidebarRows {
41
41
  readonly hint: string | undefined
42
42
  /** Whether a click on `action` really performs it (some states have no action). */
43
43
  readonly clickable: boolean
44
- /** Body rows: the three usage rows, or the short error reason. */
44
+ /**
45
+ * Body rows: the three usage rows (or the single collapsed usage row when
46
+ * not even the shortest fits), or the short error reason, then the optional
47
+ * balance row last. A row starting with `!` is an unavailable balance; the
48
+ * marker is a color directive for the renderer and never part of the copy.
49
+ */
45
50
  readonly lines: readonly string[]
46
51
  /** Drives the state color in card.ts. */
47
52
  readonly tone: "on" | "off" | "warn" | "error" | "idle"
@@ -150,10 +155,12 @@ function usageLayout(counts: Counts): UsageLayout {
150
155
 
151
156
  /**
152
157
  * One usage row, e.g. `今日 Search 0 Fetch 3 ¥0.015` when the surface is
153
- * wide, otherwise shorter forms down to `今日`. The ladder is per language:
154
- * each locale owns the shapes that read well at its widths, so no language is
155
- * squeezed into another one's budget. Counts are right-aligned in their shared
156
- * width and every row picks the same form, so the three rows read as a table.
158
+ * wide, otherwise shorter forms down to the amount or the search count alone.
159
+ * The ladder is per language: each locale owns the shapes that read well at its
160
+ * widths, so no language is squeezed into another one's budget. Counts are
161
+ * right-aligned in their shared width and every row picks the same form, so the
162
+ * three rows read as a table. `undefined` means not even the shortest rung fits;
163
+ * the caller then collapses the three rows instead of emitting blanks.
157
164
  */
158
165
  function compactUsageRow(
159
166
  period: Period,
@@ -161,42 +168,54 @@ function compactUsageRow(
161
168
  layout: UsageLayout,
162
169
  maxColumns: number,
163
170
  language: Language,
164
- ): string {
171
+ ): string | undefined {
165
172
  const label = t(language, LABEL_KEY[period])
166
173
  const search = String(counts.search).padStart(layout.search, " ")
167
174
  const fetch = String(counts.fetch).padStart(layout.fetch, " ")
168
175
  const cost = money(counts.costMicro).padStart(layout.cost, " ")
169
176
  const params = { label, search, fetch, cost }
177
+ const forms = pack(language).usageForms
170
178
  // Each candidate is a complete row, so nothing is ever left dangling and no
171
179
  // number is ever cut from its unit.
172
- for (const form of pack(language).usageForms) {
180
+ for (const form of forms.slice(0, -1)) {
173
181
  const row = format(form, params)
174
182
  if (textColumns(row) <= maxColumns) return row
175
183
  }
176
- return textColumns(label) <= maxColumns ? label : clip(label, maxColumns)
184
+ // The amount alone outranks the ladder's last rung, a lone search count: money
185
+ // is what this card is for, and a single counter is not. The row is composed
186
+ // here because it carries no count, so it is not a locale ladder entry — the
187
+ // label still comes from the locale table.
188
+ const amountRow = `${label} ${cost}`
189
+ if (textColumns(amountRow) <= maxColumns) return amountRow
190
+ const narrowest = forms[forms.length - 1]
191
+ if (narrowest !== undefined) {
192
+ const row = format(narrowest, params)
193
+ if (textColumns(row) <= maxColumns) return row
194
+ }
195
+ return undefined
177
196
  }
178
197
 
179
198
  /**
180
- * An older server only sends pre-formatted strings, and those are always the
181
- * Chinese ones this plugin used to send: the filter below is deliberately
182
- * Chinese-only and stays correct while the UI language changes. Keep the full
183
- * string when it fits, otherwise drop its trailing segments whole: the amount
184
- * and the diagnostic counters go first, then the fetch count.
199
+ * Below the shortest rung no usage row can carry a number, so the three rows
200
+ * become one that still does: the total cost first (the number this card is
201
+ * opened for), then the total search count, then the bare amount, which fits
202
+ * the card floor on its own. A label with no number behind it is a row of noise
203
+ * and is never emitted.
185
204
  */
186
- function legacyUsageRow(period: Period, text: string, maxColumns: number, language: Language): string {
187
- const label = t(language, LABEL_KEY[period])
188
- const full = `${label} ${text}`
189
- if (textColumns(full) <= maxColumns) return full
190
- const stats = text.split(" · ").filter((part) => !part.startsWith("¥") && !part.startsWith("空/失"))
205
+ function collapseUsageRow(counts: UsageCounts, layout: UsageLayout, maxColumns: number, language: Language): string {
206
+ const label = t(language, LABEL_KEY.total)
207
+ const cost = money(counts.costMicro)
191
208
  const candidates = [
192
- `${label} ${stats.join(" ")}`.trimEnd(),
193
- `${label} ${stats[0] ?? ""}`.trimEnd(),
194
- label,
209
+ `${label} ${cost.padStart(layout.cost, " ")}`,
210
+ `${label} ${String(counts.search).padStart(layout.search, " ")}S`,
211
+ cost,
195
212
  ]
196
213
  for (const row of candidates) {
197
214
  if (textColumns(row) <= maxColumns) return row
198
215
  }
199
- return clip(label, maxColumns)
216
+ // Nothing unclipped fits: only a clipped amount is left, and it still shows a
217
+ // digit as far as the columns allow.
218
+ return clip(cost, maxColumns)
200
219
  }
201
220
 
202
221
  function usageLines(status: SearchStatus, maxColumns: number, language: Language): readonly string[] {
@@ -212,11 +231,67 @@ function usageLines(status: SearchStatus, maxColumns: number, language: Language
212
231
  const counts = status.counts
213
232
  if (counts) {
214
233
  const layout = usageLayout(counts)
215
- return PERIODS.map((period) => compactUsageRow(period, counts[period], layout, maxColumns, language))
234
+ const rows: string[] = []
235
+ for (const period of PERIODS) {
236
+ const row = compactUsageRow(period, counts[period], layout, maxColumns, language)
237
+ // All three rows share their padded widths, so they either all fit or none
238
+ // does; the first miss is enough to collapse rather than half a table.
239
+ if (row === undefined) return [collapseUsageRow(counts.total, layout, maxColumns, language)]
240
+ rows.push(row)
241
+ }
242
+ return rows
216
243
  }
217
244
  return PERIODS.map((period) => legacyUsageRow(period, status[period], maxColumns, language))
218
245
  }
219
246
 
247
+ // The server normalizes `currency` to one of these codes, so the symbol is a
248
+ // lookup rather than a formatting library. An unknown code contributes nothing
249
+ // instead of a wrong symbol. The desktop panel reuses it for its account block.
250
+ export const CURRENCY_SYMBOL: Readonly<Record<string, string>> = { CNY: "¥", USD: "$" }
251
+
252
+ /**
253
+ * The account-balance row, or `undefined` when it does not fit. The amount is
254
+ * the server's string verbatim (`110.00`), never re-rounded: DeepSeek's account
255
+ * balance is authoritative and this row only mirrors it.
256
+ *
257
+ * `!` marks an unavailable balance and costs one column; it is the only marker,
258
+ * so the renderer can turn it into a color and every other consumer keeps a
259
+ * plain string. The row is never compressed into another one: below its width it
260
+ * is dropped, because half an amount is worse than no amount.
261
+ */
262
+ function balanceRow(balance: BalanceStatus, maxColumns: number, language: Language): string | undefined {
263
+ const marker = balance.isAvailable ? "" : "!"
264
+ const amount = `${CURRENCY_SYMBOL[balance.currency] ?? ""}${balance.totalBalance}`
265
+ for (const form of pack(language).balanceForms) {
266
+ const row = `${marker}${format(form, { amount })}`
267
+ if (textColumns(row) <= maxColumns) return row
268
+ }
269
+ return undefined
270
+ }
271
+
272
+ /**
273
+ * An older server only sends pre-formatted strings, and those are always the
274
+ * Chinese ones this plugin used to send: the filter below is deliberately
275
+ * Chinese-only and stays correct while the UI language changes. Keep the full
276
+ * string when it fits, otherwise drop its trailing segments whole: the amount
277
+ * and the diagnostic counters go first, then the fetch count.
278
+ */
279
+ function legacyUsageRow(period: Period, text: string, maxColumns: number, language: Language): string {
280
+ const label = t(language, LABEL_KEY[period])
281
+ const full = `${label} ${text}`
282
+ if (textColumns(full) <= maxColumns) return full
283
+ const stats = text.split(" · ").filter((part) => !part.startsWith("¥") && !part.startsWith("空/失"))
284
+ const candidates = [
285
+ `${label} ${stats.join(" ")}`.trimEnd(),
286
+ `${label} ${stats[0] ?? ""}`.trimEnd(),
287
+ label,
288
+ ]
289
+ for (const row of candidates) {
290
+ if (textColumns(row) <= maxColumns) return row
291
+ }
292
+ return clip(label, maxColumns)
293
+ }
294
+
220
295
  /**
221
296
  * The clickable label, always bracketed: a bare two-character verb is an easy
222
297
  * target to miss. At pathological widths the verb is clipped but the brackets
@@ -243,12 +318,17 @@ interface TitleFit {
243
318
  * and the title keeps the full width, and only then do the product name and the
244
319
  * wordy state shrink. Within one wording the glyph is the first thing to go,
245
320
  * because it costs two columns and the state word is right beside it.
321
+ *
322
+ * `allowActionBelow` is false on a card whose body is already full: giving the
323
+ * action its own row would push the card past its height budget, so the title
324
+ * shrinks instead — the action row always wins, because it is the only control.
246
325
  */
247
326
  function fitTitle(
248
327
  state: string,
249
328
  shortState: string,
250
329
  maxColumns: number,
251
330
  actionColumns: number | undefined,
331
+ allowActionBelow = true,
252
332
  ): TitleFit {
253
333
  const budget = (glyph: boolean, actionBelow: boolean): number => {
254
334
  if (maxColumns === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY
@@ -265,7 +345,7 @@ function fitTitle(
265
345
  ]
266
346
  // Inline first, then the action below it; a wording is never traded for a
267
347
  // shorter one that happens to fit inline, because the wording is the point.
268
- const placements = actionColumns === undefined ? [false] : [false, true]
348
+ const placements = actionColumns === undefined || !allowActionBelow ? [false] : [false, true]
269
349
  for (const candidate of candidates) {
270
350
  for (const actionBelow of placements) {
271
351
  for (const glyph of [true, false]) {
@@ -276,8 +356,9 @@ function fitTitle(
276
356
  }
277
357
  }
278
358
  // Nothing fits whole at a pathological width: clip the state and give the
279
- // action its own row so the hit area never disappears.
280
- const actionBelow = actionColumns !== undefined
359
+ // action its own row so the hit area never disappears — unless the body has
360
+ // already spent that row, in which case the clipped title shares the width.
361
+ const actionBelow = allowActionBelow && actionColumns !== undefined
281
362
  return { title: clip(shortState, budget(false, actionBelow)), glyph: false, actionBelow }
282
363
  }
283
364
 
@@ -296,15 +377,36 @@ interface ActionRows extends TitleFit {
296
377
  }
297
378
 
298
379
  /** Fit the action first: the title can only use the columns it leaves over. */
299
- function actionRows(state: string, shortState: string, verb: string, maxColumns: number): ActionRows {
380
+ function actionRows(
381
+ state: string,
382
+ shortState: string,
383
+ verb: string,
384
+ maxColumns: number,
385
+ allowActionBelow = true,
386
+ ): ActionRows {
300
387
  const action = fitAction(verb, maxColumns)
301
- return { ...fitTitle(state, shortState, maxColumns, textColumns(action)), action }
388
+ return { ...fitTitle(state, shortState, maxColumns, textColumns(action), allowActionBelow), action }
302
389
  }
303
390
 
304
391
  export function sidebarRows(input: SidebarInput): SidebarRows {
305
392
  const { status, error, language } = input
306
393
  const maxColumns = input.maxColumns ?? DEFAULT_COLUMNS
307
- const lines = status === undefined ? [] : usageLines(status, maxColumns, language)
394
+ const usage = status === undefined ? [] : usageLines(status, maxColumns, language)
395
+ // Only the two states that really point at the account show it: an enabled
396
+ // takeover or an explicit native mode. A state where nothing is taken over, a
397
+ // missing key, or a failed read leaves the body to usage and the error reason.
398
+ const balance =
399
+ status !== undefined &&
400
+ ((status.patched && status.hasKey) || status.mode === "native") &&
401
+ status.balance !== undefined
402
+ ? balanceRow(status.balance, maxColumns, language)
403
+ : undefined
404
+ // The balance row closes the body: the three usage rows read as the receipt
405
+ // (what this machine spent) and the account truth lands under them (what is
406
+ // left to spend). It still costs one body row, so the header must keep the
407
+ // action inline to stay within five rows.
408
+ const lines = balance === undefined ? usage : [...usage, balance]
409
+ const allowActionBelow = balance === undefined
308
410
 
309
411
  // No status yet: the body has no numbers to show, only the reason (or that
310
412
  // the first read is still in flight).
@@ -329,7 +431,13 @@ export function sidebarRows(input: SidebarInput): SidebarRows {
329
431
 
330
432
  if (status.patched && status.hasKey) {
331
433
  return {
332
- ...actionRows(t(language, "state.enabled"), t(language, "state.enabledShort"), t(language, "action.disable"), maxColumns),
434
+ ...actionRows(
435
+ t(language, "state.enabled"),
436
+ t(language, "state.enabledShort"),
437
+ t(language, "action.disable"),
438
+ maxColumns,
439
+ allowActionBelow,
440
+ ),
333
441
  hint: undefined,
334
442
  clickable: true,
335
443
  lines,
@@ -345,6 +453,7 @@ export function sidebarRows(input: SidebarInput): SidebarRows {
345
453
  t(language, "state.unpatchedShort"),
346
454
  t(language, "action.release"),
347
455
  maxColumns,
456
+ allowActionBelow,
348
457
  ),
349
458
  hint: undefined,
350
459
  clickable: true,
@@ -354,7 +463,13 @@ export function sidebarRows(input: SidebarInput): SidebarRows {
354
463
  }
355
464
  if (status.mode === "native") {
356
465
  return {
357
- ...actionRows(t(language, "state.disabled"), t(language, "state.disabledShort"), t(language, "action.enable"), maxColumns),
466
+ ...actionRows(
467
+ t(language, "state.disabled"),
468
+ t(language, "state.disabledShort"),
469
+ t(language, "action.enable"),
470
+ maxColumns,
471
+ allowActionBelow,
472
+ ),
358
473
  hint: undefined,
359
474
  clickable: true,
360
475
  lines,
package/src/tui/card.ts CHANGED
@@ -9,6 +9,10 @@ import type { SidebarRows } from "../status-view.ts"
9
9
 
10
10
  /** A measured width under this cannot show even the usage label; treat it as unmeasured. */
11
11
  const MIN_CARD_COLUMNS = 8
12
+ /** Body rows are inset this far from the title, so the card reads as one block. */
13
+ const INDENT = " "
14
+ /** Under this many columns the indent costs more than it explains. */
15
+ const INDENT_MIN_COLUMNS = 16
12
16
 
13
17
  /**
14
18
  * Columns the card may use. Before the first layout pass the host reports 0 (or
@@ -69,6 +73,40 @@ function element(tag: string, props: Props | undefined, children: readonly Child
69
73
  return node
70
74
  }
71
75
 
76
+ /** The amount at the end of a row, e.g. `¥0.015` / `$6.17`; it gets its own color. */
77
+ const MONEY_TAIL = /([¥$][\d.,]+)$/u
78
+
79
+ /**
80
+ * One body row split into the three tiers the card colors. The view model emits
81
+ * plain strings — one row per line, deliberately not structured — so the row is
82
+ * split here: the leading label reads faint, the counters in the middle muted,
83
+ * and the amount at the end is the number the user came for, so it gets full
84
+ * contrast.
85
+ */
86
+ interface BodyParts {
87
+ readonly label: string
88
+ readonly middle: string
89
+ readonly amount: string
90
+ /** The row starts with `!`: the balance could not be read. */
91
+ readonly unavailable: boolean
92
+ }
93
+
94
+ function bodyParts(line: string): BodyParts {
95
+ // `!` is the only unavailable marker in the row text and is consumed here as a
96
+ // color directive: it is never drawn. The label and the amount still are.
97
+ const unavailable = line.startsWith("!")
98
+ const text = unavailable ? line.slice(1) : line
99
+ const amount = MONEY_TAIL.exec(text)?.[1] ?? ""
100
+ const head = amount === "" ? text : text.slice(0, text.length - amount.length)
101
+ const gap = head.indexOf(" ")
102
+ return {
103
+ label: gap < 0 ? head : head.slice(0, gap),
104
+ middle: gap < 0 ? "" : head.slice(gap),
105
+ amount,
106
+ unavailable,
107
+ }
108
+ }
109
+
72
110
  export function sidebarCard(input: {
73
111
  readonly status: SearchStatus | undefined
74
112
  readonly error: string | undefined
@@ -85,10 +123,14 @@ export function sidebarCard(input: {
85
123
  }): JSX.Element {
86
124
  // The terminal sidebar is the surface this ladder is tuned for: the measured
87
125
  // width, not a guessed constant, decides whether the words fit.
126
+ const columns = cardColumns(input.maxColumns)
127
+ // The indent is part of the drawn row, so it is subtracted from the budget the
128
+ // model composes against: every row still ends inside the measured width.
129
+ const indent = columns >= INDENT_MIN_COLUMNS ? INDENT : ""
88
130
  const rows = sidebarRows({
89
131
  status: input.status,
90
132
  error: input.error,
91
- maxColumns: cardColumns(input.maxColumns),
133
+ maxColumns: columns - indent.length,
92
134
  language: input.language,
93
135
  })
94
136
  const theme = input.theme
@@ -108,14 +150,18 @@ export function sidebarCard(input: {
108
150
  //
109
151
  // The state word carries the tone color, so a narrow sidebar that has to drop
110
152
  // the glyph still shows the state at a glance (the desktop panel does the same).
153
+ // When the glyph is gone the word also goes bold — the emphasis has to live
154
+ // somewhere. Bold rides in `style`, because the reconciler ignores an
155
+ // `attributes` prop on text nodes and only maps `style` (fg/bg/attributes).
156
+ const stateStyle = rows.glyph ? { fg: state } : { fg: state, bold: true }
111
157
  const separator = rows.title.indexOf(" · ")
112
158
  const titleSpans: Child[] =
113
159
  separator < 0
114
- ? [element("span", { style: { fg: state } }, [rows.title])]
160
+ ? [element("span", { style: stateStyle }, [rows.title])]
115
161
  : [
116
162
  element("span", { style: { fg: theme.text.base } }, [rows.title.slice(0, separator)]),
117
163
  element("span", { style: { fg: theme.text.faint } }, [" · "]),
118
- element("span", { style: { fg: state } }, [rows.title.slice(separator + 3)]),
164
+ element("span", { style: stateStyle }, [rows.title.slice(separator + 3)]),
119
165
  ]
120
166
  if (rows.glyph) {
121
167
  titleSpans.unshift(element("span", { style: { fg: state } }, [`${GLYPH[rows.tone]} `]))
@@ -157,11 +203,28 @@ export function sidebarCard(input: {
157
203
  [action],
158
204
  )
159
205
 
160
- // The model already composed every row to fit the sidebar, so each body row
161
- // is one text node: the host must never get the chance to wrap it.
162
- const body = rows.lines.map((line) =>
163
- element("text", { content: line, fg: theme.text.muted, wrapMode: "none", width: "100%" }),
164
- )
206
+ // The model already composed every row to fit the sidebar, so each body row is
207
+ // one text node: the host must never get the chance to wrap it. The row's own
208
+ // text is split into colored spans, so the label, the counters and the amount
209
+ // each read at their own weight without a second row or a box per line.
210
+ const body = rows.lines.map((line) => {
211
+ const parts = bodyParts(line)
212
+ const spans: Child[] = []
213
+ if (indent !== "") spans.push(element("span", { style: { fg: theme.text.faint } }, [indent]))
214
+ if (parts.label !== "") {
215
+ spans.push(element("span", { style: { fg: theme.text.faint } }, [parts.label]))
216
+ }
217
+ if (parts.middle !== "") {
218
+ spans.push(element("span", { style: { fg: theme.text.muted } }, [parts.middle]))
219
+ }
220
+ if (parts.amount !== "") {
221
+ // An unavailable balance is the one thing on the card that must not look
222
+ // like an ordinary amount: it is the reason the next call will fail.
223
+ const fg = parts.unavailable ? theme.text.feedback.warning.base : theme.text.base
224
+ spans.push(element("span", { style: { fg } }, [parts.amount]))
225
+ }
226
+ return element("text", { selectable: false, wrapMode: "none", width: "100%" }, spans)
227
+ })
165
228
  // A missing key has no action, so the fix hint gets the row right under the
166
229
  // title. It is plain text: there is nothing to click.
167
230
  const hint =
package/src/tui/main.ts CHANGED
@@ -35,9 +35,14 @@ export default Plugin.define({
35
35
  // `status` takes a required first argument: plain JSON Schema degrades the
36
36
  // input type to `unknown`, and the host validates the payload against the
37
37
  // method's object schema, so an omitted input is rejected as invalid.
38
- async function refresh() {
38
+ //
39
+ // `force` asks the server to re-probe the account balance instead of serving
40
+ // the cache; only a user action may spend that request. The timer and the
41
+ // `changed` event therefore send `{}` exactly — an older server rejects
42
+ // unknown input properties, so a stray `force: false` would break it.
43
+ async function refresh(force = false) {
39
44
  try {
40
- const next = readStatus(await rpc.status({}))
45
+ const next = readStatus(await rpc.status(force ? { force: true } : {}))
41
46
  if (next) {
42
47
  setStatus(next)
43
48
  setError(undefined)
@@ -65,11 +70,12 @@ export default Plugin.define({
65
70
  }
66
71
 
67
72
  // The card labels the action it can really perform: switching the takeover
68
- // when a status is known, retrying the read when it is not.
73
+ // when a status is known, retrying the read when it is not. A retry is a user
74
+ // action, so it refreshes the cached balance snapshot as well.
69
75
  function toggle() {
70
76
  const current = status()
71
77
  if (!current || error()) {
72
- void refresh()
78
+ void refresh(true)
73
79
  return
74
80
  }
75
81
  void applyMode(current.mode === "deepseek" ? "native" : "deepseek")
@@ -88,7 +94,9 @@ export default Plugin.define({
88
94
  current: status()?.mode,
89
95
  })
90
96
  if (choice === undefined) return
91
- if (choice === "refresh") await refresh()
97
+ // The dialog's refresh is an explicit "show me now", so it bypasses the
98
+ // server's balance cache; enabling/disabling refreshes through applyMode.
99
+ if (choice === "refresh") await refresh(true)
92
100
  else await applyMode(choice)
93
101
  }
94
102