dsh-bash-terminal-ts 0.8.8 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +205 -190
  2. package/CHANGELOG.pt.md +151 -0
  3. package/README.de.md +1 -1
  4. package/README.en.md +3 -2
  5. package/README.es.md +1 -1
  6. package/README.fr.md +1 -1
  7. package/README.it.md +1 -1
  8. package/README.md +4 -3
  9. package/README.pt.md +212 -0
  10. package/README.ru.md +1 -1
  11. package/agent-presets/README.md +171 -170
  12. package/agent-presets/install-presets.mjs +180 -179
  13. package/agent-presets/standard-win-niu/agent.cordis.yml +271 -0
  14. package/agent-presets/standard-win-niu/preset.yml +2 -0
  15. package/cordis.patch.yml +84 -83
  16. package/dist/client.core.js +59 -2
  17. package/dist/client.js +59 -2
  18. package/docs/dsh-plugin-development.md +169 -0
  19. package/docs/niu-backend.md +197 -0
  20. package/dsh.plugin.json +4 -3
  21. package/lib/client.js +59 -2
  22. package/lib/dsh-types.d.ts +14 -2
  23. package/lib/index.d.ts +15 -2
  24. package/lib/index.js +43 -5
  25. package/lib/locales.js +59 -2
  26. package/lib/shell-id.d.ts +1 -1
  27. package/lib/shells.d.ts +1 -0
  28. package/lib/shells.js +8 -2
  29. package/lib/terminal.js +4 -0
  30. package/lib/webterminals/host.js +2 -2
  31. package/lib/webterminals/mount.js +1 -0
  32. package/locale/de.json +6 -6
  33. package/locale/en.json +6 -6
  34. package/locale/es.json +6 -6
  35. package/locale/fr.json +6 -6
  36. package/locale/it.json +6 -6
  37. package/locale/ja.json +6 -6
  38. package/locale/ko.json +6 -6
  39. package/locale/pt.json +6 -0
  40. package/locale/ru.json +6 -6
  41. package/locale/zh.json +6 -6
  42. package/package.json +153 -149
  43. package/scripts/check-artifacts.mjs +96 -96
  44. package/src/client.tsx +685 -685
  45. package/src/dsh-types.ts +332 -320
  46. package/src/index.ts +1316 -1275
  47. package/src/locales.ts +509 -452
  48. package/src/shell-id.ts +11 -11
  49. package/src/shells.ts +279 -272
  50. package/src/terminal.ts +616 -612
  51. package/src/webterminals/host.ts +361 -361
  52. package/src/webterminals/mount.ts +237 -236
