@keyou007/agent-bot 0.1.27-alpha.0 → 0.1.27-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +63 -7
  3. package/README.zh.md +62 -6
  4. package/SECURITY.md +18 -4
  5. package/assets/workspace-sessions.js +648 -0
  6. package/assets/workspace.css +160 -0
  7. package/assets/workspace.js +1795 -0
  8. package/config.example.yaml +3 -2
  9. package/dist/codex/CodexEventMapper.js +35 -0
  10. package/dist/codex/CodexEventMapper.js.map +1 -1
  11. package/dist/codex/CodexRuntime.js +50 -4
  12. package/dist/codex/CodexRuntime.js.map +1 -1
  13. package/dist/codex/TraeTaskNotification.js +44 -0
  14. package/dist/codex/TraeTaskNotification.js.map +1 -0
  15. package/dist/config/SettingsStore.js +1 -1
  16. package/dist/config/SettingsStore.js.map +1 -1
  17. package/dist/config/loadConfig.js +3 -2
  18. package/dist/config/loadConfig.js.map +1 -1
  19. package/dist/config/paths.js +3 -0
  20. package/dist/config/paths.js.map +1 -1
  21. package/dist/feishu/CardRenderer.js +56 -12
  22. package/dist/feishu/CardRenderer.js.map +1 -1
  23. package/dist/feishu/FeishuMessageClient.js +2 -2
  24. package/dist/feishu/FeishuMessageClient.js.map +1 -1
  25. package/dist/feishu/FeishuTurnPresenter.js +103 -16
  26. package/dist/feishu/FeishuTurnPresenter.js.map +1 -1
  27. package/dist/index.js +61 -17
  28. package/dist/index.js.map +1 -1
  29. package/dist/local-files/DiagramPreview.js +1 -1
  30. package/dist/local-files/GitDiffPreview.js +167 -0
  31. package/dist/local-files/GitDiffPreview.js.map +1 -0
  32. package/dist/local-files/LocalFileViewerServer.js +332 -30
  33. package/dist/local-files/LocalFileViewerServer.js.map +1 -1
  34. package/dist/local-files/MarkdownFileLinks.js +5 -4
  35. package/dist/local-files/MarkdownFileLinks.js.map +1 -1
  36. package/dist/local-files/TurnPreviewPage.js +138 -58
  37. package/dist/local-files/TurnPreviewPage.js.map +1 -1
  38. package/dist/local-files/WebPageTitle.js +85 -0
  39. package/dist/local-files/WebPageTitle.js.map +1 -0
  40. package/dist/local-files/WorkspaceFiles.js +553 -0
  41. package/dist/local-files/WorkspaceFiles.js.map +1 -0
  42. package/dist/local-files/WorkspaceOrigin.js +38 -0
  43. package/dist/local-files/WorkspaceOrigin.js.map +1 -0
  44. package/dist/local-files/WorkspacePage.js +19 -0
  45. package/dist/local-files/WorkspacePage.js.map +1 -0
  46. package/dist/local-files/WorkspaceSessions.js +689 -0
  47. package/dist/local-files/WorkspaceSessions.js.map +1 -0
  48. package/dist/presentation/TurnStateReducer.js +74 -13
  49. package/dist/presentation/TurnStateReducer.js.map +1 -1
  50. package/dist/presentation/turnActivity.js +41 -0
  51. package/dist/presentation/turnActivity.js.map +1 -0
  52. package/dist/presentation/turnStatus.js +11 -0
  53. package/dist/presentation/turnStatus.js.map +1 -1
  54. package/dist/presentation/visibleTurnActivities.js +4 -2
  55. package/dist/presentation/visibleTurnActivities.js.map +1 -1
  56. package/dist/proxy/ProxySessionController.js +150 -14
  57. package/dist/proxy/ProxySessionController.js.map +1 -1
  58. package/dist/runtime/types.js +1 -1
  59. package/dist/runtime/types.js.map +1 -1
  60. package/dist/state/InboundMessageStore.js +54 -0
  61. package/dist/state/InboundMessageStore.js.map +1 -0
  62. package/dist/state/StateStore.js +71 -1
  63. package/dist/state/StateStore.js.map +1 -1
  64. package/dist/state/TurnPreviewJournal.js +4 -2
  65. package/dist/state/TurnPreviewJournal.js.map +1 -1
  66. package/dist/state/migrations.js +20 -0
  67. package/dist/state/migrations.js.map +1 -1
  68. package/dist/supervision/SafeRestartNotifier.js +1 -0
  69. package/dist/supervision/SafeRestartNotifier.js.map +1 -1
  70. package/dist/supervision/SafeRestartScheduler.js +33 -16
  71. package/dist/supervision/SafeRestartScheduler.js.map +1 -1
  72. package/dist/terminal/TerminalLinks.js +32 -0
  73. package/dist/terminal/TerminalLinks.js.map +1 -1
  74. package/dist/terminal/TerminalPage.js +75 -26
  75. package/dist/terminal/TerminalPage.js.map +1 -1
  76. package/dist/terminal/TerminalServer.js +125 -56
  77. package/dist/terminal/TerminalServer.js.map +1 -1
  78. package/docs/technical-reference.md +14 -4
  79. package/docs/technical-reference.zh.md +15 -5
  80. package/npm-shrinkwrap.json +2 -2
  81. package/package.json +1 -1
  82. package/skills/agent-bot/SKILL.md +6 -2
  83. package/src/codex/CodexEventMapper.ts +39 -1
  84. package/src/codex/CodexRuntime.ts +54 -4
  85. package/src/codex/TraeTaskNotification.ts +49 -0
  86. package/src/config/SettingsStore.ts +1 -1
  87. package/src/config/loadConfig.ts +3 -2
  88. package/src/config/paths.ts +4 -0
  89. package/src/feishu/CardRenderer.ts +47 -13
  90. package/src/feishu/FeishuMessageClient.ts +2 -2
  91. package/src/feishu/FeishuTurnPresenter.ts +110 -20
  92. package/src/index.ts +62 -17
  93. package/src/local-files/DiagramPreview.ts +1 -1
  94. package/src/local-files/GitDiffPreview.ts +144 -0
  95. package/src/local-files/LocalFileViewerServer.ts +294 -31
  96. package/src/local-files/MarkdownFileLinks.ts +5 -3
  97. package/src/local-files/TurnPreviewPage.ts +159 -69
  98. package/src/local-files/WebPageTitle.ts +59 -0
  99. package/src/local-files/WorkspaceFiles.ts +468 -0
  100. package/src/local-files/WorkspaceOrigin.ts +31 -0
  101. package/src/local-files/WorkspacePage.ts +21 -0
  102. package/src/local-files/WorkspaceSessions.ts +587 -0
  103. package/src/presentation/TurnStateReducer.ts +76 -14
  104. package/src/presentation/turnActivity.ts +43 -0
  105. package/src/presentation/turnStatus.ts +14 -0
  106. package/src/presentation/turnViewTypes.ts +10 -1
  107. package/src/presentation/visibleTurnActivities.ts +4 -2
  108. package/src/proxy/ProxySessionController.ts +149 -13
  109. package/src/runtime/types.ts +17 -0
  110. package/src/state/InboundMessageStore.ts +72 -0
  111. package/src/state/StateStore.ts +80 -1
  112. package/src/state/TurnPreviewJournal.ts +4 -2
  113. package/src/state/migrations.ts +20 -0
  114. package/src/supervision/SafeRestartNotifier.ts +1 -0
  115. package/src/supervision/SafeRestartScheduler.ts +42 -18
  116. package/src/terminal/TerminalLinks.ts +26 -0
  117. package/src/terminal/TerminalPage.ts +76 -26
  118. package/src/terminal/TerminalServer.ts +119 -48
