@2cmddev/2cmd 0.0.0-stage → 0.1.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.
Files changed (93) hide show
  1. package/.opencode/command/2cmd-audit.md +5 -0
  2. package/.opencode/command/2cmd-debt.md +5 -0
  3. package/.opencode/command/2cmd-gain.md +5 -0
  4. package/.opencode/command/2cmd-help.md +5 -0
  5. package/.opencode/command/2cmd-review.md +5 -0
  6. package/.opencode/command/2cmd.md +5 -0
  7. package/.opencode/plugins/2cmd-frontmatter.cjs +63 -0
  8. package/.opencode/plugins/2cmd.mjs +206 -0
  9. package/.opencode/plugins/index.js +4 -0
  10. package/.qoder/rules/2cmd.md +31 -0
  11. package/.qoder-plugin/plugin.json +16 -0
  12. package/.zcode-plugin/plugin.json +13 -0
  13. package/AGENTS.md +33 -0
  14. package/LICENSE +22 -0
  15. package/README.md +133 -2
  16. package/codex/answer.mjs +164 -0
  17. package/codex/data.mjs +31 -0
  18. package/codex/pty.py +80 -0
  19. package/codex/stats.mjs +105 -0
  20. package/codex/terminal.mjs +388 -0
  21. package/dsh/LICENSE +22 -0
  22. package/dsh/board.js +782 -0
  23. package/dsh/build.mjs +47 -0
  24. package/dsh/bundle.json +2104 -0
  25. package/dsh/client.js +877 -0
  26. package/dsh/cordis.patch.yml +3 -0
  27. package/dsh/index.js +185 -0
  28. package/dsh/ledger.js +50 -0
  29. package/dsh/market.js +152 -0
  30. package/dsh/package.json +24 -0
  31. package/dsh/prices.json +1812 -0
  32. package/dsh/settings-text.mjs +520 -0
  33. package/dsh/settings.js +42 -0
  34. package/dsh/stats.js +106 -0
  35. package/dsh/store.js +32 -0
  36. package/dsh/update-prices.mjs +9 -0
  37. package/dsh/update.js +27 -0
  38. package/dsh/voice-helper/Info.plist +13 -0
  39. package/dsh/voice-helper/Transcript.swift +21 -0
  40. package/dsh/voice-helper/build.sh +10 -0
  41. package/dsh/voice-helper/main.swift +70 -0
  42. package/dsh/voice-helper/test.swift +17 -0
  43. package/dsh/voice.js +63 -0
  44. package/hooks/2cmd-activate.js +219 -0
  45. package/hooks/2cmd-antigravity.js +64 -0
  46. package/hooks/2cmd-band-import.js +305 -0
  47. package/hooks/2cmd-config.js +186 -0
  48. package/hooks/2cmd-instructions.js +104 -0
  49. package/hooks/2cmd-map.js +200 -0
  50. package/hooks/2cmd-mode-tracker.js +248 -0
  51. package/hooks/2cmd-runtime.js +245 -0
  52. package/hooks/2cmd-statusline.ps1 +24 -0
  53. package/hooks/2cmd-statusline.sh +18 -0
  54. package/hooks/2cmd-subagent.js +100 -0
  55. package/hooks/band/board.ts +720 -0
  56. package/hooks/band/buttons.ts +60 -0
  57. package/hooks/band/i18n/de.ts +149 -0
  58. package/hooks/band/i18n/en.ts +150 -0
  59. package/hooks/band/i18n/es.ts +149 -0
  60. package/hooks/band/i18n/fr.ts +149 -0
  61. package/hooks/band/i18n/index.ts +42 -0
  62. package/hooks/band/i18n/ja.ts +149 -0
  63. package/hooks/band/i18n/ko.ts +149 -0
  64. package/hooks/band/i18n/pt.ts +149 -0
  65. package/hooks/band/i18n/ru.ts +149 -0
  66. package/hooks/band/i18n/vi.ts +149 -0
  67. package/hooks/band/i18n/zh-Hans.ts +149 -0
  68. package/hooks/band/i18n/zh-Hant.ts +149 -0
  69. package/hooks/band/logo.ts +3 -0
  70. package/hooks/band/metrics.ts +373 -0
  71. package/hooks/band/register.tsx +681 -0
  72. package/hooks/band/types.d.ts +45 -0
  73. package/hooks/band/windows-board.mjs +20 -0
  74. package/hooks/claude-band.json +6 -0
  75. package/hooks/claude-codex-hooks.json +41 -0
  76. package/hooks/codebuddy-hooks.json +20 -0
  77. package/hooks/copilot-hooks.json +21 -0
  78. package/hooks/cursor-hooks.json +17 -0
  79. package/hooks/qoder-hooks.json +26 -0
  80. package/hooks/zcode-hooks.json +26 -0
  81. package/package.json +56 -4
  82. package/pi-extension/index.js +258 -0
  83. package/pi-extension/names.js +19 -0
  84. package/pi-extension/package.json +8 -0
  85. package/scripts/cursor-hooks.js +145 -0
  86. package/scripts/uninstall.js +92 -0
  87. package/skills/2cmd/SKILL.md +55 -0
  88. package/skills/2cmd-audit/SKILL.md +105 -0
  89. package/skills/2cmd-debt/SKILL.md +46 -0
  90. package/skills/2cmd-gain/SKILL.md +53 -0
  91. package/skills/2cmd-help/SKILL.md +87 -0
  92. package/skills/2cmd-review/SKILL.md +143 -0
  93. package/skills/plugin.json +5 -0
