dsh-hot-reload 0.1.4 → 0.2.0

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
@@ -3,6 +3,50 @@
3
3
  All notable changes to `dsh-hot-reload` are documented here. This project
4
4
  follows [semantic versioning](https://semver.org/).
5
5
 
6
+ ## 0.2.0
7
+
8
+ You can now see reload results without reading the logs. Config did not change:
9
+ `debounce` and `profileDir` are still the only keys. Detection and reloading did
10
+ not change either.
11
+
12
+ **New messages**
13
+
14
+ - **One terminal line for each reload that worked.** dsh never prints its log to
15
+ the terminal, so until now nothing this plugin wrote showed up there. A
16
+ successful reload now also writes one line. This works in every profile.
17
+ - **A short pop-up message in the dsh web app.** You get one when a reload works,
18
+ and one in every case that leaves the old code running: a reload that failed
19
+ and was rolled back, a plugin with no running copy, `dsh.hotReload: false`, and
20
+ missing loader internals. If one upgrade reloads several plugins, the messages
21
+ show one after another.
22
+ - The web part ships as `lib/client.js` (`exports["./client"]`, plus `dsh.client`
23
+ with `platform: "web"`) and attaches to the `shell.overlay` slot. It is written
24
+ by hand in the format the browser loader expects, so this package still has
25
+ **no build step** and **no new dependencies**. `react` and
26
+ `@deepseek-ai/dsh-client-ui-primitives` come from the web app's own modules.
27
+ - Messages travel over a `GET /dsh-hot-reload/events` route added to
28
+ `ctx.webServer`. Nothing is saved: if no browser is connected, the message is
29
+ gone. The log is still the lasting record.
30
+ - One `report()` call now writes the log line, the terminal line, and the browser
31
+ message from a single message string, so those surfaces cannot disagree.
32
+
33
+ **When parts are missing**
34
+
35
+ - The route is added through `ctx.inject(["webServer"], …)`. A top-level `inject`
36
+ would have made the whole plugin wait forever in a profile with no web server,
37
+ because cordis treats every injected name as required — `tui` would have
38
+ stopped reloading anything. A single `ctx.get` call would have been unreliable:
39
+ it only returns a service once that service is fully started, and the web
40
+ server starts later, after it opens its socket. It would also never recover if
41
+ the web server were replaced. `ctx.inject` only makes a small child part wait,
42
+ and it registers the route again each time the web server is replaced.
43
+ - A missing web server, a repeated route, a renamed slot, a browser module that
44
+ no longer loads, or a dsh build without `Toast` each cost you the pop-up only.
45
+ Reloading still works and the web app still starts.
46
+ - If the message channel cannot be reached at all, the browser half says so once
47
+ in the console instead of staying quiet. Otherwise a dead channel looks exactly
48
+ like "no reloads have happened yet".
49
+
6
50
  ## 0.1.4
7
51
 
8
52
  Two rounds of code-review fixes (engine + CI). No config or API changes.
@@ -93,11 +137,11 @@ Two rounds of code-review fixes (engine + CI). No config or API changes.
93
137
  skipped the release). E404 is detected structurally via `--json` rather than
94
138
  by grepping npm's error prose.
95
139
  - Concurrency is keyed per tag, so distinct releases never share a queue slot
