dsh-coding-enhanced 0.8.5 → 0.9.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.2
4
+
5
+ - Three-way **Review channel** switch in the Review tools popover: **Web** (standalone
6
+ review server only), **Both** (default), or **DSH** (sidebar tab only).
7
+ - Host `reviewChannel` setting: `builtin` keeps the outbound WSS stopped and
8
+ skips snapshot publishing; switching modes starts or stops the bridge live.
9
+ - Client gates the review tab type and the `sidebar.right.pane.tab` body:
10
+ Web mode removes the DSH tab and closes open review tabs; DSH/Both register
11
+ them again without a reload.
12
+ - Web review UI: AI explanation rows anchored to their code lines, soft-wrapped
13
+ diffs with page scrolling, an auto-growing AI message box, a collapsible
14
+ app sidebar, a topbar back button, and light-theme syntax highlighting.
15
+
16
+ ## 0.9.1
17
+
18
+ - Web review decisions: per-file Approve/Reject and Finish in the browser;
19
+ decision reaches the plugin, applies via `decideReview`, and the finished
20
+ snapshot returns to the Web UI.
21
+ - Standalone web UI moves to a pure white theme.
22
+ - Forward `review.result.error` so failed decisions surface in the browser.
23
+
24
+ ## 0.9.0
25
+
26
+ - Standalone web review server (`web/`): passkey login, one-time pairing,
27
+ device/browser WSS, review snapshot cache, React UI.
28
+ - Plugin Web review settings: URL + pairing code, outbound WSS, review.snapshot
29
+ sync, online/offline status.
30
+ - File-target shell gate (`lib/detect-writes.js`): installs, builds and tests
31
+ pass; protected workspace writes block; artifacts pass; turn/end audit stays
32
+ the backstop.
33
+ - Remove the 120s `review_bash` timeout; maxBuffer stays at 8 MiB.
34
+
3
35
  ## 0.8.5
4
36
 
5
37
  - Native `bash` is denied while Pre-review is on; shell commands go through
package/README.md CHANGED
@@ -20,7 +20,7 @@ Queue every AI edit · rewind whole turns · hand review to a non-blocking waite
20
20
  - **Pre-write change gate** — native `write` / `edit` / `apply_patch` are refused while Pre-review is on; the agent queues `review_write` / `review_patch`; nothing lands until you Finish.
21
21
  - **Workspace time machine** — per-turn shadow-git snapshots, multi-turn withdraw, a pre-withdraw backup, and a gap warning when a rewind crosses turns without snapshots.
22
22
  - **Non-blocking review handoff** — one persistent review waiter subagent holds the wait; the main agent can keep chatting or end the turn; the waiter wakes it with the per-file results.
23
- - **Remote + cross-AI (next)** — passkey-paired always-on web review, line-level AI comments (B), and an adversarial AI cross-review API.
23
+ - **Remote + cross-AI (next)** — username+key web review, line-level AI comments (B), and an adversarial AI cross-review API.
24
24
 
25
25
  > **What this is not.** Not an AI PR reviewer (CodeRabbit / Qodo / Copilot), not a hosted SaaS, and not a claim to be first. The diff UI is table stakes; the gate, the time machine, and the handoff are the product. See the [prior-art survey](docs/prior-art.md) for the direct comparison with [`dsh-diff-approval`](https://github.com/9087/dsh-diff-approval).
26
26
 
@@ -29,7 +29,7 @@ Queue every AI edit · rewind whole turns · hand review to a non-blocking waite
29
29
  | 🛡️ | **Change gate** (the `AI Change Review` switch) | The agent queues every edit with `review_write` / `review_patch`; they accumulate in one review tab; nothing lands until you approve, reject, edit or Finish. |
30
30
  | ↩️ | **Workspace time machine** (the `Turn Withdraw` switch) | Restore the workspace to before a turn and cancel that round in the model's context; multi-turn rewind, backup and gap warnings. |
31
31
  | ⏳ | **Review handoff** | One persistent review waiter subagent holds the wait; the main agent keeps working and is woken when you Finish. |
32
- | 🌐 | **Remote + cross-AI** | Planned: passkey-paired web review, line-level AI comments, adversarial external-AI cross-review. |
32
+ | 🌐 | **Remote + cross-AI** | Planned: username+key web review, line-level AI comments, adversarial external-AI cross-review. |
33
33
 
34
34
  All in one bundle — install once, use the gate and the time machine independently.
35
35
 
@@ -290,6 +290,11 @@ This is a convenience switch, separate from **Settings → Coding Enhanced → A
290
290
  Change Review** (which enables the review tab and withdraw surfaces). More
291
291
  review switches will be added to the same popover.
292
292
 
293
+ A separate **Web / Both / DSH** switch sits next to the shield and selects where
294
+ reviews are decided. **Web** uses only the standalone review server; **DSH**
295
+ uses only the sidebar review tab and keeps the outbound WSS stopped; **Both**
296
+ mirrors to both. Switching the channel is immediate and survives a restart.
297
+
293
298
  ### 4. Use the change gate
294
299
 
295
300
  Ask the agent to change files → it queues them with `review_write` / `review_patch` → the **Code review** tab opens → decide per file
@@ -310,6 +315,46 @@ confirmation lists those turns.
310
315
 
311
316
  ---
312
317
 
318
+ ## 🌐 Standalone web review
319
+
320
+ The standalone Web review app is **not part of the plugin tarball**. The npm
321
+ package ships only `lib/`, `docs/`, `README.md`, `CHANGELOG.md` and the bundle
322
+ patch; the React review UI and its Node server live in [`web/`](web/) in this
323
+ repository. Install the plugin normally if you only want the DSH sidebar review.
324
+
325
+ ### Run the web app
326
+
327
+ Requires Node **>= 22.5**.
328
+
329
+ ```sh
330
+ cd web
331
+ npm install
332
+ npm run build
333
+ node server/index.js --port 4317 --data ~/.dsh-coding-enhanced-web
334
+ ```
335
+
336
+ Open <http://localhost:4317>, register a username + user key (the key is shown
337
+ once), then generate a pairing code under **Devices**. In DSH open
338
+ **Settings → Coding Enhanced → Web review**, enter `http://localhost:4317` and
339
+ the code, and pair. Choose **Web** or **Both** in the input-bar **Review tools**
340
+ popover.
341
+
342
+ For Vite HMR during development, run the server with
343
+ `ORIGIN=http://localhost:5173` and use `npm run dev:web` (port 5173) instead of
344
+ the built page.
345
+
346
+ ### Distribution
347
+
348
+ - **Plugin-only users**: install the tarball from Releases; no web assets are
349
+ downloaded.
350
+ - **Web review users**: clone the repository (or copy `web/`), then run the
351
+ build and server steps above. Ship `web/` source, or `web/dist` + `server/`
352
+ together; the server serves the built page and assets when `dist/index.html`
353
+ exists.
354
+ - Put the server behind HTTPS/reverse proxy and set `ORIGIN` for remote use.
355
+
356
+ ---
357
+
313
358
  <a id="how-it-works"></a>
314
359
 
315
360
  ## 🧠 How it works
