@parallelworks/code 0.3.0 → 0.5.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.
Files changed (118) hide show
  1. package/README.md +625 -113
  2. package/dist/accountApi.d.ts +31 -0
  3. package/dist/accountApi.js +182 -0
  4. package/dist/agentSwitcher.d.ts +120 -0
  5. package/dist/agentSwitcher.js +187 -0
  6. package/dist/ago.d.ts +1 -3
  7. package/dist/ago.js +8 -10
  8. package/dist/allocations.d.ts +41 -0
  9. package/dist/allocations.js +76 -0
  10. package/dist/api.d.ts +1319 -50
  11. package/dist/chatStrings.d.ts +189 -0
  12. package/dist/chatStrings.js +218 -0
  13. package/dist/claudeAccounts.d.ts +57 -2
  14. package/dist/claudeAccounts.js +144 -6
  15. package/dist/claudeApi.d.ts +2 -1
  16. package/dist/claudeApi.js +50 -4
  17. package/dist/claudeSignIn.d.ts +19 -1
  18. package/dist/claudeSignIn.js +12 -2
  19. package/dist/command.d.ts +5 -1
  20. package/dist/command.js +6 -1
  21. package/dist/commandsApi.d.ts +11 -1
  22. package/dist/commandsApi.js +24 -5
  23. package/dist/createPwCodeApi.d.ts +114 -6
  24. package/dist/createPwCodeApi.js +21 -3
  25. package/dist/directories.d.ts +161 -0
  26. package/dist/directories.js +301 -0
  27. package/dist/goal.d.ts +89 -0
  28. package/dist/goal.js +164 -0
  29. package/dist/imageFit.d.ts +23 -0
  30. package/dist/imageFit.js +27 -0
  31. package/dist/images.d.ts +28 -0
  32. package/dist/images.js +38 -6
  33. package/dist/index.d.ts +31 -15
  34. package/dist/index.js +29 -14
  35. package/dist/loadError.d.ts +8 -0
  36. package/dist/loadError.js +19 -0
  37. package/dist/locales/en/agentTranscript.js +74 -12
  38. package/dist/locales/en/agents.js +86 -11
  39. package/dist/locales/en.d.ts +137 -8
  40. package/dist/locales/es/agentTranscript.js +74 -12
  41. package/dist/locales/es/agents.js +86 -11
  42. package/dist/locales/ja/agentTranscript.js +77 -15
  43. package/dist/locales/ja/agents.js +60 -122
  44. package/dist/locales/ko/agentTranscript.js +74 -12
  45. package/dist/locales/ko/agents.js +86 -11
  46. package/dist/locales/zh/agentTranscript.js +72 -10
  47. package/dist/locales/zh/agents.js +86 -11
  48. package/dist/machine.d.ts +2 -0
  49. package/dist/modelPicker.d.ts +79 -0
  50. package/dist/modelPicker.js +107 -0
  51. package/dist/notices.d.ts +2 -0
  52. package/dist/notices.js +67 -32
  53. package/dist/platformDefaults.d.ts +22 -0
  54. package/dist/platformDefaults.js +30 -0
  55. package/dist/preferences.d.ts +78 -0
  56. package/dist/preferences.js +128 -0
  57. package/dist/pullRequestList.d.ts +10 -2
  58. package/dist/pullRequestList.js +41 -22
  59. package/dist/query.d.ts +9 -2
  60. package/dist/query.js +91 -10
  61. package/dist/session.d.ts +11 -2
  62. package/dist/session.js +16 -8
  63. package/dist/sessionActions.d.ts +11 -1
  64. package/dist/sessionActions.js +14 -6
  65. package/dist/sessionEvents.d.ts +37 -5
  66. package/dist/sessionEvents.js +196 -77
  67. package/dist/sessionGroups.d.ts +5 -4
  68. package/dist/sessionGroups.js +6 -5
  69. package/dist/sessionHeader.js +6 -2
  70. package/dist/sessionList.d.ts +68 -15
  71. package/dist/sessionList.js +91 -19
  72. package/dist/sessionScreen.d.ts +197 -0
  73. package/dist/sessionScreen.js +218 -0
  74. package/dist/sessionsApi.d.ts +29 -3
  75. package/dist/sessionsApi.js +180 -33
  76. package/dist/sessionsFeed.d.ts +22 -0
  77. package/dist/sessionsFeed.js +125 -0
  78. package/dist/settingsApi.d.ts +3 -1
  79. package/dist/startPage.d.ts +153 -0
  80. package/dist/startPage.js +174 -0
  81. package/dist/startSession.d.ts +41 -7
  82. package/dist/startSession.js +26 -4
  83. package/dist/todos.d.ts +42 -0
  84. package/dist/todos.js +104 -0
  85. package/dist/transcript.d.ts +1 -2
  86. package/dist/transcript.js +111 -117
  87. package/dist/transcriptRead.d.ts +56 -0
  88. package/dist/transcriptRead.js +121 -0
  89. package/dist/types.d.ts +11 -1
  90. package/dist/useComposer.d.ts +39 -6
  91. package/dist/useComposer.js +73 -9
  92. package/dist/useComposerImages.d.ts +5 -0
  93. package/dist/useComposerImages.js +27 -5
  94. package/dist/useComposerPastes.d.ts +70 -0
  95. package/dist/useComposerPastes.js +125 -0
  96. package/dist/useConversation.d.ts +16 -1
  97. package/dist/useConversation.js +104 -10
  98. package/dist/useMounted.d.ts +3 -0
  99. package/dist/useMounted.js +14 -0
  100. package/dist/useSubagent.d.ts +51 -3
  101. package/dist/useSubagent.js +72 -7
  102. package/dist/useTranscript.d.ts +23 -3
  103. package/dist/useTranscript.js +76 -19
  104. package/dist/wording.d.ts +5 -2
  105. package/dist/wording.js +8 -6
  106. package/dist/workingDirectories.d.ts +31 -0
  107. package/dist/workingDirectories.js +25 -1
  108. package/locales/en/agentTranscript.json +68 -11
  109. package/locales/en/agents.json +82 -10
  110. package/locales/es/agentTranscript.json +68 -11
  111. package/locales/es/agents.json +82 -10
  112. package/locales/ja/agentTranscript.json +71 -14
  113. package/locales/ja/agents.json +82 -10
  114. package/locales/ko/agentTranscript.json +68 -11
  115. package/locales/ko/agents.json +82 -10
  116. package/locales/zh/agentTranscript.json +66 -9
  117. package/locales/zh/agents.json +82 -10
  118. package/package.json +6 -3