package/src/client.tsx CHANGED
@@ -1,685 +1,685 @@
1
- // dsh-bash-terminal-ts client plugin (compat-legacy): a "Default terminal"
2
- // preference row plus the bottom-terminal shell section, surfaced on the bundle
3
- // detail card and on this plugin's OWN top-level settings section (it left the
4
- // dsh-family tab in 2026-10-14 — it keeps a first-class nav row, so it no longer
5
- // needs the family container), with a shell.overlay floating-gear fallback for
6
- // hosts without any settings surface (0.1.0/0.1.1).
7
- //
8
- // compat-legacy rewiring vs upstream 0.7.1:
9
- // - no @deepseek-ai/dsh-client-store / dsh-client-ui-primitives requires:
10
- // 0.1.0/0.1.1 have no browser module table and 0.1.2 is unverified; the
11
- // row reads/writes through the host config bridge (GET/POST
12
- // /api/bash-terminal/config) and the terminal through /api/bash-terminal/terminals,
13
- // both of which work on every line.
14
- // - ui-primitives Menu/Icon replaced by a native select (same capsule CSS).
15
- // - every surface registration is independently guarded (one unknown slot
16
- // name on one line must not take down the rest).
17
- //
18
- // 0.8.0 adds two surfaces and removes one idea:
19
- // - the shell activation section (Git Bash / MSYS2 / WSL switches with a
20
- // per-row availability badge, and a default-shell choice restricted to the
21
- // activated-and-available set), all state coming from the HOST's catalog so the
22
- // browser never decides twice;
23
- // - a bottom-dock tab of our own (`ctx.betterSidebar.registerTab`, bottomOnly), which
24
- // is what makes Git Bash and MSYS2 reachable side by side - the host's own terminal
25
- // menu de-duplicates shells by executable file name and both are `bash.exe`;
26
- // - NO `ctx.provide('webTerminals')`. That was the bridge plugin's approach and it is
27
- // fatal on any host that ships its terminal controller: see the webTerminals block
28
- // near the bottom of this file.
29
-
30
- import { useEffect, useState } from "react";
31
- import { setTranslator, tr as translate } from "./browser-i18n";
32
- import { dictionaries } from "./locales";
33
- import { BridgeTerminals } from "./webterminals/browser/bridge";
34
- import { looksLikeTerminals } from "./webterminals/browser/face";
35
- import { MultiShellTerminal } from "./webterminals/browser/tab";
36
- import { ShellPicker } from "./webterminals/browser/shell-picker";
37
- import { switchableRows } from "./webterminals/browser/xterm";
38
- import { post, readConfig, readLegacyConfig, writeDefaultShell, writeLegacyDefault } from "./webterminals/browser/api";
39
- import type { CatalogEntry, ConfigSnapshot } from "./webterminals/browser/api";
40
-
41
- const SETTINGS_NS = "settings.bash-terminal";
42
- const SHELLS = ["powershell", "gitbash", "msys2", "wsl", "payload"] as const;
43
-
44
- // Injected once when the browser loads the bundle (node tests guard on document).
45
- const ROW_CSS =
46
- ".btRow{border-bottom:1px solid var(--dsw-alias-border-l2);align-items:center;gap:8px;padding:16px 0;display:flex}.btRowText{flex-direction:column;flex:1;gap:4px;min-width:0;padding-right:48px;display:flex}.btTitle{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:400;line-height:22px}.btDesc{color:var(--dsw-alias-label-tertiary);font-size:12px;font-weight:400;line-height:18px}.btSelector{background:var(--dsw-alias-bg-module-platform);height:36px;font:inherit;color:var(--dsw-alias-label-primary);cursor:pointer;border:none;border-radius:18px;align-items:center;gap:12px;padding:0 14px;font-size:14px;line-height:22px;display:inline-flex}.btSelector:hover{background:var(--dsw-alias-interactive-bg-hover)}.btGear{position:fixed;right:16px;bottom:110px;z-index:10000;width:40px;height:40px;border-radius:50%;border:1px solid rgba(127,127,127,.4);background:rgba(30,30,32,.85);color:inherit;cursor:pointer;font-size:17px;box-shadow:0 4px 16px rgba(0,0,0,.35)}.btOverlay{position:fixed;inset:0;z-index:10000;background:rgba(0,0,0,.45)}.btPanel{position:fixed;top:6vh;left:50%;transform:translateX(-50%);width:min(760px,92vw);max-height:84vh;overflow-y:auto;z-index:10001;background:var(--dsw-alias-bg-module-platform,rgba(30,30,32,.92));border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.3));border-radius:14px;padding:20px;color:var(--dsw-alias-label-primary)}.btBadge{border-radius:10px;padding:2px 8px;font-size:11px;line-height:16px;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-tertiary);white-space:nowrap}.btBadgeOk{color:var(--dsw-alias-label-primary)}.btNotice{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px;padding:8px 0}.btWarn{color:var(--dsw-status-warning-default,#b8860b)}.btRowSwitch{padding-right:0}.btSwitch{width:40px;height:24px;border-radius:12px;border:none;cursor:pointer;background:var(--dsw-alias-bg-module-platform);position:relative;flex:none;transition:background .15s ease;box-shadow:inset 0 0 0 1px var(--dsw-alias-border-l2)}.btSwitch::after{content:'';position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--dsw-alias-label-tertiary);transition:transform .15s ease,background .15s ease}.btSwitchOn{background:var(--dsw-alias-interactive-brand,#2f6fed)}.btSwitchOn::after{transform:translateX(16px);background:#fff}.btSwitch:disabled{cursor:not-allowed;opacity:.4}.btSwitch:disabled::after{background:var(--dsw-alias-label-quaternary,#8a8a8a)}.btInput{background:var(--dsw-alias-bg-module-platform);height:32px;border:none;border-radius:8px;color:var(--dsw-alias-label-primary);padding:0 10px;font:inherit;min-width:0;flex:1}.btPick{position:relative;display:inline-block}.btPickBtn{gap:6px}.btPickSm{height:28px;padding:0 10px;border-radius:14px;font-size:12px;line-height:18px}.btPickBtn:disabled{opacity:.4;cursor:not-allowed}.btPickText{max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.btPickCaret{color:var(--dsw-alias-label-tertiary);font-size:10px;line-height:1}.btPickList{position:absolute;z-index:1000;top:calc(100% + 4px);left:0;min-width:100%;max-height:260px;overflow-y:auto;padding:4px;border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-overlay);box-shadow:0 8px 24px rgba(0,0,0,.28)}.btPickOpt{padding:6px 10px;font-size:12px;line-height:18px;border-radius:6px;color:var(--dsw-alias-label-primary);cursor:pointer;white-space:nowrap}.btPickOpt:hover{background:var(--dsw-alias-interactive-bg-hover)}.btPickOptOn{color:var(--dsw-alias-interactive-brand);font-weight:600}";
47
- if (typeof document !== "undefined" && document.querySelector('style[data-plugin-css="bash-terminal-row"]') === null) {
48
- const tag = document.createElement("style");
49
- tag.dataset.plugin = "dsh-bash-terminal-ts";
50
- tag.dataset.pluginCss = "bash-terminal-row";
51
- tag.textContent = ROW_CSS;
52
- document.head.appendChild(tag);
53
- }
54
-
55
- /**
56
- * Whether the host itself owns `webTerminals` (the normal case on a DSH build that
57
- * mounts its terminal controller). Set once by `apply()`; the dock section states it,
58
- * because without that line a user cannot tell why the official terminal row and this
59
- * plugin's coexist - or which one their switches are affecting.
60
- *
61
- * A getter rather than a cached boolean: the controller may activate after our apply
62
- * runs, and a snapshot taken at apply time would be a permanent false negative. Every
63
- * render asks again, so the notice cannot go stale.
64
- */
65
- let hostOwnsTerminals: () => boolean = () => false;
66
-
67
- /**
68
- * Claim `webTerminals` for dsh-better-sidebar's OFFICIAL bottom terminal row - the one
69
- * thing this plugin can only do on a host that has no terminal controller. Returns what
70
- * actually happened so the settings row can say it, because the honest answer depends on
71
- * a live read of the service, not on the switch's own value.
72
- *
73
- * Replacing this stub is how `apply()` hands the component the real context. It stays a
74
- * function rather than a `ctx` global so the component never has to know that the apply
75
- * context is a Proxy which throws on undeclared property reads.
76
- */
77
- let tryPublishShim: () => "published" | "host-provides" = () => "host-provides";
78
-
79
- /** The published instance, kept so a later disable can dispose it. */
80
- let shimInstance: BridgeTerminals | undefined;
81
-
82
- /**
83
- * Read the current shell and, when the terminal route answers, its catalog.
84
- * The op route is preferred (it carries the catalog and validates choices); the
85
- * legacy bridge is the fallback so the row still works on a host where only the
86
- * preference channel exists.
87
- */
88
- async function bridgeConfig(): Promise<ConfigSnapshot | null> {
89
- try {
90
- return await readConfig();
91
- } catch {
92
- return await readLegacyConfig();
93
- }
94
- }
95
-
96
- /** The catalog if the terminal routes answered, else null (the old bridge shape). */
97
- function catalogOf(snapshot: ConfigSnapshot | null | undefined): CatalogEntry[] | null {
98
- if (!Array.isArray(snapshot?.catalog)) return null;
99
- return snapshot.catalog as CatalogEntry[];
100
- }
101
-
102
- /** The availability badge for one catalog row. */
103
- function badgeKey(row: CatalogEntry): string {
104
- // The floor row gets its own word: the lock EXPLANATION belongs in the row's
105
- // description, and putting it in both places reads as a rendering bug.
106
- if (!row.togglable) return "dock.state.floor";
107
- if (row.available) return "dock.state.available";
108
- return row.reason === "no-distro"
109
- ? "dock.state.noDistro"
110
- : row.reason === "launcher-only"
111
- ? "dock.state.launcherOnly"
112
- : row.reason === "wsl-preferred"
113
- ? "dock.state.wslPreferred"
114
- : "dock.state.notInstalled";
115
- }
116
-
117
- /**
118
- * Options for the default-terminal dropdown. The host's "default" write is
119
- * validated against activated+available catalog rows, so the picker must offer
120
- * exactly that set (powershell included: it is the floor and always on). A
121
- * stored value outside the set is appended - the UI shows what IS chosen, not
122
- * only what could be, and the host still refuses to re-write it.
123
- */
124
- function dropdownRows(snapshot: ConfigSnapshot | null | undefined, chosen: string): { id: string; label: string }[] {
125
- const all = SHELLS.map((id) => ({ id, label: translate("shell." + id) }));
126
- const rows = catalogOf(snapshot);
127
- if (rows === null) return all;
128
- const usable = rows
129
- .filter((row) => row.activated && row.available)
130
- .map((row) => ({ id: row.id, label: translate("shell." + row.id) }));
131
- if (chosen.length > 0 && !usable.some((row) => row.id === chosen)) {
132
- const extra = all.find((row) => row.id === chosen);
133
- if (extra !== undefined) usable.push(extra);
134
- }
135
- return usable;
136
- }
137
-
138
- /** 默认终端选择行:读写全部走宿主 bridge(六线统一)。 */
139
- function ShellPreferenceRow({ snapshot }: { snapshot?: ConfigSnapshot | null }) {
140
- const [shell, setShell] = useState("powershell");
141
- const [snap, setSnap] = useState<ConfigSnapshot | null>(snapshot ?? null);
142
- const [status, setStatus] = useState<"loading" | "ready" | "unavailable">("loading");
143
- useEffect(() => {
144
- let alive = true;
145
- const load = async (): Promise<void> => {
146
- const v = snapshot ?? (await bridgeConfig());
147
- if (!alive) return;
148
- if (v && v.defaultShell) {
149
- setShell(v.defaultShell);
150
- setSnap(v);
151
- setStatus("ready");
152
- } else {
153
- setStatus("unavailable");
154
- }
155
- };
156
- void load();
157
- return () => {
158
- alive = false;
159
- };
160
- }, [snapshot]);
161
- const change = (value: string): void => {
162
- setShell(value);
163
- // Validated write first; the legacy channel only if the op route is absent.
164
- void writeDefaultShell(value).catch(async () => {
165
- try {
166
- await writeLegacyDefault(value);
167
- } catch {
168
- /* the row keeps its optimistic value; the next read reconciles */
169
- }
170
- });
171
- };
172
- if (status === "unavailable") {
173
- return (
174
- <div className="btRow">
175
- <div className="btRowText">
176
- <div className="btTitle">{translate("shell.title")}</div>
177
- <div className="btDesc">{translate("shell.unavailable")}</div>
178
- </div>
179
- </div>
180
- );
181
- }
182
- return (
183
- <div className="btRow">
184
- <div className="btRowText">
185
- <div className="btTitle">{translate("shell.title")}</div>
186
- <div className="btDesc">{translate("shell.description")}</div>
187
- </div>
188
- <ShellPicker
189
- rows={dropdownRows(snap, shell)}
190
- value={shell}
191
- onChange={(next) => change(next)}
192
- />
193
- </div>
194
- );
195
- }
196
-
197
- /**
198
- * Whether the master switch is on, as last seen by the settings row. The bottom tab's
199
- * `available()` is synchronous, so it reads this cache instead of fetching: the
200
- * section refreshes on mount and after every write, and the tab re-reads the catalog
201
- * itself before allocating, so a stale value here can only grey out a menu entry.
202
- */
203
- let bottomTerminalEnabled = true;
204
-
205
- /**
206
- * The bottom-terminal section: a MASTER switch, then one child switch per shell the
207
- * machine actually has.
208
- *
209
- * Two levels because the two decisions are different in kind: whether this plugin
210
- * offers a terminal at all, versus which shells it may start. And every state string
211
- * comes from the host's catalog - the browser probes nothing, because two discovery
212
- * implementations drift (that is how an MSYS2 `bash.exe` ended up labelled "Git Bash"
213
- * in the sibling plugin).
214
- */
215
- function ShellDockSection() {
216
- const [snapshot, setSnapshot] = useState<ConfigSnapshot | null>(null);
217
- const [pending, setPending] = useState(false);
218
- const [error, setError] = useState("");
219
-
220
- /** Read the catalog once, reporting an absent route as an error rather than a blank. */
221
- const reload = (): void => {
222
- bridgeConfig().then((v) => {
223
- setSnapshot(v);
224
- if (v === null) setError("no-route");
225
- else {
226
- bottomTerminalEnabled = v.enabled !== false;
227
- hostSettingsSurface = v.settingsSurface ?? "unknown";
228
- }
229
- });
230
- };
231
- useEffect(() => {
232
- // The read is a `.then`, not an awaited body: the effect itself must not set
233
- // state synchronously (the host's own hook lint forbids it, and a synchronous
234
- // first paint would flash the unmounted state).
235
- reload();
236
- }, []);
237
-
238
- const rows = catalogOf(snapshot);
239
- const [shimNote, setShimNote] = useState("");
240
- /**
241
- * Flip the official-row opt-in. The config write comes first (so the choice survives a
242
- * restart), then - only when turning ON - a live check of the service: if the host (or
243
- * a previous activation) already publishes `webTerminals`, we must not add a second
244
- * provider, because cordis refuses it and the loser's entry fails.
245
- */
246
- const writeShim = async (next: boolean): Promise<void> => {
247
- setPending(true);
248
- setError("");
249
- try {
250
- const v = await post<ConfigSnapshot>({ op: "shim", shim: next });
251
- setSnapshot(v);
252
- setShimNote(next && v.shimOfficialTerminal === true ? tryPublishShim() : "");
253
- } catch (e) {
254
- setError(e instanceof Error ? e.message : String(e));
255
- } finally {
256
- setPending(false);
257
- }
258
- };
259
- const write = async (body: Record<string, unknown>): Promise<void> => {
260
- setPending(true);
261
- setError("");
262
- try {
263
- const v = await post<ConfigSnapshot>(body);
264
- setSnapshot(v);
265
- if (typeof v.enabled === "boolean") bottomTerminalEnabled = v.enabled;
266
- hostSettingsSurface = v.settingsSurface ?? hostSettingsSurface;
267
- } catch (e) {
268
- setError(e instanceof Error ? e.message : String(e));
269
- } finally {
270
- setPending(false);
271
- }
272
- };
273
-
274
- if (rows === null) {
275
- // The terminal route never answered (the legacy bridge may have). Say so and
276
- // offer a re-check: silence here is the "settings row exists but does nothing"
277
- // failure mode.
278
- return (
279
- <div className="btNotice">
280
- {translate("dock.unavailable.notInstalled")}{" "}
281
- <button type="button" className="btSelector" style={{ height: 28, fontSize: 12 }} onClick={() => reload()}>
282
- {translate("dock.refresh")}
283
- </button>
284
- </div>
285
- );
286
- }
287
-
288
- const enabled = snapshot?.enabled !== false;
289
- const usable = rows.filter((row) => row.activated && row.available);
290
- // One source of truth for "this row deserves a switch", shared with the tab's own
291
- // picker and asserted in test/browser.mjs (a render assertion cannot reach it, since
292
- // the catalog arrives in an effect).
293
- const switchable = new Set(switchableRows(rows).map((row) => row.id));
294
- const unavailableReason = snapshot?.unavailable ?? "ok";
295
- const notice = snapshot?.effective;
296
- return (
297
- <div>
298
- <div className="btRow" style={{ borderBottom: "none", paddingBottom: 4 }}>
299
- <div className="btRowText">
300
- <div className="btTitle">{translate("dock.title")}</div>
301
- <div className="btDesc">{translate("dock.hint")}</div>
302
- </div>
303
- </div>
304
- {unavailableReason !== "ok" && unavailableReason !== "disabled" ? (
305
- <div className="btNotice btWarn">
306
- {unavailableReason === "no-pty-backend"
307
- ? translate("dock.unavailable.noPty")
308
- : unavailableReason === "no-websocket-route"
309
- ? translate("dock.unavailable.noSocket")
310
- : translate("dock.unavailable.notInstalled")}
311
- </div>
312
- ) : null}
313
- {/* Which terminal surface the user is looking at: the host's own, or ours. */}
314
- {hostOwnsTerminals() ? <div className="btNotice">{translate("dock.hostProvided")}</div> : null}
315
- {/* ── level 1: the master switch ───────────────────────────────────── */}
316
- <div className="btRow btRowSwitch">
317
- <div className="btRowText">
318
- <div className="btTitle">{translate("dock.enabled.title")}</div>
319
- <div className="btDesc">{translate("dock.enabled.description")}</div>
320
- </div>
321
- <button
322
- type="button"
323
- className={"btSwitch" + (enabled ? " btSwitchOn" : "")}
324
- disabled={pending}
325
- aria-pressed={enabled}
326
- onClick={() => void write({ op: "enabled", enabled: !enabled })}
327
- />
328
- </div>
329
- {/* ── level 2: one switch per shell the machine actually has ───────── */}
330
- {!enabled ? (
331
- <div className="btNotice">{translate("dock.enabled.off")}</div>
332
- ) : (
333
- <>
334
- {rows.map((row) => (
335
- <div className="btRow btRowSwitch" key={row.id}>
336
- <div className="btRowText">
337
- <div className="btTitle">{row.label}</div>
338
- {/* The path when a shell was found, the lock rule for the floor, and
339
- the reason when there is nothing to switch on. */}
340
- <div className="btDesc">
341
- {!row.togglable
342
- ? translate("dock.powershell.locked")
343
- : row.available
344
- ? (row.path ?? translate("dock.state.notInstalled"))
345
- : translate(badgeKey(row))}
346
- </div>
347
- </div>
348
- <span className={"btBadge" + (row.available ? " btBadgeOk" : "")}>{translate(badgeKey(row))}</span>
349
- {/* No control where a choice cannot be honoured: an absent shell gets a
350
- reason, not a switch that would do nothing. */}
351
- {switchable.has(row.id) ? (
352
- <button
353
- type="button"
354
- className={"btSwitch" + (row.activated ? " btSwitchOn" : "")}
355
- disabled={pending}
356
- aria-pressed={row.activated}
357
- onClick={() => void write({ op: "switches", switches: { [row.id]: !row.activated } })}
358
- />
359
- ) : null}
360
- </div>
361
- ))}
362
- <div className="btRow btRowSwitch">
363
- <div className="btRowText">
364
- <div className="btTitle">{translate("dock.defaultChoice")}</div>
365
- <div className="btDesc">{translate("shell.description")}</div>
366
- </div>
367
- <ShellPicker
368
- rows={usable.map((row) => ({ id: row.id, label: row.label }))}
369
- value={usable.some((row) => row.id === (snapshot?.defaultShell ?? "")) ? (snapshot?.defaultShell ?? usable[0]?.id ?? "powershell") : (usable[0]?.id ?? "powershell")}
370
- onChange={(next) => void write({ op: "default", defaultShell: next })}
371
- />
372
- </div>
373
- <div className="btRow">
374
- <div className="btRowText">
375
- <div className="btTitle">{translate("dock.wslDistro")}</div>
376
- </div>
377
- <input
378
- className="btInput"
379
- type="text"
380
- defaultValue={snapshot?.wslDistro ?? ""}
381
- key={snapshot?.wslDistro ?? ""}
382
- disabled={pending}
383
- onBlur={(e) => {
384
- const value = (e.target as HTMLInputElement).value.trim();
385
- void write({ op: "switches", switches: {}, wslDistro: value });
386
- }}
387
- />
388
- </div>
389
- {notice?.floor === true ? (
390
- <div className="btNotice btWarn">{translate("dock.floor.notice", { to: notice.id })}</div>
391
- ) : notice?.fellBack === true ? (
392
- <div className="btNotice btWarn">{translate("dock.fallback.notice", { from: notice.from ?? "", to: notice.id })}</div>
393
- ) : null}
394
- {typeof snapshot?.terminals === "number" && snapshot.terminals > 0 ? (
395
- <div className="btNotice">{translate("dock.terminals", { count: snapshot.terminals })}</div>
396
- ) : null}
397
- {/* ── the official-row opt-in (off by default; see the description) ──── */}
398
- <div className="btRow btRowSwitch">
399
- <div className="btRowText">
400
- <div className="btTitle">{translate("dock.shim.title")}</div>
401
- <div className="btDesc">{translate("dock.shim.description")}</div>
402
- </div>
403
- <button
404
- type="button"
405
- className={"btSwitch" + (snapshot?.shimOfficialTerminal === true ? " btSwitchOn" : "")}
406
- disabled={pending}
407
- aria-pressed={snapshot?.shimOfficialTerminal === true}
408
- onClick={() => void writeShim(snapshot?.shimOfficialTerminal !== true)}
409
- />
410
- </div>
411
- {shimNote === "published" ? <div className="btNotice">{translate("dock.shim.published")}</div> : null}
412
- {shimNote === "host-provides" ? <div className="btNotice btWarn">{translate("dock.shim.hostProvides")}</div> : null}
413
- </>
414
- )}
415
- {pending ? <div className="btNotice">{translate("dock.applying")}</div> : null}
416
- {error !== "" && error !== "no-route" ? (
417
- <div className="btNotice btWarn">{translate("dock.failed", { message: error })}</div>
418
- ) : null}
419
- </div>
420
- );
421
- }
422
-
423
- /** dsh-better-sidebar's extension service - optional, because that plugin may be absent. */
424
- interface BetterSidebarService {
425
- registerTab(descriptor: Record<string, unknown>): () => void;
426
- }
427
-
428
- interface ClientContext {
429
- effect(fn: () => unknown, name?: string): unknown;
430
- /** Soft read: the ONLY legal way to look at a service missing from `inject`. */
431
- get?(name: string): unknown;
432
- /**
433
- * Publish a service. Exactly one call site, and it is gated: the official-row opt-in
434
- * re-reads `webTerminals` through `get` first, because providing a name the host's own
435
- * controller already claimed fails THAT entry (findings D15-1). Never call this from
436
- * `apply()` unconditionally.
437
- */
438
- provide?(name: string, service: unknown): unknown;
439
- locale: {
440
- register(ns: string, dicts: Record<string, Record<string, string>>): unknown;
441
- bind?(ns: string): (key: string, params?: Record<string, string | number>) => string;
442
- };
443
- slots: {
444
- inject(slot: string, fn: () => unknown, name?: string): void;
445
- register(options: Record<string, unknown>, Component: unknown): Record<string, unknown>;
446
- /** Read the ledger of a slot: the only way to ask whether another plugin claimed it. */
447
- entries?(slot: string): { options: { id?: string; key?: string } }[];
448
- };
449
- /**
450
- * Service-arrival callback. Optional because the oldest hosts have no browser module
451
- * table at all; where it exists it is the reliable way to find `betterSidebar`.
452
- *
453
- * Note what is NOT here: a `betterSidebar` property. Cordis exposes requested services
454
- * as properties on the ARRIVAL context only - on the apply context the same read
455
- * throws "cannot get property 'betterSidebar' without inject". Keeping the key out of
456
- * this type is what turns that runtime trap into a compile error.
457
- */
458
- inject?(deps: string[], callback: (arrived: { betterSidebar?: BetterSidebarService }) => void): void;
459
- }
460
-
461
- /**
462
- * The settings body. ONE component, rendered by whichever surface carries this plugin's
463
- * controls - the bundle detail card, the family tab and the fallback section must not be
464
- * three copies that can drift (the family contract's "one source of truth" rule).
465
- */
466
- function SettingsBody() {
467
- return (
468
- <>
469
- <ShellPreferenceRow />
470
- <ShellDockSection />
471
- </>
472
- );
473
- }
474
-
475
- /**
476
- * Whether the host renders a settings page, as the host half reported it (`page` /
477
- * `none` / `unknown`). Only `none` - 0.1.0 and 0.1.1, which declare the `settings.*` slot
478
- * map but ship no page that renders it - unlocks the floating panel below.
479
- */
480
- let hostSettingsSurface = "unknown";
481
-
482
- /**
483
- * The 0.1.0/0.1.1 way in, and nothing more.
484
- *
485
- * Those two lines declare the whole `settings.*` slot map but ship no settings page, so a
486
- * registered card there is a card nobody can open - the only surface that renders is a
487
- * shell-level overlay the plugin brings itself. Everywhere else this returns null, which
488
- * is why the arm can be registered unconditionally at apply time (the family contract's
489
- * rule) while the DECISION stays data-driven: the host half probes the first-generation
490
- * seam and the row obeys the answer.
491
- */
492
- function SettingsOverlayEntry() {
493
- const [open, setOpen] = useState(false);
494
- if (hostSettingsSurface !== "none") return null;
495
- return (
496
- <div style={{ position: "fixed", right: "16px", bottom: "110px", zIndex: 10000 }}>
497
- {open ? <div className="btOverlay" onClick={() => setOpen(false)} /> : null}
498
- {open ? (
499
- <div className="btPanel">
500
- <button
501
- type="button"
502
- className="btSelector"
503
- style={{ float: "right", height: "30px", fontSize: "12px", marginBottom: "8px" }}
504
- onClick={() => setOpen(false)}
505
- >
506
- ✕
507
- </button>
508
- <SettingsBody />
509
- </div>
510
- ) : null}
511
- <button type="button" className="btGear" title={translate("shell.title")} onClick={() => setOpen(!open)}>
512
- ⚙
513
- </button>
514
- </div>
515
- );
516
- }
517
-
518
- /**
519
- * The services this client half consumes. Declared, not guessed: the loader hands
520
- * `apply` a context carrying exactly these.
521
- *
522
- * What the declaration list really controls (learned by being wrong about it on
523
- * 0.2.0-rc.2): the context is a Proxy, and `ctx.someService` THROWS
524
- * "cannot get property 'someService' without inject" for any name absent from this
525
- * list. `ctx.get(name)` and `ctx.inject(names, cb)` are the two legal ways to reach an
526
- * undeclared or optional service - and optional is exactly what `betterSidebar` and
527
- * `webTerminals` are, so neither may ever appear as a property read.
528
- */
529
- export const inject: string[] = ["slots", "locale"];
530
-
531
- export function apply(ctx: ClientContext): void {
532
- const safe = (tag: string, fn: () => void): void => {
533
- try {
534
- fn();
535
- } catch (e) {
536
- console.warn(`[dsh-bash-terminal-ts] client surface '${tag}' failed:`, e);
537
- }
538
- };
539
- safe("locale", () => {
540
- ctx.effect(() => ctx.locale.register(SETTINGS_NS, dictionaries), "bash-terminal: settings dictionaries");
541
- // bind() exists on 0.1.2+; the oldest lines have no locale service at all, and
542
- // the module fallback (zh) is then the honest answer.
543
- const bound = ctx.locale.bind?.call(ctx.locale, SETTINGS_NS);
544
- if (typeof bound === "function") setTranslator(bound);
545
- });
546
- /**
547
- * This plugin NEVER provides `webTerminals`. Measured on 0.2.0-rc.2: the host's
548
- * `dsh-api-terminal-controller` provides the same service name and its `provide`
549
- * is unguarded, so whichever entry wins the boot race decides who dies - and ours
550
- * won, taking down the first-party terminal and the whole web boot with
551
- * `service "webTerminals" has been registered`. The bottom-dock feature does not
552
- * need the service either: this plugin ships its own tab, which works whether or
553
- * not the host has a controller. All that is left here is the read that drives the
554
- * notice above.
555
- */
556
- safe("webTerminals", () => {
557
- hostOwnsTerminals = () => looksLikeTerminals(ctx.get?.("webTerminals"));
558
- tryPublishShim = () => {
559
- if (shimInstance !== undefined) return "published";
560
- // The check is the whole point of making this opt-in: "the operator said so" is
561
- // not evidence that the name is free, and taking it anyway would fail the host's
562
- // own controller entry.
563
- if (looksLikeTerminals(ctx.get?.("webTerminals"))) return "host-provides";
564
- const terminals = new BridgeTerminals();
565
- ctx.effect(() => () => {
566
- terminals.disposeAll();
567
- shimInstance = undefined;
568
- }, "bash-terminal: official-row shim");
569
- ctx.provide?.("webTerminals", terminals);
570
- shimInstance = terminals;
571
- return "published";
572
- };
573
- });
574
- // ── settings surfaces ────────────────────────────────────────────────────────
575
- //
576
- // Two landing points plus a fallback that keeps the controls reachable when
577
- // neither has a host:
578
- //
579
- // 1. the bundle detail page (`plugins.bundle.config`, keyed by the package name) -
580
- // the host's own per-plugin configuration card, present on 0.1.7+/0.2.0; on
581
- // 0.1.2/0.1.5 the era-equivalent dispatch is `settings.plugin.item`, keyed by the
582
- // settings namespace, so both are declared;
583
- // 2. this plugin's OWN top-level `settings.section` (id `bash-terminal`), registered
584
- // unconditionally. It used to stand down while a `dsh-family` row existed and
585
- // contribute a family tab instead; that coupling made the family container a
586
- // single point of failure for these settings, and the tab is gone now (2026-10-14).
587
- // Registering under our own id — never shadowing `dsh-family` — is what keeps the
588
- // family contract intact: two nav rows, no double-rendered section.
589
- // 3. `shell.overlay` for the lines with no settings page at all.
590
- //
591
- // Every arm is registered at apply-time top level (registering from inside an inject
592
- // callback is the two-generation accident this family keeps re-learning), each is
593
- // wrapped on its own so one unknown slot name cannot take the rest down, and an inject
594
- // into a slot the host does not declare simply idles - an undischarged wait never
595
- // blocks the client half.
596
- safe("plugins.bundle.config", () => {
597
- ctx.slots.inject(
598
- "plugins.bundle.config",
599
- () => ctx.slots.register({ name: "plugins.bundle.config", key: "dsh-bash-terminal-ts", locale: SETTINGS_NS, inject: () => ({}) }, SettingsBody),
600
- "bash-terminal: bundle config card",
601
- );
602
- });
603
- safe("settings.plugin.item", () => {
604
- ctx.slots.inject(
605
- "settings.plugin.item",
606
- () => ctx.slots.register({ name: "settings.plugin.item", key: SETTINGS_NS, locale: SETTINGS_NS, inject: () => ({}) }, SettingsBody),
607
- "bash-terminal: legacy plugin settings card",
608
- );
609
- });
610
- safe("settings.section", () => {
611
- ctx.slots.inject(
612
- "settings.section",
613
- function* () {
614
- // Unconditional since the family tab was dropped: this plugin owns a nav row,
615
- // so it must not depend on another plugin's container existing. The register
616
- // still happens at the declaration event (the generator runs when the host
617
- // declares the slot), which is what kept the old probe honest about bundle order.
618
- yield ctx.slots.register(
619
- {
620
- name: "settings.section",
621
- id: "bash-terminal",
622
- order: 45,
623
- label: () => translate("shell.title"),
624
- locale: SETTINGS_NS,
625
- inject: () => ({}),
626
- },
627
- SettingsBody,
628
- );
629
- },
630
- "bash-terminal: own settings section",
631
- );
632
- });
633
- safe("shell.overlay", () => {
634
- // Registered always, rendered only on the two lines with no settings page (the
635
- // component itself returns null). Registering conditionally would mean deciding at
636
- // apply time, before the host's probe has answered.
637
- ctx.slots.inject(
638
- "shell.overlay",
639
- () => ctx.slots.register({ name: "shell.overlay", id: "bash-terminal-settings" }, SettingsOverlayEntry),
640
- "bash-terminal: last-resort panel for hosts with no settings page",
641
- );
642
- });
643
- // The multi-shell bottom tab. Reached through `ctx.inject` rather than a one-shot
644
- // `ctx.get`: reading once would make this depend on dsh-better-sidebar's client
645
- // happening to run first in the bundle order, and a silently missing tab is exactly
646
- // the failure nobody notices until it is not there. `inject` fires when the service
647
- // arrives; if that plugin is not installed the callback simply never runs - which is
648
- // also why `betterSidebar` stays out of the declared `inject` list: without it this
649
- // plugin's settings row and terminal shim must still load.
650
- let tabRegistered = false;
651
- const registerMultiShellTab = (service: BetterSidebarService | undefined): void => {
652
- if (service?.registerTab === undefined || tabRegistered) return;
653
- tabRegistered = true;
654
- ctx.effect(
655
- () =>
656
- service.registerTab({
657
- id: "dsh-bash-terminal-ts:multi",
658
- title: () => translate("tab.title"),
659
- description: () => translate("tab.description"),
660
- // Bottom workbench only: without this the type also becomes a capsule in
661
- // DSH's native right sidebar, i.e. a second "Terminal" next to the host's.
662
- bottomOnly: true,
663
- order: 41,
664
- single: false,
665
- // Reads the cached master switch: the + menu asks synchronously, and a
666
- // greyed-out entry is a far better answer than a tab that refuses to open.
667
- available: () => bottomTerminalEnabled,
668
- component: (props: unknown) => <MultiShellTerminal {...(props as object)} />,
669
- }),
670
- "bash-terminal: multi-shell bottom tab",
671
- );
672
- };
673
- safe("betterSidebar.registerTab", () => {
674
- // Arrival-driven: dsh-better-sidebar's client may run after ours, and a one-shot
675
- // read would then leave the tab silently absent.
676
- if (typeof ctx.inject === "function") {
677
- ctx.inject(["betterSidebar"], (arrived) => registerMultiShellTab(arrived.betterSidebar));
678
- }
679
- // Soft read for the case where the service is already published. `ctx.get` is the
680
- // ONLY legal way to look at an undeclared service: the client context is a Proxy
681
- // and `ctx.betterSidebar` throws "cannot get property \"betterSidebar\" without
682
- // inject" (measured on 0.2.0-rc.2), which used to kill this whole block.
683
- registerMultiShellTab(ctx.get?.("betterSidebar") as BetterSidebarService | undefined);
684
- });
685
- }
1
+ // dsh-bash-terminal-ts client plugin (compat-legacy): a "Default terminal"
2
+ // preference row plus the bottom-terminal shell section, surfaced on the bundle
3
+ // detail card and on this plugin's OWN top-level settings section (it left the
4
+ // dsh-family tab in 2026-10-14 — it keeps a first-class nav row, so it no longer
5
+ // needs the family container), with a shell.overlay floating-gear fallback for
6
+ // hosts without any settings surface (0.1.0/0.1.1).
7
+ //
8
+ // compat-legacy rewiring vs upstream 0.7.1:
9
+ // - no @deepseek-ai/dsh-client-store / dsh-client-ui-primitives requires:
10
+ // 0.1.0/0.1.1 have no browser module table and 0.1.2 is unverified; the
11
+ // row reads/writes through the host config bridge (GET/POST
12
+ // /api/bash-terminal/config) and the terminal through /api/bash-terminal/terminals,
13
+ // both of which work on every line.
14
+ // - ui-primitives Menu/Icon replaced by a native select (same capsule CSS).
15
+ // - every surface registration is independently guarded (one unknown slot
16
+ // name on one line must not take down the rest).
17
+ //
18
+ // 0.8.0 adds two surfaces and removes one idea:
19
+ // - the shell activation section (Git Bash / MSYS2 / WSL switches with a
20
+ // per-row availability badge, and a default-shell choice restricted to the
21
+ // activated-and-available set), all state coming from the HOST's catalog so the
22
+ // browser never decides twice;
23
+ // - a bottom-dock tab of our own (`ctx.betterSidebar.registerTab`, bottomOnly), which
24
+ // is what makes Git Bash and MSYS2 reachable side by side - the host's own terminal
25
+ // menu de-duplicates shells by executable file name and both are `bash.exe`;
26
+ // - NO `ctx.provide('webTerminals')`. That was the bridge plugin's approach and it is
27
+ // fatal on any host that ships its terminal controller: see the webTerminals block
28
+ // near the bottom of this file.
29
+
30
+ import { useEffect, useState } from "react";
31
+ import { setTranslator, tr as translate } from "./browser-i18n";
32
+ import { dictionaries } from "./locales";
33
+ import { BridgeTerminals } from "./webterminals/browser/bridge";
34
+ import { looksLikeTerminals } from "./webterminals/browser/face";
35
+ import { MultiShellTerminal } from "./webterminals/browser/tab";
36
+ import { ShellPicker } from "./webterminals/browser/shell-picker";
37
+ import { switchableRows } from "./webterminals/browser/xterm";
38
+ import { post, readConfig, readLegacyConfig, writeDefaultShell, writeLegacyDefault } from "./webterminals/browser/api";
39
+ import type { CatalogEntry, ConfigSnapshot } from "./webterminals/browser/api";
40
+
41
+ const SETTINGS_NS = "settings.bash-terminal";
42
+ const SHELLS = ["powershell", "gitbash", "msys2", "wsl", "payload", "niu"] as const;
43
+
44
+ // Injected once when the browser loads the bundle (node tests guard on document).
45
+ const ROW_CSS =
46
+ ".btRow{border-bottom:1px solid var(--dsw-alias-border-l2);align-items:center;gap:8px;padding:16px 0;display:flex}.btRowText{flex-direction:column;flex:1;gap:4px;min-width:0;padding-right:48px;display:flex}.btTitle{color:var(--dsw-alias-label-primary);font-size:14px;font-weight:400;line-height:22px}.btDesc{color:var(--dsw-alias-label-tertiary);font-size:12px;font-weight:400;line-height:18px}.btSelector{background:var(--dsw-alias-bg-module-platform);height:36px;font:inherit;color:var(--dsw-alias-label-primary);cursor:pointer;border:none;border-radius:18px;align-items:center;gap:12px;padding:0 14px;font-size:14px;line-height:22px;display:inline-flex}.btSelector:hover{background:var(--dsw-alias-interactive-bg-hover)}.btGear{position:fixed;right:16px;bottom:110px;z-index:10000;width:40px;height:40px;border-radius:50%;border:1px solid rgba(127,127,127,.4);background:rgba(30,30,32,.85);color:inherit;cursor:pointer;font-size:17px;box-shadow:0 4px 16px rgba(0,0,0,.35)}.btOverlay{position:fixed;inset:0;z-index:10000;background:rgba(0,0,0,.45)}.btPanel{position:fixed;top:6vh;left:50%;transform:translateX(-50%);width:min(760px,92vw);max-height:84vh;overflow-y:auto;z-index:10001;background:var(--dsw-alias-bg-module-platform,rgba(30,30,32,.92));border:1px solid var(--dsw-alias-border-l2,rgba(127,127,127,.3));border-radius:14px;padding:20px;color:var(--dsw-alias-label-primary)}.btBadge{border-radius:10px;padding:2px 8px;font-size:11px;line-height:16px;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-tertiary);white-space:nowrap}.btBadgeOk{color:var(--dsw-alias-label-primary)}.btNotice{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px;padding:8px 0}.btWarn{color:var(--dsw-status-warning-default,#b8860b)}.btRowSwitch{padding-right:0}.btSwitch{width:40px;height:24px;border-radius:12px;border:none;cursor:pointer;background:var(--dsw-alias-bg-module-platform);position:relative;flex:none;transition:background .15s ease;box-shadow:inset 0 0 0 1px var(--dsw-alias-border-l2)}.btSwitch::after{content:'';position:absolute;top:3px;left:3px;width:18px;height:18px;border-radius:50%;background:var(--dsw-alias-label-tertiary);transition:transform .15s ease,background .15s ease}.btSwitchOn{background:var(--dsw-alias-interactive-brand,#2f6fed)}.btSwitchOn::after{transform:translateX(16px);background:#fff}.btSwitch:disabled{cursor:not-allowed;opacity:.4}.btSwitch:disabled::after{background:var(--dsw-alias-label-quaternary,#8a8a8a)}.btInput{background:var(--dsw-alias-bg-module-platform);height:32px;border:none;border-radius:8px;color:var(--dsw-alias-label-primary);padding:0 10px;font:inherit;min-width:0;flex:1}.btPick{position:relative;display:inline-block}.btPickBtn{gap:6px}.btPickSm{height:28px;padding:0 10px;border-radius:14px;font-size:12px;line-height:18px}.btPickBtn:disabled{opacity:.4;cursor:not-allowed}.btPickText{max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.btPickCaret{color:var(--dsw-alias-label-tertiary);font-size:10px;line-height:1}.btPickList{position:absolute;z-index:1000;top:calc(100% + 4px);left:0;min-width:100%;max-height:260px;overflow-y:auto;padding:4px;border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-overlay);box-shadow:0 8px 24px rgba(0,0,0,.28)}.btPickOpt{padding:6px 10px;font-size:12px;line-height:18px;border-radius:6px;color:var(--dsw-alias-label-primary);cursor:pointer;white-space:nowrap}.btPickOpt:hover{background:var(--dsw-alias-interactive-bg-hover)}.btPickOptOn{color:var(--dsw-alias-interactive-brand);font-weight:600}";
47
+ if (typeof document !== "undefined" && document.querySelector('style[data-plugin-css="bash-terminal-row"]') === null) {
48
+ const tag = document.createElement("style");
49
+ tag.dataset.plugin = "dsh-bash-terminal-ts";
50
+ tag.dataset.pluginCss = "bash-terminal-row";
51
+ tag.textContent = ROW_CSS;
52
+ document.head.appendChild(tag);
53
+ }
54
+
55
+ /**
56
+ * Whether the host itself owns `webTerminals` (the normal case on a DSH build that
57
+ * mounts its terminal controller). Set once by `apply()`; the dock section states it,
58
+ * because without that line a user cannot tell why the official terminal row and this
59
+ * plugin's coexist - or which one their switches are affecting.
60
+ *
61
+ * A getter rather than a cached boolean: the controller may activate after our apply
62
+ * runs, and a snapshot taken at apply time would be a permanent false negative. Every
63
+ * render asks again, so the notice cannot go stale.
64
+ */
65
+ let hostOwnsTerminals: () => boolean = () => false;
66
+
67
+ /**
68
+ * Claim `webTerminals` for dsh-better-sidebar's OFFICIAL bottom terminal row - the one
69
+ * thing this plugin can only do on a host that has no terminal controller. Returns what
70
+ * actually happened so the settings row can say it, because the honest answer depends on
71
+ * a live read of the service, not on the switch's own value.
72
+ *
73
+ * Replacing this stub is how `apply()` hands the component the real context. It stays a
74
+ * function rather than a `ctx` global so the component never has to know that the apply
75
+ * context is a Proxy which throws on undeclared property reads.
76
+ */
77
+ let tryPublishShim: () => "published" | "host-provides" = () => "host-provides";
78
+
79
+ /** The published instance, kept so a later disable can dispose it. */
80
+ let shimInstance: BridgeTerminals | undefined;
81
+
82
+ /**
83
+ * Read the current shell and, when the terminal route answers, its catalog.
84
+ * The op route is preferred (it carries the catalog and validates choices); the
85
+ * legacy bridge is the fallback so the row still works on a host where only the
86
+ * preference channel exists.
87
+ */
88
+ async function bridgeConfig(): Promise<ConfigSnapshot | null> {
89
+ try {
90
+ return await readConfig();
91
+ } catch {
92
+ return await readLegacyConfig();
93
+ }
94
+ }
95
+
96
+ /** The catalog if the terminal routes answered, else null (the old bridge shape). */
97
+ function catalogOf(snapshot: ConfigSnapshot | null | undefined): CatalogEntry[] | null {
98
+ if (!Array.isArray(snapshot?.catalog)) return null;
99
+ return snapshot.catalog as CatalogEntry[];
100
+ }
101
+
102
+ /** The availability badge for one catalog row. */
103
+ function badgeKey(row: CatalogEntry): string {
104
+ // The floor row gets its own word: the lock EXPLANATION belongs in the row's
105
+ // description, and putting it in both places reads as a rendering bug.
106
+ if (!row.togglable) return "dock.state.floor";
107
+ if (row.available) return "dock.state.available";
108
+ return row.reason === "no-distro"
109
+ ? "dock.state.noDistro"
110
+ : row.reason === "launcher-only"
111
+ ? "dock.state.launcherOnly"
112
+ : row.reason === "wsl-preferred"
113
+ ? "dock.state.wslPreferred"
114
+ : "dock.state.notInstalled";
115
+ }
116
+
117
+ /**
118
+ * Options for the default-terminal dropdown. The host's "default" write is
119
+ * validated against activated+available catalog rows, so the picker must offer
120
+ * exactly that set (powershell included: it is the floor and always on). A
121
+ * stored value outside the set is appended - the UI shows what IS chosen, not
122
+ * only what could be, and the host still refuses to re-write it.
123
+ */
124
+ function dropdownRows(snapshot: ConfigSnapshot | null | undefined, chosen: string): { id: string; label: string }[] {
125
+ const all = SHELLS.map((id) => ({ id, label: translate("shell." + id) }));
126
+ const rows = catalogOf(snapshot);
127
+ if (rows === null) return all;
128
+ const usable = rows
129
+ .filter((row) => row.activated && row.available)
130
+ .map((row) => ({ id: row.id, label: translate("shell." + row.id) }));
131
+ if (chosen.length > 0 && !usable.some((row) => row.id === chosen)) {
132
+ const extra = all.find((row) => row.id === chosen);
133
+ if (extra !== undefined) usable.push(extra);
134
+ }
135
+ return usable;
136
+ }
137
+
138
+ /** 默认终端选择行:读写全部走宿主 bridge(六线统一)。 */
139
+ function ShellPreferenceRow({ snapshot }: { snapshot?: ConfigSnapshot | null }) {
140
+ const [shell, setShell] = useState("powershell");
141
+ const [snap, setSnap] = useState<ConfigSnapshot | null>(snapshot ?? null);
142
+ const [status, setStatus] = useState<"loading" | "ready" | "unavailable">("loading");
143
+ useEffect(() => {
144
+ let alive = true;
145
+ const load = async (): Promise<void> => {
146
+ const v = snapshot ?? (await bridgeConfig());
147
+ if (!alive) return;
148
+ if (v && v.defaultShell) {
149
+ setShell(v.defaultShell);
150
+ setSnap(v);
151
+ setStatus("ready");
152
+ } else {
153
+ setStatus("unavailable");
154
+ }
155
+ };
156
+ void load();
157
+ return () => {
158
+ alive = false;
159
+ };
160
+ }, [snapshot]);
161
+ const change = (value: string): void => {
162
+ setShell(value);
163
+ // Validated write first; the legacy channel only if the op route is absent.
164
+ void writeDefaultShell(value).catch(async () => {
165
+ try {
166
+ await writeLegacyDefault(value);
167
+ } catch {
168
+ /* the row keeps its optimistic value; the next read reconciles */
169
+ }
170
+ });
171
+ };
172
+ if (status === "unavailable") {
173
+ return (
174
+ <div className="btRow">
175
+ <div className="btRowText">
176
+ <div className="btTitle">{translate("shell.title")}</div>
177
+ <div className="btDesc">{translate("shell.unavailable")}</div>
178
+ </div>
179
+ </div>
180
+ );
181
+ }
182
+ return (
183
+ <div className="btRow">
184
+ <div className="btRowText">
185
+ <div className="btTitle">{translate("shell.title")}</div>
186
+ <div className="btDesc">{translate("shell.description")}</div>
187
+ </div>
188
+ <ShellPicker
189
+ rows={dropdownRows(snap, shell)}
190
+ value={shell}
191
+ onChange={(next) => change(next)}
192
+ />
193
+ </div>
194
+ );
195
+ }
196
+
197
+ /**
198
+ * Whether the master switch is on, as last seen by the settings row. The bottom tab's
199
+ * `available()` is synchronous, so it reads this cache instead of fetching: the
200
+ * section refreshes on mount and after every write, and the tab re-reads the catalog
201
+ * itself before allocating, so a stale value here can only grey out a menu entry.
202
+ */
203
+ let bottomTerminalEnabled = true;
204
+
205
+ /**
206
+ * The bottom-terminal section: a MASTER switch, then one child switch per shell the
207
+ * machine actually has.
208
+ *
209
+ * Two levels because the two decisions are different in kind: whether this plugin
210
+ * offers a terminal at all, versus which shells it may start. And every state string
211
+ * comes from the host's catalog - the browser probes nothing, because two discovery
212
+ * implementations drift (that is how an MSYS2 `bash.exe` ended up labelled "Git Bash"
213
+ * in the sibling plugin).
214
+ */
215
+ function ShellDockSection() {
216
+ const [snapshot, setSnapshot] = useState<ConfigSnapshot | null>(null);
217
+ const [pending, setPending] = useState(false);
218
+ const [error, setError] = useState("");
219
+
220
+ /** Read the catalog once, reporting an absent route as an error rather than a blank. */
221
+ const reload = (): void => {
222
+ bridgeConfig().then((v) => {
223
+ setSnapshot(v);
224
+ if (v === null) setError("no-route");
225
+ else {
226
+ bottomTerminalEnabled = v.enabled !== false;
227
+ hostSettingsSurface = v.settingsSurface ?? "unknown";
228
+ }
229
+ });
230
+ };
231
+ useEffect(() => {
232
+ // The read is a `.then`, not an awaited body: the effect itself must not set
233
+ // state synchronously (the host's own hook lint forbids it, and a synchronous
234
+ // first paint would flash the unmounted state).
235
+ reload();
236
+ }, []);
237
+
238
+ const rows = catalogOf(snapshot);
239
+ const [shimNote, setShimNote] = useState("");
240
+ /**
241
+ * Flip the official-row opt-in. The config write comes first (so the choice survives a
242
+ * restart), then - only when turning ON - a live check of the service: if the host (or
243
+ * a previous activation) already publishes `webTerminals`, we must not add a second
244
+ * provider, because cordis refuses it and the loser's entry fails.
245
+ */
246
+ const writeShim = async (next: boolean): Promise<void> => {
247
+ setPending(true);
248
+ setError("");
249
+ try {
250
+ const v = await post<ConfigSnapshot>({ op: "shim", shim: next });
251
+ setSnapshot(v);
252
+ setShimNote(next && v.shimOfficialTerminal === true ? tryPublishShim() : "");
253
+ } catch (e) {
254
+ setError(e instanceof Error ? e.message : String(e));
255
+ } finally {
256
+ setPending(false);
257
+ }
258
+ };
259
+ const write = async (body: Record<string, unknown>): Promise<void> => {
260
+ setPending(true);
261
+ setError("");
262
+ try {
263
+ const v = await post<ConfigSnapshot>(body);
264
+ setSnapshot(v);
265
+ if (typeof v.enabled === "boolean") bottomTerminalEnabled = v.enabled;
266
+ hostSettingsSurface = v.settingsSurface ?? hostSettingsSurface;
267
+ } catch (e) {
268
+ setError(e instanceof Error ? e.message : String(e));
269
+ } finally {
270
+ setPending(false);
271
+ }
272
+ };
273
+
274
+ if (rows === null) {
275
+ // The terminal route never answered (the legacy bridge may have). Say so and
276
+ // offer a re-check: silence here is the "settings row exists but does nothing"
277
+ // failure mode.
278
+ return (
279
+ <div className="btNotice">
280
+ {translate("dock.unavailable.notInstalled")}{" "}
281
+ <button type="button" className="btSelector" style={{ height: 28, fontSize: 12 }} onClick={() => reload()}>
282
+ {translate("dock.refresh")}
283
+ </button>
284
+ </div>
285
+ );
286
+ }
287
+
288
+ const enabled = snapshot?.enabled !== false;
289
+ const usable = rows.filter((row) => row.activated && row.available);
290
+ // One source of truth for "this row deserves a switch", shared with the tab's own
291
+ // picker and asserted in test/browser.mjs (a render assertion cannot reach it, since
292
+ // the catalog arrives in an effect).
293
+ const switchable = new Set(switchableRows(rows).map((row) => row.id));
294
+ const unavailableReason = snapshot?.unavailable ?? "ok";
295
+ const notice = snapshot?.effective;
296
+ return (
297
+ <div>
298
+ <div className="btRow" style={{ borderBottom: "none", paddingBottom: 4 }}>
299
+ <div className="btRowText">
300
+ <div className="btTitle">{translate("dock.title")}</div>
301
+ <div className="btDesc">{translate("dock.hint")}</div>
302
+ </div>
303
+ </div>
304
+ {unavailableReason !== "ok" && unavailableReason !== "disabled" ? (
305
+ <div className="btNotice btWarn">
306
+ {unavailableReason === "no-pty-backend"
307
+ ? translate("dock.unavailable.noPty")
308
+ : unavailableReason === "no-websocket-route"
309
+ ? translate("dock.unavailable.noSocket")
310
+ : translate("dock.unavailable.notInstalled")}
311
+ </div>
312
+ ) : null}
313
+ {/* Which terminal surface the user is looking at: the host's own, or ours. */}
314
+ {hostOwnsTerminals() ? <div className="btNotice">{translate("dock.hostProvided")}</div> : null}
315
+ {/* ── level 1: the master switch ───────────────────────────────────── */}
316
+ <div className="btRow btRowSwitch">
317
+ <div className="btRowText">
318
+ <div className="btTitle">{translate("dock.enabled.title")}</div>
319
+ <div className="btDesc">{translate("dock.enabled.description")}</div>
320
+ </div>
321
+ <button
322
+ type="button"
323
+ className={"btSwitch" + (enabled ? " btSwitchOn" : "")}
324
+ disabled={pending}
325
+ aria-pressed={enabled}
326
+ onClick={() => void write({ op: "enabled", enabled: !enabled })}
327
+ />
328
+ </div>
329
+ {/* ── level 2: one switch per shell the machine actually has ───────── */}
330
+ {!enabled ? (
331
+ <div className="btNotice">{translate("dock.enabled.off")}</div>
332
+ ) : (
333
+ <>
334
+ {rows.map((row) => (
335
+ <div className="btRow btRowSwitch" key={row.id}>
336
+ <div className="btRowText">
337
+ <div className="btTitle">{row.label}</div>
338
+ {/* The path when a shell was found, the lock rule for the floor, and
339
+ the reason when there is nothing to switch on. */}
340
+ <div className="btDesc">
341
+ {!row.togglable
342
+ ? translate("dock.powershell.locked")
343
+ : row.available
344
+ ? (row.path ?? translate("dock.state.notInstalled"))
345
+ : translate(badgeKey(row))}
346
+ </div>
347
+ </div>
348
+ <span className={"btBadge" + (row.available ? " btBadgeOk" : "")}>{translate(badgeKey(row))}</span>
349
+ {/* No control where a choice cannot be honoured: an absent shell gets a
350
+ reason, not a switch that would do nothing. */}
351
+ {switchable.has(row.id) ? (
352
+ <button
353
+ type="button"
354
+ className={"btSwitch" + (row.activated ? " btSwitchOn" : "")}
355
+ disabled={pending}
356
+ aria-pressed={row.activated}
357
+ onClick={() => void write({ op: "switches", switches: { [row.id]: !row.activated } })}
358
+ />
359
+ ) : null}
360
+ </div>
361
+ ))}
362
+ <div className="btRow btRowSwitch">
363
+ <div className="btRowText">
364
+ <div className="btTitle">{translate("dock.defaultChoice")}</div>
365
+ <div className="btDesc">{translate("shell.description")}</div>
366
+ </div>
367
+ <ShellPicker
368
+ rows={usable.map((row) => ({ id: row.id, label: row.label }))}
369
+ value={usable.some((row) => row.id === (snapshot?.defaultShell ?? "")) ? (snapshot?.defaultShell ?? usable[0]?.id ?? "powershell") : (usable[0]?.id ?? "powershell")}
370
+ onChange={(next) => void write({ op: "default", defaultShell: next })}
371
+ />
372
+ </div>
373
+ <div className="btRow">
374
+ <div className="btRowText">
375
+ <div className="btTitle">{translate("dock.wslDistro")}</div>
376
+ </div>
377
+ <input
378
+ className="btInput"
379
+ type="text"
380
+ defaultValue={snapshot?.wslDistro ?? ""}
381
+ key={snapshot?.wslDistro ?? ""}
382
+ disabled={pending}
383
+ onBlur={(e) => {
384
+ const value = (e.target as HTMLInputElement).value.trim();
385
+ void write({ op: "switches", switches: {}, wslDistro: value });
386
+ }}
387
+ />
388
+ </div>
389
+ {notice?.floor === true ? (
390
+ <div className="btNotice btWarn">{translate("dock.floor.notice", { to: notice.id })}</div>
391
+ ) : notice?.fellBack === true ? (
392
+ <div className="btNotice btWarn">{translate("dock.fallback.notice", { from: notice.from ?? "", to: notice.id })}</div>
393
+ ) : null}
394
+ {typeof snapshot?.terminals === "number" && snapshot.terminals > 0 ? (
395
+ <div className="btNotice">{translate("dock.terminals", { count: snapshot.terminals })}</div>
396
+ ) : null}
397
+ {/* ── the official-row opt-in (off by default; see the description) ──── */}
398
+ <div className="btRow btRowSwitch">
399
+ <div className="btRowText">
400
+ <div className="btTitle">{translate("dock.shim.title")}</div>
401
+ <div className="btDesc">{translate("dock.shim.description")}</div>
402
+ </div>
403
+ <button
404
+ type="button"
405
+ className={"btSwitch" + (snapshot?.shimOfficialTerminal === true ? " btSwitchOn" : "")}
406
+ disabled={pending}
407
+ aria-pressed={snapshot?.shimOfficialTerminal === true}
408
+ onClick={() => void writeShim(snapshot?.shimOfficialTerminal !== true)}
409
+ />
410
+ </div>
411
+ {shimNote === "published" ? <div className="btNotice">{translate("dock.shim.published")}</div> : null}
412
+ {shimNote === "host-provides" ? <div className="btNotice btWarn">{translate("dock.shim.hostProvides")}</div> : null}
413
+ </>
414
+ )}
415
+ {pending ? <div className="btNotice">{translate("dock.applying")}</div> : null}
416
+ {error !== "" && error !== "no-route" ? (
417
+ <div className="btNotice btWarn">{translate("dock.failed", { message: error })}</div>
418
+ ) : null}
419
+ </div>
420
+ );
421
+ }
422
+
423
+ /** dsh-better-sidebar's extension service - optional, because that plugin may be absent. */
424
+ interface BetterSidebarService {
425
+ registerTab(descriptor: Record<string, unknown>): () => void;
426
+ }
427
+
428
+ interface ClientContext {
429
+ effect(fn: () => unknown, name?: string): unknown;
430
+ /** Soft read: the ONLY legal way to look at a service missing from `inject`. */
431
+ get?(name: string): unknown;
432
+ /**
433
+ * Publish a service. Exactly one call site, and it is gated: the official-row opt-in
434
+ * re-reads `webTerminals` through `get` first, because providing a name the host's own
435
+ * controller already claimed fails THAT entry (findings D15-1). Never call this from
436
+ * `apply()` unconditionally.
437
+ */
438
+ provide?(name: string, service: unknown): unknown;
439
+ locale: {
440
+ register(ns: string, dicts: Record<string, Record<string, string>>): unknown;
441
+ bind?(ns: string): (key: string, params?: Record<string, string | number>) => string;
442
+ };
443
+ slots: {
444
+ inject(slot: string, fn: () => unknown, name?: string): void;
445
+ register(options: Record<string, unknown>, Component: unknown): Record<string, unknown>;
446
+ /** Read the ledger of a slot: the only way to ask whether another plugin claimed it. */
447
+ entries?(slot: string): { options: { id?: string; key?: string } }[];
448
+ };
449
+ /**
450
+ * Service-arrival callback. Optional because the oldest hosts have no browser module
451
+ * table at all; where it exists it is the reliable way to find `betterSidebar`.
452
+ *
453
+ * Note what is NOT here: a `betterSidebar` property. Cordis exposes requested services
454
+ * as properties on the ARRIVAL context only - on the apply context the same read
455
+ * throws "cannot get property 'betterSidebar' without inject". Keeping the key out of
456
+ * this type is what turns that runtime trap into a compile error.
457
+ */
458
+ inject?(deps: string[], callback: (arrived: { betterSidebar?: BetterSidebarService }) => void): void;
459
+ }
460
+
461
+ /**
462
+ * The settings body. ONE component, rendered by whichever surface carries this plugin's
463
+ * controls - the bundle detail card, the family tab and the fallback section must not be
464
+ * three copies that can drift (the family contract's "one source of truth" rule).
465
+ */
466
+ function SettingsBody() {
467
+ return (
468
+ <>
469
+ <ShellPreferenceRow />
470
+ <ShellDockSection />
471
+ </>
472
+ );
473
+ }
474
+
475
+ /**
476
+ * Whether the host renders a settings page, as the host half reported it (`page` /
477
+ * `none` / `unknown`). Only `none` - 0.1.0 and 0.1.1, which declare the `settings.*` slot
478
+ * map but ship no page that renders it - unlocks the floating panel below.
479
+ */
480
+ let hostSettingsSurface = "unknown";
481
+
482
+ /**
483
+ * The 0.1.0/0.1.1 way in, and nothing more.
484
+ *
485
+ * Those two lines declare the whole `settings.*` slot map but ship no settings page, so a
486
+ * registered card there is a card nobody can open - the only surface that renders is a
487
+ * shell-level overlay the plugin brings itself. Everywhere else this returns null, which
488
+ * is why the arm can be registered unconditionally at apply time (the family contract's
489
+ * rule) while the DECISION stays data-driven: the host half probes the first-generation
490
+ * seam and the row obeys the answer.
491
+ */
492
+ function SettingsOverlayEntry() {
493
+ const [open, setOpen] = useState(false);
494
+ if (hostSettingsSurface !== "none") return null;
495
+ return (
496
+ <div style={{ position: "fixed", right: "16px", bottom: "110px", zIndex: 10000 }}>
497
+ {open ? <div className="btOverlay" onClick={() => setOpen(false)} /> : null}
498
+ {open ? (
499
+ <div className="btPanel">
500
+ <button
501
+ type="button"
502
+ className="btSelector"
503
+ style={{ float: "right", height: "30px", fontSize: "12px", marginBottom: "8px" }}
504
+ onClick={() => setOpen(false)}
505
+ >
506
+ ✕
507
+ </button>
508
+ <SettingsBody />
509
+ </div>
510
+ ) : null}
511
+ <button type="button" className="btGear" title={translate("shell.title")} onClick={() => setOpen(!open)}>
512
+ ⚙
513
+ </button>
514
+ </div>
515
+ );
516
+ }
517
+
518
+ /**
519
+ * The services this client half consumes. Declared, not guessed: the loader hands
520
+ * `apply` a context carrying exactly these.
521
+ *
522
+ * What the declaration list really controls (learned by being wrong about it on
523
+ * 0.2.0-rc.2): the context is a Proxy, and `ctx.someService` THROWS
524
+ * "cannot get property 'someService' without inject" for any name absent from this
525
+ * list. `ctx.get(name)` and `ctx.inject(names, cb)` are the two legal ways to reach an
526
+ * undeclared or optional service - and optional is exactly what `betterSidebar` and
527
+ * `webTerminals` are, so neither may ever appear as a property read.
528
+ */
529
+ export const inject: string[] = ["slots", "locale"];
530
+
531
+ export function apply(ctx: ClientContext): void {
532
+ const safe = (tag: string, fn: () => void): void => {
533
+ try {
534
+ fn();
535
+ } catch (e) {
536
+ console.warn(`[dsh-bash-terminal-ts] client surface '${tag}' failed:`, e);
537
+ }
538
+ };
539
+ safe("locale", () => {
540
+ ctx.effect(() => ctx.locale.register(SETTINGS_NS, dictionaries), "bash-terminal: settings dictionaries");
541
+ // bind() exists on 0.1.2+; the oldest lines have no locale service at all, and
542
+ // the module fallback (zh) is then the honest answer.
543
+ const bound = ctx.locale.bind?.call(ctx.locale, SETTINGS_NS);
544
+ if (typeof bound === "function") setTranslator(bound);
545
+ });
546
+ /**
547
+ * This plugin NEVER provides `webTerminals`. Measured on 0.2.0-rc.2: the host's
548
+ * `dsh-api-terminal-controller` provides the same service name and its `provide`
549
+ * is unguarded, so whichever entry wins the boot race decides who dies - and ours
550
+ * won, taking down the first-party terminal and the whole web boot with
551
+ * `service "webTerminals" has been registered`. The bottom-dock feature does not
552
+ * need the service either: this plugin ships its own tab, which works whether or
553
+ * not the host has a controller. All that is left here is the read that drives the
554
+ * notice above.
555
+ */
556
+ safe("webTerminals", () => {
557
+ hostOwnsTerminals = () => looksLikeTerminals(ctx.get?.("webTerminals"));
558
+ tryPublishShim = () => {
559
+ if (shimInstance !== undefined) return "published";
560
+ // The check is the whole point of making this opt-in: "the operator said so" is
561
+ // not evidence that the name is free, and taking it anyway would fail the host's
562
+ // own controller entry.
563
+ if (looksLikeTerminals(ctx.get?.("webTerminals"))) return "host-provides";
564
+ const terminals = new BridgeTerminals();
565
+ ctx.effect(() => () => {
566
+ terminals.disposeAll();
567
+ shimInstance = undefined;
568
+ }, "bash-terminal: official-row shim");
569
+ ctx.provide?.("webTerminals", terminals);
570
+ shimInstance = terminals;
571
+ return "published";
572
+ };
573
+ });
574
+ // ── settings surfaces ────────────────────────────────────────────────────────
575
+ //
576
+ // Two landing points plus a fallback that keeps the controls reachable when
577
+ // neither has a host:
578
+ //
579
+ // 1. the bundle detail page (`plugins.bundle.config`, keyed by the package name) -
580
+ // the host's own per-plugin configuration card, present on 0.1.7+/0.2.0; on
581
+ // 0.1.2/0.1.5 the era-equivalent dispatch is `settings.plugin.item`, keyed by the
582
+ // settings namespace, so both are declared;
583
+ // 2. this plugin's OWN top-level `settings.section` (id `bash-terminal`), registered
584
+ // unconditionally. It used to stand down while a `dsh-family` row existed and
585
+ // contribute a family tab instead; that coupling made the family container a
586
+ // single point of failure for these settings, and the tab is gone now (2026-10-14).
587
+ // Registering under our own id — never shadowing `dsh-family` — is what keeps the
588
+ // family contract intact: two nav rows, no double-rendered section.
589
+ // 3. `shell.overlay` for the lines with no settings page at all.
590
+ //
591
+ // Every arm is registered at apply-time top level (registering from inside an inject
592
+ // callback is the two-generation accident this family keeps re-learning), each is
593
+ // wrapped on its own so one unknown slot name cannot take the rest down, and an inject
594
+ // into a slot the host does not declare simply idles - an undischarged wait never
595
+ // blocks the client half.
596
+ safe("plugins.bundle.config", () => {
597
+ ctx.slots.inject(
598
+ "plugins.bundle.config",
599
+ () => ctx.slots.register({ name: "plugins.bundle.config", key: "dsh-bash-terminal-ts", locale: SETTINGS_NS, inject: () => ({}) }, SettingsBody),
600
+ "bash-terminal: bundle config card",
601
+ );
602
+ });
603
+ safe("settings.plugin.item", () => {
604
+ ctx.slots.inject(
605
+ "settings.plugin.item",
606
+ () => ctx.slots.register({ name: "settings.plugin.item", key: SETTINGS_NS, locale: SETTINGS_NS, inject: () => ({}) }, SettingsBody),
607
+ "bash-terminal: legacy plugin settings card",
608
+ );
609
+ });
610
+ safe("settings.section", () => {
611
+ ctx.slots.inject(
612
+ "settings.section",
613
+ function* () {
614
+ // Unconditional since the family tab was dropped: this plugin owns a nav row,
615
+ // so it must not depend on another plugin's container existing. The register
616
+ // still happens at the declaration event (the generator runs when the host
617
+ // declares the slot), which is what kept the old probe honest about bundle order.
618
+ yield ctx.slots.register(
619
+ {
620
+ name: "settings.section",
621
+ id: "bash-terminal",
622
+ order: 45,
623
+ label: () => translate("shell.title"),
624
+ locale: SETTINGS_NS,
625
+ inject: () => ({}),
626
+ },
627
+ SettingsBody,
628
+ );
629
+ },
630
+ "bash-terminal: own settings section",
631
+ );
632
+ });
633
+ safe("shell.overlay", () => {
634
+ // Registered always, rendered only on the two lines with no settings page (the
635
+ // component itself returns null). Registering conditionally would mean deciding at
636
+ // apply time, before the host's probe has answered.
637
+ ctx.slots.inject(
638
+ "shell.overlay",
639
+ () => ctx.slots.register({ name: "shell.overlay", id: "bash-terminal-settings" }, SettingsOverlayEntry),
640
+ "bash-terminal: last-resort panel for hosts with no settings page",
641
+ );
642
+ });
643
+ // The multi-shell bottom tab. Reached through `ctx.inject` rather than a one-shot
644
+ // `ctx.get`: reading once would make this depend on dsh-better-sidebar's client
645
+ // happening to run first in the bundle order, and a silently missing tab is exactly
646
+ // the failure nobody notices until it is not there. `inject` fires when the service
647
+ // arrives; if that plugin is not installed the callback simply never runs - which is
648
+ // also why `betterSidebar` stays out of the declared `inject` list: without it this
649
+ // plugin's settings row and terminal shim must still load.
650
+ let tabRegistered = false;
651
+ const registerMultiShellTab = (service: BetterSidebarService | undefined): void => {
652
+ if (service?.registerTab === undefined || tabRegistered) return;
653
+ tabRegistered = true;
654
+ ctx.effect(
655
+ () =>
656
+ service.registerTab({
657
+ id: "dsh-bash-terminal-ts:multi",
658
+ title: () => translate("tab.title"),
659
+ description: () => translate("tab.description"),
660
+ // Bottom workbench only: without this the type also becomes a capsule in
661
+ // DSH's native right sidebar, i.e. a second "Terminal" next to the host's.
662
+ bottomOnly: true,
663
+ order: 41,
664
+ single: false,
665
+ // Reads the cached master switch: the + menu asks synchronously, and a
666
+ // greyed-out entry is a far better answer than a tab that refuses to open.
667
+ available: () => bottomTerminalEnabled,
668
+ component: (props: unknown) => <MultiShellTerminal {...(props as object)} />,
669
+ }),
670
+ "bash-terminal: multi-shell bottom tab",
671
+ );
672
+ };
673
+ safe("betterSidebar.registerTab", () => {
674
+ // Arrival-driven: dsh-better-sidebar's client may run after ours, and a one-shot
675
+ // read would then leave the tab silently absent.
676
+ if (typeof ctx.inject === "function") {
677
+ ctx.inject(["betterSidebar"], (arrived) => registerMultiShellTab(arrived.betterSidebar));
678
+ }
679
+ // Soft read for the case where the service is already published. `ctx.get` is the
680
+ // ONLY legal way to look at an undeclared service: the client context is a Proxy
681
+ // and `ctx.betterSidebar` throws "cannot get property \"betterSidebar\" without
682
+ // inject" (measured on 0.2.0-rc.2), which used to kill this whole block.
683
+ registerMultiShellTab(ctx.get?.("betterSidebar") as BetterSidebarService | undefined);
684
+ });
685
+ }