@@ -399,7 +444,7 @@ The gate, the time machine, and the handoff are the product. The local diff UI
399
444
  is deliberately simple; [`dsh-diff-approval`](https://github.com/9087/dsh-diff-approval)
400
445
  already covers the “beautiful diff panel” case. Next:
401
446
 
402
- - **P1 — standalone web review**: passkey pairing, always-on standby, outbound
447
+ - **P1 — standalone web review**: username+key pairing, always-on standby, outbound
403
448
  WSS bridge, review display and decisions.
404
449
  - **P2 — line-level AI comments (B)**: a dedicated comment subagent; line
405
450
  selection; suggestions.
package/lib/client.js CHANGED
@@ -42,6 +42,21 @@ window.__ModuleLoader__.load({
42
42
  autoReview: 'Pre-review',
43
43
  aiExplain: 'AI explanations',
44
44
  aiExplainDesc: 'Require at least one note per changed file. Off: queue changes without notes.',
45
+ channelLabel: 'Review channel',
46
+ channelHint: 'Where reviews are decided: the standalone web server, both surfaces, or the DSH sidebar only.',
47
+ channelWeb: 'Web',
48
+ channelBoth: 'Both',
49
+ channelBuiltin: 'DSH',
50
+ webTitle: 'Web review',
51
+ webDesc: 'Pair a standalone review server. DSH stays authoritative; the web UI only mirrors reviews.',
52
+ webUrlPlaceholder: 'http://localhost:4317',
53
+ webCodePlaceholder: 'Pairing code',
54
+ webPair: 'Pair',
55
+ webDisconnect: 'Disconnect',
56
+ webOnline: 'online',
57
+ webOffline: 'offline',
58
+ webUnpaired: 'not paired',
59
+ settingsGroupWeb: 'Web review',
45
60
  autoReviewDesc: 'The agent must queue every edit with review_write / review_patch before it lands. Off: native write/edit.',
46
61
  reviewFeatureOff: 'AI Change Review is off in Settings. Enable it first, then use this switch.',
47
62
  reviewOn: 'On',
@@ -95,7 +110,7 @@ window.__ModuleLoader__.load({
95
110
  pillarGate: 'Pre-write gate',
96
111
  pillarRewind: 'Multi-turn rewind',
97
112
  pillarWaiter: 'Non-blocking waiter',
98
- pillarRemote: 'Passkey web + cross-AI · next',
113
+ pillarRemote: 'Web review + cross-AI · next',
99
114
  settingsReview: 'AI Change Review',
100
115
  settingsReviewDesc: 'Queue every write/edit in the review tab; nothing lands until you finish. The main agent keeps working while the review waits.',
101
116
  settingsWithdraw: 'Turn Withdraw',
@@ -156,6 +171,21 @@ window.__ModuleLoader__.load({
156
171
  autoReview: 'AI 改动预审查',
157
172
  aiExplain: 'AI 解释',
158
173
  aiExplainDesc: '每个改动文件至少一条说明。关闭后排队不再要求解释。',
174
+ channelLabel: 'Review 通道',
175
+ channelHint: '在哪里处理 review:独立 Web 服务、两者,或仅 DSH 侧栏。',
176
+ channelWeb: 'Web',
177
+ channelBoth: '两者',
178
+ channelBuiltin: 'DSH',
179
+ webTitle: '网页 review',
180
+ webDesc: '配对独立 review 服务;DSH 仍是权威,网页只镜像 review。',
181
+ webUrlPlaceholder: 'http://localhost:4317',
182
+ webCodePlaceholder: '配对码',
183
+ webPair: '配对',
184
+ webDisconnect: '断开',
185
+ webOnline: '在线',
186
+ webOffline: '离线',
187
+ webUnpaired: '未配对',
188
+ settingsGroupWeb: '网页 review',
159
189
  autoReviewDesc: 'AI 的每次改动都必须先进入 review(review_write / review_patch)才能落盘。关闭后走原生 write/edit。',
160
190
  reviewFeatureOff: '设置里的 AI Change Review 处于关闭状态,先启用后再用这个开关。',
161
191
  reviewOn: '开',
@@ -208,7 +238,7 @@ window.__ModuleLoader__.load({
208
238
  pillarGate: '写入前闸门',
209
239
  pillarRewind: '多轮回退',
210
240
  pillarWaiter: '非阻塞 waiter',
211
- pillarRemote: 'Passkey Web + 跨 AI · 下一步',
241
+ pillarRemote: 'Web review + 跨 AI · 下一步',
212
242
  settingsReview: 'AI 改动审查',
213
243
  settingsReviewDesc: '每次 write/edit 先进入审查页,Finish 前不落盘;review 等待期间主 agent 可以继续工作。',
214
244
  settingsWithdraw: '撤回本轮',
@@ -325,6 +355,13 @@ window.__ModuleLoader__.load({
325
355
  .ce-review-trigger.disabled{opacity:.5}
326
356
  .ce-review-dot{position:absolute;right:3px;bottom:3px;width:6px;height:6px;border-radius:50%;background:var(--dsw-alias-label-tertiary,#bbb);box-shadow:0 0 0 2px var(--dsw-alias-bg-base,#fff)}
327
357
  .ce-review-dot.on{background:var(--dsw-alias-state-success-primary,#2da44e)}
358
+ .ce-channel-switch{display:inline-flex;align-items:center;gap:1px;padding:2px;border-radius:999px;background:var(--dsw-alias-interactive-bg-hover);border:1px solid var(--dsw-alias-border-l1,rgba(0,0,0,.08))}
359
+ .ce-channel-option{height:calc(22px + var(--dsh-content-font-delta,0px));padding:0 .5em;border:0;border-radius:999px;background:transparent;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:calc(11px + var(--dsh-content-font-delta,0px));line-height:1;cursor:pointer;white-space:nowrap}
360
+ .ce-channel-option:hover:not(:disabled){color:var(--dsw-alias-label-primary)}
361
+ .ce-channel-option.on{background:var(--dsw-alias-bg-layer-1,#fff);color:var(--dsw-alias-label-primary);box-shadow:0 1px 2px rgba(0,0,0,.12)}
362
+ .ce-channel-option:disabled{cursor:default;opacity:.6}
363
+ .ce-review-row.ce-channel-row{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:start;gap:12px}
364
+ .ce-review-row.ce-channel-row .ce-channel-switch{margin-left:0;justify-self:end}
328
365
  .ce-review-popover{z-index:10000;box-sizing:border-box;padding:14px;border:1px solid var(--dsw-alias-border-l2,rgba(0,0,0,.12));border-radius:14px;background:var(--dsw-alias-bg-layer-1,#fff);box-shadow:0 12px 36px rgba(0,0,0,.18);color:var(--dsw-alias-label-primary,#1a1a1a);font-size:14px}
329
366
  .ce-review-head{display:flex;align-items:center;justify-content:space-between;gap:8px}
330
367
  .ce-review-title{font-size:14px;font-weight:600;line-height:20px}
@@ -439,6 +476,25 @@ div:has(> [data-detail-document]) > [data-plugin-config]{order:-1}
439
476
  }
440
477
  }
441
478
 
479
+ // -------------------------------------------------- review channel ---
480
+ // Which review surface is live: 'web' (standalone server only),
481
+ // 'builtin' (DSH sidebar only), or 'both'. The host mirrors settings.
482
+ const REVIEW_CHANNELS = new Set(['web', 'both', 'builtin'])
483
+ let reviewChannel = 'both'
484
+ const channelListeners = new Set()
485
+ const getReviewChannel = () => reviewChannel
486
+ const subscribeReviewChannel = (listener) => {
487
+ channelListeners.add(listener)
488
+ return () => {
489
+ channelListeners.delete(listener)
490
+ }
491
+ }
492
+ const setReviewChannel = (value) => {
493
+ if (!REVIEW_CHANNELS.has(value) || value === reviewChannel) return
494
+ reviewChannel = value
495
+ for (const listener of [...channelListeners]) listener()
496
+ }
497
+
442
498
  // -------------------------------------------------- withdraw store ---
443
499
  const records = new Map()
444
500
  const listeners = new Map()
@@ -972,6 +1028,7 @@ div:has(> [data-detail-document]) > [data-plugin-config]{order:-1}
972
1028
  const { sessionId, t } = props
973
1029
  const state = useReviews()
974
1030
  const tabs = useOpenTabs()
1031
+ const channel = React.useSyncExternalStore(subscribeReviewChannel, getReviewChannel)
975
1032
  const review = pendingReview(state.reviews)
976
1033
  const audit = state.audits?.[sessionId]
977
1034
  const auditOutside = Array.isArray(audit?.outside) ? audit.outside : []
@@ -979,17 +1036,17 @@ div:has(> [data-detail-document]) > [data-plugin-config]{order:-1}
979
1036
  const tabOpen = tabs.some((tab) => tab.kind === REVIEW_KIND && tab.sessionId === sessionId)
980
1037
 
981
1038
  React.useEffect(() => {
982
- if (!state.loaded || review === undefined) return
1039
+ if (channel === 'web' || !state.loaded || review === undefined) return
983
1040
  if (opened.current === review.id) return
984
1041
  opened.current = review.id
985
1042
  openReviewTab(review.id)
986
- }, [state.loaded, review?.id])
1043
+ }, [state.loaded, review?.id, channel])
987
1044
 
988
1045
  React.useEffect(() => {
989
1046
  if (review === undefined) opened.current = null
990
1047
  }, [review?.id])
991
1048
 
992
- if (!state.loaded || review === undefined || tabOpen) return null
1049
+ if (channel === 'web' || !state.loaded || review === undefined || tabOpen) return null
993
1050
  return ReactDOM.createPortal(
994
1051
  React.createElement(
995
1052
  'button',
@@ -1514,9 +1571,9 @@ div:has(> [data-detail-document]) > [data-plugin-config]{order:-1}
1514
1571
  className: 'ce-review-popover',
1515
1572
  style: {
1516
1573
  position: 'fixed',
1517
- left: `${Math.max(8, Math.min(window.innerWidth - 300, rect.left))}px`,
1574
+ left: `${Math.max(8, Math.min(window.innerWidth - 368, rect.left))}px`,
1518
1575
  bottom: `${Math.max(8, window.innerHeight - rect.top + 8)}px`,
1519
- width: '280px',
1576
+ width: 'min(360px, calc(100vw - 16px))',
1520
1577
  },
1521
1578
  },
1522
1579
  React.createElement(
@@ -1558,6 +1615,17 @@ div:has(> [data-detail-document]) > [data-plugin-config]{order:-1}
1558
1615
  React.createElement('span', { className: 'ce-switch-thumb' }),
1559
1616
  ),
1560
1617
  ),
1618
+ React.createElement(
1619
+ 'div',
1620
+ { className: 'ce-review-row ce-channel-row' },
1621
+ React.createElement(
1622
+ 'div',
1623
+ { className: 'ce-review-text' },
1624
+ React.createElement('div', { className: 'ce-review-row-title' }, typeof t === 'function' ? t('channelLabel') : 'Review channel'),
1625
+ React.createElement('div', { className: 'ce-review-row-desc' }, typeof t === 'function' ? t('channelHint') : ''),
1626
+ ),
1627
+ React.createElement(ReviewModeSwitch, { t }),
1628
+ ),
1561
1629
  React.createElement(
1562
1630
  'div',
1563
1631
  { className: 'ce-review-row' },
@@ -1609,7 +1677,118 @@ div:has(> [data-detail-document]) > [data-plugin-config]{order:-1}
1609
1677
  )
1610
1678
  }
1611
1679
 
1680
+ function ReviewModeSwitch({ t }) {
1681
+ const channel = React.useSyncExternalStore(subscribeReviewChannel, getReviewChannel)
1682
+ const [busy, setBusy] = React.useState(false)
1683
+ const label = (key, fallback) => (typeof t === 'function' ? t(key) : fallback)
1684
+ const options = [
1685
+ { value: 'web', text: label('channelWeb', 'Web') },
1686
+ { value: 'both', text: label('channelBoth', 'Both') },
1687
+ { value: 'builtin', text: label('channelBuiltin', 'DSH') },
1688
+ ]
1689
+ const choose = async (value) => {
1690
+ if (busy || value === channel) return
1691
+ setBusy(true)
1692
+ const result = await call('setSettings', { reviewChannel: value })
1693
+ setBusy(false)
1694
+ if (result.ok === true) setReviewChannel(result.value.reviewChannel)
1695
+ }
1696
+ return React.createElement(
1697
+ 'div',
1698
+ {
1699
+ className: 'ce-channel-switch',
1700
+ role: 'group',
1701
+ 'aria-label': label('channelLabel', 'Review channel'),
1702
+ title: label('channelHint', 'Where reviews are decided'),
1703
+ },
1704
+ options.map((option) =>
1705
+ React.createElement(
1706
+ 'button',
1707
+ {
1708
+ key: option.value,
1709
+ type: 'button',
1710
+ className: `ce-channel-option${channel === option.value ? ' on' : ''}`,
1711
+ 'aria-pressed': channel === option.value,
1712
+ disabled: busy,
1713
+ onClick: () => { void choose(option.value) },
1714
+ },
1715
+ option.text,
1716
+ ),
1717
+ ),
1718
+ )
1719
+ }
1720
+
1612
1721
  // ------------------------------------------------- settings section ---
1722
+ function WebReviewCard({ t }) {
1723
+ const [status, setStatus] = React.useState(null)
1724
+ const [url, setUrl] = React.useState('')
1725
+ const [code, setCode] = React.useState('')
1726
+ const [busy, setBusy] = React.useState(false)
1727
+ const [message, setMessage] = React.useState(null)
1728
+ const label = (key, fallback) => (typeof t === 'function' ? t(key) : fallback)
1729
+ const refresh = async () => {
1730
+ const result = await call('webStatus')
1731
+ if (result.ok === true) setStatus(result.value)
1732
+ }
1733
+ React.useEffect(() => { void refresh() }, [])
1734
+ const pair = async () => {
1735
+ setBusy(true)
1736
+ setMessage(null)
1737
+ try {
1738
+ const result = await call('webPair', { url, code })
1739
+ if (result.ok === true) {
1740
+ const value = result.value ?? {}
1741
+ if (value.ok === false) setMessage(value.error ?? 'pair failed')
1742
+ else {
1743
+ setCode('')
1744
+ setStatus(value.status ?? null)
1745
+ await refresh()
1746
+ }
1747
+ }
1748
+ } catch (error) {
1749
+ setMessage(String(error))
1750
+ } finally {
1751
+ setBusy(false)
1752
+ }
1753
+ }
1754
+ const disconnect = async () => {
1755
+ setBusy(true)
1756
+ try {
1757
+ const result = await call('webDisconnect')
1758
+ if (result.ok === true) setStatus(result.value)
1759
+ } catch (error) {
1760
+ setMessage(String(error))
1761
+ } finally {
1762
+ setBusy(false)
1763
+ }
1764
+ }
1765
+ const paired = status?.paired === true
1766
+ const connected = status?.connected === true
1767
+ return React.createElement(
1768
+ 'div',
1769
+ { className: 'ce-card' },
1770
+ React.createElement(
1771
+ 'div',
1772
+ { className: 'ce-row' },
1773
+ React.createElement(
1774
+ 'div',
1775
+ { className: 'ce-row-text' },
1776
+ React.createElement('div', { className: 'ce-row-title' }, label('webTitle', 'Web review')),
1777
+ React.createElement('div', { className: 'ce-row-desc' }, label('webDesc', 'Pair a standalone review server. DSH stays authoritative; the web UI only mirrors reviews.')),
1778
+ ),
1779
+ React.createElement('span', { className: 'ce-row-desc' }, paired ? (connected ? label('webOnline', 'online') : label('webOffline', 'offline')) : label('webUnpaired', 'not paired')),
1780
+ ),
1781
+ React.createElement(
1782
+ 'div',
1783
+ { style: { display: 'flex', gap: '8px', flexWrap: 'wrap', padding: '0 1em 1em' } },
1784
+ React.createElement('input', { className: 'ce-number', style: { flex: '1 1 220px' }, placeholder: label('webUrlPlaceholder', 'http://localhost:4317'), value: url, disabled: busy, onChange: (event) => setUrl(event.target.value) }),
1785
+ React.createElement('input', { className: 'ce-number', style: { width: '120px' }, placeholder: label('webCodePlaceholder', 'Pairing code'), value: code, disabled: busy, onChange: (event) => setCode(event.target.value.toUpperCase()) }),
1786
+ React.createElement('button', { type: 'button', className: 'ce-action primary', disabled: busy || url.trim() === '' || code.trim() === '', onClick: () => { void pair() } }, busy ? '…' : label('webPair', 'Pair')),
1787
+ paired ? React.createElement('button', { type: 'button', className: 'ce-action', disabled: busy, onClick: () => { void disconnect() } }, label('webDisconnect', 'Disconnect')) : null,
1788
+ ),
1789
+ message !== null ? React.createElement('div', { className: 'ce-row-desc', style: { padding: '0 1em 1em' } }, message) : null,
1790
+ )
1791
+ }
1613
1792
  function SettingsSection({ t, compact }) {
1614
1793
  const [flags, setFlags] = React.useState(null)
1615
1794
  const [busy, setBusy] = React.useState(null)
@@ -1845,6 +2024,8 @@ div:has(> [data-detail-document]) > [data-plugin-config]{order:-1}
1845
2024
  row('review', typeof t === 'function' ? t('settingsReview') : 'AI Change Review', typeof t === 'function' ? t('settingsReviewDesc') : ''),
1846
2025
  row('aiExplain', typeof t === 'function' ? t('aiExplain') : 'AI explanations', typeof t === 'function' ? t('aiExplainDesc') : 'Require a short note for every added group. Off: queue changes without notes.'),
1847
2026
  ),
2027
+ React.createElement('div', { className: 'ce-group-title' }, typeof t === 'function' ? t('settingsGroupWeb') : 'Web review'),
2028
+ React.createElement(WebReviewCard, { t }),
1848
2029
  React.createElement('div', { className: 'ce-group-title' }, typeof t === 'function' ? t('settingsGroupWithdraw') : 'Turn withdraw'),
1849
2030
  React.createElement(
1850
2031
  'div',
@@ -1954,16 +2135,74 @@ div:has(> [data-detail-document]) > [data-plugin-config]{order:-1}
1954
2135
  }, 1000)
1955
2136
  return () => window.clearInterval(timer)
1956
2137
  }, 'coding-enhanced: withdrawn turn markers')
1957
- try {
1958
- ctx.effect(() => ctx.sidebarRightTabs.register({
1959
- id: REVIEW_TAB_ID,
1960
- kind: REVIEW_KIND,
1961
- title: () => (typeof bindT === 'function' ? bindT('reviewTitle') : 'Code review'),
1962
- }), 'coding-enhanced: review tab type')
1963
- } catch (error) {
1964
- ctx.logger?.warn?.(`coding-enhanced: cannot register the review tab type: ${String(error)}`)
2138
+
2139
+ // The channel is imperative rather than a one-shot ctx.effect: switching
2140
+ // to 'web' removes the DSH tab (and closes open ones) without a reload;
2141
+ // switching back registers it again.
2142
+ let sidebarTypeDispose = null
2143
+ let sidebarPaneDispose = null
2144
+ let sidebarRegistered = false
2145
+
2146
+ const closeReviewTabs = () => {
2147
+ try {
2148
+ const open = ctx.sidebarRight?.openTabs?.getSnapshot?.() ?? []
2149
+ for (const tab of open) {
2150
+ if (tab.kind !== REVIEW_KIND) continue
2151
+ ctx.sidebarRight.closeIn(tab.sessionId, tab.tabId)
2152
+ }
2153
+ } catch (error) {
2154
+ ctx.logger?.warn?.(`coding-enhanced: cannot close the review tabs: ${String(error)}`)
2155
+ }
2156
+ }
2157
+
2158
+ const teardownReviewSidebar = () => {
2159
+ if (!sidebarRegistered) return
2160
+ sidebarRegistered = false
2161
+ closeReviewTabs()
2162
+ try { sidebarPaneDispose?.() } catch {}
2163
+ sidebarPaneDispose = null
2164
+ try { sidebarTypeDispose?.() } catch {}
2165
+ sidebarTypeDispose = null
1965
2166
  }
1966
2167
 
2168
+ const ensureReviewSidebar = () => {
2169
+ if (reviewChannel === 'web') {
2170
+ teardownReviewSidebar()
2171
+ return
2172
+ }
2173
+ if (sidebarRegistered) return
2174
+ sidebarRegistered = true
2175
+ try {
2176
+ sidebarTypeDispose = ctx.sidebarRightTabs.register({
2177
+ id: REVIEW_TAB_ID,
2178
+ kind: REVIEW_KIND,
2179
+ title: () => (typeof bindT === 'function' ? bindT('reviewTitle') : 'Code review'),
2180
+ })
2181
+ sidebarPaneDispose = ctx.slots.inject('sidebar.right.pane.tab', () =>
2182
+ ctx.slots.register(
2183
+ {
2184
+ name: 'sidebar.right.pane.tab',
2185
+ key: REVIEW_TAB_ID,
2186
+ locale: NS,
2187
+ },
2188
+ ReviewTab,
2189
+ ),
2190
+ )
2191
+ } catch (error) {
2192
+ sidebarRegistered = false
2193
+ ctx.logger?.warn?.(`coding-enhanced: cannot register the review tab: ${String(error)}`)
2194
+ }
2195
+ }
2196
+
2197
+ ctx.effect(() => {
2198
+ ensureReviewSidebar()
2199
+ return () => teardownReviewSidebar()
2200
+ }, 'coding-enhanced: review channel surfaces')
2201
+ subscribeReviewChannel(ensureReviewSidebar)
2202
+ void call('settings').then((result) => {
2203
+ if (result.ok === true) setReviewChannel(result.value.reviewChannel)
2204
+ })
2205
+
1967
2206
  // ------------------------------------------------------------ slots ---
1968
2207
  ctx.slots.inject('plugins.bundle.config', () =>
1969
2208
  ctx.slots.register(
@@ -2041,17 +2280,6 @@ div:has(> [data-detail-document]) > [data-plugin-config]{order:-1}
2041
2280
  ),
2042
2281
  )
2043
2282
 
2044
- ctx.slots.inject('sidebar.right.pane.tab', () =>
2045
- ctx.slots.register(
2046
- {
2047
- name: 'sidebar.right.pane.tab',
2048
- key: REVIEW_TAB_ID,
2049
- locale: NS,
2050
- },
2051
- ReviewTab,
2052
- ),
2053
- )
2054
-
2055
2283
  ctx.on('connection/reset', () => {
2056
2284
  for (const sessionId of records.keys()) {
2057
2285
  fetchedAt.delete(sessionId)
@@ -0,0 +1,136 @@
1
+ import path from 'node:path'
2
+
3
+ const ARTIFACT_DIRS = ['dist', 'build', 'out', 'target', 'node_modules', '.next', '.cache', 'coverage', '.vitest', '__pycache__', '.pytest_cache', '.turbo', '.parcel-cache']
4
+
5
+ const cleanTarget = (value) => String(value).replace(/^['"]|['"]$/g, '').replace(/^\.\//, '')
6
+
7
+ const isArtifactPath = (value) => {
8
+ const cleaned = cleanTarget(value)
9
+ if (cleaned === '/dev/null' || cleaned.startsWith('/tmp/') || cleaned === '/tmp') return true
10
+ return ARTIFACT_DIRS.some((dir) => cleaned === dir || cleaned.startsWith(`${dir}/`) || cleaned.includes(`/${dir}/`))
11
+ }
12
+
13
+ const isInsideQuotes = (value, index) => {
14
+ let quote = null
15
+ for (let i = 0; i < index; i += 1) {
16
+ const ch = value[i]
17
+ if (quote !== null) {
18
+ if (ch === quote && value[i - 1] !== '\\') quote = null
19
+ } else if (ch === '"' || ch === "'") {
20
+ quote = ch
21
+ }
22
+ }
23
+ return quote !== null
24
+ }
25
+
26
+ const isProtectedTarget = (target, cwd) => {
27
+ const cleaned = cleanTarget(target)
28
+ if (cleaned === '' || cleaned.startsWith('&') || /^\d+$/.test(cleaned)) return false
29
+ if (isArtifactPath(cleaned)) return false
30
+ const root = path.resolve(cwd)
31
+ const resolved = path.resolve(root, cleaned)
32
+ return resolved === root || resolved.startsWith(`${root}${path.sep}`)
33
+ }
34
+
35
+ const splitArgs = (value) => value.split(/\s+/).filter((part) => part !== '')
36
+ const optionless = (args) => args.filter((part) => !part.startsWith('-') && !part.includes('='))
37
+
38
+ /**
39
+ * Detect shell commands that write protected workspace files.
40
+ *
41
+ * The unit of protection is a file target, not a command. Installs, builds,
42
+ * tests and environment commands pass; only targets inside the workspace that
43
+ * are not artifacts block. Ambiguous writes (patch/apply, git worktree,
44
+ * archives, wrapped commands, inline interpreters) require a second
45
+ * confirmation; the turn/end audit remains the backstop.
46
+ */
47
+ export const detectShellWrites = (command, cwd) => {
48
+ const reasons = []
49
+ const targets = []
50
+ const add = (reason, target) => {
51
+ reasons.push(reason)
52
+ if (typeof target === 'string' && target !== '') targets.push(target)
53
+ }
54
+
55
+ for (const match of command.matchAll(/(?:^|[^>=-])>{1,2}\s*([^\s;&|]+)/g)) {
56
+ const index = match.index + match[1].length
57
+ if (isInsideQuotes(command, index)) continue
58
+ const target = cleanTarget(match[2])
59
+ if (target.startsWith('&') || /^\d+$/.test(target)) continue
60
+ add('shell redirection', target)
61
+ }
62
+ for (const match of command.matchAll(/(?:^|[^>=-])>\|\s*([^\s;&|]+)/g)) {
63
+ const index = match.index + match[1].length
64
+ if (isInsideQuotes(command, index)) continue
65
+ add('shell redirection', cleanTarget(match[2]))
66
+ }
67
+
68
+ const tee = /\btee\s+(?:-[A-Za-z]+\s+)*([^\s;&|]+)/.exec(command)
69
+ if (tee !== null && !isInsideQuotes(command, tee.index + tee[0].lastIndexOf(tee[1]))) add('tee', tee[1])
70
+ const sed = /\bsed\s+(?:[^;&|]*\s)?-i(?:\.\w+)?\s+([^\s;&|]+)/.exec(command)
71
+ if (sed !== null) add('in-place edit', sed[1])
72
+ const perl = /\bperl\s+-i\s+([^\s;&|]+)/.exec(command)
73
+ if (perl !== null) add('in-place edit', perl[1])
74
+ const ruby = /\bruby\s+-i(?:\.\w+)?\s+([^\s;&|]+)/.exec(command)
75
+ if (ruby !== null) add('in-place edit', ruby[1])
76
+ const dd = /\bdd\b[^;&|]*\bof=([^\s;&|]+)/.exec(command)
77
+ if (dd !== null) add('dd', dd[1])
78
+ const curl = /\bcurl\b[^;&|]*\s-o\s*([^\s;&|]+)/.exec(command)
79
+ if (curl !== null) add('curl -o', curl[1])
80
+ const wget = /\bwget\b[^;&|]*\s-O\s*([^\s;&|]+)/.exec(command)
81
+ if (wget !== null) add('wget -O', wget[1])
82
+
83
+ const cp = /\bcp\b([^;&|]*)/.exec(command)
84
+ if (cp !== null) {
85
+ const args = optionless(splitArgs(cp[1]))
86
+ if (args.length > 0) add('cp', args[args.length - 1])
87
+ }
88
+ const mv = /\bmv\b([^;&|]*)/.exec(command)
89
+ if (mv !== null) {
90
+ for (const arg of optionless(splitArgs(mv[1]))) add('mv', arg)
91
+ }
92
+ const rm = /\brm\b([^;&|]*)/.exec(command)
93
+ if (rm !== null) {
94
+ for (const arg of optionless(splitArgs(rm[1]))) add('rm', arg)
95
+ }
96
+ const touch = /\btouch\b([^;&|]*)/.exec(command)
97
+ if (touch !== null) {
98
+ for (const arg of optionless(splitArgs(touch[1]))) add('touch', arg)
99
+ }
100
+ const ln = /\bln\b([^;&|]*)/.exec(command)
101
+ if (ln !== null) {
102
+ const args = optionless(splitArgs(ln[1]))
103
+ if (args.length > 0) add('ln', args[args.length - 1])
104
+ }
105
+ const rsync = /\brsync\b([^;&|]*)/.exec(command)
106
+ if (rsync !== null) {
107
+ const args = optionless(splitArgs(rsync[1]))
108
+ if (args.length > 0) add('rsync', args[args.length - 1])
109
+ }
110
+ const scp = /\bscp\b([^;&|]*)/.exec(command)
111
+ if (scp !== null) {
112
+ const args = optionless(splitArgs(scp[1]))
113
+ if (args.length > 0) add('scp', args[args.length - 1])
114
+ }
115
+
116
+ for (const op of ['truncate', 'shred', 'unlink']) {
117
+ const match = new RegExp(`\\b${op}\\b([^;&|]*)`).exec(command)
118
+ if (match !== null) {
119
+ for (const arg of optionless(splitArgs(match[1]))) add(op, arg)
120
+ }
121
+ }
122
+
123
+ if (/\bgit\s+apply\b/.test(command)) add('git apply')
124
+ if (/\bpatch\b/.test(command)) add('patch')
125
+ if (/\bgit\s+(?:restore|checkout\s+--|reset\s+--hard|clean\s+-[A-Za-z]*f[A-Za-z]*|stash)\b/.test(command)) add('git worktree write')
126
+ if (/\btar\b[^;&|]*\s-[A-Za-z]*x[A-Za-z]*/.test(command)) add('archive extract')
127
+ if (/\bunzip\b/.test(command)) add('archive extract')
128
+ if (/\bgit\s+clone\b/.test(command)) add('git clone')
129
+ if (/\b(?:bash|sh|zsh)\s+-c\b|\beval\b|\bsource\b|\bfind\b[^;&|]*\s-exec\b|\bxargs\b/.test(command)) add('wrapped command')
130
+ if (/\b(?:python3?|node|ruby|perl)\b/.test(command) && /\b(?:open|writeFileSync|writeFile|write_text|to_csv|savefig|fs\.write|shutil\.(?:copy|move|rmtree)|os\.(?:rename|remove|unlink))\b/.test(command)) add('inline write')
131
+
132
+ const protectedTargets = targets.filter((target) => isProtectedTarget(target, cwd))
133
+ const blocked = protectedTargets.length > 0
134
+ const needsConfirm = !blocked && reasons.length > 0
135
+ return { blocked, needsConfirm, reasons, targets, protectedTargets }
136
+ }
package/lib/index.js CHANGED
@@ -22,6 +22,8 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from '
22
22
  import fs from 'node:fs/promises'
23
23
  import os from 'node:os'
24
24
  import path from 'node:path'
25
+ import { detectShellWrites } from './detect-writes.js'
26
+ import { createWebBridge } from './web-bridge.js'
25
27
  import { fileURLToPath } from 'node:url'
26
28
 
27
29
  export const name = 'coding-enhanced'
@@ -416,7 +418,8 @@ export function apply(ctx) {
416
418
  const settingsPath = path.join(root, 'settings.json')
417
419
  mkdirSync(root, { recursive: true })
418
420
 
419
- const featureFlags = { review: true, withdraw: true, autoReview: true, aiExplain: true, allowBlockingReviewWait: false, keepTurns: 10, nestedSnapshots: true, autoGc: true }
421
+ const REVIEW_CHANNELS = new Set(['web', 'both', 'builtin'])
422
+ const featureFlags = { review: true, withdraw: true, autoReview: true, aiExplain: true, allowBlockingReviewWait: false, keepTurns: 10, nestedSnapshots: true, autoGc: true, reviewChannel: 'both', webUrl: '', webDeviceToken: '', webDeviceId: '' }
420
423
  try {
421
424
  const parsed = JSON.parse(readFileSync(settingsPath, 'utf8'))
422
425
  if (typeof parsed.review === 'boolean') featureFlags.review = parsed.review
@@ -429,6 +432,10 @@ export function apply(ctx) {
429
432
  }
430
433
  if (typeof parsed.nestedSnapshots === 'boolean') featureFlags.nestedSnapshots = parsed.nestedSnapshots
431
434
  if (typeof parsed.autoGc === 'boolean') featureFlags.autoGc = parsed.autoGc
435
+ if (REVIEW_CHANNELS.has(parsed.reviewChannel)) featureFlags.reviewChannel = parsed.reviewChannel
436
+ if (typeof parsed.webUrl === 'string') featureFlags.webUrl = parsed.webUrl
437
+ if (typeof parsed.webDeviceToken === 'string') featureFlags.webDeviceToken = parsed.webDeviceToken
438
+ if (typeof parsed.webDeviceId === 'string') featureFlags.webDeviceId = parsed.webDeviceId
432
439
  } catch {}
433
440
 
434
441
  const saveFeatureFlags = () => {
@@ -873,7 +880,7 @@ const isArtifactPath = (value) => {
873
880
  if (cleaned === '/dev/null' || cleaned.startsWith('/tmp/') || cleaned === '/tmp') return true
874
881
  return ARTIFACT_DIRS.some((dir) => cleaned === dir || cleaned.startsWith(`${dir}/`) || cleaned.includes(`/${dir}/`))
875
882
  }
876
- const detectShellWrites = (command) => {
883
+ const detectShellWritesLegacy = (command) => {
877
884
  const reasons = []
878
885
  const targets = []
879
886
  const add = (reason, target) => {
@@ -909,9 +916,13 @@ const detectShellWrites = (command) => {
909
916
  const reviewWaiters = new Map()
910
917
  const audits = new Map()
911
918
  let reviewVersion = 0
919
+ let webBridge = null
912
920
 
913
921
  const bumpReview = () => {
914
922
  reviewVersion += 1
923
+ // The built-in channel has no web consumer; keep the bridge silent so the
924
+ // DSH sidebar stays the only review surface in that mode.
925
+ if (featureFlags.reviewChannel !== 'builtin') webBridge?.publishAll()
915
926
  }
916
927
 
917
928
  const ensureReview = (sessionId) => {
@@ -1148,6 +1159,29 @@ const detectShellWrites = (command) => {
1148
1159
  })),
1149
1160
  })
1150
1161
 
1162
+ webBridge = createWebBridge({
1163
+ getConfig: () => ({ url: featureFlags.webUrl, token: featureFlags.webDeviceToken, deviceId: featureFlags.webDeviceId }),
1164
+ saveConfig: (config) => {
1165
+ if (typeof config.url === 'string') featureFlags.webUrl = config.url
1166
+ if (typeof config.token === 'string') featureFlags.webDeviceToken = config.token
1167
+ if (typeof config.deviceId === 'string') featureFlags.webDeviceId = config.deviceId
1168
+ saveFeatureFlags()
1169
+ },
1170
+ isEnabled: () => featureFlags.reviewChannel !== 'builtin',
1171
+ serializeReview,
1172
+ getReviews: () => [...reviews.values()],
1173
+ getVersion: () => reviewVersion,
1174
+ pluginVersion: PLUGIN_VERSION,
1175
+ onDecision: (message) => {
1176
+ const result = decideReview(message.reviewId, message.decisions)
1177
+ if (result.ok !== true) {
1178
+ webBridge.send({ type: 'review.result', reviewId: message.reviewId, results: [], error: result.error ?? result.message ?? 'decision failed' })
1179
+ }
1180
+ },
1181
+ })
1182
+ // 'builtin' means DSH's own review UI only; do not open the outbound WSS.
1183
+ if (featureFlags.reviewChannel !== 'builtin') webBridge.start()
1184
+
1151
1185
  const decideReview = (id, decisions) => {
1152
1186
  const review = [...reviews.values()].find((candidate) => candidate.id === id)
1153
1187
  if (review === undefined) return fail('review-not-found', 'This review is no longer open')
@@ -1162,9 +1196,14 @@ const detectShellWrites = (command) => {
1162
1196
  const entries = [...review.entries.values()]
1163
1197
  const missing = []
1164
1198
  const tooLarge = []
1199
+ const stale = []
1165
1200
  const normalized = new Map()
1166
1201
  for (const entry of entries) {
1167
1202
  const decision = byEntry.get(entry.id)
1203
+ if (decision !== undefined && decision !== null && typeof decision.baseAfterText === 'string' && entry.editable === true && entry.after !== decision.baseAfterText) {
1204
+ stale.push(entry.display)
1205
+ continue
1206
+ }
1168
1207
  if (decision !== undefined && decision.outcome === 'edited') {
1169
1208
  const text = decision.editedAfter
1170
1209
  if (entry.editable !== true || typeof text !== 'string' || text === entry.after) {
@@ -1175,7 +1214,7 @@ const detectShellWrites = (command) => {
1175
1214
  tooLarge.push(entry.display)
1176
1215
  continue
1177
1216
  }
1178
- normalized.set(entry.id, { outcome: 'edited', editedAfter: text, comment: '' })
1217
+ normalized.set(entry.id, { outcome: 'edited', editedAfter: text, comment: typeof decision.comment === 'string' ? decision.comment.slice(0, 4000) : '' })
1179
1218
  continue
1180
1219
  }
1181
1220
  if (decision === undefined || typeof decision.approved !== 'boolean') {
@@ -1189,6 +1228,7 @@ const detectShellWrites = (command) => {
1189
1228
  }
1190
1229
  if (missing.length > 0) return fail('incomplete', `No decision for: ${missing.join(', ')}`)
1191
1230
  if (tooLarge.length > 0) return fail('edit-too-large', `The edited content is too large for: ${tooLarge.join(', ')}`)
1231
+ if (stale.length > 0) return fail('stale', `The file changed while you were reviewing: ${stale.join(', ')}. Reopen the review and decide again.`)
1192
1232
 
1193
1233
  for (const entry of entries) {
1194
1234
  const decision = normalized.get(entry.id)
@@ -1574,7 +1614,7 @@ const detectShellWrites = (command) => {
1574
1614
  }
1575
1615
 
1576
1616
  const execShell = (command, cwd) => new Promise((resolve) => {
1577
- execFile('/bin/sh', ['-c', command], { cwd, timeout: 120000, maxBuffer: 8 * 1024 * 1024, env: process.env }, (error, stdout, stderr) => {
1617
+ execFile('/bin/sh', ['-c', command], { cwd, maxBuffer: 8 * 1024 * 1024, env: process.env }, (error, stdout, stderr) => {
1578
1618
  resolve({ code: error === null ? 0 : (typeof error.code === 'number' ? error.code : 1), stdout: String(stdout ?? ''), stderr: String(stderr ?? '') })
1579
1619
  })
1580
1620
  })
@@ -1612,7 +1652,7 @@ const detectShellWrites = (command) => {
1612
1652
  if (command.trim() === '') return { status: 'error', command, writes: false, message: 'command is required.' }
1613
1653
  const base = typeof session.header?.cwd === 'string' && session.header.cwd !== '' ? session.header.cwd : process.cwd()
1614
1654
  const cwd = typeof args?.cwd === 'string' && args.cwd !== '' ? path.resolve(base, args.cwd) : base
1615
- const detection = detectShellWrites(command)
1655
+ const detection = detectShellWrites(command, cwd)
1616
1656
  if (args?.confirmed !== true) {
1617
1657
  return {
1618
1658
  status: 'confirm',
@@ -2184,6 +2224,18 @@ const detectShellWrites = (command) => {
2184
2224
  return fail('bad-request', 'settings patch must be an object')
2185
2225
  }
2186
2226
  let changed = false
2227
+ if (typeof patch.reviewChannel === 'string' && REVIEW_CHANNELS.has(patch.reviewChannel) && patch.reviewChannel !== featureFlags.reviewChannel) {
2228
+ const previous = featureFlags.reviewChannel
2229
+ featureFlags.reviewChannel = patch.reviewChannel
2230
+ changed = true
2231
+ // Start only on a transition away from 'builtin'; stop only when entering
2232
+ // it, so web <-> both never reconnects an already-live bridge.
2233
+ if (previous === 'builtin' && patch.reviewChannel !== 'builtin') {
2234
+ webBridge.start()
2235
+ } else if (previous !== 'builtin' && patch.reviewChannel === 'builtin') {
2236
+ webBridge.stop()
2237
+ }
2238
+ }
2187
2239
  if (typeof patch.review === 'boolean' && patch.review !== featureFlags.review) {
2188
2240
  featureFlags.review = patch.review
2189
2241
  changed = true
@@ -2227,7 +2279,7 @@ const detectShellWrites = (command) => {
2227
2279
  cancelReview(review.id, (entry) => `The review gate was turned off in Settings. Nothing was written for "${entry.display}". Do not retry immediately; wait for the user.`)
2228
2280
  }
2229
2281
  }
2230
- return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, aiExplain: featureFlags.aiExplain, allowBlockingReviewWait: featureFlags.allowBlockingReviewWait, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc, version: PLUGIN_VERSION })
2282
+ return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, aiExplain: featureFlags.aiExplain, allowBlockingReviewWait: featureFlags.allowBlockingReviewWait, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc, reviewChannel: featureFlags.reviewChannel, version: PLUGIN_VERSION })
2231
2283
  }
2232
2284
 
2233
2285
  const handleUpdateCheck = async () => {
@@ -2292,7 +2344,10 @@ const detectShellWrites = (command) => {
2292
2344
  const dispatch = async (endpoint, payload) => {
2293
2345
  try {
2294
2346
  if (endpoint === 'status') return handleStatus(payload?.sessionId)
2295
- if (endpoint === 'settings') return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, aiExplain: featureFlags.aiExplain, allowBlockingReviewWait: featureFlags.allowBlockingReviewWait, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc, version: PLUGIN_VERSION })
2347
+ if (endpoint === 'webStatus') return ok(webBridge.status())
2348
+ if (endpoint === 'webPair') return ok(await webBridge.pair(payload))
2349
+ if (endpoint === 'webDisconnect') return ok(webBridge.disconnect())
2350
+ if (endpoint === 'settings') return ok({ review: featureFlags.review, withdraw: featureFlags.withdraw, autoReview: featureFlags.autoReview, aiExplain: featureFlags.aiExplain, allowBlockingReviewWait: featureFlags.allowBlockingReviewWait, keepTurns: featureFlags.keepTurns, nestedSnapshots: featureFlags.nestedSnapshots, autoGc: featureFlags.autoGc, reviewChannel: featureFlags.reviewChannel, version: PLUGIN_VERSION })
2296
2351
  if (endpoint === 'setSettings') return updateSettings(payload)
2297
2352
  if (endpoint === 'cleanup') return ok(await cleanupSnapshots())
2298
2353
  if (endpoint === 'withdraw') return await handleWithdraw(payload)
@@ -0,0 +1,173 @@
1
+ import os from 'node:os'
2
+
3
+ const RECONNECT_MS = [1000, 2000, 5000, 10000]
4
+
5
+ /**
6
+ * Outbound bridge from the DSH plugin host to the standalone web review server.
7
+ *
8
+ * The plugin is the authority; this module only mirrors review snapshots and
9
+ * carries decisions back. It never opens an inbound port: the plugin connects
10
+ * to /ws/device with a device token obtained through the web pairing code.
11
+ */
12
+ export const createWebBridge = (options) => {
13
+ const { getConfig, saveConfig, serializeReview, getReviews, getVersion, pluginVersion, isEnabled } = options
14
+ let socket = null
15
+ let timer = null
16
+ let attempt = 0
17
+ let connected = false
18
+ let stopped = true
19
+ let lastError = null
20
+
21
+ const status = () => {
22
+ const config = getConfig()
23
+ return {
24
+ url: config.url ?? '',
25
+ deviceId: config.deviceId ?? '',
26
+ paired: Boolean(config.token && config.deviceId),
27
+ connected,
28
+ lastError,
29
+ }
30
+ }
31
+
32
+ const send = (value) => {
33
+ if (socket !== null && socket.readyState === 1) socket.send(JSON.stringify(value))
34
+ }
35
+
36
+ const envelope = (review) => ({
37
+ ...serializeReview(review),
38
+ version: getVersion(),
39
+ status: review.finished ? 'finished' : review.canceled ? 'canceled' : review.submitted ? 'submitted' : 'open',
40
+ })
41
+
42
+ const publish = (review) => {
43
+ send({ type: 'review.snapshot', review: envelope(review) })
44
+ }
45
+
46
+ const publishAll = () => {
47
+ for (const review of getReviews()) publish(review)
48
+ }
49
+
50
+ const schedule = () => {
51
+ if (stopped) return
52
+ const delay = RECONNECT_MS[Math.min(attempt, RECONNECT_MS.length - 1)]
53
+ attempt += 1
54
+ timer = setTimeout(connect, delay)
55
+ if (typeof timer.unref === 'function') timer.unref()
56
+ }
57
+
58
+ const connect = () => {
59
+ const config = getConfig()
60
+ if (!config.url || !config.token) return
61
+ if (typeof WebSocket === 'undefined') {
62
+ lastError = 'WebSocket is not available in this Node runtime'
63
+ return
64
+ }
65
+ try {
66
+ const base = String(config.url).replace(/^http/, 'ws').replace(/\/+$/, '')
67
+ const ws = new WebSocket(`${base}/ws/device?token=${encodeURIComponent(config.token)}`)
68
+ socket = ws
69
+ ws.addEventListener('open', () => {
70
+ connected = true
71
+ attempt = 0
72
+ lastError = null
73
+ send({ type: 'hello', deviceId: config.deviceId, pluginVersion: pluginVersion ?? '', capabilities: {} })
74
+ publishAll()
75
+ })
76
+ ws.addEventListener('message', (event) => {
77
+ let message
78
+ try {
79
+ message = JSON.parse(String(event.data))
80
+ } catch {
81
+ return
82
+ }
83
+ if (message === null || typeof message !== 'object') return
84
+ if (message.type === 'ping') {
85
+ send({ type: 'pong' })
86
+ return
87
+ }
88
+ if (message.type === 'decision' && typeof options.onDecision === 'function') {
89
+ options.onDecision(message)
90
+ }
91
+ })
92
+ ws.addEventListener('close', () => {
93
+ connected = false
94
+ if (socket === ws) socket = null
95
+ schedule()
96
+ })
97
+ ws.addEventListener('error', () => {
98
+ lastError = 'WebSocket error'
99
+ })
100
+ } catch (error) {
101
+ lastError = String(error)
102
+ schedule()
103
+ }
104
+ }
105
+
106
+ const start = () => {
107
+ stopped = false
108
+ // 'builtin' keeps the web channel off even when pairing saves a token.
109
+ if (typeof isEnabled === 'function' && isEnabled() === false) return
110
+ const config = getConfig()
111
+ if (config.url && config.token) connect()
112
+ }
113
+
114
+ const stop = () => {
115
+ stopped = true
116
+ // A disabled channel must not leave a reconnect timer or socket behind.
117
+ if (typeof isEnabled === 'function' && isEnabled() === false) {
118
+ if (timer !== null) clearTimeout(timer)
119
+ timer = null
120
+ }
121
+ if (timer !== null) {
122
+ clearTimeout(timer)
123
+ timer = null
124
+ }
125
+ if (socket !== null) {
126
+ try {
127
+ socket.close()
128
+ } catch {
129
+ // Ignore close errors; the bridge is best-effort.
130
+ }
131
+ socket = null
132
+ }
133
+ connected = false
134
+ }
135
+
136
+ const pair = async (payload) => {
137
+ const base = String(payload?.url ?? '').trim().replace(/\/+$/, '')
138
+ const code = String(payload?.code ?? '').trim().toUpperCase()
139
+ if (!/^https?:\/\//.test(base)) return { ok: false, error: 'Web URL must start with http:// or https://' }
140
+ if (code === '') return { ok: false, error: 'Pairing code is required' }
141
+ try {
142
+ const response = await fetch(`${base}/api/pair`, {
143
+ method: 'POST',
144
+ headers: { 'content-type': 'application/json' },
145
+ body: JSON.stringify({
146
+ code,
147
+ deviceName: String(payload?.deviceName ?? os.hostname()).slice(0, 64),
148
+ instanceId: os.hostname(),
149
+ }),
150
+ signal: AbortSignal.timeout(10_000),
151
+ })
152
+ const data = await response.json().catch(() => ({}))
153
+ if (!response.ok) return { ok: false, error: data.error ?? `pair failed (${response.status})` }
154
+ if (typeof data.token !== 'string' || data.token === '' || typeof data.deviceId !== 'string') {
155
+ return { ok: false, error: 'pair response did not include a device token' }
156
+ }
157
+ saveConfig({ url: base, token: data.token, deviceId: data.deviceId })
158
+ stop()
159
+ start()
160
+ return { ok: true, status: status() }
161
+ } catch (error) {
162
+ return { ok: false, error: String(error) }
163
+ }
164
+ }
165
+
166
+ const disconnect = () => {
167
+ stop()
168
+ saveConfig({ token: '', deviceId: '' })
169
+ return { ok: true, status: status() }
170
+ }
171
+
172
+ return { start, stop, pair, disconnect, status, publish, publishAll, connect, send }
173
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-coding-enhanced",
3
- "version": "0.8.5",
3
+ "version": "0.9.2",
4
4
  "description": "The DSH change gate: queue AI edits before write, rewind turns with shadow-git snapshots, and hand review to a non-blocking waiter subagent.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -41,6 +41,9 @@
41
41
  "license": "MIT",
42
42
  "author": "dsh-coding-enhanced contributors",
43
43
  "scripts": {
44
+ "check": "node --check lib/index.js && node --check lib/client.js && node --check lib/web-bridge.js",
45
+ "test": "node scripts/smoke-host.mjs",
46
+ "web:build": "npm --prefix web run build",
44
47
  "pack": "node -e \"require('node:fs').mkdirSync('dist',{recursive:true})\" && npm pack --pack-destination dist"
45
48
  },
46
49
  "repository": {