dsh-client-auto-continue 0.7.4 → 0.8.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.
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Host status bridge, browser side.
3
+ *
4
+ * Subscribes to the host engine's `/api/auto-continue-bridge` SSE stream:
5
+ * notifications (shown via the browser Notification API, action buttons POST
6
+ * to `/api/auto-continue-action`) and runtime state (today's stats and the
7
+ * paused-sessions list) consumed by the settings card's live panels.
8
+ */
9
+ /** 今日统计视图(与 host 引擎的 DayStats 对应)。 */
10
+ export interface DayStatsView {
11
+ date: string;
12
+ sent: number;
13
+ skipped: number;
14
+ recovered: number;
15
+ failed: number;
16
+ gaveUp: number;
17
+ looped: number;
18
+ byCode: Record<string, number>;
19
+ }
20
+ /** 已暂停会话视图。 */
21
+ export interface PausedSessionView {
22
+ sessionId: string;
23
+ until: number;
24
+ }
25
+ /** 当前桥状态里的已暂停会话(卡片面板用)。 */
26
+ export declare function pausedSessions(): PausedSessionView[];
27
+ /** 当前桥状态里的今日统计(卡片面板用)。 */
28
+ export declare function readTodayStats(): DayStatsView;
29
+ /** 清零今日统计(经动作端点交给 host 引擎执行)。 */
30
+ export declare function resetTodayStats(): void;
31
+ /** 解除某个会话的暂停(经动作端点交给 host 引擎执行)。 */
32
+ export declare function unpauseSession(sessionId: string): void;
33
+ /** 订阅桥状态变化(卡片面板刷新用)。 */
34
+ export declare function subscribeBridge(listener: () => void): () => void;
35
+ /**
36
+ * 启动桥订阅(带断线重连), 返回停止函数。
37
+ * 由 client apply 的 ctx.effect 持有。
38
+ */
39
+ export declare function startBridge(): () => void;
@@ -229,8 +229,13 @@ export declare class AutoContinueRunner {
229
229
  private buildContinueText;
230
230
  /** 上一步工具调用的护栏状态(实时路径, 由 mux 帧维护)。 */
231
231
  private currentGuard;
232
- /** 会话标题缓存(来自 session.list 投影, {sessionTitle} 占位符用)。 */
233
- private readonly titles;
232
+ /**
233
+ * 宿主权威兜底: 历史里最后一条事件是否就是同一文本的 user 消息。
234
+ * 是 = 它还在排队未被处理, 不应再叠加发送; 否(回合结束等其他事件)= 放行。
235
+ * 查询失败时返回 false(放行, 本地防线仍在)。
236
+ */
237
+ private hostHasPendingSameText;
238
+ /** 会话标题缓存(来自 session.list 投影, {sessionTitle} 占位符用)。 */ private readonly titles;
234
239
  /** 查一次 session.list, 顺带缓存该会话的标题。 */
235
240
  private fetchSessionInfo;
236
241
  private runningViaList;
@@ -1,20 +1,16 @@
1
1
  /**
2
- * Auto-continue plugin, browser half.
2
+ * Auto-continue plugin, browser half (thin shell).
3
3
  *
4
- * - Runs the auto-continue engine over the live mux + host event streams.
5
- * - Registers the `auto-continue` settings card into the plugin-configuration
6
- * section (`settings.plugin.item`), editing the same namespace the engine
7
- * reads every behavior knob is configurable from the GUI.
4
+ * Since 0.8.0 the auto-continue ENGINE runs inside the host process (single
5
+ * instance see src/host/engine.ts), so this half only:
6
+ * - registers the `auto-continue` settings card (`settings.plugin.item`),
7
+ * - subscribes to the host status bridge (SSE) and shows browser
8
+ * notifications with action buttons (Resume now / Pause 1h) via the bridge
9
+ * action endpoint,
10
+ * - feeds the card's stats / paused-sessions panels from the bridge state.
8
11
  */
9
12
  import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client';
10
- import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client';
11
13
  import { type SettingsCardKey } from './locales.ts';
12
- /** 客户端根上下文的 connection 服务(由 dsh-client-connection 挂载)。 */
13
- declare module '@deepseek-ai/cordis' {
14
- interface Context {
15
- connection: ConnectionHandle;
16
- }
17
- }
18
14
  declare module '@deepseek-ai/dsh-client-ui-slots' {
19
15
  interface LocaleNamespaceMap {
20
16
  /** auto-continue settings-card copy. */
@@ -23,9 +19,10 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
23
19
  }
24
20
  /** Services required by this plugin. */
25
21
  export declare const inject: string[];
26
- export { fillTemplate, pauseSession, pausedSessions, readTodayStats, resetTodayStats, sessionPauseUntil, unpauseSession, } from './engine.ts';
22
+ export { pausedSessions, readTodayStats, resetTodayStats, unpauseSession, } from './bridge.ts';
27
23
  /**
28
- * Plugin body: mount the engine and the settings card.
24
+ * Plugin body: settings card + host status bridge (notifications, stats,
25
+ * paused sessions).
29
26
  * @param ctx - client root context.
30
27
  */
31
28
  export declare function apply(ctx: ClientContext): void;
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Auto-continue engine — host half core (single instance).
3
+ *
4
+ * Runs inside the dsh host process, so there is exactly ONE engine regardless
5
+ * of how many browser tabs are open — the multi-tab duplicate-send class of
6
+ * bugs (issue #13) cannot exist by construction. Listens to the session event
7
+ * firehose (`session/event`), sends through the agent registry
8
+ * (`agent.followup`), cancels through `agent.cancel`, and reads configuration
9
+ * from the settings service.
10
+ *
11
+ * All behavior is driven by the `auto-continue` settings namespace (see the
12
+ * plugin's settings card); every knob below is user-configurable there.
13
+ */
14
+ import type { Context } from '@deepseek-ai/cordis';
15
+ import type { SessionId } from '@deepseek-ai/dsh-session/types';
16
+ /** The `auto-continue` settings section (all fields optional on the wire; the host schema carries defaults). */
17
+ export interface AutoContinueSettings {
18
+ /** Text automatically sent after an interruption. */
19
+ continueText?: string;
20
+ /** Text sent when the output token ceiling is reached (same placeholders as `continueText`). */
21
+ continueTextMaxTokens?: string;
22
+ /** Idempotency guard: inspect the last tool call before resuming and steer the model. */
23
+ guardTools?: boolean;
24
+ /** Guard text appended when the last tool call has no confirmed result (it may have partially executed). */
25
+ guardPendingText?: string;
26
+ /** Guard text appended when the last tool call completed successfully (don't rerun it). */
27
+ guardDoneText?: string;
28
+ /** Grace period after an interruption before auto-sending (ms). */
29
+ graceMs?: number;
30
+ /** Minimum interval between two auto-continues per session (ms). */
31
+ cooldownMs?: number;
32
+ /** Max consecutive auto-continues per session before stopping. */
33
+ maxConsecutive?: number;
34
+ /** Scan recently interrupted sessions on page load / reconnect. */
35
+ scanOnBoot?: boolean;
36
+ /** Max sessions the scan checks (most recently updated). */
37
+ scanLimit?: number;
38
+ /** Scan only considers interruptions inside this window (ms). */
39
+ freshMs?: number;
40
+ /** Delay before scanning after a reconnect (ms). */
41
+ reconnectScanDelayMs?: number;
42
+ /** SSE reconnect backoff (ms). */
43
+ reconnectBackoffMs?: number;
44
+ /** Log `[auto-continue]` lines to the browser console. */
45
+ verbose?: boolean;
46
+ /** Classify failures: auto-continue transient errors only; permanent ones (auth/balance/model) are skipped and notified. */
47
+ classify?: boolean;
48
+ /** Cooldown multiplier per consecutive failure (adaptive backoff). */
49
+ backoffFactor?: number;
50
+ /** Cap on the effective backoff interval (ms). */
51
+ backoffMaxMs?: number;
52
+ /** Show browser notifications for auto-continue events. */
53
+ notify?: boolean;
54
+ /** Globally pause auto-continue: no live or scan send, queued pending sends cancelled. */
55
+ paused?: boolean;
56
+ /** Loop guard: detect a running turn spinning in place (short talk without tools, or the same tool repeating) and restart it. */
57
+ loopGuard?: boolean;
58
+ /** A model message shorter than this many chars counts as a "short sentence" (loop signal). */
59
+ loopShortChars?: number;
60
+ /** Consecutive short sentences within this window (ms) with no tool call in between trip the loop guard. */
61
+ loopWindowMs?: number;
62
+ /** Consecutive short sentences trip the loop guard. */
63
+ loopShortCount?: number;
64
+ /** Consecutive identical tool calls with identical arguments AND identical results trip the loop guard. */
65
+ loopToolRepeat?: number;
66
+ /** Consecutive identical short sentences trip the loop guard (strongest spinning signal). */
67
+ loopRepeatText?: number;
68
+ /** Text sent after the loop guard cancels and restarts a turn (supports {tool}). */
69
+ loopText?: string;
70
+ }
71
+ /** Fully resolved configuration (built-in defaults + user overrides). */
72
+ export type AutoContinueConfig = Required<AutoContinueSettings>;
73
+ /** Built-in defaults — must match the host schema defaults in src/index.ts. */
74
+ export declare const DEFAULT_CONFIG: AutoContinueConfig;
75
+ /** Resolve a (possibly partial / not-yet-loaded) settings section to a full config. */
76
+ export declare function resolveConfig(section: AutoContinueSettings | undefined): AutoContinueConfig;
77
+ /** 一次回合失败的机器可读事实(turn/end error 的 LlmFailure 载荷)。 */
78
+ export interface FailureFacts {
79
+ /** 稳定机器路由码(如 UPSTREAM、RATE_LIMIT_EXCEEDED、INVALID_API_KEY)。 */
80
+ code: string;
81
+ /** 人类可读的失败描述。 */
82
+ message: string;
83
+ /** 供应商 HTTP 状态码(可用时)。 */
84
+ status?: number;
85
+ }
86
+ /**
87
+ * 错误分类: 该失败是否值得自动继续。
88
+ * 永久性失败(认证/余额/模型不存在/上下文超限等)重试也不会成功, 应跳过并通知用户;
89
+ * 其余(网络、超时、5xx、429 等)视为临时性失败, 允许自动恢复。
90
+ */
91
+ export declare function isTransientFailure(failure: FailureFacts): boolean;
92
+ /**
93
+ * host/agent-error 消息分类: 仅明确属于网络/传输类的临时错误才自动继续。
94
+ * 其余(序列化失败、配置/宿主内部错误等)视为永久性——重试无益, 且用户停止导致的
95
+ * 序列化失败(如 Windows 下 abort 的 DOMException reason)绝不能自动续跑。
96
+ */
97
+ export declare function isTransientAgentError(message: string): boolean;
98
+ /** 通知上的一个操作按钮(action 标识 + 显示文案)。 */
99
+ export interface NotifyAction {
100
+ /** 稳定动作标识, 点击时经 onAction 回调传出。 */
101
+ action: string;
102
+ /** 按钮显示文案。 */
103
+ title: string;
104
+ }
105
+ /** 通知的可选行为: 操作按钮列表与点击回调。 */
106
+ export interface NotifyOptions {
107
+ actions?: NotifyAction[];
108
+ onAction?: (action: string) => void;
109
+ }
110
+ /** 模板填充所需的上下文(全部可选, 缺失的占位符填为空串)。 */
111
+ export interface TemplateContext {
112
+ /** 失败事实(错误码/消息/HTTP 状态), 对应 {code}/{message}/{status}。 */
113
+ facts?: FailureFacts;
114
+ /** 失败前最后一次工具调用的名称, 对应 {tool}。 */
115
+ tool?: string;
116
+ /** 失败回合的编号, 对应 {turn}。 */
117
+ turn?: number;
118
+ /** 连续失败次数(含本次), 对应 {errorCount}。 */
119
+ errorCount?: number;
120
+ /** 会话标题(来自 session.list 投影, 可用时), 对应 {sessionTitle}。 */
121
+ sessionTitle?: string;
122
+ /** 自失败发生以来的毫秒数, 对应 {elapsed}。 */
123
+ elapsedMs?: number;
124
+ /** 上一步工具结果摘要(截断), 对应 {result}(护栏模板用)。 */
125
+ result?: string;
126
+ }
127
+ /** 用失败事实与回合信息填充 continueText 模板占位符({code}/{message}/{status}/{tool}/{turn}/{errorCount}/{sessionTitle}/{elapsed}/{result})。 */
128
+ export declare function fillTemplate(template: string, ctx: TemplateContext): string;
129
+ /** 上一步工具调用的判定结果: 是否已确认完成, 以及文本摘要。 */
130
+ export interface ToolResultFacts {
131
+ /** 工具是否成功完成(内部失败或 isError 视为未成功)。 */
132
+ ok: boolean;
133
+ /** 工具输出的文本摘要(截断)。 */
134
+ excerpt: string;
135
+ }
136
+ /** 自适应退避: 同一会话连续失败时的有效冷却间隔。 */
137
+ export declare function effectiveCooldown(consecutive: number, base: number, factor: number, max: number): number;
138
+ /** 一天的自动继续统计(host 单实例内存态)。 */
139
+ export interface DayStats {
140
+ /** 本地日期 YYYY-MM-DD。 */
141
+ date: string;
142
+ /** 自动发送次数。 */
143
+ sent: number;
144
+ /** 因永久性错误跳过的次数。 */
145
+ skipped: number;
146
+ /** 发送后回合成功完成(恢复成功)的次数。 */
147
+ recovered: number;
148
+ /** 发送后再次失败的次数。 */
149
+ failed: number;
150
+ /** 达到连续上限而停止的次数(按停止事件计)。 */
151
+ gaveUp: number;
152
+ /** loop guard 打断并重启回合的次数。 */
153
+ looped: number;
154
+ /** 按错误码计数的失败分布。 */
155
+ byCode: Record<string, number>;
156
+ }
157
+ /** 通知桥事件: host 引擎产生, browser 侧订阅展示(Notification / 动作按钮)。 */
158
+ export interface HostNotice {
159
+ /** 稳定标识(供 browser 去重)。 */
160
+ id: string;
161
+ title: string;
162
+ body: string;
163
+ /** 会话 id(通知按钮「立即续跑 / 暂停该会话」作用于它)。 */
164
+ sessionId?: SessionId;
165
+ actions: NotifyAction[];
166
+ /** 产生时间。 */
167
+ at: number;
168
+ }
169
+ /** 插件主体: 一条 mux 流 + 一条 host 流 + 启动/重连扫描。 */
170
+ export declare class AutoContinueRunner {
171
+ private readonly ctx;
172
+ private readonly getConfig;
173
+ private readonly states;
174
+ private readonly pauseUntil;
175
+ private dayStats;
176
+ private readonly notices;
177
+ private readonly noticeListeners;
178
+ private readonly stateListeners;
179
+ private disposed;
180
+ /**
181
+ * @param ctx - host plugin context (agents registry, session events, settings).
182
+ * @param getConfig - read the current resolved configuration (settings service).
183
+ */
184
+ constructor(ctx: Context, getConfig: () => AutoContinueConfig);
185
+ private log;
186
+ /** 对外(状态桥): 今日统计快照。 */
187
+ todayStats(): DayStats;
188
+ /** 对外(状态桥): 当前生效的会话级暂停列表。 */
189
+ activePauses(): {
190
+ sessionId: SessionId;
191
+ until: number;
192
+ }[];
193
+ /** 对外(状态桥): 订阅通知事件(SSE 端点推送)。 */
194
+ subscribeNotices(listener: () => void): () => void;
195
+ /** 对外(状态桥): 订阅运行时状态变化(统计/暂停列表)。 */
196
+ subscribeState(listener: () => void): () => void;
197
+ private emitState;
198
+ /** 对外(状态桥): 消费待展示的通知。 */
199
+ drainNotices(): HostNotice[];
200
+ /** 通知动作(browser 通知按钮回传): 立即续跑 / 暂停该会话 / 解除暂停 / 清零统计。 */
201
+ handleNoticeAction(sessionId: SessionId | undefined, action: string): void;
202
+ dispose(): void;
203
+ private state;
204
+ /**
205
+ * 事件入口(host 单实例): 预处理工具调用/结果/模型消息(护栏与循环信号),
206
+ * 然后交给回合状态机。
207
+ */
208
+ private onHostEvent;
209
+ /** 从 assistant/message 事件提取纯文本。 */
210
+ private assistantText;
211
+ private onAssistantMessage;
212
+ /** 两个循环信号的公共检查; 命中且本回合未打断过则打断。 */
213
+ private checkLoop;
214
+ /**
215
+ * 打断运行中的回合: cancel(带来源标记)+ 进冷却。
216
+ * 随后的 turn/end aborted 会因 loopCancelled 走「可恢复中断」路径,
217
+ * 用 loopText 重启回合——不会与用户手动停止混淆。
218
+ */
219
+ private interruptLoop;
220
+ private onSessionEvent;
221
+ private onTurnFailure;
222
+ /** 通知操作按钮与回调(「立即续跑」/「暂停该会话 1 小时」)。 */
223
+ private notifyOptions;
224
+ private onNotifyAction;
225
+ /** 内存统计(host 单实例): 按今日桶累计。 */
226
+ private bumpStat;
227
+ /** 通知桥: 产生一条通知事件, SSE 端点推给 browser 侧展示。 */
228
+ private notify;
229
+ /** 恢复结果记账: 自动发送后窗口内的回合结束, 判定恢复成功或失败。 */
230
+ private noteRecovery;
231
+ /** 立即为该会话发送一次自动继续(无视冷却与连续上限; 由通知按钮触发)。 */
232
+ resumeNow(sessionId: SessionId): Promise<void>;
233
+ /** 本会话当前生效的冷却间隔(自适应退避)。 */
234
+ private cooldownFor;
235
+ private schedule;
236
+ private cancelPending;
237
+ private fire;
238
+ /**
239
+ * 组装本次续跑消息: 模板填充 + 幂等护栏。
240
+ * 护栏依据上一步工具调用的执行状态附加指引, 防止重跑副作用操作:
241
+ * - 结果未确认(可能已部分执行)→ 提示先确认状态、不要重复执行
242
+ * - 已确认成功 → 提示已完成、不要重复执行
243
+ * - 已失败 → 不加护栏(重试工具本来就是目的)
244
+ */
245
+ private buildContinueText;
246
+ /** 上一步工具调用的护栏状态(实时路径, 由 mux 帧维护)。 */
247
+ private currentGuard;
248
+ private bootScanLoop;
249
+ /** 反复尝试扫描, 直到成功(宿主就绪)或达到次数上限。 */
250
+ private scanLoop;
251
+ /**
252
+ * 扫描最近中断过的会话: 最后回合以非人为原因结束, 且其后没有新回合或用户消息。
253
+ * @returns 是否成功完成一次扫描(宿主就绪)。
254
+ */
255
+ private scanInterrupted;
256
+ /** 从历史事件恢复上一步工具调用状态(扫描路径的幂等护栏)。 */
257
+ private applyGuardFromEvents;
258
+ }
@@ -1,7 +1,13 @@
1
1
  /**
2
- * Host half of the auto-continue plugin: registers the `auto-continue`
3
- * settings namespace so the browser half's settings card can edit it and the
4
- * engine can read it. No other host-side behavior.
2
+ * Host half of the auto-continue plugin.
3
+ *
4
+ * - Registers the `auto-continue` settings namespace (the browser half's
5
+ * settings card edits it; the host engine reads it).
6
+ * - Runs the single-instance auto-continue engine: listens to the session
7
+ * event firehose, sends via `agent.followup`, cancels via `agent.cancel`.
8
+ * - Serves a status bridge the browser half subscribes to: notifications and
9
+ * runtime state (stats / pauses), plus an action endpoint for notification
10
+ * buttons.
5
11
  */
6
12
  import type { Context } from '@deepseek-ai/cordis';
7
13
  import z from '@deepseek-ai/schemastery';
@@ -116,8 +122,8 @@ export declare const AutoContinueSchema: z<Schemastery.ObjectS<{
116
122
  loopText: z<string, string>;
117
123
  }>>;
118
124
  /**
119
- * Plugin body: register the settings namespace when a settings provider is
120
- * composed. Changes apply live — the browser half observes the scope.
125
+ * Plugin body: register the settings namespace, start the single-instance
126
+ * engine, and serve the status bridge.
121
127
  * @param ctx - host plugin context.
122
128
  */
123
129
  export declare function apply(ctx: Context): void;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-client-auto-continue",
3
3
  "description": "DSH Web UI plugin: automatically sends \"继续\" (continue) when a request is interrupted by network errors or other non-human causes",
4
- "version": "0.7.4",
4
+ "version": "0.8.0",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/types/index.d.ts",
@@ -47,7 +47,7 @@
47
47
  "build": "node build.mjs && tsc -p tsconfig.build.json",
48
48
  "watch": "node build.mjs --watch",
49
49
  "typecheck": "tsc --noEmit",
50
- "test": "node tests/simulate.mjs",
50
+ "test": "node tests/simulate-host.mjs",
51
51
  "prepack": "npm run build"
52
52
  },
53
53
  "keywords": [
@@ -76,7 +76,8 @@
76
76
  "@deepseek-ai/dsh-client-ui-slots": "^0.1.0-rc.7",
77
77
  "@deepseek-ai/dsh-session": "^0.1.0-rc.7",
78
78
  "@deepseek-ai/dsh-settings": "^0.1.0-rc.7",
79
- "@deepseek-ai/schemastery": "^3.18.1"
79
+ "@deepseek-ai/schemastery": "^3.18.1",
80
+ "@types/node": "^22.0.0"
80
81
  },
81
82
  "license": "MIT",
82
83
  "peerDependencies": {
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Host status bridge, browser side.
3
+ *
4
+ * Subscribes to the host engine's `/api/auto-continue-bridge` SSE stream:
5
+ * notifications (shown via the browser Notification API, action buttons POST
6
+ * to `/api/auto-continue-action`) and runtime state (today's stats and the
7
+ * paused-sessions list) consumed by the settings card's live panels.
8
+ */
9
+
10
+ /** 今日统计视图(与 host 引擎的 DayStats 对应)。 */
11
+ export interface DayStatsView {
12
+ date: string;
13
+ sent: number;
14
+ skipped: number;
15
+ recovered: number;
16
+ failed: number;
17
+ gaveUp: number;
18
+ looped: number;
19
+ byCode: Record<string, number>;
20
+ }
21
+
22
+ /** 已暂停会话视图。 */
23
+ export interface PausedSessionView {
24
+ sessionId: string;
25
+ until: number;
26
+ }
27
+
28
+ interface BridgeState {
29
+ stats: DayStatsView;
30
+ paused: PausedSessionView[];
31
+ }
32
+
33
+ interface BridgeNotice {
34
+ id: string;
35
+ title: string;
36
+ body: string;
37
+ sessionId?: string;
38
+ actions: { action: string; title: string }[];
39
+ at: number;
40
+ }
41
+
42
+ const EMPTY_STATS: DayStatsView = {
43
+ date: '',
44
+ sent: 0,
45
+ skipped: 0,
46
+ recovered: 0,
47
+ failed: 0,
48
+ gaveUp: 0,
49
+ looped: 0,
50
+ byCode: {},
51
+ };
52
+
53
+ let state: BridgeState = { stats: EMPTY_STATS, paused: [] };
54
+ const listeners = new Set<() => void>();
55
+
56
+ /** 当前桥状态里的已暂停会话(卡片面板用)。 */
57
+ export function pausedSessions(): PausedSessionView[] {
58
+ return state.paused;
59
+ }
60
+
61
+ /** 当前桥状态里的今日统计(卡片面板用)。 */
62
+ export function readTodayStats(): DayStatsView {
63
+ return state.stats;
64
+ }
65
+
66
+ /** 清零今日统计(经动作端点交给 host 引擎执行)。 */
67
+ export function resetTodayStats(): void {
68
+ void postAction({ action: 'reset-stats' });
69
+ }
70
+
71
+ /** 解除某个会话的暂停(经动作端点交给 host 引擎执行)。 */
72
+ export function unpauseSession(sessionId: string): void {
73
+ void postAction({ action: 'unpause', sessionId });
74
+ }
75
+
76
+ /** 订阅桥状态变化(卡片面板刷新用)。 */
77
+ export function subscribeBridge(listener: () => void): () => void {
78
+ listeners.add(listener);
79
+ return () => {
80
+ listeners.delete(listener);
81
+ };
82
+ }
83
+
84
+ /** 通知按钮动作回传 host(立即续跑 / 暂停该会话 1 小时 / 解除暂停 / 清零统计)。 */
85
+ async function postAction(payload: { action: string; sessionId?: string }): Promise<void> {
86
+ try {
87
+ await fetch('/api/auto-continue-action', {
88
+ method: 'POST',
89
+ headers: { 'content-type': 'application/json' },
90
+ body: JSON.stringify(payload),
91
+ });
92
+ } catch {
93
+ /* host 不可达时静默 */
94
+ }
95
+ }
96
+
97
+ function handleEvent(event: { type: string; notice?: BridgeNotice; stats?: DayStatsView; paused?: PausedSessionView[] }): void {
98
+ if (event.type === 'state') {
99
+ state = {
100
+ stats: event.stats ?? EMPTY_STATS,
101
+ paused: event.paused ?? [],
102
+ };
103
+ for (const listener of listeners) listener();
104
+ } else if (event.type === 'notice' && event.notice !== undefined) {
105
+ showNotification(event.notice);
106
+ }
107
+ }
108
+
109
+ /** 浏览器通知: 展示 host 通知并挂动作按钮。 */
110
+ function showNotification(notice: BridgeNotice): void {
111
+ try {
112
+ const N = (globalThis as { Notification?: unknown }).Notification as
113
+ | (new (t: string, o: { body: string; actions?: { action: string; title: string }[] }) => unknown)
114
+ | undefined;
115
+ if (typeof N === 'undefined') return;
116
+ const permission = (N as unknown as { permission?: string }).permission;
117
+ const create = (): void => {
118
+ const instance = new N(notice.title, {
119
+ body: notice.body,
120
+ ...(notice.actions.length > 0 ? { actions: notice.actions } : {}),
121
+ });
122
+ const target = instance as {
123
+ onclick?: (() => void) | null;
124
+ onaction?: ((event: { action: string }) => void) | null;
125
+ };
126
+ target.onclick = () => {
127
+ try {
128
+ (globalThis as { focus?: () => void }).focus?.();
129
+ } catch {
130
+ /* ignore */
131
+ }
132
+ };
133
+ target.onaction = (event) => {
134
+ if (notice.sessionId !== undefined) {
135
+ void postAction({ action: event.action, sessionId: notice.sessionId });
136
+ }
137
+ };
138
+ };
139
+ if (permission === 'granted') {
140
+ create();
141
+ } else if (permission === 'default') {
142
+ void (N as unknown as { requestPermission?: () => Promise<string> }).requestPermission?.()
143
+ .then((result) => {
144
+ if (result === 'granted') create();
145
+ })
146
+ .catch(() => {});
147
+ }
148
+ } catch {
149
+ /* 通知失败不影响核心逻辑 */
150
+ }
151
+ }
152
+
153
+ /**
154
+ * 启动桥订阅(带断线重连), 返回停止函数。
155
+ * 由 client apply 的 ctx.effect 持有。
156
+ */
157
+ export function startBridge(): () => void {
158
+ let stopped = false;
159
+ let controller: AbortController | undefined;
160
+
161
+ const loop = async (): Promise<void> => {
162
+ while (!stopped) {
163
+ controller = new AbortController();
164
+ try {
165
+ const response = await fetch('/api/auto-continue-bridge', { signal: controller.signal });
166
+ if (!response.ok || response.body === null) throw new Error(`bridge HTTP ${response.status}`);
167
+ const reader = response.body.getReader();
168
+ const decoder = new TextDecoder();
169
+ let buffer = '';
170
+ for (;;) {
171
+ const { done, value } = await reader.read();
172
+ if (done) break;
173
+ buffer += decoder.decode(value, { stream: true });
174
+ let idx = buffer.indexOf('\n\n');
175
+ while (idx !== -1) {
176
+ const chunk = buffer.slice(0, idx);
177
+ buffer = buffer.slice(idx + 2);
178
+ for (const line of chunk.split('\n')) {
179
+ if (line.startsWith('data: ')) {
180
+ try {
181
+ handleEvent(JSON.parse(line.slice(6)) as Parameters<typeof handleEvent>[0]);
182
+ } catch {
183
+ /* 忽略坏帧 */
184
+ }
185
+ }
186
+ }
187
+ idx = buffer.indexOf('\n\n');
188
+ }
189
+ }
190
+ } catch {
191
+ /* 断线: 退避重连 */
192
+ }
193
+ if (!stopped) await new Promise((resolve) => setTimeout(resolve, 3000));
194
+ }
195
+ };
196
+ void loop();
197
+
198
+ return () => {
199
+ stopped = true;
200
+ controller?.abort();
201
+ };
202
+ }