package/dist/query.js CHANGED
@@ -1,25 +1,106 @@
1
1
  import "./apiClient.js";
2
- import { useCallback, useMemo } from "react";
3
- import useSWR from "swr";
2
+ import { useCallback, useEffect, useMemo, useRef } from "react";
3
+ import useSWR, { unstable_serialize, useSWRConfig } from "swr";
4
4
  // src/query.ts
5
+ /** What a read given up rejects with. It is no answer, so it is never shown
6
+ * and never retried. */
7
+ var GIVEN_UP = Object.freeze({});
8
+ /** Runs a hook's reads of a key so that each is aborted once the hook no
9
+ * longer shows that key, and then rejects with GIVEN_UP. */
10
+ function useGivingUp(shown) {
11
+ const reads = useRef(/* @__PURE__ */ new Map());
12
+ const showing = useRef(void 0);
13
+ useEffect(() => {
14
+ if (shown === void 0) return;
15
+ showing.current = shown;
16
+ const started = reads.current;
17
+ return () => {
18
+ showing.current = void 0;
19
+ queueMicrotask(() => {
20
+ if (showing.current !== shown) for (const read of started.get(shown) ?? []) read.abort();
21
+ });
22
+ };
23
+ }, [shown]);
24
+ return useCallback(async (name, run) => {
25
+ const read = new AbortController();
26
+ const started = reads.current.get(name) ?? /* @__PURE__ */ new Set();
27
+ reads.current.set(name, started.add(read));
28
+ try {
29
+ return await run(read.signal);
30
+ } catch (error) {
31
+ throw read.signal.aborted ? GIVEN_UP : error;
32
+ } finally {
33
+ started.delete(read);
34
+ }
35
+ }, []);
36
+ }
5
37
  /** A data hook over `client` that keys each read `[prefix, path, init]`, or
6
38
  * `null` to skip it, and fetches it, as swr-openapi's query hook does: a host
7
39
  * reading the same routes through `@parallelworks/client/swr` shares each
8
- * cache entry with it. It throws the client's error, so SWR keeps it. */
40
+ * cache entry with it. It throws the client's error, so SWR keeps it.
41
+ *
42
+ * With `giveUpWhenLeft` a read still on its way when the hook stops showing
43
+ * its key is aborted, for a large read only this hook shows: the connection
44
+ * goes to what the reader moved on to. */
9
45
  function createQuery(client) {
10
46
  const reader = client;
11
- return function useQuery(path, init, config) {
47
+ return function useQuery(path, init, config, giveUpWhenLeft = false, readWith) {
12
48
  const key = useMemo(() => init !== null ? [
13
49
  "api",
14
50
  path,
15
51
  init
16
52
  ] : null, [path, init]);
17
- const fetcher = useCallback(async ([, route, options]) => {
18
- const { data, error } = await reader.GET(route, options);
19
- if (error) throw error;
20
- return data;
21
- }, []);
22
- return useSWR(key, fetcher, config);
53
+ const leaving = useGivingUp(giveUpWhenLeft && key ? unstable_serialize(key) : void 0);
54
+ const fetcher = useCallback((read) => {
55
+ const [, route, options] = read;
56
+ const name = unstable_serialize(read);
57
+ const get = async (signal) => {
58
+ if (readWith) return readWith(name, signal);
59
+ const { data, error } = await reader.GET(route, signal ? {
60
+ ...options,
61
+ signal
62
+ } : options);
63
+ if (error) throw error;
64
+ return data;
65
+ };
66
+ return giveUpWhenLeft ? leaving(name, get) : get();
67
+ }, [
68
+ giveUpWhenLeft,
69
+ leaving,
70
+ readWith
71
+ ]);
72
+ const shared = useSWRConfig();
73
+ const retry = config?.shouldRetryOnError ?? shared.shouldRetryOnError;
74
+ const onError = config?.onError ?? shared.onError;
75
+ const answered = useMemo(() => giveUpWhenLeft ? {
76
+ ...config,
77
+ shouldRetryOnError: (error) => error !== GIVEN_UP && (typeof retry === "function" ? retry(error) : retry !== false),
78
+ onError: (error, ...rest) => {
79
+ if (error !== GIVEN_UP) onError?.(error, ...rest);
80
+ }
81
+ } : config, [
82
+ giveUpWhenLeft,
83
+ config,
84
+ retry,
85
+ onError
86
+ ]);
87
+ const response = useSWR(key, fetcher, answered);
88
+ if (!giveUpWhenLeft) return response;
89
+ return {
90
+ get data() {
91
+ return response.data;
92
+ },
93
+ get error() {
94
+ return response.error === GIVEN_UP ? void 0 : response.error;
95
+ },
96
+ get isValidating() {
97
+ return response.isValidating;
98
+ },
99
+ get isLoading() {
100
+ return response.isLoading;
101
+ },
102
+ mutate: response.mutate
103
+ };
23
104
  };
24
105
  }
25
106
  export { createQuery };
package/dist/session.d.ts CHANGED
@@ -20,8 +20,13 @@ export interface PwCodeSession {
20
20
  group?: string | undefined;
21
21
  /** Links to the pull requests the session opened or was pointed at. */
22
22
  pullRequests?: string[] | null | undefined;
23
+ createdAt?: string | undefined;
23
24
  updatedAt?: string | undefined;
24
25
  turnStartedAt?: string | undefined;
26
+ /** The running turn waits for a usage limit to reset. */
27
+ waitingForUsageLimit?: boolean | undefined;
28
+ /** When that usage limit resets, once the machine knows. */
29
+ usageLimitResumeAt?: string | undefined;
25
30
  workspace?: string | undefined;
26
31
  }
27
32
  /** The approvals a session waits on, as far as their kinds. */
@@ -48,6 +53,8 @@ export declare function sessionClock(s: Pick<PwCodeSession, 'status' | 'turnStar
48
53
  export declare function isActiveSession(s: Pick<PwCodeSession, 'status' | 'liveHost'>): boolean;
49
54
  /** The daemon lists archived sessions too and leaves hiding them to its clients. */
50
55
  export declare function isArchived(s: Pick<PwCodeSession, 'archivedAt'>): boolean;
56
+ /** The running turn is held until a usage limit resets, and goes on by itself then. */
57
+ export declare function waitsOnUsageLimit(s: Pick<PwCodeSession, 'status' | 'waitingForUsageLimit'>): boolean;
51
58
  /** A turn is in flight: there is work to stop, and the daemon refuses a fork. */
52
59
  export declare function isMidTurn(s: Pick<PwCodeSession, 'status'>): boolean;
53
60
  /** A dropped machine outranks the session state: it reads as the machine's
@@ -62,12 +69,14 @@ export interface RecentDirectory {
62
69
  sessions: number;
63
70
  updatedAt: string;
64
71
  }
65
- /** The daemon offers no way to browse, so the machine's own sessions are the
66
- * only paths we can honestly suggest. */
72
+ /** The directories the machine's sessions worked in, newest first. */
67
73
  export declare function recentDirectories(sessions: readonly Pick<PwCodeSession, 'machineId' | 'workspace' | 'updatedAt'>[], machineId: string | undefined): RecentDirectory[];
68
74
  export declare function newestFirst<T extends {
69
75
  updatedAt?: string | undefined;
70
76
  }>(items: readonly T[]): T[];
77
+ /** Live sessions update with every message, so ordering them by that would
78
+ * move a row out from under the reader's pointer; when each began holds still. */
79
+ export declare function newestCreatedFirst<T extends Pick<PwCodeSession, 'machineId' | 'id' | 'createdAt'>>(items: readonly T[]): T[];
71
80
  /** An approval blocks the agent and goes first; a running turn is context;
72
81
  * everything else is what the reader last touched, newest first. */
73
82
  export declare function triageSessions<S extends Pick<PwCodeSession, 'machineId' | 'status' | 'archivedAt' | 'updatedAt'>>(sessions: readonly S[], machineById: ReadonlyMap<string, Pick<PwCodeMachine, 'status'>>): {
package/dist/session.js CHANGED
@@ -50,6 +50,10 @@ function isActiveSession(s) {
50
50
  function isArchived(s) {
51
51
  return !!s.archivedAt;
52
52
  }
53
+ /** The running turn is held until a usage limit resets, and goes on by itself then. */
54
+ function waitsOnUsageLimit(s) {
55
+ return s.status === "running" && !!s.waitingForUsageLimit;
56
+ }
53
57
  /** A turn is in flight: there is work to stop, and the daemon refuses a fork. */
54
58
  function isMidTurn(s) {
55
59
  return s.status === "running" || s.status === "awaiting_approval";
@@ -65,8 +69,7 @@ function sessionVariant(status, machine, idle) {
65
69
  function needsYou(s, machine) {
66
70
  return !isArchived(s) && s.status === "awaiting_approval" && isConnected(machine);
67
71
  }
68
- /** The daemon offers no way to browse, so the machine's own sessions are the
69
- * only paths we can honestly suggest. */
72
+ /** The directories the machine's sessions worked in, newest first. */
70
73
  function recentDirectories(sessions, machineId) {
71
74
  if (!machineId) return [];
72
75
  const byPath = /* @__PURE__ */ new Map();
@@ -75,7 +78,7 @@ function recentDirectories(sessions, machineId) {
75
78
  const found = byPath.get(s.workspace);
76
79
  if (found) {
77
80
  found.sessions += 1;
78
- if (updatedMillis(s) > updatedMillis(found)) found.updatedAt = s.updatedAt ?? "";
81
+ if (millis(s.updatedAt) > millis(found.updatedAt)) found.updatedAt = s.updatedAt ?? "";
79
82
  continue;
80
83
  }
81
84
  byPath.set(s.workspace, {
@@ -89,12 +92,17 @@ function recentDirectories(sessions, machineId) {
89
92
  }
90
93
  /** An unparseable timestamp would make the comparator return NaN, which leaves
91
94
  * the sort order up to the engine. */
92
- function updatedMillis(item) {
93
- const millis = DateTime.fromISO(item.updatedAt ?? "").toMillis();
94
- return Number.isFinite(millis) ? millis : 0;
95
+ function millis(iso) {
96
+ const ms = DateTime.fromISO(iso ?? "").toMillis();
97
+ return Number.isFinite(ms) ? ms : 0;
95
98
  }
96
99
  function newestFirst(items) {
97
- return [...items].sort((a, b) => updatedMillis(b) - updatedMillis(a));
100
+ return [...items].sort((a, b) => millis(b.updatedAt) - millis(a.updatedAt));
101
+ }
102
+ /** Live sessions update with every message, so ordering them by that would
103
+ * move a row out from under the reader's pointer; when each began holds still. */
104
+ function newestCreatedFirst(items) {
105
+ return [...items].sort((a, b) => millis(b.createdAt) - millis(a.createdAt) || sessionKey(a).localeCompare(sessionKey(b)));
98
106
  }
99
107
  /** An approval blocks the agent and goes first; a running turn is context;
100
108
  * everything else is what the reader last touched, newest first. */
@@ -108,4 +116,4 @@ function triageSessions(sessions, machineById) {
108
116
  idle: rest.filter((s) => s.status !== "running")
109
117
  };
110
118
  }
111
- export { isActiveSession, isArchived, isMidTurn, isSession, needsYou, newestFirst, pathBasename, recentDirectories, sessionClock, sessionKey, sessionStatusVariant, sessionVariant, sharedStoreCopy, spansMachines, triageSessions, waitsOnAnswer };
119
+ export { isActiveSession, isArchived, isMidTurn, isSession, needsYou, newestCreatedFirst, newestFirst, pathBasename, recentDirectories, sessionClock, sessionKey, sessionStatusVariant, sessionVariant, sharedStoreCopy, spansMachines, triageSessions, waitsOnAnswer, waitsOnUsageLimit };
@@ -3,6 +3,7 @@ import type { PwCodeApi } from './createPwCodeApi.js';
3
3
  import { type PwCodeMachine } from './machine.js';
4
4
  import type { PwCodeWorktreeRef } from './sessionHeader.js';
5
5
  type Session = Schemas['AgentSession'];
6
+ export declare const DELETE_KEYS: readonly ['Backspace', 'Delete'];
6
7
  /** The session the reader has open, if any. */
7
8
  export interface OpenSessionRef {
8
9
  machine?: string | undefined;
@@ -53,8 +54,17 @@ export interface SessionConfirmation<R> {
53
54
  /** Rejects with the machine's refusal, for the host to show while it still asks. */
54
55
  onConfirm: (removeWorktree?: string) => Promise<void>;
55
56
  }
57
+ /** What a prompt for a name says. */
58
+ export interface NamePromptWords {
59
+ title: string;
60
+ label: string;
61
+ placeholder: string;
62
+ confirmLabel: string;
63
+ }
64
+ /** A name as typed, without the spaces around it; undefined when nothing else was typed. */
65
+ export declare function nameToSave(name: string): string | undefined;
56
66
  /** The session being renamed while the host's prompt for its name is up. */
57
- export interface SessionRename {
67
+ export interface SessionRename extends NamePromptWords {
58
68
  session: Session | null;
59
69
  name: string;
60
70
  setName: (name: string) => void;
@@ -6,6 +6,10 @@ import { useState } from "react";
6
6
  // src/sessionActions.ts
7
7
  var DELETE_KEYS = ["Backspace", "Delete"];
8
8
  var ARCHIVE_KEY = "A";
9
+ /** A name as typed, without the spaces around it; undefined when nothing else was typed. */
10
+ function nameToSave(name) {
11
+ return name.trim() || void 0;
12
+ }
9
13
  function machineBlocked(machine, t) {
10
14
  return isMachineDown(machine) ? machineHint(machine, t)?.text : void 0;
11
15
  }
@@ -36,9 +40,9 @@ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarni
36
40
  setName("");
37
41
  };
38
42
  const confirmRename = async () => {
39
- const trimmed = name.trim();
40
- if (toRename === null || !trimmed) return;
41
- const refusal = await renameSession(toRename, trimmed).catch((thrown) => thrown);
43
+ const saved = nameToSave(name);
44
+ if (toRename === null || !saved) return;
45
+ const refusal = await renameSession(toRename, saved).catch((thrown) => thrown);
42
46
  if (refusal) {
43
47
  onRefusal(refusal);
44
48
  return;
@@ -130,7 +134,7 @@ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarni
130
134
  const midTurn = isMidTurn(session) ? t("sidebar.forkMidTurn") : void 0;
131
135
  return [
132
136
  rename,
133
- menuCommand(session.pinnedAt ? "unpin" : "pin", t(session.pinnedAt ? "sidebar.unpin" : "sidebar.pin"), () => togglePin(session), machineDown),
137
+ menuCommand(session.pinnedAt ? "unpin" : "pin", session.pinnedAt ? t("sidebar.unpin") : t("sidebar.pin"), () => togglePin(session), machineDown),
134
138
  menuCommand("fork", t("sidebar.fork"), () => fork(session), disabledReason ?? midTurn),
135
139
  ...worktree ? [menuCommand("leaveWorktree", t("sidebar.leaveWorktree"), () => requestLeaveWorktree(session, worktree), disabledReason ?? midTurn)] : [],
136
140
  ...isMidTurn(session) ? [menuCommand("stop", t("sidebar.stop"), () => stop(session), machineDown)] : [],
@@ -157,7 +161,11 @@ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarni
157
161
  name,
158
162
  setName,
159
163
  confirm: confirmRename,
160
- close: closeRename
164
+ close: closeRename,
165
+ title: t("sidebar.renameTitle"),
166
+ label: t("sidebar.renameLabel"),
167
+ placeholder: t("sidebar.renamePlaceholder"),
168
+ confirmLabel: t("sidebar.renameAction")
161
169
  },
162
170
  requestRename,
163
171
  requestDelete,
@@ -175,4 +183,4 @@ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarni
175
183
  archiveBlocked: (session) => sessionActionBlocked(session, machineById.get(session.machineId), t)
176
184
  };
177
185
  }
178
- export { menuCommand, useSessionActions };
186
+ export { DELETE_KEYS, menuCommand, nameToSave, useSessionActions };
@@ -10,18 +10,50 @@ export interface PwCodeSocketOptions {
10
10
  * frames are applied as they arrive. */
11
11
  hidden?: (() => boolean) | undefined;
12
12
  }
13
- /** The path a session's event feed is served at, resuming after frame `after`. */
14
- export declare function sessionEventsPath(machine: string, id: string, after: number): string;
15
- /** Frames after which the list of subagents may read differently: one started
16
- * or ended, one asked for or got an approval, or a turn began or closed. */
13
+ /** The seconds between the heartbeats a feed asks the platform for. */
14
+ export declare const HEARTBEAT_S = 10;
15
+ /** The path a session's event feed is served at, resuming after frame `after`.
16
+ * With `previewsByRef` the images a tool read come without their previews,
17
+ * which the host loads by URL: a preview is tens of kilobytes, and over a slow
18
+ * connection what the session says next waits behind it. */
19
+ export declare function sessionEventsPath(machine: string, id: string, after: number, previewsByRef?: boolean): string;
20
+ /** Whether a frame is the heartbeat the platform sends a feed that asked for one. */
21
+ export declare function isHeartbeat(data: unknown): boolean;
22
+ /** Frames after which the list of subagents may read differently: one started,
23
+ * ended or was dismissed, one asked for or got an approval, or a turn began or closed. */
17
24
  export declare function changesSubagents(ev: StreamEvent): boolean;
18
25
  /** `machines` with each one in `fed` that the listing lost counted as connected. */
19
26
  export declare function reachedByFeed(machines: Machine[], fed: ReadonlySet<string>): Machine[];
20
- export declare function sessionEvents({ openSocket, hidden }: PwCodeSocketOptions): {
27
+ /** What a held socket reads at each step, so its holder can change them
28
+ * without the socket reopening. */
29
+ export interface HeldSocket {
30
+ open: ((path: string) => WebSocket | Promise<WebSocket>) | undefined;
31
+ /** Read on every attempt, so a reconnect resumes where the last one left off. */
32
+ path: () => string;
33
+ /** `revived` when it is the socket that had gone silent, carrying on. */
34
+ onOpen: (revived: boolean) => void;
35
+ onMessage: (data: unknown) => void;
36
+ onClose: () => void;
37
+ /** Hands over what tries the socket at once if it is waiting to try again,
38
+ * for whoever learns its far end can be reached; returns what takes it back. */
39
+ whenReachable?: ((tryNow: () => void) => () => void) | undefined;
40
+ /** Whether a frame is the far end's heartbeat, which is no message. Once a
41
+ * socket has sent one, it is left when it says nothing for too long. */
42
+ heartbeat?: ((data: unknown) => boolean) | undefined;
43
+ }
44
+ /** Holds one socket open until the returned call, reopening it with backoff
45
+ * after it drops. */
46
+ export declare function holdSocket(latest: {
47
+ current: HeldSocket;
48
+ }, setConnected: (connected: boolean) => void): () => void;
49
+ export declare function sessionEvents({ openSocket, hidden, previewsByRef, }: PwCodeSocketOptions & {
50
+ previewsByRef?: boolean | undefined;
51
+ }): {
21
52
  useSessionEvents: (machine: string, id: string, cursor: (() => number) | undefined, onEvent: (event: StreamEvent) => void) => {
22
53
  connected: boolean;
23
54
  disconnected: boolean;
24
55
  };
25
56
  useFedMachines: () => ReadonlySet<string>;
57
+ listed: (machines: readonly Machine[]) => void;
26
58
  };
27
59
  export {};
@@ -1,18 +1,36 @@
1
+ import { PREVIEWS_BY_REF } from "./images.js";
1
2
  import { isConnected } from "./machine.js";
2
3
  import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
3
4
  // src/sessionEvents.ts
4
5
  var INITIAL_RETRY_MS = 1e3;
5
6
  var MAX_RETRY_MS = 3e4;
7
+ /** How long a socket that has sent a heartbeat may say nothing: two are missed. */
8
+ var SILENT_AFTER_MS = 25e3;
9
+ /** The platform gives a machine 15 seconds to answer before it refuses a socket. */
10
+ var OPEN_WITHIN_MS = 2e4;
6
11
  var SOCKET_OPEN = 1;
7
12
  var SOCKET_CLOSED = 3;
8
- /** The path a session's event feed is served at, resuming after frame `after`. */
9
- function sessionEventsPath(machine, id, after) {
10
- return `/ws/code/machines/${encodeURIComponent(machine)}/sessions/${encodeURIComponent(id)}/events?after=${after}`;
13
+ /** The path a session's event feed is served at, resuming after frame `after`.
14
+ * With `previewsByRef` the images a tool read come without their previews,
15
+ * which the host loads by URL: a preview is tens of kilobytes, and over a slow
16
+ * connection what the session says next waits behind it. */
17
+ function sessionEventsPath(machine, id, after, previewsByRef = false) {
18
+ const previews = previewsByRef ? `&previews=${PREVIEWS_BY_REF}` : "";
19
+ return `/ws/code/machines/${encodeURIComponent(machine)}/sessions/${encodeURIComponent(id)}/events?after=${after}${previews}&heartbeat=10`;
11
20
  }
12
- /** Frames after which the list of subagents may read differently: one started
13
- * or ended, one asked for or got an approval, or a turn began or closed. */
21
+ /** Whether a frame is the heartbeat the platform sends a feed that asked for one. */
22
+ function isHeartbeat(data) {
23
+ if (typeof data !== "string" || data.length > 64) return false;
24
+ try {
25
+ return JSON.parse(data).type === "heartbeat";
26
+ } catch {
27
+ return false;
28
+ }
29
+ }
30
+ /** Frames after which the list of subagents may read differently: one started,
31
+ * ended or was dismissed, one asked for or got an approval, or a turn began or closed. */
14
32
  function changesSubagents(ev) {
15
- return ev.type === "subagent_start" || ev.type === "subagent_end" || ev.type === "approval_request" || ev.type === "approval_resolved" || ev.type === "user_message" || ev.type === "done" || ev.type === "error";
33
+ return ev.type === "subagent_start" || ev.type === "subagent_end" || ev.type === "subagent_dismissed" || ev.type === "approval_request" || ev.type === "approval_resolved" || ev.type === "user_message" || ev.type === "done" || ev.type === "error";
16
34
  }
17
35
  /** `machines` with each one in `fed` that the listing lost counted as connected. */
18
36
  function reachedByFeed(machines, fed) {
@@ -27,94 +45,177 @@ function reachedByFeed(machines, fed) {
27
45
  };
28
46
  });
29
47
  }
48
+ /** Holds one socket open until the returned call, reopening it with backoff
49
+ * after it drops. */
50
+ function holdSocket(latest, setConnected) {
51
+ let stopped = false;
52
+ let socket = null;
53
+ let silent = null;
54
+ let attempt = 0;
55
+ let attempts = 0;
56
+ let hurried = false;
57
+ let timer;
58
+ let opening;
59
+ let silence;
60
+ const retry = () => {
61
+ const delay = Math.min(INITIAL_RETRY_MS * 2 ** attempts, MAX_RETRY_MS);
62
+ attempts += 1;
63
+ timer = setTimeout(connect, delay);
64
+ };
65
+ const failed = () => {
66
+ clearTimeout(opening);
67
+ if (stopped) return;
68
+ latest.current.onClose();
69
+ retry();
70
+ };
71
+ const attach = (ws) => {
72
+ if (stopped) {
73
+ ws.close();
74
+ return;
75
+ }
76
+ socket = ws;
77
+ let beats = false;
78
+ const opened = () => {
79
+ if (socket !== ws) return;
80
+ clearTimeout(opening);
81
+ const left = silent;
82
+ silent = null;
83
+ left?.close();
84
+ attempts = 0;
85
+ hurried = false;
86
+ setConnected(true);
87
+ latest.current.onOpen(false);
88
+ };
89
+ const revived = () => {
90
+ silent = null;
91
+ clearTimeout(timer);
92
+ timer = void 0;
93
+ clearTimeout(opening);
94
+ attempt += 1;
95
+ const tried = socket;
96
+ socket = ws;
97
+ tried?.close();
98
+ attempts = 0;
99
+ hurried = false;
100
+ setConnected(true);
101
+ latest.current.onOpen(true);
102
+ };
103
+ const wentSilent = () => {
104
+ if (socket !== ws) return;
105
+ silent = ws;
106
+ socket = null;
107
+ setConnected(false);
108
+ latest.current.onClose();
109
+ connect();
110
+ };
111
+ const closed = () => {
112
+ if (silent === ws) {
113
+ silent = null;
114
+ return;
115
+ }
116
+ if (socket !== ws) return;
117
+ socket = null;
118
+ clearTimeout(opening);
119
+ clearTimeout(silence);
120
+ setConnected(false);
121
+ latest.current.onClose();
122
+ if (!stopped) retry();
123
+ };
124
+ ws.addEventListener("open", opened);
125
+ const heartbeat = (data) => {
126
+ const beat = latest.current.heartbeat?.(data) === true;
127
+ beats ||= beat;
128
+ if (beats) {
129
+ clearTimeout(silence);
130
+ silence = setTimeout(wentSilent, SILENT_AFTER_MS);
131
+ }
132
+ return beat;
133
+ };
134
+ ws.addEventListener("message", (event) => {
135
+ if (silent === ws) revived();
136
+ if (socket === ws && !heartbeat(event.data)) latest.current.onMessage(event.data);
137
+ });
138
+ ws.addEventListener("close", closed);
139
+ if (ws.readyState === SOCKET_OPEN) opened();
140
+ else if (ws.readyState === SOCKET_CLOSED) closed();
141
+ };
142
+ function connect() {
143
+ timer = void 0;
144
+ const opener = latest.current.open;
145
+ if (!opener) return;
146
+ attempt += 1;
147
+ const mine = attempt;
148
+ opening = setTimeout(() => {
149
+ const ws = socket;
150
+ socket = null;
151
+ latest.current.onClose();
152
+ ws?.close();
153
+ connect();
154
+ }, OPEN_WITHIN_MS);
155
+ let made;
156
+ try {
157
+ made = opener(latest.current.path());
158
+ } catch {
159
+ failed();
160
+ return;
161
+ }
162
+ if ("then" in made) made.then((ws) => mine === attempt ? attach(ws) : ws.close(), () => {
163
+ if (mine === attempt) failed();
164
+ });
165
+ else attach(made);
166
+ }
167
+ connect();
168
+ const forget = latest.current.whenReachable?.(() => {
169
+ if (stopped || timer === void 0 || hurried) return;
170
+ hurried = true;
171
+ clearTimeout(timer);
172
+ attempts = 0;
173
+ connect();
174
+ });
175
+ return () => {
176
+ stopped = true;
177
+ forget?.();
178
+ clearTimeout(timer);
179
+ clearTimeout(opening);
180
+ clearTimeout(silence);
181
+ const ws = socket;
182
+ const left = silent;
183
+ socket = null;
184
+ silent = null;
185
+ ws?.close();
186
+ left?.close();
187
+ setConnected(false);
188
+ };
189
+ }
30
190
  /** Holds one socket open while `enabled`, reopening it with backoff after it
31
191
  * drops, and from scratch whenever `connectionKey` changes. */
32
- function useReconnectingSocket({ open, path, connectionKey, enabled, onOpen, onMessage, onClose }) {
192
+ function useReconnectingSocket({ open, path, connectionKey, enabled, onOpen, onMessage, onClose, whenReachable, heartbeat }) {
33
193
  const [connected, setConnected] = useState(false);
34
194
  const latest = useRef({
35
195
  open,
36
196
  path,
37
197
  onOpen,
38
198
  onMessage,
39
- onClose
199
+ onClose,
200
+ whenReachable,
201
+ heartbeat
40
202
  });
41
203
  latest.current = {
42
204
  open,
43
205
  path,
44
206
  onOpen,
45
207
  onMessage,
46
- onClose
208
+ onClose,
209
+ whenReachable,
210
+ heartbeat
47
211
  };
48
212
  useEffect(() => {
49
213
  if (!enabled || !latest.current.open) return;
50
- let stopped = false;
51
- let socket = null;
52
- let attempts = 0;
53
- let timer;
54
- const retry = () => {
55
- const delay = Math.min(INITIAL_RETRY_MS * 2 ** attempts, MAX_RETRY_MS);
56
- attempts += 1;
57
- timer = setTimeout(connect, delay);
58
- };
59
- const failed = () => {
60
- if (stopped) return;
61
- latest.current.onClose();
62
- retry();
63
- };
64
- const attach = (ws) => {
65
- if (stopped) {
66
- ws.close();
67
- return;
68
- }
69
- socket = ws;
70
- const opened = () => {
71
- if (socket !== ws) return;
72
- attempts = 0;
73
- setConnected(true);
74
- latest.current.onOpen();
75
- };
76
- const closed = () => {
77
- if (socket !== ws) return;
78
- socket = null;
79
- setConnected(false);
80
- latest.current.onClose();
81
- if (!stopped) retry();
82
- };
83
- ws.addEventListener("open", opened);
84
- ws.addEventListener("message", (event) => {
85
- if (socket === ws) latest.current.onMessage(event.data);
86
- });
87
- ws.addEventListener("close", closed);
88
- if (ws.readyState === SOCKET_OPEN) opened();
89
- else if (ws.readyState === SOCKET_CLOSED) closed();
90
- };
91
- function connect() {
92
- timer = void 0;
93
- const opener = latest.current.open;
94
- if (!opener) return;
95
- let made;
96
- try {
97
- made = opener(latest.current.path());
98
- } catch {
99
- failed();
100
- return;
101
- }
102
- if ("then" in made) made.then(attach, failed);
103
- else attach(made);
104
- }
105
- connect();
106
- return () => {
107
- stopped = true;
108
- clearTimeout(timer);
109
- const ws = socket;
110
- socket = null;
111
- ws?.close();
112
- setConnected(false);
113
- };
214
+ return holdSocket(latest, setConnected);
114
215
  }, [enabled, connectionKey]);
115
216
  return connected;
116
217
  }
117
- function sessionEvents({ openSocket, hidden }) {
218
+ function sessionEvents({ openSocket, hidden, previewsByRef = false }) {
118
219
  const openFeeds = /* @__PURE__ */ new Map();
119
220
  const listeners = /* @__PURE__ */ new Set();
120
221
  let fedMachines = /* @__PURE__ */ new Set();
@@ -134,6 +235,21 @@ function sessionEvents({ openSocket, hidden }) {
134
235
  listeners.delete(notify);
135
236
  };
136
237
  }
238
+ const waiting = /* @__PURE__ */ new Map();
239
+ function whenListed(machine, tryNow) {
240
+ const feeds = waiting.get(machine) ?? /* @__PURE__ */ new Set();
241
+ waiting.set(machine, feeds.add(tryNow));
242
+ return () => {
243
+ feeds.delete(tryNow);
244
+ if (feeds.size === 0) waiting.delete(machine);
245
+ };
246
+ }
247
+ /** The listing answered, so the platform can be reached: a feed waiting to
248
+ * try a machine the listing shows connected again tries at once, once for
249
+ * each time it drops. */
250
+ function listed(machines) {
251
+ for (const machine of machines) if (isConnected(machine)) for (const tryNow of [...waiting.get(machine.id) ?? []]) tryNow();
252
+ }
137
253
  /** The machines a session feed is open to. */
138
254
  function useFedMachines() {
139
255
  return useSyncExternalStore(subscribe, () => fedMachines);
@@ -166,9 +282,11 @@ function sessionEvents({ openSocket, hidden }) {
166
282
  }, [key]);
167
283
  const connected = useReconnectingSocket({
168
284
  open: openSocket,
169
- path: () => sessionEventsPath(machine, id, cursor?.() ?? 0),
285
+ path: () => sessionEventsPath(machine, id, cursor?.() ?? 0, previewsByRef),
170
286
  connectionKey: key,
171
287
  enabled: cursor !== void 0,
288
+ whenReachable: (tryNow) => whenListed(machine, tryNow),
289
+ heartbeat: isHeartbeat,
172
290
  onOpen: () => setFeed({
173
291
  key,
174
292
  open: true
@@ -206,7 +324,8 @@ function sessionEvents({ openSocket, hidden }) {
206
324
  }
207
325
  return {
208
326
  useSessionEvents,
209
- useFedMachines
327
+ useFedMachines,
328
+ listed
210
329
  };
211
330
  }
212
- export { changesSubagents, reachedByFeed, sessionEvents, sessionEventsPath };
331
+ export { changesSubagents, holdSocket, isHeartbeat, reachedByFeed, sessionEvents, sessionEventsPath };