package/dsh/client.js ADDED
@@ -0,0 +1,877 @@
1
+ // DeepSeek Harness browser half, written in the format DSH loads directly, so it needs no build step.
2
+ window.__ModuleLoader__.load({ id: '2cmd-dsh', factory: require => {
3
+ const { createElement: h, useCallback, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore } = require('react')
4
+ const { createPortal } = require('react-dom')
5
+ const { IconChevronDownOutlineRegular, Menu } = require('@deepseek-ai/dsh-client-ui-primitives')
6
+
7
+ // Applies only in the working window, only while the panel is on screen, and only if the composer has the parts
8
+ // this layout expects. Otherwise, or while a plugin such as voice input takes over the row, DSH's layout stays.
9
+ const ON = '[data-content-phase="active"]:has([data-2cmd]):has([data-composer-card] > :last-child > :first-child:not([hidden]) + * [data-slot="conversation.input.model"]):has([data-composer-dock])'
10
+ const CARD = `${ON} [data-composer-card]`
11
+ const ROW = `${CARD} > :last-child`
12
+ const DOCK = `${ON} [data-composer-dock]`
13
+ // DSH pulls the row below attachments up by 6px, so the 14px there leaves 8px above the + button.
14
+ // The panel uses the composer's own surface: its background, corners and shadow.
15
+ // The permission icon lines up with the composer's left edge. Its padding is set too, because it varies by DSH version.
16
+ const CSS = `
17
+ [data-2cmd]{display:none}
18
+ [data-content-phase="active"] [data-2cmd]{display:block}
19
+ [data-2cmd]{box-sizing:border-box;width:calc(100% - 2*var(--dsh-composer-side-clearance));max-width:var(--dsh-composer-card-max-width);margin:0 auto;padding:6px 12px;border-radius:var(--dsw-radius-panel);background:var(--dsw-specific-input-major);--dsw-elevation-stroke-color:var(--dsw-alias-border-l2);box-shadow:var(--dsw-elevation-soft);color:var(--dsw-alias-label-secondary);font:13px/20px var(--dsw-font-family)}
20
+ [data-2cmd] *{box-sizing:border-box}
21
+ .pt-bar{display:flex;flex-wrap:wrap;align-items:center;gap:4px 8px;min-height:32px}
22
+ .pt-bar button{position:relative;height:28px;padding:0 8px;border:0;border-radius:7px;background:transparent;color:inherit;font:inherit;white-space:nowrap;cursor:pointer}
23
+ .pt-bar button:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:-2px}
24
+ .pt-bar button:disabled{opacity:.5;cursor:default}
25
+ .pt-end{display:flex;margin-left:auto}
26
+ .pt-switch{position:relative;display:flex;gap:2px;border-radius:7px;background:rgba(0,0,0,.06)}
27
+ .pt-switch button,.pt-chip{padding:0 10px!important}
28
+ .pt-switch button[aria-checked=true],.pt-chip{color:var(--dsw-alias-label-primary)!important;font-weight:600!important}
29
+ .pt-thumb{position:absolute;inset:0 auto 0 0;overflow:hidden;border-radius:7px;opacity:.5;pointer-events:none}
30
+ .pt-thumb.pt-move{transition:transform .2s ease-out,width .2s ease-out}
31
+ .pt-thumb::before{content:"";position:absolute;inset:0 0 0 -28.284px;background:repeating-linear-gradient(45deg,transparent 0 10px,rgba(255,255,255,.5) 10px 20px)}
32
+ .pt-thumb[data-live=true]::before{animation:pt-flow 1.6s linear infinite}
33
+ .pt-chip .pt-thumb,.pt-hover{width:100%}.pt-hover{display:none}.pt-chip>span:not([class]),.pt-switch button>span:not([class]){position:relative}
34
+ .pt-thumb[data-mode=hindsight]{background:#45a16b}.pt-thumb[data-mode=reuse]{background:#598ad9}.pt-thumb[data-mode=pushback]{background:#d97757}.pt-thumb[data-mode=scout]{background:#9a73d9}
35
+ body[data-ds-dark-theme] .pt-switch{background:rgba(255,255,255,.06)}
36
+ body[data-ds-dark-theme] .pt-thumb::before{background:repeating-linear-gradient(45deg,transparent 0 10px,rgba(0,0,0,.4) 10px 20px)}
37
+ .pt-note{color:var(--dsw-alias-label-caption);font-size:12px}
38
+ .pt-switch+.pt-note,.pt-note+.pt-note{flex:1 1 0;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
39
+ .pt-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));margin-top:4px;padding:8px 0 4px;border-top:1px solid var(--dsw-alias-border-l2)}
40
+ .pt-stats>div{min-width:0;padding:0 12px;border-left:1px solid var(--dsw-alias-border-l2)}
41
+ .pt-stats>div:first-child{padding-left:0;border-left:0}
42
+ .pt-stats span,.pt-stats small,.pt-stats strong{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px;line-height:17px;color:var(--dsw-alias-label-caption)}
43
+ .pt-stats strong{font-size:16px;line-height:22px;font-weight:600;font-variant-numeric:tabular-nums;color:var(--dsw-alias-label-primary)}
44
+ .pt-tip{position:absolute;z-index:20;top:calc(100% + 6px);left:50%;transform:translateX(-50%);width:max-content;max-width:min(320px,80vw);padding:4px 8px;border-radius:6px;background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-base);font:12px/18px var(--dsw-font-family);white-space:nowrap;pointer-events:none;opacity:0;visibility:hidden}
45
+ .pt-end .pt-tip{left:auto;right:0;transform:none}
46
+ .pt-bar>:first-child .pt-tip,.pt-switch button:nth-of-type(1) .pt-tip{left:0;transform:none}
47
+ .pt-bar button:focus-visible .pt-tip{opacity:1;visibility:visible}
48
+ @media(hover:hover){.pt-switch button:hover:not(:disabled) .pt-hover{display:block}.pt-bar button:hover:not(:disabled){color:var(--dsw-alias-label-primary)}.pt-end button:hover:not(:disabled),.pt-bar>button:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}.pt-bar button:hover .pt-tip{opacity:1;visibility:visible;transition:opacity .1s .3s,visibility 0s .3s}}
49
+ .pt-board{width:min(1400px,94vw);height:92vh;max-width:none;max-height:none;padding:0;border:0;border-radius:14px;overflow:hidden;background:#060606;font:13px/20px var(--dsw-font-family)}
50
+ .pt-row{display:flex;align-items:center;gap:8px;padding:16px 0;border-bottom:.5px solid var(--dsw-alias-border-l2);font:14px/22px var(--dsw-font-family);color:var(--dsw-alias-label-primary)}
51
+ .pt-row:last-child{border-bottom:0}
52
+ .pt-toggle{appearance:none;flex:none;position:relative;width:36px;height:20px;margin:0;border:0;border-radius:999px;background:var(--dsw-alias-border-l3);cursor:pointer}
53
+ .pt-toggle::before{content:"";position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-switch-thumb);transition:transform .12s ease}
54
+ .pt-toggle:checked{background:var(--dsw-alias-brand-primary)}
55
+ .pt-toggle:checked::before{transform:translateX(16px);background:var(--dsw-alias-label-primary-foreground)}
56
+ .pt-toggle:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
57
+ .pt-page{height:100%;overflow:auto;box-sizing:border-box;padding:28px clamp(24px,4vw,48px) 48px}
58
+ .pt-page>*{max-width:720px;margin-inline:auto}
59
+ .pt-page>h1{display:flex;align-items:center;gap:10px;margin-block:0 8px;font:600 20px/28px var(--dsw-font-family);color:var(--dsw-alias-label-primary)}
60
+ .pt-row>div:first-child{flex:1;min-width:0;padding-right:16px}
61
+ .pt-row small{display:block;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}
62
+ .pt-button-row{align-items:flex-start}
63
+ .pt-custom{display:flex;flex-direction:column;gap:8px;margin-top:8px}
64
+ .pt-custom input,.pt-custom textarea{box-sizing:border-box;width:100%;padding:8px 10px;border:1px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-md);background:transparent;color:inherit;font:inherit;resize:vertical}
65
+ .pt-custom>div{display:flex;align-items:center;gap:10px}
66
+ .pt-row a{color:inherit;text-decoration:underline}
67
+ .pt-select{display:inline-flex;flex:none;align-items:center;gap:12px;height:36px;padding:0 14px;border:0;border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-module-platform);color:inherit;font:inherit;cursor:pointer}
68
+ .pt-select:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary)}
69
+ .pt-select:disabled{opacity:.5;cursor:default}
70
+ @media(hover:hover){.pt-select:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}}
71
+ .pt-board::backdrop{background:rgba(0,0,0,.55)}
72
+ .pt-board iframe{display:block;width:100%;height:calc(100% - 40px);border:0}
73
+ .pt-board button{display:block;height:28px;margin:6px 8px 6px auto;padding:0 12px;border:0;border-radius:7px;background:rgba(255,255,255,.1);color:#fff;font:inherit;cursor:pointer}
74
+ .pt-board button:focus-visible{outline:2px solid #598ad9}
75
+ @media(max-width:600px){.pt-stats{grid-template-columns:1fr 1fr;row-gap:8px}.pt-stats>div:nth-child(odd){padding-left:0;border-left:0}}
76
+ @media(prefers-reduced-motion:reduce){.pt-thumb,.pt-thumb::before{animation:none!important;transition:none!important}}
77
+ @media(prefers-reduced-motion:reduce){.pt-spin{animation-duration:3s!important}}
78
+ .pt-voice{position:relative;display:inline-flex}
79
+ .pt-voice button{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;border:0;border-radius:50%;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer}
80
+ .pt-voice button:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary)}
81
+ .pt-voice button:disabled{opacity:.5;cursor:default}
82
+ .pt-voice[data-pt-voice=recording] button{background:var(--dsw-alias-interactive-bg-hover);color:#d97757}
83
+ @media(hover:hover){.pt-voice button:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}}
84
+ .pt-voice-note{position:absolute;z-index:20;right:0;bottom:calc(100% + 10px);width:max-content;max-width:min(260px,70vw);padding:6px 10px;border-radius:8px;background:var(--dsw-alias-label-primary);color:var(--dsw-alias-bg-base);font:12px/18px var(--dsw-font-family)}
85
+ .pt-wave{flex:none;width:64px;height:16px;color:var(--dsw-alias-label-secondary)}
86
+ .pt-spin{animation:pt-spin .8s linear infinite}
87
+ @keyframes pt-spin{to{transform:rotate(360deg)}}
88
+ @keyframes pt-flow{to{transform:translateX(28.284px)}}
89
+
90
+ ${CARD}{gap:0;padding-top:8px;background:transparent;box-shadow:none;isolation:isolate}
91
+ ${CARD}::before{content:"";position:absolute;z-index:-1;inset:0 0 36px;border-radius:var(--dsw-radius-panel);background:var(--dsw-specific-input-major);box-shadow:var(--dsw-elevation-soft)}
92
+ ${CARD} [data-composer-input]{min-height:36px;padding:2px 96px 10px 48px}
93
+ ${CARD} [data-composer-input]+*{inset:2px 96px auto 48px}
94
+ ${CARD} [data-slot="conversation.input.attachments"]:has(img,button)+*{margin-top:14px}
95
+ ${ROW}{position:relative;box-sizing:border-box;flex-wrap:nowrap;gap:4px;height:36px;padding:6px calc(var(--pt-dock,56px) + 4px) 0 0}
96
+ ${ROW}>:first-child{gap:4px}
97
+ ${ROW} [data-slot="conversation.input.permission"]>*>button:first-child{margin-left:-8px;padding-left:8px}
98
+ ${ROW}>:last-child{flex:0 1 auto;gap:4px}
99
+ ${ROW}>:first-child>button:first-child,${ROW}>:last-child>button{position:absolute;bottom:calc(100% + 22px);transform:translateY(50%)}
100
+ ${ROW}>:first-child>button:first-child{left:8px}
101
+ ${ROW}>:last-child>button{right:6px}
102
+ ${ROW}>:last-child>button:nth-last-child(2){right:46px}
103
+ ${ROW} [data-pt-voice]{position:absolute;right:46px;bottom:calc(100% + 22px);transform:translateY(50%)}
104
+ ${ROW}>:last-child:has(>button+button) [data-pt-voice]{right:86px}
105
+ ${CARD}:has([data-pt-voice]):has(>:last-child>:last-child>button+button) [data-composer-input]{padding-right:136px}
106
+ ${DOCK}{position:relative;z-index:1;align-self:center;justify-content:flex-end;box-sizing:border-box;width:100%;max-width:var(--dsh-composer-card-max-width);height:30px;min-height:30px!important;margin-top:-30px;padding:0;pointer-events:none}
107
+ ${DOCK}>*{pointer-events:auto}
108
+ ${DOCK} [data-composer-stat=activity],${DOCK} [data-composer-stat=usage]{display:none}
109
+ `
110
+
111
+ const fill = (text, values) => text.replace(/\{(\w+)\}/g, (_, key) => values[key])
112
+ const formatMoney = (value, { currency, rate }, language) => {
113
+ const amount = value * rate
114
+ // Small amounts get more digits, so they do not show as 0. Yen and won normally have none.
115
+ const digits = amount > 0 && amount < 0.01 ? { minimumFractionDigits: 4, maximumFractionDigits: 4 } : amount < 100 ? { minimumFractionDigits: 2, maximumFractionDigits: 2 } : {}
116
+ return new Intl.NumberFormat(language, { style: 'currency', currency, currencyDisplay: currency === 'USD' ? 'narrowSymbol' : 'symbol', ...digits }).format(amount)
117
+ }
118
+ const count = n => (n < 1000 ? String(n) : n < 1e6 ? `${(n / 1000).toFixed(1)}k` : `${(n / 1e6).toFixed(1)}M`)
119
+ const elapsed = (ms) => {
120
+ const s = Math.round(ms / 1000)
121
+ return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m ${s % 60}s` : `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`
122
+ }
123
+ // The language chosen in 2Cmd's settings, or 'auto' for DSH's own. Set when the texts load and when it changes.
124
+ let chosen = 'auto'
125
+ // DSH calls Simplified Chinese "zh"; its other language codes match ours.
126
+ const packFor = (strings, appLanguage) => {
127
+ const language = chosen === 'auto' ? appLanguage : chosen
128
+ return [language,
129
+ /^zh-(hant|tw|hk|mo)/i.test(language) ? 'zh-Hant' : language.startsWith('zh') ? 'zh-Hans' : language.split('-')[0],
130
+ ].find(id => Object.hasOwn(strings, id)) ?? 'en'
131
+ }
132
+
133
+ async function request(url, options) {
134
+ const response = await fetch(url, { credentials: 'same-origin', ...options })
135
+ if (!response.ok) throw new Error(`2cmd: ${response.status}`)
136
+ return response.json()
137
+ }
138
+ let strings
139
+ const loadStrings = () => (strings ??= request('/api/2cmd.strings').then((all) => {
140
+ chosen = all.chosen ?? 'auto'
141
+ return all
142
+ }, (error) => {
143
+ strings = undefined
144
+ throw error
145
+ }))
146
+
147
+ const Button = ({ tip, children, ...props }) => h('button', { type: 'button', ...props }, children, h('span', { className: 'pt-tip', role: 'tooltip' }, tip))
148
+ const Stripes = ({ mode, live, ...props }) => h('span', { 'aria-hidden': true, className: 'pt-thumb', 'data-mode': mode, 'data-live': live, ...props })
149
+
150
+ function Switch({ mode, live, t, onPick }) {
151
+ const root = useRef(null)
152
+ const [box, setBox] = useState(null)
153
+ const [move, setMove] = useState(false)
154
+ useLayoutEffect(() => {
155
+ const measure = () => {
156
+ const button = root.current?.querySelector('[aria-checked=true]')
157
+ setBox(button ? { width: button.offsetWidth, transform: `translateX(${button.offsetLeft}px)` } : null)
158
+ }
159
+ measure()
160
+ const observer = new ResizeObserver(measure)
161
+ observer.observe(root.current)
162
+ return () => observer.disconnect()
163
+ }, [mode, t])
164
+ // Slide only between modes, not when the thumb first appears.
165
+ useEffect(() => setMove(box !== null), [box])
166
+ const onKeyDown = (event) => {
167
+ const step = { ArrowRight: 1, ArrowDown: 1, ArrowLeft: -1, ArrowUp: -1 }[event.key]
168
+ if (!step) return
169
+ event.preventDefault()
170
+ const buttons = [...root.current.querySelectorAll('button')]
171
+ const next = buttons[(buttons.indexOf(event.target.closest('button')) + step + buttons.length) % buttons.length]
172
+ next.focus()
173
+ next.click()
174
+ }
175
+ return h('div', { ref: root, className: 'pt-switch', role: 'radiogroup', 'aria-label': '2Cmd', onKeyDown },
176
+ box && h(Stripes, { mode, live, style: box, className: `pt-thumb${move ? ' pt-move' : ''}` }),
177
+ [['hindsight', t.tipHindsight], ['reuse', t.tipReuse], ['pushback', t.tipPushback], ['scout', t.tipScout]].map(([id, tip]) => h(Button, {
178
+ key: id, tip, role: 'radio', 'aria-checked': mode === id, tabIndex: mode === id || (mode === 'off' && id === 'hindsight') ? 0 : -1, onClick: () => onPick(id),
179
+ }, mode !== id && h(Stripes, { mode: id, live: true, className: 'pt-thumb pt-hover' }), h('span', null, t[id]))))
180
+ }
181
+
182
+ // On the Mac app, clicks near the top of the window drag it, even through a dialog. DSH makes an exception for
183
+ // anything placed directly in the page body, so the board goes there. The sandbox keeps the board page away from DSH's own page, login and storage.
184
+ function Board({ html, t, onClose }) {
185
+ const dialog = useRef(null)
186
+ useEffect(() => { dialog.current.showModal() }, [])
187
+ return createPortal(h('dialog', { ref: dialog, className: 'pt-board', 'aria-label': t.board, onClose, onClick: event => event.target === dialog.current && dialog.current.close() },
188
+ h('button', { type: 'button', onClick: () => dialog.current.close() }, t.close),
189
+ h('iframe', { title: t.board, sandbox: 'allow-scripts allow-downloads', srcDoc: html })), document.body)
190
+ }
191
+
192
+ function Dock(props) {
193
+ return useUi() ? h(Panel, props) : null
194
+ }
195
+
196
+ function Panel({ sessionId, session, input, inputActions, useProjection, useLanguage }) {
197
+ const usage = useProjection('tokenUsage')
198
+ const progress = useProjection('sessionStats')
199
+ const { running } = session
200
+ const language = useLanguage()
201
+ const root = useRef(null)
202
+ const latest = useRef(0)
203
+ const [texts, setTexts] = useState()
204
+ const [state, setState] = useState()
205
+ const [note, setNote] = useState('')
206
+ const [open, setOpen] = useState(true)
207
+ const [board, setBoard] = useState()
208
+
209
+ // Only the newest reply counts, so a slow one cannot undo a newer choice.
210
+ const sync = useCallback(async (body) => {
211
+ const id = ++latest.current
212
+ const next = await request(`/api/2cmd.session${body ? '' : `?session=${encodeURIComponent(sessionId)}`}`, body && {
213
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ session: sessionId, ...body }),
214
+ })
215
+ if (id === latest.current) setState(next)
216
+ }, [sessionId])
217
+
218
+ useEffect(() => { loadStrings().then(setTexts, console.warn) }, [])
219
+ useEffect(() => { sync().catch(console.warn) }, [sync, usage, progress, running, input.phase])
220
+ useEffect(() => {
221
+ const update = () => { sync().catch(console.warn) }
222
+ window.addEventListener('2cmd-settings', update)
223
+ return () => window.removeEventListener('2cmd-settings', update)
224
+ }, [sync])
225
+ // The choice is applied just after a turn starts, before any stats change.
226
+ const waiting = running && state?.pending != null
227
+ useEffect(() => {
228
+ if (!waiting) return undefined
229
+ const timer = setInterval(() => { sync().catch(console.warn) }, 1000)
230
+ return () => clearInterval(timer)
231
+ }, [waiting, sync])
232
+ useEffect(() => {
233
+ if (!note) return undefined
234
+ const timer = setTimeout(() => setNote(''), 3000)
235
+ return () => clearTimeout(timer)
236
+ }, [note])
237
+ // Other plugins can add to DSH's bottom row, so its width is measured.
238
+ const ready = Boolean(texts && state)
239
+ useEffect(() => {
240
+ const content = root.current?.closest('[data-conversation-content]')
241
+ const dock = content?.querySelector('[data-composer-dock]')
242
+ if (!dock) return undefined
243
+ const measure = () => {
244
+ const boxes = [...dock.querySelectorAll('button, [data-slot] > *')].map(e => e.getBoundingClientRect()).filter(box => box.width > 0)
245
+ const width = boxes.length ? Math.max(...boxes.map(b => b.right)) - Math.min(...boxes.map(b => b.left)) : 0
246
+ content.style.setProperty('--pt-dock', `${Math.ceil(width)}px`)
247
+ }
248
+ measure()
249
+ const observer = new MutationObserver(measure)
250
+ observer.observe(dock, { childList: true, subtree: true, characterData: true })
251
+ return () => {
252
+ observer.disconnect()
253
+ content.style.removeProperty('--pt-dock')
254
+ }
255
+ }, [ready])
256
+
257
+ if (!ready) return null
258
+ const pack = packFor(texts, language)
259
+ const t = texts[pack]
260
+ const { stats } = state
261
+ const cash = value => formatMoney(value, state.money, pack)
262
+ const mode = state.pending ?? state.mode
263
+ const live = state.pending === null
264
+ const act = body => sync(body).catch((error) => {
265
+ console.warn(error)
266
+ setNote(t.saveFail)
267
+ })
268
+ const cells = [
269
+ [t.cost, stats.cost ? `${stats.cost.partial ? '≥ ' : ''}${cash(stats.cost.total)}` : '–', stats.cost && !stats.cost.partial ? fill(t.costSub, { last: cash(stats.cost.last), avg: cash(stats.cost.avg) }) : ''],
270
+ [t.tokens, stats.tokens ? count(stats.tokens) : '–', fill(t.turnsN, { n: stats.turns })],
271
+ [t.cache, stats.cache ? `${stats.cache.last}%` : '–', stats.cache ? fill(t.cacheSub, { n: stats.cache.turns, v: stats.cache.avg }) : ''],
272
+ [t.time, stats.ms ? elapsed(stats.ms) : '–', stats.ms ? fill(t.avgTurn, { t: elapsed(stats.ms / stats.turns) }) : ''],
273
+ ]
274
+ const showBoard = () => request(`/api/2cmd.board?session=${encodeURIComponent(sessionId)}&lang=${pack}`).then(({ html }) => setBoard(html), (error) => {
275
+ console.warn(error)
276
+ setNote(t.boardFail)
277
+ })
278
+ // A button never sends: a command goes before the draft, any other text at the cursor.
279
+ const put = (text) => {
280
+ const rest = input.draft.trim().replace(/^\/\S+(?:(?<=2cmd-review)\s+(?:fix|commit|push)(?=\s|$))?\s*/, '') // replaces a command already there, as commandDraft() does
281
+ if (text.startsWith('/')) inputActions.setDraft(rest ? `${text} ${rest}` : `${text} `)
282
+ else if (!inputActions.insertText(text, inputActions.captureInsertion())) setNote(t.voiceInsert)
283
+ }
284
+ const labels = { fix: t.reviewFix, commit: t.reviewCommit, push: t.reviewPush, copy: t.copy, review: t.review, audit: t.audit }
285
+ const hints = { fix: t.tipFix, commit: t.tipCommit, push: t.tipPush, copy: t.tipCopy, review: t.tipReview, audit: t.tipAudit }
286
+ const copy = () => navigator.clipboard
287
+ .writeText(['## 2Cmd', '', '| | |', '|---|---|', ...[[t.model, stats.model || '–'], ...cells, [t.mode, state.mode], [t.session, sessionId]].map(([label, value, sub]) => `| ${label} | ${value}${sub ? ` · ${sub}` : ''} |`)].join('\n'))
288
+ .then(() => setNote(t.copied), error => setNote(String(error.message ?? error)))
289
+
290
+ return h('section', { ref: root, 'data-2cmd': '', 'aria-label': '2Cmd' },
291
+ h('div', { className: 'pt-bar' },
292
+ open && h(Button, { tip: mode === 'off' ? t.tipOn : t.tipOff, onClick: () => act({ mode: mode === 'off' ? state.resume : 'off' }) }, mode === 'off' ? t.turnOn : t.turnOff),
293
+ open
294
+ ? h(Switch, { mode, live, t, onPick: id => id !== mode && act({ mode: id }) })
295
+ : h(Button, { className: 'pt-chip', tip: t.tipLevel, onClick: () => setOpen(true) }, mode !== 'off' && h(Stripes, { mode, live }), h('span', null, mode === 'off' ? t.modeOff : t[mode])),
296
+ h('span', { className: 'pt-note', role: 'status', title: note || (live ? '' : t.pending) }, note || (live ? '' : t.pending)),
297
+ !open && h('span', { className: 'pt-note' }, `${t.cost} ${cells[0][1]} · ${t.cache} ${cells[2][1]} · ${t.time} ${cells[3][1]}`),
298
+ h('div', { className: 'pt-end' },
299
+ // Collapsed, like Claude's panel: every button but Copy, which needs the details to make sense.
300
+ state.buttons.map((button, i) => button.kind === 'none' || (!open && button.kind === 'copy') ? null : h(Button, {
301
+ key: i,
302
+ tip: button.kind === 'prompt' ? `${button.text.slice(0, 40)}${button.text.length > 40 ? '…' : ''}` : hints[button.kind],
303
+ onClick: button.kind === 'copy' ? copy : () => put(button.text),
304
+ }, button.kind === 'prompt' ? button.label : labels[button.kind])),
305
+ h(Button, { tip: t.tipBoard, onClick: showBoard }, t.board),
306
+ h(Button, { tip: open ? t.tipCollapse : t.tipExpand, 'aria-expanded': open, onClick: () => setOpen(!open) }, open ? t.collapse : t.expand))),
307
+ open && h('div', { className: 'pt-stats' }, cells.map(([label, value, sub]) => h('div', { key: label }, h('span', null, label), h('strong', null, value), h('small', { title: sub }, sub || ' ')))),
308
+ board && h(Board, { html: board, t, onClose: () => setBoard(undefined) }))
309
+ }
310
+
311
+ // ---- Voice input: DSH's own voice service recognizes the speech. This part is the microphone, waveform and sounds. ----
312
+
313
+ // Shared by the microphone and the waveform, which DSH draws in two places.
314
+ const recordings = new Map() // session id -> reads the loudness, 0 to 1
315
+ const listeners = new Set()
316
+ const setRecording = (id, level) => {
317
+ if (level) recordings.set(id, level)
318
+ else recordings.delete(id)
319
+ for (const listener of [...listeners]) listener()
320
+ }
321
+ const watchRecordings = (listener) => {
322
+ listeners.add(listener)
323
+ return () => listeners.delete(listener)
324
+ }
325
+
326
+ // Original two-note sounds, up to start and down to stop. Made here, so there are no audio files.
327
+ async function chime(context, notes) {
328
+ const now = context.currentTime
329
+ notes.forEach((frequency, i) => {
330
+ const at = now + i * 0.09
331
+ const note = context.createOscillator()
332
+ const volume = context.createGain()
333
+ note.type = 'sine'
334
+ note.frequency.value = frequency
335
+ volume.gain.setValueAtTime(0.0001, at)
336
+ volume.gain.exponentialRampToValueAtTime(0.12, at + 0.015)
337
+ volume.gain.exponentialRampToValueAtTime(0.0001, at + 0.16)
338
+ note.connect(volume).connect(context.destination)
339
+ note.start(at)
340
+ note.stop(at + 0.17)
341
+ })
342
+ await new Promise(done => setTimeout(done, 270))
343
+ }
344
+
345
+ /** 16 kHz mono PCM16, the only format DSH accepts. */
346
+ function wave(samples) {
347
+ const view = new DataView(new ArrayBuffer(44 + samples.length * 2))
348
+ const text = (at, value) => [...value].forEach((c, i) => view.setUint8(at + i, c.charCodeAt(0)))
349
+ text(0, 'RIFF')
350
+ view.setUint32(4, 36 + samples.length * 2, true)
351
+ text(8, 'WAVEfmt ')
352
+ view.setUint32(16, 16, true)
353
+ view.setUint16(20, 1, true)
354
+ view.setUint16(22, 1, true)
355
+ view.setUint32(24, 16000, true)
356
+ view.setUint32(28, 32000, true)
357
+ view.setUint16(32, 2, true)
358
+ view.setUint16(34, 16, true)
359
+ text(36, 'data')
360
+ view.setUint32(40, samples.length * 2, true)
361
+ samples.forEach((sample, i) => view.setInt16(44 + i * 2, Math.max(-1, Math.min(1, sample)) * 32767, true))
362
+ return new Uint8Array(view.buffer)
363
+ }
364
+
365
+ function base64(bytes) {
366
+ let text = ''
367
+ for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192))
368
+ return btoa(text)
369
+ }
370
+
371
+ async function startCapture(signal, onLost) {
372
+ if (!navigator.mediaDevices || typeof MediaRecorder === 'undefined') throw new Error('voiceNoMic')
373
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } }).catch((error) => {
374
+ throw new Error(error.name === 'NotAllowedError' ? 'voiceMicDenied' : 'voiceNoMic')
375
+ })
376
+ let context
377
+ let recorder
378
+ const close = () => {
379
+ if (recorder && recorder.state !== 'inactive') recorder.stop()
380
+ for (const track of stream.getTracks()) track.stop()
381
+ if (context && context.state !== 'closed') void context.close().catch(() => {})
382
+ }
383
+ try {
384
+ signal.throwIfAborted()
385
+ context = new AudioContext()
386
+ await context.resume()
387
+ const analyser = context.createAnalyser()
388
+ analyser.fftSize = 512
389
+ context.createMediaStreamSource(stream).connect(analyser)
390
+ // Recording starts after the sound, so the sound is not recorded.
391
+ await chime(context, [660, 880])
392
+ signal.throwIfAborted()
393
+ const chunks = []
394
+ recorder = new MediaRecorder(stream)
395
+ recorder.ondataavailable = event => chunks.push(event.data)
396
+ recorder.start()
397
+ for (const track of stream.getTracks()) track.onended = onLost
398
+ const buffer = new Float32Array(analyser.fftSize)
399
+ return {
400
+ close,
401
+ level() {
402
+ analyser.getFloatTimeDomainData(buffer)
403
+ const power = buffer.reduce((sum, x) => sum + x * x, 0) / buffer.length
404
+ // -50 to -20 dB maps to 0 to 1.
405
+ return power > 0 ? Math.max(0, Math.min(1, (10 * Math.log10(power) + 50) / 30)) : 0
406
+ },
407
+ async stop(maxSeconds) {
408
+ try {
409
+ await new Promise((done, fail) => {
410
+ recorder.onstop = done
411
+ recorder.onerror = () => fail(new Error('voiceFailed'))
412
+ recorder.stop()
413
+ })
414
+ for (const track of stream.getTracks()) {
415
+ track.onended = null
416
+ track.stop()
417
+ }
418
+ void chime(context, [880, 660])
419
+ const decoded = await context.decodeAudioData(await new Blob(chunks, { type: recorder.mimeType }).arrayBuffer())
420
+ const offline = new OfflineAudioContext(1, Math.max(1, Math.floor(Math.min(decoded.duration, maxSeconds) * 16000)), 16000)
421
+ const source = offline.createBufferSource()
422
+ source.buffer = decoded
423
+ source.connect(offline.destination)
424
+ source.start()
425
+ return wave((await offline.startRendering()).getChannelData(0))
426
+ } finally {
427
+ // Leaves time for the stop sound.
428
+ setTimeout(close, 400)
429
+ }
430
+ },
431
+ }
432
+ } catch (error) {
433
+ close()
434
+ throw error
435
+ }
436
+ }
437
+
438
+ const unwrap = (result) => {
439
+ if (!result.ok) throw result.error
440
+ return result.value
441
+ }
442
+ const READY = ['ready', 'standby', 'waking']
443
+ // Errors from the helper app arrive inside DSH's own error message.
444
+ const HELPER_ERRORS = { permission: 'voiceSpeechDenied', language: 'voiceLanguage', dictation: 'voiceDictation', timeout: 'voiceTimeout' }
445
+ function voiceError(error) {
446
+ if (String(error?.message).startsWith('voice')) return error.message
447
+ const code = `${error?.message} ${JSON.stringify(error?.details ?? '')}`.match(/2cmd-voice:(\w+)/)?.[1]
448
+ return HELPER_ERRORS[code] ?? 'voiceFailed'
449
+ }
450
+
451
+ function Microphone({ sessionId, inputActions, locked, useLanguage, speech, openVoice }) {
452
+ const language = useLanguage()
453
+ const [texts, setTexts] = useState()
454
+ const [phase, setPhase] = useState('idle') // idle, connecting, recording, finishing
455
+ const [notice, setNotice] = useState('')
456
+ const [pending, setPending] = useState('') // recognized text that could not be put in the message box yet
457
+ const current = useRef()
458
+ const actions = useRef(inputActions)
459
+ actions.current = inputActions
460
+
461
+ const end = useCallback((run) => {
462
+ if (current.current !== run) return false
463
+ current.current = undefined
464
+ clearTimeout(run.timer)
465
+ run.abort.abort()
466
+ run.capture?.close()
467
+ setRecording(sessionId)
468
+ setPhase('idle')
469
+ return true
470
+ }, [sessionId])
471
+ const fail = useCallback((run, error) => {
472
+ if (!end(run)) return
473
+ console.warn(error)
474
+ setNotice(voiceError(error))
475
+ }, [end])
476
+
477
+ useEffect(() => { loadStrings().then(setTexts, console.warn) }, [])
478
+ useEffect(() => {
479
+ const cancel = () => { if (current.current) end(current.current) }
480
+ const onKey = (event) => {
481
+ if (event.key !== 'Escape' || !current.current) return
482
+ event.preventDefault()
483
+ cancel()
484
+ }
485
+ const onHide = () => { if (document.hidden && !current.current?.finishing) cancel() }
486
+ document.addEventListener('keydown', onKey)
487
+ document.addEventListener('visibilitychange', onHide)
488
+ return () => {
489
+ document.removeEventListener('keydown', onKey)
490
+ document.removeEventListener('visibilitychange', onHide)
491
+ cancel()
492
+ }
493
+ }, [end])
494
+ useEffect(() => {
495
+ if (!notice || pending) return undefined
496
+ const timer = setTimeout(() => setNotice(''), 5000)
497
+ return () => clearTimeout(timer)
498
+ }, [notice, pending])
499
+
500
+ const insert = (text, span) => {
501
+ // If the message changed while listening, the text goes where the cursor is now.
502
+ const done = actions.current.insertText(text, span) || actions.current.insertText(text, actions.current.captureInsertion())
503
+ setPending(done ? '' : text)
504
+ setNotice(done ? '' : 'voiceInsert')
505
+ }
506
+
507
+ const finish = async (run) => {
508
+ if (current.current !== run || run.finishing || !run.capture) return
509
+ run.finishing = true
510
+ clearTimeout(run.timer)
511
+ setRecording(sessionId)
512
+ setPhase('finishing')
513
+ try {
514
+ const audio = await run.capture.stop(run.catalog.maxDurationSeconds)
515
+ if (current.current !== run) return
516
+ if (audio.byteLength > run.catalog.maxAudioBytes) throw new Error('voiceTooLong')
517
+ const { text } = unwrap(await speech.transcribe({ audioBase64: base64(audio), ...run.catalog.selection }, run.abort.signal))
518
+ if (current.current !== run) return
519
+ // Not end(): that would cut the stop sound short. capture.stop() closes the microphone.
520
+ current.current = undefined
521
+ setPhase('idle')
522
+ if (text) insert(text, run.span)
523
+ else setNotice('voiceEmpty')
524
+ } catch (error) {
525
+ fail(run, error)
526
+ }
527
+ }
528
+
529
+ const start = async () => {
530
+ const run = { abort: new AbortController(), span: actions.current.captureInsertion() }
531
+ current.current = run
532
+ setNotice('')
533
+ setPhase('connecting')
534
+ try {
535
+ run.catalog = unwrap(await speech.catalog())
536
+ if (current.current !== run) return
537
+ const provider = run.catalog.providers.find(({ id }) => id === run.catalog.selection.providerId)
538
+ if (!READY.includes(provider?.preparation.phase)) {
539
+ end(run)
540
+ setNotice(['checking', 'downloading', 'loading'].includes(provider?.preparation.phase) ? 'voicePreparing' : 'voiceSetup')
541
+ if (!['checking', 'downloading', 'loading'].includes(provider?.preparation.phase)) openVoice()
542
+ return
543
+ }
544
+ const capture = await startCapture(run.abort.signal, () => fail(run, new Error('voiceMicLost')))
545
+ if (current.current !== run) {
546
+ capture.close()
547
+ return
548
+ }
549
+ run.capture = capture
550
+ run.readyAt = performance.now()
551
+ run.timer = setTimeout(() => { void finish(run) }, run.catalog.maxDurationSeconds * 1000)
552
+ setRecording(sessionId, capture.level)
553
+ setPhase('recording')
554
+ } catch (error) {
555
+ fail(run, error)
556
+ }
557
+ }
558
+
559
+ if (!texts) return null
560
+ const t = texts[packFor(texts, language)]
561
+ const busy = phase === 'connecting' || phase === 'finishing'
562
+ const label = t[{ idle: pending ? 'voiceInsert' : 'voiceStart', connecting: 'voiceConnecting', recording: 'voiceStop', finishing: 'voiceWorking' }[phase]]
563
+ const onClick = () => {
564
+ if (pending) insert(pending, actions.current.captureInsertion())
565
+ else if (phase === 'idle') void start()
566
+ // The second click of a double click must not stop the recording it just started.
567
+ else if (phase === 'recording' && performance.now() - current.current?.readyAt > 300) void finish(current.current)
568
+ }
569
+ return h('span', { className: 'pt-voice', 'data-pt-voice': phase },
570
+ notice && h('span', { className: 'pt-voice-note', role: 'status' }, t[notice]),
571
+ h('button', { type: 'button', title: label, 'aria-label': label, 'aria-pressed': phase === 'recording', 'aria-busy': busy, disabled: locked && phase === 'idle', onMouseDown: event => event.preventDefault(), onClick },
572
+ h('svg', { width: 18, height: 18, viewBox: '0 0 16 16', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, strokeLinecap: 'round', 'aria-hidden': true, className: busy ? 'pt-spin' : undefined },
573
+ busy
574
+ ? [h('circle', { key: 'a', cx: 8, cy: 8, r: 5.5, opacity: 0.3 }), h('path', { key: 'b', d: 'M8 2.5A5.5 5.5 0 0 1 13.5 8' })]
575
+ : [h('rect', { key: 'a', x: 5.5, y: 1.75, width: 5, height: 8.5, rx: 2.5 }), h('path', { key: 'b', d: 'M3.25 7.5a4.75 4.75 0 0 0 9.5 0M8 12.25v2.25' })])))
576
+ }
577
+
578
+ // Dots drift left. Each new one is as tall as the voice is loud, so silence is a dotted line.
579
+ function Waveform({ sessionId, useLanguage }) {
580
+ const language = useLanguage()
581
+ const level = useSyncExternalStore(watchRecordings, () => recordings.get(sessionId))
582
+ const canvas = useRef(null)
583
+ const [texts, setTexts] = useState()
584
+ useEffect(() => { loadStrings().then(setTexts, console.warn) }, [])
585
+ useEffect(() => {
586
+ const element = canvas.current
587
+ if (!level || !element) return undefined
588
+ const [width, height, step, dot] = [64, 16, 4, 2]
589
+ const still = matchMedia('(prefers-reduced-motion:reduce)').matches
590
+ const ratio = window.devicePixelRatio || 1
591
+ element.width = width * ratio
592
+ element.height = height * ratio
593
+ const context = element.getContext('2d')
594
+ const dots = Array(width / step + 1).fill(0)
595
+ let [offset, smooth, last, frame] = [0, 0, performance.now(), 0]
596
+ const draw = (now) => {
597
+ const elapsed = Math.min(now - last, 100) / 1000
598
+ last = now
599
+ smooth += (level() - smooth) * Math.min(1, elapsed * 12)
600
+ if (still) dots.fill(smooth)
601
+ else offset += elapsed * 40
602
+ while (offset >= step) {
603
+ offset -= step
604
+ dots.shift()
605
+ dots.push(smooth)
606
+ }
607
+ context.setTransform(ratio, 0, 0, ratio, 0, 0)
608
+ context.clearRect(0, 0, width, height)
609
+ context.fillStyle = getComputedStyle(element).color
610
+ dots.forEach((value, i) => {
611
+ const size = dot + value * (height - dot)
612
+ context.beginPath()
613
+ context.roundRect(i * step - offset, (height - size) / 2, dot, size, dot / 2)
614
+ context.fill()
615
+ })
616
+ frame = requestAnimationFrame(draw)
617
+ }
618
+ frame = requestAnimationFrame(draw)
619
+ return () => cancelAnimationFrame(frame)
620
+ }, [level, texts])
621
+ if (!level || !texts) return null
622
+ return h('canvas', { ref: canvas, className: 'pt-wave', role: 'status', 'aria-label': texts[packFor(texts, language)].voiceListening })
623
+ }
624
+
625
+ function VoiceSettings({ t, speechRef, openVoice }) {
626
+ const speech = useSyncExternalStore(speechRef.subscribe, speechRef.get)
627
+ const [catalog, setCatalog] = useState()
628
+ const [open, setOpen] = useState(false)
629
+ const [note, setNote] = useState('')
630
+ useEffect(() => {
631
+ let live = true
632
+ setCatalog(undefined)
633
+ speech?.catalog().then(unwrap).then(next => live && setCatalog(next)).catch(console.warn)
634
+ return () => { live = false }
635
+ }, [speech])
636
+ const name = provider => (provider.id === '2cmd-macos' ? t.voiceSystem : `DSH · ${provider.name}`)
637
+ const selected = catalog?.providers.find(({ id }) => id === catalog.selection.providerId)
638
+ const choose = async (providerId) => {
639
+ setOpen(false)
640
+ setNote('')
641
+ try {
642
+ // Not every recognizer knows every language, so switching goes back to automatic.
643
+ unwrap(await speech.configure({ providerId, language: 'auto' }))
644
+ setCatalog(unwrap(await speech.catalog()))
645
+ } catch (error) {
646
+ console.warn(error)
647
+ setNote(t.settingsFailed)
648
+ }
649
+ }
650
+ return h('div', { className: 'pt-row' },
651
+ h('div', null, t.voiceTitle, h('small', null, speech ? t.voiceNote : t.voiceOff), h('small', { role: 'status' }, note)),
652
+ catalog
653
+ ? h(Menu, {
654
+ open, align: 'end', portal: true, selectedId: catalog.selection.providerId,
655
+ items: catalog.providers.map(provider => ({ id: provider.id, label: name(provider) })),
656
+ onClose: () => setOpen(false),
657
+ onSelect: id => void choose(id),
658
+ anchor: h('button', { type: 'button', className: 'pt-select', 'aria-haspopup': 'menu', 'aria-expanded': open, onClick: () => setOpen(!open) }, selected ? name(selected) : '–', h(IconChevronDownOutlineRegular)),
659
+ })
660
+ : !speech && h('button', { type: 'button', className: 'pt-select', onClick: openVoice }, t.voiceOpen))
661
+ }
662
+
663
+ // The three panel buttons before Board and Less. Copy runs here; the rest only fill the message box.
664
+ const KINDS = ['fix', 'commit', 'push', 'copy', 'review', 'audit', 'prompt', 'none']
665
+ function ButtonRow({ t, index, button, busy, save }) {
666
+ const [open, setOpen] = useState(false)
667
+ const [label, setLabel] = useState(button.label ?? '')
668
+ const [text, setText] = useState(button.text ?? '')
669
+ const [kind, setKind] = useState(button.kind)
670
+ const [note, setNote] = useState('')
671
+ useEffect(() => {
672
+ setKind(button.kind)
673
+ setLabel(button.label ?? '')
674
+ setText(button.text ?? '')
675
+ }, [button.kind, button.label, button.text])
676
+ const names = { fix: t.btnFix, commit: t.btnCommit, push: t.btnPush, copy: t.btnCopy, review: t.btnReview, audit: t.btnAudit, prompt: t.btnCustom, none: t.btnNone }
677
+ const hints = { fix: t.tipFix, commit: t.tipCommit, push: t.tipPush, copy: t.tipCopy, review: t.tipReview, audit: t.tipAudit, prompt: t.btnText, none: '' }
678
+ const valid = label.trim() && [...label.trim()].length <= 8 && text.trim()
679
+ const pick = (next) => {
680
+ setOpen(false)
681
+ setKind(next)
682
+ setNote('')
683
+ if (next !== 'prompt') void save(index, { kind: next })
684
+ }
685
+ return h('div', { className: 'pt-row pt-button-row' },
686
+ h('div', null, fill(t.btnSlot, { n: index + 1 }), h('small', null, hints[kind]),
687
+ kind === 'prompt' && h('div', { className: 'pt-custom' },
688
+ h('input', { value: label, maxLength: 8, placeholder: t.btnName, 'aria-label': t.btnName, onChange: event => setLabel(event.target.value) }),
689
+ h('textarea', { value: text, rows: 2, maxLength: 4000, placeholder: t.btnText, 'aria-label': t.btnText, onChange: event => setText(event.target.value) }),
690
+ h('div', null,
691
+ h('button', { type: 'button', className: 'pt-select', disabled: busy, onClick: () => (valid ? void save(index, { kind, label: label.trim(), text: text.trim() }) : setNote(t.btnInvalid)) }, t.btnSave),
692
+ h('small', { role: 'status' }, note)))),
693
+ h(Menu, {
694
+ open, align: 'end', portal: true, selectedId: kind,
695
+ items: KINDS.map(id => ({ id, label: names[id] })),
696
+ onClose: () => setOpen(false),
697
+ onSelect: pick,
698
+ anchor: h('button', { type: 'button', className: 'pt-select', 'aria-label': `${fill(t.btnSlot, { n: index + 1 })}: ${names[kind]}`, 'aria-haspopup': 'menu', 'aria-expanded': open, disabled: busy, onClick: () => setOpen(!open) }, names[kind], h(IconChevronDownOutlineRegular)),
699
+ }))
700
+ }
701
+
702
+ // The "2Cmd on" switch: off draws no panel, and DSH's composer layout comes back with it (the layout needs the panel).
703
+ // Kept in this window's storage, as in codex/page.js.
704
+ const UI_KEY = 'twocmd-ui'
705
+ const uiListeners = new Set()
706
+ const readUi = () => { try { return localStorage.getItem(UI_KEY) !== 'off' } catch { return true } }
707
+ const subscribeUi = (listener) => { uiListeners.add(listener); return () => uiListeners.delete(listener) }
708
+ const setUi = (on) => {
709
+ try { localStorage.setItem(UI_KEY, on ? 'on' : 'off') } catch {}
710
+ for (const listener of [...uiListeners]) listener()
711
+ }
712
+ const useUi = () => useSyncExternalStore(subscribeUi, readUi)
713
+ const UI_TEXT = {
714
+ en: ['2Cmd on', 'Off restores the original message box height.'],
715
+ 'zh-Hans': ['2Cmd 启动', '关闭后,恢复原来的输入框高度。'],
716
+ 'zh-Hant': ['2Cmd 啟動', '關閉後,恢復原本的輸入框高度。'],
717
+ ja: ['2Cmd を有効にする', 'オフにすると、元の入力欄の高さに戻ります。'],
718
+ ko: ['2Cmd 켜기', '끄면 원래 입력창 높이로 돌아갑니다.'],
719
+ es: ['2Cmd activado', 'Desactivado, el cuadro de mensaje vuelve a su altura original.'],
720
+ fr: ['2Cmd activé', 'Désactivé, la zone de message reprend sa hauteur d’origine.'],
721
+ de: ['2Cmd an', 'Aus stellt die ursprüngliche Höhe des Eingabefelds wieder her.'],
722
+ pt: ['2Cmd ligado', 'Desligado, a caixa de mensagem volta à altura original.'],
723
+ ru: ['2Cmd включён', 'Выключено: поле ввода возвращается к исходной высоте.'],
724
+ vi: ['Bật 2Cmd', 'Tắt sẽ trả ô nhập tin nhắn về chiều cao ban đầu.'],
725
+ }
726
+
727
+ // Check for updates, only when asked (dsh/index.js reads 2cmd.dev). A newer version, or no answer, leads to 2Cmd's
728
+ // site, opened the way DSH opens a link in a message; the install command there is run again.
729
+ function UpdateRow({ t, pack }) {
730
+ const [state, setState] = useState() // undefined, 'checking', or the answer
731
+ const check = () => {
732
+ setState('checking')
733
+ request(`/api/2cmd.update?lang=${encodeURIComponent(pack)}`).then(setState, () => setState({}))
734
+ }
735
+ const done = state && state !== 'checking'
736
+ const latest = done && state.latest && !state.newer
737
+ const say = text => fill(text, { v: state.latest, c: state.current })
738
+ const note = state === 'checking' ? t.siteChecking : !done ? t.siteNote : latest ? say(t.siteLatest) : state.latest ? say(t.siteNewer) : t.siteFailed
739
+ const open = done && !latest
740
+ return h('div', { className: 'pt-row' },
741
+ h('div', null, t.siteTitle, h('small', { role: 'status' }, note)),
742
+ h('button', { type: 'button', className: 'pt-select', disabled: state === 'checking',
743
+ onClick: open ? () => window.open(state.url ?? 'https://2cmd.dev/', '_blank', 'noopener,noreferrer') : check }, open ? t.siteOpen : t.siteCheck))
744
+ }
745
+
746
+ function Settings({ useLanguage, speechRef, openVoice }) {
747
+ const language = useLanguage()
748
+ const [texts, setTexts] = useState()
749
+ const [data, setData] = useState()
750
+ const [open, setOpen] = useState(false)
751
+ const [langOpen, setLangOpen] = useState(false)
752
+ const [busy, setBusy] = useState(false)
753
+ const [note, setNote] = useState('')
754
+ const ui = useUi()
755
+ useEffect(() => {
756
+ loadStrings().then(setTexts, console.warn)
757
+ request('/api/2cmd.settings').then(setData, console.warn)
758
+ }, [])
759
+ if (!texts || !data) return null
760
+ const pack = packFor(texts, language)
761
+ const t = texts[pack]
762
+ const names = new Intl.DisplayNames([pack], { type: 'currency' })
763
+ const label = code => `${names.of(code)} (${code})`
764
+ const date = ms => new Intl.DateTimeFormat(pack, { dateStyle: 'medium' }).format(ms)
765
+ // Each language in its own words, so a person who cannot read the current one still finds theirs.
766
+ const languageLabel = id => (id === 'auto' ? t.languageAuto : new Intl.DisplayNames([id], { type: 'language' }).of(id))
767
+ const save = async (body) => {
768
+ setBusy(true)
769
+ setNote('')
770
+ try {
771
+ const next = await request('/api/2cmd.settings', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
772
+ setData(next)
773
+ chosen = next.language ?? 'auto' // every 2Cmd text redraws in it, through the event below
774
+ if (body.refresh) setNote(next.failed ? t.updateFailed : t.updateDone)
775
+ if (body.buttons) setNote(t.btnApplied)
776
+ window.dispatchEvent(new Event('2cmd-settings'))
777
+ } catch (error) {
778
+ console.warn(error)
779
+ setNote(t.settingsFailed)
780
+ }
781
+ setBusy(false)
782
+ }
783
+ const [uiTitle, uiNote] = UI_TEXT[pack] ?? UI_TEXT.en
784
+ return h('div', null,
785
+ // The whole row is the switch's label, so a click anywhere on it turns 2Cmd on or off.
786
+ h('label', { className: 'pt-row pt-toggle-row' },
787
+ h('div', null, uiTitle, h('small', null, uiNote)),
788
+ h('input', { type: 'checkbox', role: 'switch', className: 'pt-toggle', checked: ui, onChange: event => setUi(event.target.checked) })),
789
+ h(UpdateRow, { t, pack }),
790
+ h('div', { className: 'pt-row' },
791
+ h('div', null, t.language, h('small', null, t.languageNote)),
792
+ h(Menu, {
793
+ open: langOpen, align: 'end', portal: true, selectedId: data.language,
794
+ items: data.languages.map(id => ({ id, label: languageLabel(id) })),
795
+ onClose: () => setLangOpen(false),
796
+ onSelect: (language) => {
797
+ setLangOpen(false)
798
+ void save({ language })
799
+ },
800
+ anchor: h('button', { type: 'button', className: 'pt-select', 'aria-label': `${t.language}: ${languageLabel(data.language)}`, 'aria-haspopup': 'menu', 'aria-expanded': langOpen, disabled: busy, onClick: () => setLangOpen(!langOpen) }, languageLabel(data.language), h(IconChevronDownOutlineRegular)),
801
+ })),
802
+ h('div', { className: 'pt-row' },
803
+ h('div', null, t.currency,
804
+ h('small', null, data.shown !== data.currency ? t.noRate : data.currency === 'USD' ? t.currencyNote : fill(t.rateDate, { d: date(data.ratesUpdated) })),
805
+ // The free rates require this link.
806
+ data.currency !== 'USD' && h('small', null, h('a', { href: 'https://www.exchangerate-api.com', target: '_blank', rel: 'noreferrer' }, 'Rates By Exchange Rate API'))),
807
+ h(Menu, {
808
+ open, align: 'end', portal: true, selectedId: data.currency,
809
+ items: data.currencies.map(id => ({ id, label: label(id) })),
810
+ onClose: () => setOpen(false),
811
+ onSelect: (currency) => {
812
+ setOpen(false)
813
+ void save({ currency })
814
+ },
815
+ anchor: h('button', { type: 'button', className: 'pt-select', 'aria-label': `${t.currency}: ${label(data.currency)}`, 'aria-haspopup': 'menu', 'aria-expanded': open, disabled: busy, onClick: () => setOpen(!open) }, label(data.currency), h(IconChevronDownOutlineRegular)),
816
+ })),
817
+ h('div', { className: 'pt-row' },
818
+ h('div', null, t.priceTitle, h('small', null, fill(t.priceNote, { n: data.models, d: date(data.pricesUpdated) })), h('small', { role: 'status' }, note === t.btnApplied ? '' : note)),
819
+ h('button', { type: 'button', className: 'pt-select', disabled: busy, onClick: () => void save({ refresh: true }) }, busy ? t.updating : t.updateNow)),
820
+ h(VoiceSettings, { t, speechRef, openVoice }),
821
+ h('div', { className: 'pt-row' }, h('div', null, t.btnTitle, h('small', null, t.btnNote), h('small', { role: 'status' }, data.buttons && note === t.btnApplied ? note : ''))),
822
+ data.buttons.map((button, index) => h(ButtonRow, {
823
+ key: index, t, index, button, busy,
824
+ save: (i, next) => save({ buttons: data.buttons.map((old, j) => (j === i ? next : old)) }),
825
+ })))
826
+ }
827
+
828
+ const PANEL = '2cmd'
829
+ // The 2Cmd icon, same artwork as assets/icon.svg and hooks/band/logo.ts: change them together. The sidebar wants the
830
+ // svg itself as the row's icon, not a wrapper.
831
+ const LOGO_PATHS = '<defs><linearGradient id="pt-arrow" gradientUnits="userSpaceOnUse" x1="30" y1="20" x2="120" y2="120"><stop offset="0" stop-color="#FFB020"/><stop offset=".5" stop-color="#FF4F5E"/><stop offset="1" stop-color="#9B3DF0"/></linearGradient></defs><rect x="1" y="1" width="138" height="138" rx="31" fill="#15161A" stroke="#fff" stroke-opacity=".14" stroke-width="2"/><g fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-width="18" transform="translate(70 70) scale(.82) translate(-70 -70)"><path stroke="#fff" d="M26 52a21 21 0 0 1 42 0c0 11-6 19-14 26L26 104h40"/><path stroke="url(#pt-arrow)" d="M90 46l24 24-24 24"/></g>'
832
+ const Logo = ({ size }) => h('svg', { viewBox: '0 0 140 140', width: size, height: size, 'aria-hidden': true, dangerouslySetInnerHTML: { __html: LOGO_PATHS } })
833
+
834
+ function apply(ctx) {
835
+ ctx.effect(() => {
836
+ const style = document.createElement('style')
837
+ style.textContent = CSS
838
+ document.head.append(style)
839
+ return () => style.remove()
840
+ }, '2cmd: styles')
841
+ const subscribe = listener => ctx.locale.subscribe(listener)
842
+ const useLanguage = () => useSyncExternalStore(subscribe, () => ctx.locale.getLocale().active)
843
+ const openVoice = () => ctx.get('pluginNavigation')?.openBundle('@deepseek-ai/dsh-experimental-voice-input-bundle')
844
+ const speechListeners = new Set()
845
+ let speechNow
846
+ const speechRef = {
847
+ get: () => speechNow,
848
+ set: (next) => {
849
+ speechNow = next
850
+ for (const listener of [...speechListeners]) listener()
851
+ },
852
+ subscribe: (listener) => {
853
+ speechListeners.add(listener)
854
+ return () => speechListeners.delete(listener)
855
+ },
856
+ }
857
+ ctx.slots.inject('conversation.input.dock', () => ctx.slots.register({ name: 'conversation.input.dock', id: '2cmd', order: 100 }, props => h(Dock, { ...props, useLanguage })))
858
+ // A page of its own, opened from the sidebar row under Automations (order 10; Plugins is 0), like DSH's own panels.
859
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: PANEL }, () => h('div', { className: 'pt-page' },
860
+ h('h1', null, h(Logo, { size: 24 }), '2Cmd'),
861
+ h(Settings, { useLanguage, speechRef, openVoice }))))
862
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id: PANEL, order: 20, label: () => '2Cmd' }, Logo))
863
+
864
+ // Only while DSH's voice plugin is on. The lower priority number shows this microphone instead of DSH's; its setup page stays.
865
+ ctx.inject(['remote', 'remote.speech'], (scope) => {
866
+ const { speech } = scope.remote
867
+ scope.effect(() => {
868
+ speechRef.set(speech)
869
+ return () => speechRef.set(undefined)
870
+ }, '2cmd: voice')
871
+ scope.slots.inject('conversation.input.activity', () => scope.slots.register({ name: 'conversation.input.activity', priority: -1 }, props => h(Microphone, { ...props, useLanguage, speech, openVoice })))
872
+ scope.slots.inject('conversation.input.right', () => scope.slots.register({ name: 'conversation.input.right', id: '2cmd-wave', order: 100 }, props => h(Waveform, { ...props, useLanguage })))
873
+ })
874
+ }
875
+
876
+ return { apply, inject: ['slots', 'locale'] }
877
+ } })