@@ -0,0 +1,72 @@
1
+ import type Database from "better-sqlite3";
2
+ import type { IncomingMessage } from "../feishu/types.js";
3
+
4
+ export interface PendingInboundMessage {
5
+ message: IncomingMessage;
6
+ localSessionId?: string;
7
+ executionGeneration: number;
8
+ status: "received" | "dispatching";
9
+ createdAt: string;
10
+ }
11
+
12
+ export class InboundMessageStore {
13
+ constructor(private readonly db: Database.Database) {}
14
+
15
+ claim(message: IncomingMessage, localSessionId?: string, executionGeneration = 0): boolean {
16
+ return this.db.transaction(() => {
17
+ const now = new Date().toISOString();
18
+ const receipt = this.db.prepare(`INSERT OR IGNORE INTO inbound_event_receipts
19
+ (event_id, event_kind, created_at) VALUES (?, 'message', ?)`).run(message.messageId, now);
20
+ if (!receipt.changes) return false;
21
+ this.db.prepare(`INSERT INTO inbound_messages
22
+ (message_id, context_key, message_json, local_session_id, execution_generation, status, created_at)
23
+ VALUES (?, ?, ?, ?, ?, 'received', ?)`).run(
24
+ message.messageId, message.contextKey, JSON.stringify(message), localSessionId ?? null, executionGeneration, now,
25
+ );
26
+ return true;
27
+ })();
28
+ }
29
+
30
+ beginDispatch(messageId: string): void {
31
+ this.db.prepare("UPDATE inbound_messages SET status = 'dispatching' WHERE message_id = ? AND status = 'received'")
32
+ .run(messageId);
33
+ }
34
+
35
+ isPending(messageId: string): boolean {
36
+ return Boolean(this.db.prepare("SELECT 1 FROM inbound_messages WHERE message_id = ? AND status IN ('received', 'dispatching')")
37
+ .get(messageId));
38
+ }
39
+
40
+ finish(messageId: string): void {
41
+ this.db.prepare("UPDATE inbound_messages SET status = 'handled', message_json = NULL WHERE message_id = ?")
42
+ .run(messageId);
43
+ }
44
+
45
+ listPending(): PendingInboundMessage[] {
46
+ const rows = this.db.prepare(`SELECT message_json, local_session_id, execution_generation, status, created_at
47
+ FROM inbound_messages WHERE status IN ('received', 'dispatching') ORDER BY rowid`).all() as Array<{
48
+ message_json: string; local_session_id: string | null; execution_generation: number;
49
+ status: PendingInboundMessage["status"]; created_at: string;
50
+ }>;
51
+ return rows.map((row) => ({
52
+ message: JSON.parse(row.message_json) as IncomingMessage,
53
+ localSessionId: row.local_session_id ?? undefined,
54
+ executionGeneration: row.execution_generation,
55
+ status: row.status,
56
+ createdAt: row.created_at,
57
+ }));
58
+ }
59
+
60
+ hasNewerMessage(messageId: string, contextKey: string, localSessionId?: string): boolean {
61
+ return Boolean(this.db.prepare(`SELECT 1 FROM inbound_messages
62
+ WHERE (context_key = ? OR local_session_id = ?)
63
+ AND rowid > (SELECT rowid FROM inbound_messages WHERE message_id = ?) LIMIT 1`)
64
+ .get(contextKey, localSessionId ?? null, messageId));
65
+ }
66
+
67
+ hasDurableWork(messageId: string): boolean {
68
+ return Boolean(this.db.prepare(`SELECT 1 FROM message_turn_bindings WHERE message_id = ?
69
+ UNION ALL SELECT 1 FROM turn_attempts WHERE message_id = ?
70
+ UNION ALL SELECT 1 FROM queued_prompts WHERE message_id = ? LIMIT 1`).get(messageId, messageId, messageId));
71
+ }
72
+ }
@@ -7,6 +7,7 @@ import Database from "better-sqlite3";
7
7
  import { ScheduledTaskStore } from "../scheduling/ScheduledTaskStore.js";
8
8
  import { migrations } from "./migrations.js";
9
9
  import { ExecutionProvenanceStore } from "./ExecutionProvenanceStore.js";
10
+ import { InboundMessageStore } from "./InboundMessageStore.js";
10
11
  import type { UpdateCheckSchedule, UpdateNotice } from "../updates/types.js";
11
12
  import type { ConversationTurn, RuntimeExecutionSettings } from "../runtime/types.js";
12
13
 