96
- (a shared group could silently cancel a pending release's run). Because that
97
- allows two releases to publish concurrently, a post-publish step re-points
98
- `latest` at the highest published version `npm publish` sets `latest`
99
- unconditionally, so otherwise the run finishing last would win regardless of
100
- version order.
140
+ (a shared group could silently cancel a pending release's run). Two releases
141
+ cut within a couple of minutes can therefore publish concurrently, leaving
142
+ the `latest` dist-tag on whichever finished last; releases are cut one at a
143
+ time and the repair is a single `npm dist-tag add`, so this is accepted
144
+ rather than automated.
101
145
 
102
146
  ## 0.1.3
103
147
 
package/README.md CHANGED
@@ -42,6 +42,63 @@ Two cases produce no reload, by design:
42
42
  It **never restarts dsh for you** — restarting is left to you (and your
43
43
  supervisor, if any).
44
44
 
45
+ ## How you see what happened
46
+
47
+ The plugin writes every result to dsh's log. But dsh does not print its log to
48
+ your terminal, so those lines are easy to miss. Two extra places show you what
49
+ happened.
50
+
51
+ **1. One line in your terminal, for each reload that worked.** You get this in
52
+ every profile:
53
+
54
+ ```
55
+ dsh-hot-reload: hot-reloaded some-plugin@1.2.0 (1 module(s))
56
+ ```
57
+
58
+ **2. A short pop-up message in the dsh web app.** You get one when a reload
59
+ works. You also get one in every case where the new code did *not* load, so the
60
+ old code is still running:
61
+
62
+ - the reload failed, and the old version was put back
63
+ - the plugin has no running copy to swap out
64
+ - the plugin turned off hot reload with `dsh.hotReload: false`
65
+ - dsh did not provide the internal parts the reload needs
66
+
67
+ The message slides in, stays a few seconds, then fades out. If one upgrade
68
+ reloads several plugins, the messages line up and show one after another.
69
+
70
+ The web part only loads in a profile that runs a web server. It sends the
71
+ messages over `GET /dsh-hot-reload/events`. A profile with no web server, such
72
+ as `tui`, still gets the terminal line and the log.
73
+
74
+ Messages are not saved. If no browser tab is open when a reload happens, that
75
+ message is gone. The log still has the record.
76
+
77
+ ### If you want every line in your terminal
78
+
79
+ The terminal line above only covers reloads that worked. To see everything this
80
+ plugin writes to the log, including failures, add dsh's console logger to your
81
+ profile. It is a separate package:
82
+
83
+ ```sh
84
+ dsh plugin --profile web add @deepseek-ai/cordis-plugin-logger-console
85
+ ```
86
+
87
+ Then add a row for it in that profile's `cordis.patch.yml` and restart dsh:
88
+
89
+ ```yaml
90
+ - insert:
91
+ - id: logger-console
92
+ name: '@deepseek-ai/cordis-plugin-logger-console'
93
+ ```
94
+
95
+ This prints all dsh log lines, not only this plugin's.
96
+
97
+ > **Note for full-screen profiles.** The terminal line is written straight to the
98
+ > screen. In a profile that draws a full-screen interface, such as `tui`, the
99
+ > line can land in the middle of the drawing and make the screen look wrong. It
100
+ > looks wrong only until the screen is drawn again.
101
+
45
102
  ## Install
46
103
 
47
104
  ```sh
@@ -73,8 +130,26 @@ future dsh that changes any of them may require an update:
73
130
  | `entry.disabled` | skipping disabled rows (inherited getter) |
74
131
  | `entry.options.group` | skipping group container rows |
75
132
 
76
- It fails safe: if the internals it needs are missing, it degrades to reporting
77
- "restart needed" rather than breaking dsh.
133
+ The pop-up message in the web app (and only that part) also uses:
134
+
135
+ | dsh part | Used for |
136
+ |---|---|
137
+ | `ctx.webServer.register` | serving the message channel |
138
+ | `window.__ModuleLoader__` | loading the browser half |
139
+ | the `shell.overlay` slot | placing the message over the app |
140
+ | `Toast` from `@deepseek-ai/dsh-client-ui-primitives` | drawing it |
141
+
142
+ The plugin fails safe. If a part it needs is missing, it reports "restart needed"
143
+ instead of breaking dsh. The pop-up behaves the same way. A missing web server,
144
+ a browser module it cannot load, an unknown slot, a repeated registration, or a
145
+ dsh build with no `Toast` each cost you the pop-up only. Reloading still works,
146
+ and the web app still starts.
147
+
148
+ One exception: the browser half asks dsh for a service named `slots`. dsh's web
149
+ app refuses to start if any plugin never becomes ready. So if some future dsh
150
+ build had no `slots` service at all, this part would wait forever and show up in
151
+ dsh's start-up error list. Every other failure listed above is caught and simply
152
+ does nothing.
78
153
 
79
154
  ## Opting out
80
155
 
@@ -117,6 +192,11 @@ live fiber to swap). It does **not** detect *silent* leaks:
117
192
  [Compatibility](#compatibility). If they are unavailable (no
118
193
  `--expose-internals` and no `node-addon-require-builtin` addon), the plugin
119
194
  degrades to reporting "restart needed" for every change instead of reloading.
195
+ - The message channel (`GET /dsh-hot-reload/events`) has **no password check**,
196
+ the same as dsh's own `/plugins/events`. It sends plugin names and version
197
+ numbers. dsh already shows those through its plugin list, so this adds no new
198
+ secret. But if you bind dsh to `0.0.0.0`, count it as one more address that
199
+ anyone on your network can open.
120
200
 
121
201
  Scope note: this handles **upgrades of already-loaded plugins**. Installing a
122
202
  *brand-new* plugin is a separate concern (adding its row to `cordis.patch.yml`,
package/README.zh.md CHANGED
@@ -35,6 +35,57 @@ dsh 自带的热重载(`cordis-plugin-hmr`)刻意忽略 `node_modules`,所
35
35
 
36
36
  它**绝不会替你重启 dsh**——重启交给你(以及你的守护进程,如果有的话)。
37
37
 
38
+ ## 你如何知道发生了什么
39
+
40
+ 插件会把每个结果写进 dsh 的日志。但 dsh 不会把日志打印到你的终端,所以这些内容
41
+ 很容易被忽略。另有两个地方会告诉你发生了什么。
42
+
43
+ **1. 每次重载成功,在你的终端里输出一行。** 任意 profile 都有:
44
+
45
+ ```
46
+ dsh-hot-reload: hot-reloaded some-plugin@1.2.0 (1 module(s))
47
+ ```
48
+
49
+ **2. dsh web 应用里的一条短提示。** 重载成功时会出现一条。凡是新代码*没有*加载、
50
+ 旧代码仍在运行的情况,也都会出现一条:
51
+
52
+ - 重载失败,已换回旧版本
53
+ - 该插件没有正在运行的副本可供替换
54
+ - 该插件用 `dsh.hotReload: false` 关闭了热重载
55
+ - dsh 没有提供重载所需的内部接口
56
+
57
+ 提示会滑入,停留数秒,然后淡出。如果一次升级重载了多个插件,提示会排队逐条显示。
58
+
59
+ web 那一部分只在运行 web 服务器的 profile 中加载,并通过
60
+ `GET /dsh-hot-reload/events` 发送提示。没有 web 服务器的 profile(例如 `tui`)
61
+ 仍然有终端那一行和日志。
62
+
63
+ 提示不会被保存。如果重载发生时没有打开任何浏览器标签页,那条提示就没有了。
64
+ 日志里仍有记录。
65
+
66
+ ### 如果你想在终端里看到全部内容
67
+
68
+ 上面那一行只覆盖成功的重载。若想看到本插件写进日志的全部内容(包括失败),请把
69
+ dsh 的控制台日志插件加进你的 profile。它是一个独立的包:
70
+
71
+ ```sh
72
+ dsh plugin --profile web add @deepseek-ai/cordis-plugin-logger-console
73
+ ```
74
+
75
+ 然后在该 profile 的 `cordis.patch.yml` 中加入一行,并重启 dsh:
76
+
77
+ ```yaml
78
+ - insert:
79
+ - id: logger-console
80
+ name: '@deepseek-ai/cordis-plugin-logger-console'
81
+ ```
82
+
83
+ 这会打印 dsh 的所有日志,而不只是本插件的。
84
+
85
+ > **全屏界面 profile 的注意事项。** 终端那一行是直接写到屏幕上的。在绘制全屏
86
+ > 界面的 profile(例如 `tui`)中,这一行可能落在画面中间,让屏幕看起来乱掉。
87
+ > 这只会持续到屏幕下一次重绘为止。
88
+
38
89
  ## 安装
39
90
 
40
91
  ```sh
@@ -65,7 +116,23 @@ dsh plugin --profile web add some-plugin@newer # 自动热重载
65
116
  | `entry.disabled` | 跳过已禁用的行(继承式 getter) |
66
117
  | `entry.options.group` | 跳过 group 容器行 |
67
118
 
68
- 它是失败安全的:一旦所需内部不可用,会退化为报告“需要重启”,而不会弄坏 dsh。
119
+ web 应用里的提示(且仅这一部分)还用到:
120
+
121
+ | dsh 的部件 | 用途 |
122
+ |---|---|
123
+ | `ctx.webServer.register` | 提供提示通道 |
124
+ | `window.__ModuleLoader__` | 加载浏览器侧那一半 |
125
+ | `shell.overlay` 插槽 | 把提示放到应用之上 |
126
+ | `@deepseek-ai/dsh-client-ui-primitives` 的 `Toast` | 绘制提示 |
127
+
128
+ 本插件是失败安全的。若所需部件缺失,它会报告“需要重启”,而不会弄坏 dsh。提示
129
+ 也一样:缺少 web 服务器、浏览器模块加载不了、插槽名未知、重复注册、或 dsh 构建
130
+ 中没有 `Toast`,代价都只是没有提示。重载照常工作,web 应用也照常启动。
131
+
132
+ 有一个例外:浏览器侧那一半会向 dsh 索取名为 `slots` 的服务。只要有任何插件始终
133
+ 没有就绪,dsh 的 web 应用就会拒绝启动。所以,假如将来某个 dsh 构建完全没有
134
+ `slots` 服务,这一部分就会一直等待,并出现在 dsh 的启动错误列表里。上面列出的
135
+ 其他失败都会被捕获,只是什么都不做。
69
136
 
70
137
  ## 退出热重载(opt-out)
71
138
 
@@ -102,6 +169,10 @@ dsh plugin --profile web add some-plugin@newer # 自动热重载
102
169
  - 重载路径依赖[兼容性](#兼容性)一节列出的 cordis/loader 内部接口。若这些内部
103
170
  不可用(既无 `--expose-internals`,也无 `node-addon-require-builtin` 原生
104
171
  插件),本插件会退化为对每次变化只报告“需要重启”,而不做重载。
172
+ - 提示通道(`GET /dsh-hot-reload/events`)**不做任何密码校验**,与 dsh 自带的
173
+ `/plugins/events` 相同。它发送的是插件名和版本号。dsh 的插件列表本来就会显示
174
+ 这些内容,所以并没有多暴露什么秘密。但如果你把 dsh 绑定到 `0.0.0.0`,请把它
175
+ 算作局域网里任何人都能打开的又一个地址。
105
176
 
106
177
  范围说明:本插件处理的是**已加载插件的升级**。安装一个**全新**插件是另一回事
107
178
  (把它的行加入 `cordis.patch.yml`,这个 dsh 本身已经会热应用)。
package/lib/client.js ADDED
@@ -0,0 +1,167 @@
1
+ // dsh-hot-reload — web half: raise a transient banner when the host half
2
+ // reloads (or fails to reload) a plugin package.
3
+ //
4
+ // This file is hand-written in the shape a built client bundle takes, because
5
+ // the package deliberately has no build step: a classic script that REGISTERS a
6
+ // factory with the browser module loader, whose body runs at materialization
7
+ // rather than at script execution. Consequences for editing it:
8
+ //
9
+ // - no JSX (React.createElement instead) and no import/export syntax — the
10
+ // factory takes a synchronous `require` and RETURNS its exports;
11
+ // - only the platform seed modules may be required, under their exact keys:
12
+ // react, react/jsx-runtime, react-dom, react-dom/client,
13
+ // @deepseek-ai/cordis, and the @deepseek-ai/dsh-client-{ui-slots,
14
+ // web-react, ui-primitives, ui-attachment, schema-form} set. They come from
15
+ // the web shell's own build, so this half needs no other plugin bundle;
16
+ // - `id` must be the package name: the loader resolves "<id>/client" and the
17
+ // bare id to these same exports.
18
+ //
19
+ // The host half only serves this to browsers (package.json's dsh.client pins
20
+ // platform "web"), and nothing here is required for reloading to work. Every
21
+ // failure path below degrades to "no banner" — but note the shell fails its
22
+ // boot if a plugin entry never activates, so a throw at factory scope would
23
+ // cost the page: that is why the requires are guarded rather than bare.
24
+
25
+ window.__ModuleLoader__.load({
26
+ id: "dsh-hot-reload",
27
+ factory: (require) => {
28
+ // Guarded because a throw here escapes the factory, leaves this entry
29
+ // without a fiber, and the web shell's boot-time sweep turns any entry that
30
+ // did not reach ACTIVE into a thrown boot failure — i.e. an unguarded
31
+ // require miss costs the whole page, not just the banner. Degrade to a
32
+ // no-op plugin instead, so the entry still activates.
33
+ let React = null;
34
+ let primitives = null;
35
+ let seedError = null;
36
+ try {
37
+ React = require("react");
38
+ primitives = require("@deepseek-ai/dsh-client-ui-primitives");
39
+ } catch (error) {
40
+ seedError = error;
41
+ }
42
+
43
+ /** Must match EVENTS_ENDPOINT in lib/index.js. The two halves ship as
44
+ * separate bundles with no module in common, so this constant is duplicated
45
+ * rather than shared — change one, change the other. */
46
+ const EVENTS_ENDPOINT = "/dsh-hot-reload/events";
47
+
48
+ /** Root-scoped list slot that the shell frame renders over the whole app,
49
+ * and dsh's documented home for a plugin's own floating surface. Root scope
50
+ * matters here: reloads are triggered from a terminal, so a notice must be
51
+ * able to appear with no conversation open. (The `root` slot itself is
52
+ * single-occupancy — registering there would shadow the entire app frame.) */
53
+ const SLOT = "shell.overlay";
54
+
55
+ /** Cordis plugin name. */
56
+ const name = "dsh-hot-reload";
57
+ /** Required services: the slot registry this half contributes its banner to. */
58
+ const inject = ["slots"];
59
+
60
+ /** Leading glyphs, built once: `primitives` is fixed for the life of the
61
+ * factory, so rebuilding these per render would only churn element identity
62
+ * and force the icon span to reconcile. Undefined when this dsh build no
63
+ * longer ships the icon — the banner reads fine without one. */
64
+ const icon = (Icon) => (typeof Icon === "function" ? React.createElement(Icon) : undefined);
65
+ const ICONS = seedError !== null ? {} : {
66
+ reloaded: icon(primitives.IconRefreshOutline16),
67
+ other: icon(primitives.IconWarningOutline16),
68
+ };
69
+
70
+ /**
71
+ * The shell.overlay entry: subscribes to the host's notice channel and shows
72
+ * one banner at a time, oldest first.
73
+ *
74
+ * Notices queue rather than replace: one lockfile write can reload several
75
+ * packages, and showing only the newest would silently drop the rest.
76
+ *
77
+ * @param props.warn - reports a dead channel; supplied by apply() through the
78
+ * wrapper it registers, so nothing about this component is factory-global and
79
+ * a second plugin row cannot repoint the first row's logger.
80
+ */
81
+ function ReloadNotices({ warn }) {
82
+ const [queue, setQueue] = React.useState([]);
83
+ // Stable identity is load-bearing: Toast restarts its hold-and-fade timer
84
+ // whenever `onDone` changes, so a fresh arrow per render would let a burst
85
+ // of arrivals keep resetting the banner already on screen instead of
86
+ // letting it finish and hand over to the next one.
87
+ const shift = React.useCallback(() => setQueue((q) => q.slice(1)), []);
88
+
89
+ React.useEffect(() => {
90
+ let seq = 0;
91
+ const source = new EventSource(EVENTS_ENDPOINT);
92
+ source.addEventListener("message", (event) => {
93
+ let frame;
94
+ try {
95
+ frame = JSON.parse(event.data);
96
+ } catch {
97
+ return;
98
+ }
99
+ if (frame === null || typeof frame !== "object") return;
100
+ if (frame.type !== "notice" || typeof frame.text !== "string") return;
101
+ seq += 1;
102
+ setQueue((q) => q.concat({ seq, kind: frame.kind, text: frame.text }));
103
+ });
104
+ // A dead channel is otherwise invisible: with no route registered, the
105
+ // request falls through to the SPA fallback and answers 200 text/html,
106
+ // which EventSource rejects as a permanent failure rather than retrying.
107
+ // Say so once, so "the feature is off" is distinguishable from "broken".
108
+ let reported = false;
109
+ source.addEventListener("error", () => {
110
+ if (reported || source.readyState !== 2 /* CLOSED */) return;
111
+ reported = true;
112
+ warn(`dsh-hot-reload: notice channel ${EVENTS_ENDPOINT} is unavailable — no reload banners`);
113
+ });
114
+ // Otherwise EventSource reconnects on its own; the host holds no per-tab
115
+ // state, so a reconnect costs nothing and misses only what it was down for.
116
+ return () => source.close();
117
+ }, []);
118
+
119
+ const head = queue[0];
120
+ if (head === undefined) return null;
121
+ // Keyed by arrival sequence so two identical texts in a row remount and
122
+ // replay the slide/hold/fade, instead of reusing an already-faded banner.
123
+ return React.createElement(primitives.Toast, {
124
+ key: head.seq,
125
+ text: `dsh-hot-reload: ${head.text}`,
126
+ icon: head.kind === "reloaded" ? ICONS.reloaded : ICONS.other,
127
+ onDone: shift,
128
+ });
129
+ }
130
+
131
+ /**
132
+ * Client plugin body: mount the banner into the shell overlay.
133
+ * @param ctx - client root context.
134
+ */
135
+ function apply(ctx) {
136
+ if (seedError !== null) {
137
+ ctx.logger?.warn?.("dsh-hot-reload: a platform module is unavailable — reload notices disabled");
138
+ ctx.logger?.warn?.(seedError);
139
+ return;
140
+ }
141
+ if (typeof primitives.Toast !== "function") {
142
+ ctx.logger?.warn?.("dsh-hot-reload: this dsh build ships no Toast primitive — reload notices disabled");
143
+ return;
144
+ }
145
+ const warn = (message) => ctx.logger?.warn?.(message);
146
+ // slots.inject waits for the slot to be declared and disposes with this
147
+ // fiber, so an unknown slot name parks quietly instead of throwing.
148
+ ctx.slots.inject(SLOT, () => {
149
+ try {
150
+ return ctx.slots.register({ name: SLOT, id: "dsh-hot-reload.notices", order: 100 }, () =>
151
+ React.createElement(ReloadNotices, { warn })
152
+ );
153
+ } catch (error) {
154
+ // A changed registration contract, or a duplicate id from a second
155
+ // dsh-hot-reload row: lose the notices, never the page.
156
+ ctx.logger?.warn?.("dsh-hot-reload: could not mount reload notices");
157
+ ctx.logger?.warn?.(error);
158
+ return () => {};
159
+ }
160
+ });
161
+ }
162
+
163
+ // The loader takes the factory's return value AS the module exports, so the
164
+ // CJS `module.exports` preamble a built bundle carries is not needed here.
165
+ return { apply, inject, name };
166
+ },
167
+ });
package/lib/index.js CHANGED
@@ -16,6 +16,11 @@
16
16
  // Disabled rows are skipped silently (nothing is running to swap); an enabled
17
17
  // row with no fiber attached yet is reported and left for a later change.
18
18
  //
19
+ // Outcomes are announced on two surfaces besides ctx.logger — one stderr line
20
+ // per successful reload, and an SSE channel the browser half (lib/client.js)
21
+ // turns into a transient toast. Both are additive and best-effort; see the
22
+ // "notification surfaces" section in apply().
23
+ //
19
24
  // NOTE: the reload path uses cordis/loader internals (loader.internal.loadCache,
20
25
  // registry.plugin/delete, fiber.entry) — the same ones HMR uses. If a future
21
26
  // cordis changes them, reloads will fail closed to "restart needed", never
@@ -32,6 +37,12 @@ export const name = "dsh-hot-reload";
32
37
  const getOuterStack = () => [];
33
38
  const cjsRequire = createRequire(import.meta.url);
34
39
 
40
+ /** SSE channel the web half subscribes to for reload notices. Duplicated
41
+ * verbatim in lib/client.js: the two halves are separate bundles (Node ESM
42
+ * here, a browser classic script there) with no module in common, and this
43
+ * package has no build step to generate a shared one from. */
44
+ const EVENTS_ENDPOINT = "/dsh-hot-reload/events";
45
+
35
46
  /** handlePackage outcome: a reload was attempted and failed — never retry it. */
36
47
  const TERMINAL = Symbol("dsh-hot-reload:terminal");
37
48
 
@@ -69,6 +80,116 @@ export function apply(ctx, config = {}) {
69
80
  );
70
81
  }
71
82
 
83
+ // ---- notification surfaces ----
84
+ //
85
+ // Both are strictly ADDITIVE to ctx.logger, which stays the record of truth,
86
+ // and neither may throw into a reload cycle: a broken notification must never
87
+ // turn a working reload into a failed one.
88
+ //
89
+ // - stderr, successful reloads only. cordis's logger fans messages out to
90
+ // registered exporters, and the dsh host process registers none (only the
91
+ // browser shell does), so nothing this plugin logs reaches the terminal dsh
92
+ // runs in. One line per reload is the profile-independent baseline.
93
+ // - an SSE channel the web half subscribes to (lib/client.js) and renders as
94
+ // a transient toast. Registered only when a webServer service exists, so a
95
+ // profile without one — tui — behaves exactly as it does today.
96
+ //
97
+ // Fire and forget: nothing is buffered and no delivery is confirmed. A notice
98
+ // raised while no browser is connected is simply lost. That is deliberate —
99
+ // the logger already holds the durable record, and replaying on connect would
100
+ // need a per-tab cursor to avoid re-announcing old reloads on every reload of
101
+ // the page itself.
102
+ const connections = new Set();
103
+
104
+ /** Announce one cycle outcome on every surface, from ONE message.
105
+ *
106
+ * Call this for outcomes; call `log.*` directly for diagnostics. Writing the
107
+ * message once is the point: an earlier version had each site author a log
108
+ * string and a near-identical notice string, which is the one code path whose
109
+ * whole job is telling the truth about what happened — the two can drift and
110
+ * nothing catches it. Here the terminal and the banner cannot disagree.
111
+ *
112
+ * `kind` is "reloaded" (it worked), "failed" (attempted and rolled back), or
113
+ * "stale" (not attempted; the old code is still running). It selects the log
114
+ * level and the browser's icon, and only "reloaded" reaches stderr. Callers
115
+ * pass the bare message — every surface adds its own prefix. */
116
+ function report(kind, message) {
117
+ if (kind === "reloaded") {
118
+ log.info?.(`dsh-hot-reload: ${message}`);
119
+ try {
120
+ process.stderr.write(`dsh-hot-reload: ${message}\n`);
121
+ } catch {}
122
+ } else {
123
+ log.warn?.(`dsh-hot-reload: ${message}`);
124
+ }
125
+ if (!connections.size) return;
126
+ const line = `data: ${JSON.stringify({ type: "notice", kind, text: message })}\n\n`;
127
+ for (const res of connections) {
128
+ try {
129
+ res.write(line);
130
+ } catch {} // a half-dead socket is the browser's problem, not the reloader's
131
+ }
132
+ }
133
+
134
+ // ctx.inject, NOT a module-level `export const inject`, and NOT a one-shot
135
+ // ctx.get. The distinction matters three ways:
136
+ //
137
+ // - a module-level inject is REQUIRED (Inject.resolve maps every declared
138
+ // name to a wait), so it would park the whole plugin forever in a profile
139
+ // that has no web server — tui would stop reloading anything at all;
140
+ // - ctx.inject parks only this CHILD fiber, leaving the reloader running;
141
+ // - ctx.get would be both racy and one-shot. It resolves strictly, returning
142
+ // undefined unless the providing fiber is already ACTIVE, and WebServer
143
+ // only becomes active after its async listen() binds — while loader entries
144
+ // start concurrently, so whether we win that race is chance. Being a single
145
+ // read, it also never recovers: a web server that reloads (port change, a
146
+ // dsh HMR cycle) comes back with an empty route table and nothing would
147
+ // re-register. ctx.inject re-runs this body on exactly that event.
148
+ ctx.inject(["webServer"], (webCtx) => {
149
+ // Acquire and release in one effect, as dsh's own client-hmr channel does:
150
+ // the disposer drops the route and every open stream when this child fiber
151
+ // unloads — on shutdown, and before the body re-runs for a replaced server.
152
+ webCtx.effect(() => {
153
+ let disposeRoute;
154
+ try {
155
+ disposeRoute = webCtx.webServer.register({
156
+ kind: "exact",
157
+ path: EVENTS_ENDPOINT,
158
+ handler: (req, res) => {
159
+ if (req.method !== "GET" && req.method !== "HEAD") {
160
+ res.writeHead(405);
161
+ res.end();
162
+ return;
163
+ }
164
+ res.writeHead(200, {
165
+ "content-type": "text/event-stream",
166
+ "cache-control": "no-cache",
167
+ connection: "keep-alive",
168
+ });
169
+ res.write(": connected\n\n");
170
+ connections.add(res);
171
+ res.on("close", () => connections.delete(res));
172
+ },
173
+ });
174
+ } catch (err) {
175
+ // Duplicate path (a second dsh-hot-reload row) or a webserver API change.
176
+ // The notices are optional; the reloader is not — degrade, never throw.
177
+ log.warn?.("dsh-hot-reload: could not register the notice channel; web notices are disabled");
178
+ log.warn?.(err);
179
+ return () => {};
180
+ }
181
+ return () => {
182
+ disposeRoute();
183
+ for (const res of connections) {
184
+ try {
185
+ res.destroy();
186
+ } catch {}
187
+ }
188
+ connections.clear();
189
+ };
190
+ }, "dsh-hot-reload: notice channel");
191
+ });
192
+
72
193
  // ---- package <-> loader-entry helpers ----
73
194
 
74
195
  /** Package name backing a loader entry's module specifier, or null for local/builtin. */
@@ -286,11 +407,11 @@ export function apply(ctx, config = {}) {
286
407
  const { version, live, fiberless } = rec;
287
408
 
288
409
  if (rec.json?.dsh?.hotReload === false) {
289
- log.info?.(`dsh-hot-reload: ${pkg}@${version} sets dsh.hotReload:false — restart dsh to load the new version`);
410
+ report("stale", `${pkg}@${version} sets dsh.hotReload:false — restart dsh to load the new version`);
290
411
  return version;
291
412
  }
292
413
  if (!internal) {
293
- log.info?.(`dsh-hot-reload: ${pkg}@${version} changed — restart dsh to load the new version`);
414
+ report("stale", `${pkg}@${version} changed — restart dsh to load the new version`);
294
415
  return version;
295
416
  }
296
417
 
@@ -299,8 +420,9 @@ export function apply(ctx, config = {}) {
299
420
  // Enabled but nothing attached: mid-import or a load failure. Say so once,
300
421
  // don't commit, and stay retryable — no reload was attempted, so a plugin
301
422
  // that was merely still activating picks this up on a later event.
302
- log.warn?.(
303
- `dsh-hot-reload: ${pkg}@${version} has no live fiber to reload right now — restart dsh if it stays on the old version`
423
+ report(
424
+ "stale",
425
+ `${pkg}@${version} has no live fiber to reload right now — restart dsh if it stays on the old version`
304
426
  );
305
427
  return false;
306
428
  }
@@ -325,12 +447,13 @@ export function apply(ctx, config = {}) {
325
447
  committed ??= imported;
326
448
  }
327
449
  committed ??= version;
328
- log.info?.(`dsh-hot-reload: hot-reloaded ${pkg}@${committed} (${live.length} module(s))`);
450
+ report("reloaded", `hot-reloaded ${pkg}@${committed} (${live.length} module(s))`);
329
451
  return committed;
330
452
  } catch (err) {
331
453
  if (disposed) return false; // aborted by teardown, not a real failure — stay quiet
332
- log.warn?.(
333
- `dsh-hot-reload: could not hot-reload ${pkg}@${version} — not retrying; restart dsh (or install a different version) to load it`
454
+ report(
455
+ "failed",
456
+ `could not hot-reload ${pkg}@${version} — not retrying; restart dsh (or install a different version) to load it`
334
457
  );
335
458
  log.warn?.(err);
336
459
  return TERMINAL; // attempted and failed: never retried for this version
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-hot-reload",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "description": "Live-reload upgraded DeepSeek Harness (dsh) plugins without restarting dsh \u2014 the running plugin is swapped in place, and a reload that fails rolls back to the working old version and asks for a manual restart.",
6
6
  "keywords": [
@@ -29,6 +29,7 @@
29
29
  "main": "lib/index.js",
30
30
  "exports": {
31
31
  ".": "./lib/index.js",
32
+ "./client": "./lib/client.js",
32
33
  "./package.json": "./package.json"
33
34
  },
34
35
  "files": [
@@ -42,6 +43,9 @@
42
43
  "dsh": {
43
44
  "bundle": {
44
45
  "patch": "./cordis.patch.yml"
46
+ },
47
+ "client": {
48
+ "platform": "web"
45
49
  }
46
50
  },
47
51
  "dependencies": {