@@ -296,6 +297,7 @@ export class StateStore {
296
297
  readonly previews: TurnPreviewJournal;
297
298
  readonly schedules: ScheduledTaskStore;
298
299
  readonly provenance: ExecutionProvenanceStore;
300
+ readonly inboundMessages: InboundMessageStore;
299
301
 
300
302
  constructor(sqlitePath: string, onPreviewError?: (error: unknown) => void) {
301
303
  this.previews = new TurnPreviewJournal(path.join(path.dirname(sqlitePath), "turn-previews"), onPreviewError);
@@ -315,6 +317,7 @@ export class StateStore {
315
317
  this.ensureRecentContextReceiptColumns();
316
318
  this.schedules = new ScheduledTaskStore(this.db);
317
319
  this.provenance = new ExecutionProvenanceStore(this.db);
320
+ this.inboundMessages = new InboundMessageStore(this.db);
318
321
  this.initializeContextSessionMappings();
319
322
  this.db.exec("DROP INDEX IF EXISTS idx_sessions_remote_session_id_unique");
320
323
  this.reconcileDuplicateRemoteSessions();
@@ -1287,6 +1290,81 @@ export class StateStore {
1287
1290
  })();
1288
1291
  }
1289
1292
 
1293
+ workspaceRequest(id: string) {
1294
+ return this.db.prepare(`SELECT local_session_id AS localSessionId, fingerprint, status, posted, message
1295
+ FROM workspace_requests WHERE id = ?`).get(id) as
1296
+ { localSessionId: string; fingerprint: string; status: string; posted: number; message: string | null } | undefined;
1297
+ }
1298
+
1299
+ beginWorkspaceRequest(id: string, localSessionId: string, fingerprint: string): void {
1300
+ this.db.prepare("INSERT INTO workspace_requests (id, local_session_id, fingerprint, status, created_at) VALUES (?, ?, ?, 'pending', ?)")
1301
+ .run(id, localSessionId, fingerprint, Date.now());
1302
+ }
1303
+
1304
+ updateWorkspaceRequest(id: string, status: "pending" | "accepted" | "failed" | "unknown" | "stale", posted = false, message?: string): void {
1305
+ this.db.prepare("UPDATE workspace_requests SET status = ?, posted = max(posted, ?), message = ? WHERE id = ?")
1306
+ .run(status, Number(posted), message ?? null, id);
1307
+ }
1308
+
1309
+ workspaceTurnHead(task: SessionRecord): string | undefined {
1310
+ if (task.lastTurnId && task.status !== "running" && task.status !== "starting"
1311
+ && this.db.prepare("SELECT 1 FROM turn_snapshots WHERE turn_id = ?").get(task.lastTurnId)) return task.lastTurnId;
1312
+ const row = this.db.prepare(`SELECT turn_id AS id FROM turn_snapshots
1313
+ WHERE local_session_id = ? ORDER BY coalesce(json_extract(snapshot_json, '$.startedAt'), 0) DESC, updated_at DESC, rowid DESC LIMIT 1`)
1314
+ .get(task.localSessionId) as { id: string } | undefined;
1315
+ return row?.id ?? this.findForkSourceTurnId(task.localSessionId);
1316
+ }
1317
+
1318
+ workspaceTurnPage(localSessionId: string, head: string | undefined, before?: string, limit = 20): {
1319
+ ids: string[]; more: boolean; beforeMissing: boolean;
1320
+ } {
1321
+ const read = this.db.prepare(`SELECT s.local_session_id AS owner, p.turn_id AS linked, p.parent_turn_id AS parent
1322
+ FROM turn_snapshots s LEFT JOIN turn_parent_links p ON p.turn_id = s.turn_id WHERE s.turn_id = ?`);
1323
+ type Node = { owner: string; linked: string | null; parent: string | null };
1324
+ let id = head;
1325
+ let fallback = true;
1326
+ const ids: string[] = [], seen = new Set<string>();
1327
+ let found = !before;
1328
+ while (id && !seen.has(id) && seen.size < 20_000 && ids.length <= limit) {
1329
+ seen.add(id);
1330
+ let node = read.get(id) as Node | undefined;
1331
+ if (!node || seen.size === 1 && node.owner !== localSessionId && !this.hasTaskHistoryTurn(localSessionId, id)) break;
1332
+ if (fallback && !node.linked) {
1333
+ this.backfillTurnParents(node.owner);
1334
+ node = read.get(id) as Node;
1335
+ fallback = false;
1336
+ }
1337
+ if (found) ids.push(id);
1338
+ if (id === before) found = true;
1339
+ id = node.parent ?? (seen.size === 1 && node.owner === localSessionId
1340
+ ? this.findForkSourceTurnId(localSessionId) : undefined);
1341
+ }
1342
+ return { ids: ids.slice(0, limit), more: ids.length > limit, beforeMissing: !found };
1343
+ }
1344
+
1345
+ workspaceTurnText(turnId: string) {
1346
+ return this.db.prepare(`SELECT updated_at AS revision,
1347
+ substr(json_extract(snapshot_json, '$.prompt'), 1, 24001) AS prompt,
1348
+ snapshot_json -> '$.promptImagePaths' AS promptImages,
1349
+ substr(json_extract(snapshot_json, '$.finalResponse'), 1, 48001) AS answer,
1350
+ substr(json_extract(snapshot_json, '$.assistantText'), 1, 48001) AS live,
1351
+ substr(json_extract(snapshot_json, '$.error'), 1, 3000) AS error,
1352
+ substr(json_extract(snapshot_json, '$.statusMessage'), 1, 3000) AS notice,
1353
+ json_extract(snapshot_json, '$.status') AS status,
1354
+ json_extract(snapshot_json, '$.startedAt') AS startedAt,
1355
+ json_extract(snapshot_json, '$.historyDetail') AS detail,
1356
+ (SELECT json_group_array(json_object('kind', kind, 'id', id, 'text', body, 'images', json(images))) FROM (
1357
+ SELECT json_extract(value, '$.kind') AS kind, json_extract(value, '$.id') AS id,
1358
+ substr(json_extract(value, '$.text'), 1, 4000) AS body,
1359
+ value -> '$.localImagePaths' AS images
1360
+ FROM json_each(snapshot_json, '$.activities')
1361
+ WHERE json_extract(value, '$.kind') IN ('user', 'assistant') LIMIT 30)) AS dialogue
1362
+ FROM turn_snapshots WHERE turn_id = ?`).get(turnId) as {
1363
+ revision: string; prompt: string | null; promptImages: string | null; answer: string | null; live: string | null;
1364
+ error: string | null; notice: string | null; status: string; startedAt: number; detail: string | null; dialogue: string;
1365
+ } | undefined;
1366
+ }
1367
+
1290
1368
  getTurnSnapshot(turnId: string): unknown {
1291
1369
  const row = this.db
1292
1370
  .prepare("SELECT snapshot_json FROM turn_snapshots WHERE turn_id = ?")
@@ -1957,7 +2035,8 @@ export class StateStore {
1957
2035
  FROM turn_snapshots AS snapshots
1958
2036
  LEFT JOIN turn_deliveries AS deliveries ON deliveries.turn_id = snapshots.turn_id
1959
2037
  WHERE json_extract(snapshots.snapshot_json, '$.status') = 'completed'
1960
- AND length(coalesce(json_extract(snapshots.snapshot_json, '$.finalResponse'), '')) > 0
2038
+ AND (length(coalesce(json_extract(snapshots.snapshot_json, '$.finalResponse'), '')) > 0
2039
+ OR json_array_length(snapshots.snapshot_json, '$.taskNotificationCard') > 0)
1961
2040
  AND deliveries.final_delivered_at IS NULL
1962
2041
  ORDER BY snapshots.updated_at ASC
1963
2042
  `).all() as Array<{
@@ -4,6 +4,7 @@ import { createHash, type Hash } from "node:crypto";
4
4
  import type { AgentEvent, ToolState } from "../runtime/types.js";
5
5
  import { approvalActivityId, continueTurnView, reduceTurnEvent } from "../presentation/TurnStateReducer.js";
6
6
  import type { TurnViewState } from "../presentation/turnViewTypes.js";
7
+ import { normalizeTurnActivity } from "../presentation/turnActivity.js";
7
8
 
8
9
  type TextChange = { key: string; field: string; append: boolean; text: string };
9
10
  export type PreviewRecord =
@@ -307,7 +308,7 @@ export class TurnPreviewProjection {
307
308
 
308
309
  apply(record: PreviewRecord, revision: number): void {
309
310
  if (record.kind === "seed") {
310
- this.state = { ...record.state, activities: [...record.state.activities], activitiesTruncated: false };
311
+ this.state = { ...record.state, activities: record.state.activities.map(normalizeTurnActivity), activitiesTruncated: false };
311
312
  for (const change of seedTexts(record.state)) this.text.set(change.key, this.wantsFull(change.key) ? change.text : change.text.slice(0, 6000));
312
313
  if (this.details !== true) {
313
314
  this.state = { ...this.state, fullToolOutputs: {}, fullToolErrors: {}, activities: this.state.activities.map((a) => a.kind === "tool"
@@ -383,7 +384,8 @@ export class TurnPreviewProjection {
383
384
  const reasoningId = event.type === "reasoning_delta" || event.type === "reasoning_completed" ? event.itemId
384
385
  : event.type === "progress" ? event.reasoning?.itemId : undefined;
385
386
  if (reasoningId) this.state.reasoningItems = this.state.reasoningItems?.map((r) => r.itemId === reasoningId ? { ...r, previewRevision: revision } : r);
386
- if (event.type === "context_compaction") {
387
+ if (event.type === "context_compaction" || event.type === "model_queue_updated"
388
+ || old.modelQueueActivityId && !this.state.modelQueueActivityId) {
387
389
  for (const a of this.state.activities) if (!old.activities.includes(a)) this.changed.add(a.id);
388
390
  }
389
391
  if (event.type === "approval_resolved") this.changed.add(approvalActivityId(event.turnId, event.requestId));
@@ -1,4 +1,9 @@
1
1
  export const migrations = [
2
+ `CREATE TABLE IF NOT EXISTS workspace_requests (
3
+ id TEXT PRIMARY KEY, local_session_id TEXT NOT NULL, fingerprint TEXT NOT NULL,
4
+ status TEXT NOT NULL, posted INTEGER NOT NULL DEFAULT 0, message TEXT, created_at INTEGER NOT NULL
5
+ );
6
+ CREATE INDEX IF NOT EXISTS idx_workspace_requests_task ON workspace_requests(local_session_id, created_at DESC);`,
2
7
  `CREATE TABLE IF NOT EXISTS execution_provenance (
3
8
  submission_id TEXT PRIMARY KEY, instruction_id TEXT NOT NULL, attempt_id TEXT NOT NULL,
4
9
  local_session_id TEXT NOT NULL, turn_id TEXT, trigger TEXT NOT NULL, parent_source_turn_id TEXT,
@@ -70,6 +75,19 @@ export const migrations = [
70
75
  );
71
76
  `,
72
77
  `
78
+ CREATE TABLE IF NOT EXISTS inbound_messages (
79
+ message_id TEXT PRIMARY KEY,
80
+ context_key TEXT NOT NULL,
81
+ message_json TEXT,
82
+ local_session_id TEXT,
83
+ execution_generation INTEGER NOT NULL DEFAULT 0,
84
+ status TEXT NOT NULL,
85
+ created_at TEXT NOT NULL
86
+ );
87
+ CREATE INDEX IF NOT EXISTS idx_inbound_messages_status ON inbound_messages(status);
88
+ CREATE INDEX IF NOT EXISTS idx_inbound_messages_context ON inbound_messages(context_key, created_at);
89
+ `,
90
+ `
73
91
  CREATE TABLE IF NOT EXISTS message_reactions (
74
92
  message_id TEXT PRIMARY KEY,
75
93
  context_key TEXT NOT NULL,
@@ -184,6 +202,7 @@ export const migrations = [
184
202
  ON turn_attempts(local_session_id, updated_at);
185
203
  CREATE INDEX IF NOT EXISTS idx_turn_attempts_turn
186
204
  ON turn_attempts(turn_id);
205
+ CREATE INDEX IF NOT EXISTS idx_turn_attempts_message ON turn_attempts(message_id);
187
206
  `,
188
207
  `
189
208
  CREATE TABLE IF NOT EXISTS goal_card_deliveries (
@@ -259,5 +278,6 @@ export const migrations = [
259
278
  CREATE INDEX IF NOT EXISTS idx_scheduled_runs_status ON scheduled_runs(status);
260
279
  CREATE INDEX IF NOT EXISTS idx_scheduled_runs_job ON scheduled_runs(job_id);
261
280
  CREATE INDEX IF NOT EXISTS idx_turn_attempts_pending_turn ON turn_attempts(pending_turn_id);
281
+ CREATE INDEX IF NOT EXISTS idx_workspace_turn_head ON turn_snapshots(local_session_id, coalesce(json_extract(snapshot_json, '$.startedAt'), 0) DESC, updated_at DESC);
262
282
  `,
263
283
  ] as const;
@@ -156,6 +156,7 @@ export class SafeRestartNotifier {
156
156
  phase: status.phase,
157
157
  remainingMs: status.remainingMs,
158
158
  pendingFinalDeliveries: status.activity.pendingFinalDeliveries,
159
+ pendingInboundMessages: status.activity.pendingInboundMessages,
159
160
  activeTerminals: status.activity.activeTerminals,
160
161
  terminalBlockers: status.activity.terminalBlockers,
161
162
  contextKey,
@@ -5,6 +5,7 @@ export interface ServerActivityState {
5
5
  terminalBlockers?: ActiveTerminal[];
6
6
  runningSessions: number;
7
7
  pendingFinalDeliveries: number;
8
+ pendingInboundMessages?: number;
8
9
  latestInboundAt?: string;
9
10
  }
10
11
 
@@ -32,7 +33,7 @@ export interface SafeRestartStatus {
32
33
 
33
34
  export interface SafeRestartSchedulerOptions {
34
35
  readActivity(): ServerActivityState;
35
- onReady(reason: string, notificationTargets: RestartNotificationTarget[]): void | Promise<void>;
36
+ onReady(reason: string, notificationTargets: RestartNotificationTarget[]): void | boolean | Promise<void | boolean>;
36
37
  onStatus?(status: SafeRestartStatus): void | Promise<void>;
37
38
  onStatusError?(error: unknown): void;
38
39
  quietPeriodMs?: number;
@@ -54,6 +55,7 @@ export class SafeRestartScheduler {
54
55
  private scheduleId = 0;
55
56
  private restartImmediatelyIfIdle = false;
56
57
  private restartingNow = false;
58
+ private forcingNow = false;
57
59
 
58
60
  constructor(private readonly options: SafeRestartSchedulerOptions) {}
59
61
 
@@ -65,6 +67,10 @@ export class SafeRestartScheduler {
65
67
  return this.restartingNow;
66
68
  }
67
69
 
70
+ get forcing(): boolean {
71
+ return this.forcingNow;
72
+ }
73
+
68
74
  get pendingReason(): string | undefined {
69
75
  return this.reason;
70
76
  }
@@ -108,14 +114,13 @@ export class SafeRestartScheduler {
108
114
 
109
115
  async forceScheduled(expectedScheduleId: number): Promise<boolean> {
110
116
  const reason = this.reason;
111
- if (!reason || this.scheduleId !== expectedScheduleId) return false;
112
- await this.restart(reason, expectedScheduleId, this.options.readActivity());
113
- return true;
117
+ if (!reason || this.restartingNow || this.scheduleId !== expectedScheduleId) return false;
118
+ return this.restart(reason, expectedScheduleId, this.options.readActivity(), true);
114
119
  }
115
120
 
116
121
  async cancelScheduled(expectedScheduleId: number): Promise<boolean> {
117
122
  const reason = this.reason;
118
- if (!reason || this.scheduleId !== expectedScheduleId) return false;
123
+ if (!reason || this.restartingNow || this.scheduleId !== expectedScheduleId) return false;
119
124
  const activity = this.options.readActivity();
120
125
  const notificationTargets = this.notificationTargetsSnapshot();
121
126
  this.clear();
@@ -218,20 +223,28 @@ export class SafeRestartScheduler {
218
223
  await this.restart(reason, scheduleId, confirmed);
219
224
  }
220
225
 
221
- private async restart(reason: string, scheduleId: number, activity: ServerActivityState): Promise<void> {
226
+ private async restart(reason: string, scheduleId: number, activity: ServerActivityState, force = false): Promise<boolean> {
227
+ if (this.restartingNow) return false;
222
228
  this.restartingNow = true;
229
+ this.forcingNow = force;
223
230
  const notificationTargets = this.notificationTargetsSnapshot();
224
- this.clear();
225
- await this.emitStatus({
226
- scheduleId,
227
- reason,
228
- notificationTargets,
229
- phase: "restarting",
230
- activity,
231
- remainingMs: 0,
232
- });
233
- try { await this.options.onReady(reason, notificationTargets); }
234
- finally { this.restartingNow = false; }
231
+ try {
232
+ await this.emitStatus({ scheduleId, reason, notificationTargets, phase: "restarting", activity, remainingMs: 0 });
233
+ const confirmed = this.options.readActivity();
234
+ if (this.scheduleId !== scheduleId || !this.reason || (!force && (
235
+ hasActiveWork(confirmed) || confirmed.pendingFinalDeliveries > 0
236
+ || confirmed.latestInboundAt !== activity.latestInboundAt
237
+ ))) return false;
238
+ if (await this.options.onReady(reason, notificationTargets) === false) return false;
239
+ if (this.scheduleId === scheduleId) this.clear();
240
+ return true;
241
+ } finally {
242
+ this.restartingNow = false;
243
+ this.forcingNow = false;
244
+ this.idleSince = undefined;
245
+ this.idleInboundAt = undefined;
246
+ if (this.reason && this.scheduleId === scheduleId) this.restartImmediatelyIfIdle = false;
247
+ }
235
248
  }
236
249
 
237
250
  private requestPoll(): void {
@@ -285,7 +298,18 @@ export class SafeRestartScheduler {
285
298
  }
286
299
 
287
300
  function hasActiveWork(state: ServerActivityState): boolean {
288
- return state.runningSessions > 0 || (state.activeTerminals ?? 0) > 0;
301
+ return state.runningSessions > 0 || (state.activeTerminals ?? 0) > 0 || (state.pendingInboundMessages ?? 0) > 0;
302
+ }
303
+
304
+ export function commitRestartHandoff(
305
+ state: ServerActivityState,
306
+ expectedInboundAt: string | undefined,
307
+ pauseInbound: () => void,
308
+ force = false,
309
+ ): boolean {
310
+ if (!force && (hasActiveWork(state) || state.pendingFinalDeliveries > 0 || state.latestInboundAt !== expectedInboundAt)) return false;
311
+ pauseInbound();
312
+ return true;
289
313
  }
290
314
 
291
315
  function normalizedNotificationTarget(
@@ -4,6 +4,7 @@ import path from "node:path";
4
4
  import { z } from "zod";
5
5
 
6
6
  const record = z.object({ token: z.string().regex(/^[A-Za-z0-9_-]{8}$/u), jobId: z.string().regex(/^[a-f0-9-]{36}$/u) });
7
+ const workspaceRecord = z.object({ token: record.shape.token, cwd: z.string().min(1), ownerId: z.string().min(1), instance: z.string().regex(/^[a-f0-9]{16}$/u) });
7
8
 
8
9
  export class TerminalLinks {
9
10
  constructor(private readonly directory: string, private readonly secret: Buffer) {
@@ -40,6 +41,31 @@ export class TerminalLinks {
40
41
  throw new Error("Unable to allocate a terminal recovery link.");
41
42
  }
42
43
 
44
+ createWorkspace(cwd: string, ownerId: string, instance: string): string {
45
+ workspaceRecord.omit({ token: true }).parse({ cwd, ownerId, instance });
46
+ for (let attempt = 0; attempt < 16; attempt++) {
47
+ const token = createHmac("sha256", this.secret).update(JSON.stringify(["terminal:workspace", cwd, ownerId, instance, attempt])).digest("base64url").slice(0, 8);
48
+ const existing = this.resolveWorkspace(token);
49
+ if (existing?.cwd === cwd && existing.ownerId === ownerId && existing.instance === instance) return token;
50
+ try {
51
+ fs.writeFileSync(this.filePath(token), JSON.stringify({ token, cwd, ownerId, instance }), { flag: "wx", mode: 0o600 });
52
+ return token;
53
+ } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
54
+ }
55
+ throw new Error("Unable to allocate a workspace terminal link.");
56
+ }
57
+
58
+ resolveWorkspace(token: string): z.infer<typeof workspaceRecord> | undefined {
59
+ if (!/^[A-Za-z0-9_-]{8}$/u.test(token)) return undefined;
60
+ try {
61
+ const parsed = workspaceRecord.safeParse(JSON.parse(fs.readFileSync(this.filePath(token), "utf8")) as unknown);
62
+ return parsed.success && parsed.data.token === token ? parsed.data : undefined;
63
+ } catch (error) {
64
+ if (error instanceof SyntaxError || (error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
65
+ throw error;
66
+ }
67
+ }
68
+
43
69
  resolve(token: string): string | undefined {
44
70
  if (!/^[A-Za-z0-9_-]{8}$/u.test(token)) return undefined;
45
71
  let content: string;
@@ -1,17 +1,23 @@
1
- export function terminalPage(base: string, recovery = false): string {
1
+ import { DEFAULT_TERMINAL_PASSWORD } from "../config/schema.js";
2
+
3
+ export function terminalPage(base: string, recovery = false, autoResume = false, defaultPassword = false, workspace = false): string {
4
+ defaultPassword = defaultPassword && !autoResume && !workspace;
2
5
  base = base.replaceAll("&", "&amp;").replaceAll(String.fromCharCode(34), "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
3
6
  return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
4
7
  <title>AgentBot Terminal</title><link rel="stylesheet" href="${base}/assets/xterm.css"><link rel="stylesheet" href="${base}/assets/terminal.css">
5
8
  <script defer src="${base}/assets/xterm.js"></script><script defer src="${base}/assets/fit.js"></script><script defer src="${base}/assets/terminal.js"></script></head>
6
- <body data-base="${base}" data-recovery="${recovery}"><header><strong>AgentBot <span>Terminal</span></strong><div id="status" role="status">尚未连接</div><button id="connect">连接</button><button id="interrupt" disabled>Ctrl+C</button><button id="close" disabled>关闭终端</button></header>
7
- <section id="welcome"><h1>连接终端</h1><p>此终端拥有 AgentBot 所在电脑的系统用户权限。</p><label for="password">终端密码</label><div class="password-row"><input id="password" type="password" autocomplete="current-password" maxlength="256" autofocus><button id="welcome-connect" type="button">连接</button></div></section><div id="terminal"></div>
8
- <footer id="details">前台连接时不因空闲关闭;后台空闲 30 分钟或网页断开 3 分钟后自动关闭 Shell · 成功重连取消断开计时并重置空闲计时 · 可从原会话的终端管理卡打开或关闭终端</footer></body></html>`;
9
+ <body data-base="${base}" data-recovery="${recovery}" data-resume="${autoResume}" data-default-password="${defaultPassword}" data-workspace="${workspace}"><header><strong>AgentBot <span>Terminal</span></strong><div id="status" role="status">尚未连接</div><button id="connect">连接</button><button id="interrupt" disabled>Ctrl+C</button><button id="close" title="前台连接不因空闲关闭;后台空闲或网页断开 30 分钟后关闭。重连重新计时,可从原会话的终端管理卡打开或关闭终端。" disabled>关闭终端</button></header>
10
+ <section id="welcome"><h1>连接终端</h1><p>此终端拥有 AgentBot 所在电脑的系统用户权限。</p>${workspace
11
+ ? '<button id="welcome-connect" type="button">连接</button>'
12
+ : `<label for="password">终端密码</label><div class="password-row"><input id="password" type="password" autocomplete="current-password" maxlength="256" value="${defaultPassword ? DEFAULT_TERMINAL_PASSWORD : ""}" aria-describedby="password-hint" autofocus><button id="welcome-connect" type="button">连接</button></div><p id="password-hint">与工作台共用密码,可在飞书 /setting → 高级 → 工作台 / 终端密码中修改。</p>`}</section><div id="terminal"></div>
13
+ </body></html>`;
9
14
  }
10
15
 
11
16
  export const TERMINAL_CSS = `
12
17
  #welcome-connect{padding:10px 20px;font:inherit}
13
18
  #welcome{width:100%}.password-row{display:flex;gap:12px;margin-top:8px;max-width:440px}#password{min-width:0;flex:1;background:#191f2b;border:1px solid #415775;border-radius:6px;padding:10px 12px;color:inherit;font:inherit}#password:focus{outline:2px solid #84c1ff;outline-offset:2px}
14
- :root{color-scheme:dark;font:14px system-ui,sans-serif;background:#10141b;color:#dbe4f1}*{box-sizing:border-box}body{margin:0;height:100dvh;display:flex;flex-direction:column}header{display:flex;gap:12px;align-items:center;padding:12px 18px;background:#191f2b;border-bottom:1px solid #303a4d;flex-wrap:wrap}header strong{font-size:17px}header strong span{font-weight:400;color:#9aacc7}#status{flex:1;color:#adbfdb;font-size:13px}button{background:#25334a;border:1px solid #415775;border-radius:7px;padding:8px 12px;color:#e5efff;cursor:pointer}button:hover{background:#304661}button:disabled{opacity:.45;cursor:default}#close{border-color:#86505a}#welcome{margin:40px auto;max-width:780px;padding:0 24px;line-height:1.8}h1{font-size:25px}#terminal{flex:1;min-height:0;padding:12px 14px;display:none}.xterm{height:100%}footer{font-size:12px;color:#8f9eb7;padding:9px 18px;border-top:1px solid #293142}body.connected #welcome{display:none}body.connected #terminal{display:block}@media(max-width:650px){header{padding:10px;gap:8px}#status{min-width:100%}footer{padding:7px 10px}#terminal{padding:6px}}
19
+ :root{color-scheme:dark;font:14px system-ui,sans-serif;background:#10141b;color:#dbe4f1}*{box-sizing:border-box}body{margin:0;height:100dvh;display:flex;flex-direction:column}header{display:flex;gap:12px;align-items:center;padding:12px 18px;background:#191f2b;border-bottom:1px solid #303a4d;flex-wrap:wrap}header strong{font-size:17px}header strong span{font-weight:400;color:#9aacc7}#status{flex:1;color:#adbfdb;font-size:13px}button{background:#25334a;border:1px solid #415775;border-radius:7px;padding:8px 12px;color:#e5efff;cursor:pointer}button:hover{background:#304661}button:disabled{opacity:.45;cursor:default}#close{border-color:#86505a}#welcome{margin:40px auto;max-width:780px;padding:0 24px;line-height:1.8}h1{font-size:25px}#terminal{flex:1;min-height:0;padding:12px 14px;display:none}.xterm{height:100%}body.connected #welcome{display:none}body.connected #terminal{display:block}
20
+ @media(max-width:650px){header{padding:4px 6px;gap:6px;flex-shrink:0}header strong{display:none}#status{flex:0 0 100%;min-width:0;font-size:12px;line-height:1.4;overflow-wrap:anywhere}#status:has(.terminal-directory){flex:1}.terminal-directory{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px}header button{flex-shrink:0;min-height:44px;padding:6px 8px;font-size:12px}#terminal{padding:6px}}
15
21
  `;
16
22
 
17
23
  export const TERMINAL_SCRIPT = String.raw`(() => {
@@ -24,16 +30,22 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
24
30
  const interrupt = document.getElementById('interrupt');
25
31
  const storageKey = 'agentbot-terminal:' + location.pathname;
26
32
  const recovery = document.body.dataset.recovery === 'true';
33
+ const autoResume = recovery && document.body.dataset.resume === 'true';
34
+ const defaultPassword = document.body.dataset.defaultPassword === 'true';
35
+ const workspace = document.body.dataset.workspace === 'true';
36
+ const initialPassword = password?.value;
37
+ if (autoResume) document.getElementById('welcome').hidden = true;
27
38
  if (recovery) document.querySelector('#welcome h1').textContent = '恢复已有终端';
28
- let session, ws, term, observer, retryTimer, socketTimer, checking, visibilityTimer;
29
- let socketReady = false;
39
+ let session, ws, term, observer, retryTimer, socketTimer, checking, visibilityTimer, countdownTimer;
40
+ let socketReady = false, startRequested = false;
30
41
  let epoch = 0, failures = 0, stopped = false, pageHidden = false, offline = false, busy = false;
31
42
  try { session = JSON.parse(sessionStorage.getItem(storageKey) || 'null'); } catch {}
32
- const awake = () => !pageHidden && !document.hidden && !offline;
43
+ let parentVisible = window.parent === window;
44
+ const awake = () => parentVisible && !pageHidden && !document.hidden && !offline;
33
45
  const post = async (route, data, controller = new AbortController()) => {
34
46
  const timer = setTimeout(() => controller.abort(), 10000);
35
47
  try {
36
- const response = await fetch(base + '/api/' + route, { method:'POST', credentials:'omit', cache:'no-store',
48
+ const response = await fetch(base + '/api/' + route, { method:'POST', credentials:workspace?'same-origin':'omit', cache:'no-store',
37
49
  signal:controller.signal, headers:{'Content-Type':'application/json'}, body:JSON.stringify(data) });
38
50
  let value;
39
51
  try { value = await response.json(); } catch {
@@ -54,20 +66,40 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
54
66
  button.disabled = busy || (!!session && !retry);
55
67
  }
56
68
  close.disabled = busy || !session;
57
- password.disabled = busy;
69
+ if (password) password.disabled = busy;
58
70
  }
59
71
  function invalidate() {
72
+ cancelDefaultConnect();
60
73
  epoch++; clearTimeout(retryTimer); clearTimeout(socketTimer);
61
74
  clearTimeout(visibilityTimer); socketReady = false;
62
75
  checking?.abort(); checking = undefined;
63
76
  const old = ws; ws = undefined; old?.close(); interrupt.disabled = true;
64
77
  if (term) term.options.disableStdin = true;
65
78
  }
79
+ function cancelDefaultConnect() {
80
+ if (countdownTimer === undefined) return;
81
+ clearTimeout(countdownTimer); countdownTimer = undefined;
82
+ status.textContent = '已取消自动连接';
83
+ }
84
+ function countdown(seconds = 5) {
85
+ if (!awake() || busy || session || password.value !== initialPassword) { cancelDefaultConnect(); return; }
86
+ status.textContent = '使用默认密码,' + seconds + ' 秒后自动连接';
87
+ countdownTimer = setTimeout(() => {
88
+ if (!awake() || password.value !== initialPassword) { cancelDefaultConnect(); return; }
89
+ if (seconds === 1) connect.click(); else countdown(seconds - 1);
90
+ }, 1000);
91
+ }
66
92
  function forget() {
67
93
  session = undefined; sessionStorage.removeItem(storageKey);
68
94
  buttons(true);
69
95
  }
70
- function end(text) { stopped = true; invalidate(); forget(); status.textContent = text; }
96
+ function end(text, clear = false) {
97
+ stopped = true; invalidate(); forget(); status.textContent = text;
98
+ if (clear) {
99
+ observer?.disconnect(); term?.dispose(); term = undefined;
100
+ document.body.classList.remove('connected');
101
+ }
102
+ }
71
103
  function fail(text) { stopped = true; invalidate(); status.textContent = text; buttons(true); }
72
104
  function schedule(delay) {
73
105
  clearTimeout(retryTimer);
@@ -95,7 +127,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
95
127
  const url = new URL(base + '/socket', location.origin); url.protocol = location.protocol === 'https:' ? 'wss:' : 'ws:';
96
128
  let socket;
97
129
  try { socket = new WebSocket(url); } catch (error) { retry('WebSocket 连接失败', error); return; }
98
- ws = socket; status.textContent = '授权已通过,正在连接终端…'; buttons();
130
+ ws = socket; status.textContent = workspace ? '正在连接终端…' : '授权已通过,正在连接终端…'; buttons();
99
131
  const valid = () => ws === socket && generation === epoch && session === current && !stopped;
100
132
  socketTimer = setTimeout(() => {
101
133
  if (!valid()) return;
@@ -133,13 +165,16 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
133
165
  const restored = () => {
134
166
  if (!active()) return;
135
167
  terminal.options.disableStdin = false; terminal.focus();
136
- status.textContent = '已连接 · ' + result.cwd; interrupt.disabled = false; buttons();
168
+ status.textContent = '已连接 · ';
169
+ const directory = document.createElement('span');
170
+ directory.className = 'terminal-directory'; directory.textContent = result.cwd; directory.title = result.cwd;
171
+ status.append(directory); interrupt.disabled = false; buttons();
137
172
  };
138
173
  // xterm parses asynchronously. Keep replay silent until its write callback,
139
174
  // before subsequently queued live output is parsed. Startup output is live.
140
175
  if (result.output) terminal.write(result.output, restored); else restored();
141
176
  } else if (result.type === 'data') term?.write(result.data);
142
- else if (result.type === 'exit') end(result.message || '终端已结束');
177
+ else if (result.type === 'exit') end(result.message || '终端已结束', workspace && result.clear === true);
143
178
  else if (result.type === 'error') fail((result.stage === 'spawn' ? 'Shell 启动失败:' : '终端连接被拒绝:') + result.message);
144
179
  } catch (error) { fail('终端界面初始化或消息处理失败:' + message(error)); }
145
180
  };
@@ -164,7 +199,7 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
164
199
  else end(result.message || '授权已失效,请重新请求连接');
165
200
  } catch (error) {
166
201
  if (generation !== epoch || current !== session || stopped || !awake()) return;
167
- if ([400,401,404,410].includes(error.httpStatus)) end('授权状态查询失败:' + message(error) + '。请重新请求连接。');
202
+ if ([400,401,404,410].includes(error.httpStatus)) end('连接状态查询失败:' + message(error) + '。请重新请求连接。', workspace && error.httpStatus === 401);
168
203
  else if (error.httpStatus === 403) fail('授权状态查询被拒绝:' + message(error));
169
204
  else retry('暂时无法查询授权状态', error);
170
205
  } finally { if (checking === controller) checking = undefined; }
@@ -174,23 +209,25 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
174
209
  stopped = false; failures = 0; invalidate();
175
210
  if (session) { status.textContent = '正在恢复已有终端授权…'; buttons(); check(); return; }
176
211
  document.body.classList.remove('connected');
177
- if (!password.value) { status.textContent = '请输入终端密码'; password.focus(); return; }
178
- busy = true; buttons(); status.textContent = '正在验证密码…';
212
+ if (password && !autoResume && !password.value) { status.textContent = '请输入终端密码'; password.focus(); return; }
213
+ busy = true; buttons(); status.textContent = workspace ? '正在打开终端…' : autoResume ? '正在恢复原终端…' : '正在验证密码…';
179
214
  try {
180
215
  if (!globalThis.crypto?.getRandomValues) throw new Error('浏览器不支持安全随机数,请使用新版浏览器。');
181
216
  const browserKey = Array.from(crypto.getRandomValues(new Uint8Array(32)), (n) => n.toString(16).padStart(2,'0')).join('');
182
- const result = await post('request', {launch:location.pathname,browserKey,password:password.value});
183
- password.value = '';
217
+ const result = await post('request', {launch:location.pathname,browserKey,password:autoResume ? undefined : password?.value});
218
+ if (password) password.value = '';
184
219
  session = {requestId:result.requestId,browserKey}; sessionStorage.setItem(storageKey,JSON.stringify(session));
185
- status.textContent = '密码已验证,正在连接终端…';
186
- } catch (error) { status.textContent = '连接失败:' + message(error); password.focus(); }
220
+ status.textContent = workspace ? '正在连接终端…' : autoResume ? '正在恢复原终端…' : '密码已验证,正在连接终端…';
221
+ } catch (error) { status.textContent = '连接失败:' + message(error); password?.focus(); }
187
222
  finally { busy = false; buttons(!session); }
188
223
  check();
189
224
  };
190
- password.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); welcomeConnect.click(); } });
225
+ password?.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); welcomeConnect.click(); } });
226
+ password?.addEventListener('input', cancelDefaultConnect);
227
+ password?.addEventListener('change', cancelDefaultConnect);
191
228
  interrupt.onclick = () => { if (ws?.readyState === WebSocket.OPEN && !interrupt.disabled) ws.send(JSON.stringify({type:'input',data:String.fromCharCode(3)})); };
192
229
  close.onclick = async () => {
193
- if (busy || !session || !confirm('关闭该终端和 Shell?已脱离终端的后台进程可能继续运行。')) return;
230
+ if (busy || !session || !confirm('关闭该终端和 Shell?\n' + close.title + '\n已脱离终端的后台进程可能继续运行。')) return;
194
231
  busy = true; stopped = true; invalidate(); buttons();
195
232
  try { await post('close',session); end('终端已关闭'); }
196
233
  catch (error) {
@@ -203,8 +240,12 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
203
240
  if (session && !stopped) { status.textContent = '连接已暂停,返回网页或网络恢复后自动重连'; buttons(true); }
204
241
  }
205
242
  function resume() {
206
- if (stopped || !awake() || busy || !session) return;
207
- clearTimeout(retryTimer); check();
243
+ if (stopped || !awake() || busy) return;
244
+ if (startRequested) {
245
+ startRequested = false;
246
+ if (!session) { connect.click(); return; }
247
+ }
248
+ if (session) { clearTimeout(retryTimer); check(); }
208
249
  }
209
250
  window.addEventListener('pagehide', () => { pageHidden = true; suspend(); });
210
251
  window.addEventListener('pageshow', () => { pageHidden = false; resume(); });
@@ -212,5 +253,14 @@ export const TERMINAL_SCRIPT = String.raw`(() => {
212
253
  window.addEventListener('offline', () => { offline = true; suspend(); });
213
254
  window.addEventListener('online', () => { offline = false; resume(); });
214
255
  window.addEventListener('focus', resume);
215
- buttons(); check();
256
+ window.addEventListener('message', event => {
257
+ if (window.parent === window || event.source !== window.parent || event.origin !== location.origin || event.data?.type !== 'agentbot-workspace-visibility' || typeof event.data.visible !== 'boolean') return;
258
+ if (workspace && event.data.start === true) startRequested = true;
259
+ parentVisible = event.data.visible; reportVisibility();
260
+ if (parentVisible) resume(); else if (!ws) suspend();
261
+ });
262
+ buttons();
263
+ if (!session && autoResume) connect.click();
264
+ else if (!session && defaultPassword) countdown();
265
+ else check();
216
266
  })();`;