@parallelworks/code 0.4.0 → 0.6.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 (93) hide show
  1. package/README.md +92 -24
  2. package/dist/agentSwitcher.d.ts +13 -2
  3. package/dist/agentSwitcher.js +28 -6
  4. package/dist/ago.d.ts +1 -3
  5. package/dist/ago.js +1 -3
  6. package/dist/api.d.ts +267 -5
  7. package/dist/chatStrings.d.ts +4 -0
  8. package/dist/chatStrings.js +5 -1
  9. package/dist/claudeAccounts.d.ts +20 -2
  10. package/dist/claudeAccounts.js +51 -7
  11. package/dist/claudeApi.d.ts +2 -1
  12. package/dist/claudeApi.js +49 -3
  13. package/dist/command.d.ts +7 -1
  14. package/dist/command.js +11 -2
  15. package/dist/commandsApi.d.ts +8 -3
  16. package/dist/commandsApi.js +25 -4
  17. package/dist/createPwCodeApi.d.ts +92 -58
  18. package/dist/createPwCodeApi.js +4 -2
  19. package/dist/index.d.ts +11 -9
  20. package/dist/index.js +7 -5
  21. package/dist/locales/en/agentTranscript.js +6 -2
  22. package/dist/locales/en/agents.js +50 -6
  23. package/dist/locales/en.d.ts +46 -0
  24. package/dist/locales/es/agentTranscript.js +6 -2
  25. package/dist/locales/es/agents.js +50 -6
  26. package/dist/locales/ja/agentTranscript.js +6 -2
  27. package/dist/locales/ja/agents.js +45 -6
  28. package/dist/locales/ko/agentTranscript.js +6 -2
  29. package/dist/locales/ko/agents.js +50 -6
  30. package/dist/locales/zh/agentTranscript.js +6 -2
  31. package/dist/locales/zh/agents.js +50 -6
  32. package/dist/machine.d.ts +27 -2
  33. package/dist/machine.js +23 -2
  34. package/dist/notices.d.ts +2 -0
  35. package/dist/notices.js +29 -14
  36. package/dist/pwUpdate.d.ts +52 -0
  37. package/dist/pwUpdate.js +115 -0
  38. package/dist/query.d.ts +4 -1
  39. package/dist/query.js +9 -3
  40. package/dist/session.d.ts +7 -1
  41. package/dist/session.js +6 -2
  42. package/dist/sessionActions.js +5 -2
  43. package/dist/sessionEvents.d.ts +39 -5
  44. package/dist/sessionEvents.js +213 -83
  45. package/dist/sessionGroups.d.ts +3 -3
  46. package/dist/sessionGroups.js +3 -3
  47. package/dist/sessionHeader.js +6 -2
  48. package/dist/sessionList.d.ts +13 -8
  49. package/dist/sessionList.js +20 -10
  50. package/dist/sessionScreen.d.ts +8 -3
  51. package/dist/sessionScreen.js +20 -9
  52. package/dist/sessionsApi.d.ts +27 -5
  53. package/dist/sessionsApi.js +128 -17
  54. package/dist/sessionsFeed.d.ts +22 -0
  55. package/dist/sessionsFeed.js +125 -0
  56. package/dist/startPage.d.ts +6 -3
  57. package/dist/startPage.js +34 -12
  58. package/dist/startSession.d.ts +31 -11
  59. package/dist/startSession.js +126 -44
  60. package/dist/terminalHandoffPanel.js +8 -1
  61. package/dist/todos.d.ts +42 -0
  62. package/dist/todos.js +104 -0
  63. package/dist/transcript.d.ts +27 -5
  64. package/dist/transcript.js +148 -112
  65. package/dist/transcriptRead.d.ts +57 -0
  66. package/dist/transcriptRead.js +122 -0
  67. package/dist/types.d.ts +13 -1
  68. package/dist/useComposer.d.ts +36 -15
  69. package/dist/useComposer.js +94 -31
  70. package/dist/useComposerImages.d.ts +38 -1
  71. package/dist/useComposerImages.js +62 -8
  72. package/dist/useComposerPastes.js +3 -8
  73. package/dist/useConversation.d.ts +16 -0
  74. package/dist/useConversation.js +78 -8
  75. package/dist/useMounted.d.ts +3 -0
  76. package/dist/useMounted.js +14 -0
  77. package/dist/useSubagent.d.ts +22 -5
  78. package/dist/useSubagent.js +41 -17
  79. package/dist/useTranscript.d.ts +27 -1
  80. package/dist/useTranscript.js +217 -45
  81. package/dist/wording.d.ts +6 -3
  82. package/dist/wording.js +20 -6
  83. package/locales/en/agentTranscript.json +6 -2
  84. package/locales/en/agents.json +46 -4
  85. package/locales/es/agentTranscript.json +6 -2
  86. package/locales/es/agents.json +46 -4
  87. package/locales/ja/agentTranscript.json +6 -2
  88. package/locales/ja/agents.json +46 -4
  89. package/locales/ko/agentTranscript.json +6 -2
  90. package/locales/ko/agents.json +46 -4
  91. package/locales/zh/agentTranscript.json +6 -2
  92. package/locales/zh/agents.json +46 -4
  93. package/package.json +3 -3
@@ -1,7 +1,8 @@
1
1
  import type { ApprovalAnswerValue, MessagePaste } from '@parallelworks/ui/ai/headless';
2
2
  import { DateTime } from 'luxon';
3
- import type { KeyedMutator } from 'swr';
4
- import type { PwCodeApiError, PwCodeClient, PwCodeQuery, PwCodeResult, Schemas } from './apiClient.js';
3
+ import { type KeyedMutator } from 'swr';
4
+ import { type PwCodeApiError, type PwCodeClient, type PwCodeQuery, type PwCodeResult, type Schemas } from './apiClient.js';
5
+ import type { SessionsFeed } from './sessionsFeed.js';
5
6
  type Session = Schemas['AgentSession'];
6
7
  type SessionDetail = Schemas['AgentSessionDetail'];
7
8
  type SessionsResponse = Schemas['AgentSessionsResponse'];
@@ -37,6 +38,7 @@ export type PwCodePasteUpload = {
37
38
  } | {
38
39
  unsupported: true;
39
40
  };
41
+ type SessionRef = Pick<Session, 'machineId' | 'id'>;
40
42
  export interface PwCodeSessionOptions {
41
43
  /** Whether the host shows an image from its URL on the platform's API, signed
42
44
  * in as the API client is, as a browser on the platform's origin does. Set,
@@ -44,12 +46,26 @@ export interface PwCodeSessionOptions {
44
46
  * and the preview is loaded from there when it is drawn: previews are most
45
47
  * of what a transcript with pictures weighs. */
46
48
  previewsByRef?: boolean | undefined;
49
+ /** Whether the host's `fetch` hands over a response's body as it arrives
50
+ * (`response.body`), as a browser's does. Set, a session's transcript is
51
+ * read end first, and the end of the conversation is drawn while the rest
52
+ * arrives: over a slow connection the transcript is most of the wait. A
53
+ * host without it, such as React Native's own fetch, reads the session
54
+ * whole. */
55
+ transcriptEndFirst?: boolean | undefined;
47
56
  }
48
- export declare function sessionsApi(client: PwCodeClient, { previewsByRef }?: PwCodeSessionOptions): {
57
+ export declare function sessionsApi(client: PwCodeClient, { previewsByRef, transcriptEndFirst, }?: PwCodeSessionOptions,
58
+ /** Told the machines of each listing that answers. */
59
+ listed?: (machines: Schemas['AgentMachine'][]) => void,
60
+ /** The listing as the platform sends it over a socket, for a host that opens them. */
61
+ feed?: SessionsFeed): {
49
62
  useSessions: () => PwCodeQuery<SessionsResponse>;
50
63
  useWaitingSessionCount: (enabled: boolean) => number;
51
64
  useSessionDetail: (machine: string, id: string, listed: Session | undefined) => {
52
65
  data: SessionDetail | undefined;
66
+ /** The session with only the end of its history, while the rest of the
67
+ * transcript is still arriving and there is nothing else to show. */
68
+ preview: SessionDetail | undefined;
53
69
  error: PwCodeApiError | undefined;
54
70
  isLoading: boolean;
55
71
  mutate: KeyedMutator<SessionDetail>;
@@ -75,6 +91,7 @@ export declare function sessionsApi(client: PwCodeClient, { previewsByRef }?: Pw
75
91
  };
76
92
  stopSubagent: (machine: string, id: string, subId: string) => Promise<unknown>;
77
93
  stopAllSubagents: (machine: string, id: string) => Promise<unknown>;
94
+ dismissSubagent: (machine: string, id: string, subId: string) => Promise<unknown>;
78
95
  useSessionWorktree: (s: Session | undefined) => PwCodeQuery<Schemas['AgentSessionWorktree']>;
79
96
  leaveWorktree: (s: Session, removeRoot?: string) => Promise<{
80
97
  left?: Schemas['AgentWorktreeLeft'];
@@ -82,7 +99,7 @@ export declare function sessionsApi(client: PwCodeClient, { previewsByRef }?: Pw
82
99
  }>;
83
100
  useSessionMutations: () => {
84
101
  /** Given the root of the worktree the session works in, removes that worktree too. */
85
- deleteSession: (s: Session, removeWorktree?: string) => Promise<unknown>;
102
+ deleteSession: (s: SessionRef, removeWorktree?: string) => Promise<unknown>;
86
103
  renameSession: (s: Session, name: string) => Promise<unknown>;
87
104
  archiveSession: (s: Session) => Promise<unknown>;
88
105
  archiveAfterTurn: (s: Session) => Promise<{
@@ -92,7 +109,7 @@ export declare function sessionsApi(client: PwCodeClient, { previewsByRef }?: Pw
92
109
  restoreSession: (s: Session) => Promise<unknown>;
93
110
  pinSession: (s: Session, pinned: boolean) => Promise<unknown>;
94
111
  /** `group` is the id of one of the reader's groups, or null for none. */
95
- groupSession: (s: Session, group: string | null) => Promise<unknown>;
112
+ groupSession: (s: SessionRef, group: string | null) => Promise<unknown>;
96
113
  stopSession: (s: Session) => Promise<unknown>;
97
114
  forkSession: (s: Session) => Promise<{
98
115
  forked?: Schemas['AgentSessionForked'];
@@ -110,6 +127,11 @@ export declare function sessionsApi(client: PwCodeClient, { previewsByRef }?: Pw
110
127
  saveImage: (machine: string, id: string, body: Schemas['AgentImageBody']) => Promise<PwCodeResult<Schemas['AgentImageSaved']>>;
111
128
  answerApproval: (machine: string, sessionId: string, approvalId: string, answer: ApprovalAnswerValue) => Promise<unknown>;
112
129
  removeSessionDirectory: (machine: string, sessionId: string, path: string) => Promise<unknown>;
130
+ upgradePw: (machine: string, sessionId: string) => Promise<{
131
+ answer: string;
132
+ } | {
133
+ error: unknown;
134
+ }>;
113
135
  uploadPaste: (machine: string, sessionId: string, text: string, describe: (error: unknown) => string) => Promise<PwCodePasteUpload>;
114
136
  };
115
137
  export {};
@@ -1,3 +1,4 @@
1
+ import "./apiClient.js";
1
2
  import { bytesToBase64 } from "./base64.js";
2
3
  import { PREVIEWS_BY_REF } from "./images.js";
3
4
  import { createQuery } from "./query.js";
@@ -5,19 +6,26 @@ import { machinesById } from "./machine.js";
5
6
  import { labeledPullRequests } from "./pullRequestList.js";
6
7
  import { isSession, triageSessions } from "./session.js";
7
8
  import { approvalAnswerBody } from "./transcript.js";
8
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
9
+ import { createTranscriptReads } from "./transcriptRead.js";
10
+ import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
11
+ import { unstable_serialize, useSWRConfig } from "swr";
9
12
  import { DateTime } from "luxon";
13
+ import { toApiError } from "@parallelworks/problem";
10
14
  // src/sessionsApi.ts
11
15
  var SESSIONS_REFRESH_MS = 5e3;
12
16
  var WAITING_REFRESH_MS = 3e4;
13
17
  var PULL_REQUESTS_REFRESH_MS = 6e4;
14
18
  var CLOSED_PULL_REQUESTS_REFRESH_MS = 36e5;
15
19
  var SUBAGENTS_REFRESH_MS = 1e3;
20
+ function notLoaded(error) {
21
+ return !!error && toApiError(error).status === 404;
22
+ }
16
23
  /** Whether a copy cached by an earlier visit still holds everything the
17
24
  * session's listed row reports. A running session's copy trails its turn. */
18
25
  function cachedCopyCurrent(listed, cached) {
19
26
  return !!listed && listed.status !== "running" && listed.status === cached.status && listed.messages === cached.messages && listed.updatedAt === cached.updatedAt;
20
27
  }
28
+ var SESSION_DETAIL = "/api/code/machines/{machine}/sessions/{id}";
21
29
  var SESSION_DETAIL_READ = {
22
30
  revalidateIfStale: false,
23
31
  revalidateOnFocus: false,
@@ -147,15 +155,73 @@ function sessionPath(s) {
147
155
  id: s.id
148
156
  } } };
149
157
  }
150
- function sessionsApi(client, { previewsByRef = false } = {}) {
158
+ function sessionsApi(client, { previewsByRef = false, transcriptEndFirst = false } = {}, listed, feed) {
151
159
  const useQuery = createQuery(client);
160
+ const transcripts = createTranscriptReads(client, previewsByRef);
161
+ const useFed = feed?.useFed ?? (() => false);
162
+ /** The listing, asked for again every `every` ms while no socket sends it.
163
+ * `live` holds that socket open. */
164
+ function useListing(enabled, every, live = false) {
165
+ const { onErrorRetry } = useSWRConfig();
166
+ const fed = useFed();
167
+ const config = useMemo(() => ({
168
+ refreshInterval: fed ? 0 : every,
169
+ onSuccess: (listing) => {
170
+ listed?.(listing.machines ?? []);
171
+ feed?.reachable();
172
+ },
173
+ onErrorRetry: (error, key, swr, revalidate, attempt) => {
174
+ if (toApiError(error).code === "network") {
175
+ setTimeout(() => void revalidate(attempt), SESSIONS_REFRESH_MS);
176
+ return;
177
+ }
178
+ onErrorRetry(error, key, swr, revalidate, attempt);
179
+ }
180
+ }), [
181
+ every,
182
+ fed,
183
+ onErrorRetry
184
+ ]);
185
+ const response = useQuery("/api/code/sessions", enabled ? void 0 : null, config);
186
+ const { mutate } = response;
187
+ useEffect(() => {
188
+ if (!live || !enabled || !feed) return;
189
+ return feed.read((listing) => void mutate(listing, { revalidate: false }));
190
+ }, [
191
+ live,
192
+ enabled,
193
+ mutate
194
+ ]);
195
+ return {
196
+ get data() {
197
+ return response.data;
198
+ },
199
+ get error() {
200
+ return response.error;
201
+ },
202
+ get isValidating() {
203
+ return response.isValidating;
204
+ },
205
+ get isLoading() {
206
+ return response.isLoading;
207
+ },
208
+ mutate: useCallback(async (...args) => {
209
+ const landed = feed?.pause();
210
+ try {
211
+ return await mutate(...args);
212
+ } finally {
213
+ landed?.();
214
+ }
215
+ }, [mutate])
216
+ };
217
+ }
152
218
  /** Every session on every machine the reader can reach, with each machine's reachability. */
153
219
  function useSessions() {
154
- return useQuery("/api/code/sessions", void 0, { refreshInterval: SESSIONS_REFRESH_MS });
220
+ return useListing(true, SESSIONS_REFRESH_MS, true);
155
221
  }
156
222
  /** Every listing asks each machine, so an app-wide count polls slower; the list's own poll keeps it current beside the list. */
157
223
  function useWaitingSessionCount(enabled) {
158
- const { data } = useQuery("/api/code/sessions", enabled ? void 0 : null, { refreshInterval: WAITING_REFRESH_MS });
224
+ const { data } = useListing(enabled, WAITING_REFRESH_MS);
159
225
  return useMemo(() => data ? triageSessions(data.sessions ?? [], machinesById(data.machines ?? [])).blocked.length : 0, [data]);
160
226
  }
161
227
  /** `fresh` once this visit has fetched the session: a copy cached by an earlier
@@ -164,18 +230,30 @@ function sessionsApi(client, { previewsByRef = false } = {}) {
164
230
  * A cached copy the listed row says the session has moved past stays hidden
165
231
  * until that fetch answers, so the newer turns don't land under the reader. */
166
232
  function useSessionDetail(machine, id, listed) {
167
- const { data, error, isLoading, isValidating, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}", { params: {
168
- path: {
169
- machine,
170
- id
171
- },
172
- ...previewsByRef ? { query: { previews: PREVIEWS_BY_REF } } : {}
173
- } }, SESSION_DETAIL_READ, true);
233
+ const init = useMemo(() => {
234
+ return { params: {
235
+ path: {
236
+ machine,
237
+ id
238
+ },
239
+ ...previewsByRef ? { query: { previews: PREVIEWS_BY_REF } } : {}
240
+ } };
241
+ }, [machine, id]);
242
+ const read = useCallback((name, signal) => transcripts.read(machine, id, name, signal), [machine, id]);
243
+ const { data, error, isLoading, isValidating, mutate } = useQuery(SESSION_DETAIL, init, SESSION_DETAIL_READ, true, transcriptEndFirst ? read : void 0);
244
+ const name = useMemo(() => unstable_serialize([
245
+ "api",
246
+ SESSION_DETAIL,
247
+ init
248
+ ]), [init]);
249
+ const tail = useSyncExternalStore(transcripts.subscribe, () => transcripts.tail(name), () => void 0);
174
250
  const [current] = useState(() => data !== void 0 && cachedCopyCurrent(listed, data));
175
251
  const answered = useReadThisVisit(data, isValidating, mutate);
176
252
  const hidden = !current && !answered;
253
+ const shown = hidden ? void 0 : data;
177
254
  return {
178
- data: hidden ? void 0 : data,
255
+ data: shown,
256
+ preview: shown === void 0 ? tail : void 0,
179
257
  error,
180
258
  isLoading: isLoading || hidden,
181
259
  mutate,
@@ -233,18 +311,19 @@ function sessionsApi(client, { previewsByRef = false } = {}) {
233
311
  * daemon has not loaded, or from a pw code that does not say how each stands.
234
312
  * The feed says when to ask again, so nothing polls. */
235
313
  function useSubagents(machine, id, enabled) {
236
- const { data, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}/subagents", enabled ? { params: { path: {
314
+ const { data, error, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}/subagents", enabled ? { params: { path: {
237
315
  machine,
238
316
  id
239
317
  } } } : null, {
240
318
  revalidateOnFocus: false,
241
319
  shouldRetryOnError: false
242
320
  });
321
+ const gone = notLoaded(error);
243
322
  return {
244
323
  subagents: useMemo(() => {
245
- const listed = data?.subagents ?? [];
324
+ const listed = gone ? [] : data?.subagents ?? [];
246
325
  return listed.every((s) => s.status) ? listed : [];
247
- }, [data]),
326
+ }, [data, gone]),
248
327
  refresh: useThrottled(() => mutate(), SUBAGENTS_REFRESH_MS)
249
328
  };
250
329
  }
@@ -252,6 +331,7 @@ function sessionsApi(client, { previewsByRef = false } = {}) {
252
331
  * cached trails the session's feed, and seeding from it would drop what
253
332
  * streamed since. */
254
333
  function useSubagentDetail(machine, id, subId) {
334
+ const [readHere, setReadHere] = useState(false);
255
335
  const { data, error, isValidating, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}", { params: { path: {
256
336
  machine,
257
337
  id,
@@ -260,12 +340,13 @@ function sessionsApi(client, { previewsByRef = false } = {}) {
260
340
  revalidateIfStale: false,
261
341
  revalidateOnFocus: false,
262
342
  revalidateOnReconnect: false,
263
- shouldRetryOnError: false
343
+ shouldRetryOnError: false,
344
+ onSuccess: () => setReadHere(true)
264
345
  });
265
346
  const answered = useReadThisVisit(data, isValidating, mutate);
266
347
  const refresh = useThrottled(() => mutate(), SUBAGENTS_REFRESH_MS);
267
348
  return {
268
- data: answered ? data : void 0,
349
+ data: answered && (readHere || !notLoaded(error)) ? data : void 0,
269
350
  error: answered ? error : void 0,
270
351
  refresh
271
352
  };
@@ -283,6 +364,18 @@ function sessionsApi(client, { previewsByRef = false } = {}) {
283
364
  return thrown;
284
365
  }
285
366
  }
367
+ async function dismissSubagent(machine, id, subId) {
368
+ try {
369
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/dismiss", { params: { path: {
370
+ machine,
371
+ id,
372
+ subId
373
+ } } });
374
+ return error ?? null;
375
+ } catch (thrown) {
376
+ return thrown;
377
+ }
378
+ }
286
379
  async function stopAllSubagents(machine, id) {
287
380
  try {
288
381
  const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/stop-all", { params: { path: {
@@ -525,6 +618,22 @@ function sessionsApi(client, { previewsByRef = false } = {}) {
525
618
  });
526
619
  return error ?? null;
527
620
  }
621
+ /** Runs /upgrade on the session, which installs the newest pw on its machine
622
+ * in the background; resolves to what the daemon answered, or its refusal. */
623
+ async function upgradePw(machine, sessionId) {
624
+ try {
625
+ const { data, error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/commands", {
626
+ params: { path: {
627
+ machine,
628
+ id: sessionId
629
+ } },
630
+ body: { name: "upgrade" }
631
+ });
632
+ return error ? { error } : { answer: data.output };
633
+ } catch (thrown) {
634
+ return { error: thrown };
635
+ }
636
+ }
528
637
  /** Saves a paste with the session on its machine. A machine whose pw code
529
638
  * predates paste uploads answers 404, and the paste stays text. */
530
639
  async function uploadPaste(machine, sessionId, text, describe) {
@@ -550,6 +659,7 @@ function sessionsApi(client, { previewsByRef = false } = {}) {
550
659
  useSubagentDetail,
551
660
  stopSubagent,
552
661
  stopAllSubagents,
662
+ dismissSubagent,
553
663
  useSessionWorktree,
554
664
  leaveWorktree,
555
665
  useSessionMutations,
@@ -564,6 +674,7 @@ function sessionsApi(client, { previewsByRef = false } = {}) {
564
674
  saveImage,
565
675
  answerApproval,
566
676
  removeSessionDirectory,
677
+ upgradePw,
567
678
  uploadPaste
568
679
  };
569
680
  }
@@ -0,0 +1,22 @@
1
+ import type { Schemas } from './apiClient.js';
2
+ import { type PwCodeSocketOptions } from './sessionEvents.js';
3
+ type Listing = Schemas['AgentSessionsResponse'];
4
+ /** Where the platform sends the sessions listing as it changes. */
5
+ export declare const SESSIONS_FEED_PATH = "/ws/code/sessions?heartbeat=10";
6
+ /** The sessions listing as the platform sends it over a socket: at once, and
7
+ * again each time it changes. A listing that is polled for shows a change up
8
+ * to a poll late, and when a connection that went silent returns it waits
9
+ * most of a minute on the request it had out, which a fetch cannot take to
10
+ * another connection as a socket can. One socket serves every hook that reads
11
+ * the listing, open while any does and the app is in sight: out of sight the
12
+ * listing is not polled for either. */
13
+ export declare function sessionsFeed({ openSocket, hidden }: PwCodeSocketOptions,
14
+ /** Told each listing, once however many read it. */
15
+ onListing: (listing: Listing) => void): {
16
+ read: (reader: (listing: Listing) => void) => () => void;
17
+ pause: () => () => void;
18
+ useFed: () => boolean;
19
+ reachable: () => void;
20
+ };
21
+ export type SessionsFeed = ReturnType<typeof sessionsFeed>;
22
+ export {};
@@ -0,0 +1,125 @@
1
+ import { holdSocket, isHeartbeat } from "./sessionEvents.js";
2
+ import { useSyncExternalStore } from "react";
3
+ // src/sessionsFeed.ts
4
+ /** Where the platform sends the sessions listing as it changes. */
5
+ var SESSIONS_FEED_PATH = `/ws/code/sessions?heartbeat=10`;
6
+ function listingFrame(data) {
7
+ try {
8
+ const frame = JSON.parse(String(data));
9
+ return frame.type === "sessions" ? frame.listing : void 0;
10
+ } catch {
11
+ return;
12
+ }
13
+ }
14
+ /** The sessions listing as the platform sends it over a socket: at once, and
15
+ * again each time it changes. A listing that is polled for shows a change up
16
+ * to a poll late, and when a connection that went silent returns it waits
17
+ * most of a minute on the request it had out, which a fetch cannot take to
18
+ * another connection as a socket can. One socket serves every hook that reads
19
+ * the listing, open while any does and the app is in sight: out of sight the
20
+ * listing is not polled for either. */
21
+ function sessionsFeed({ openSocket, hidden }, onListing) {
22
+ const readers = /* @__PURE__ */ new Set();
23
+ const watchers = /* @__PURE__ */ new Set();
24
+ let fed = false;
25
+ let sent = false;
26
+ let stop;
27
+ let tryNow;
28
+ let writing = 0;
29
+ function setFed(next) {
30
+ if (fed !== next) {
31
+ fed = next;
32
+ for (const notify of [...watchers]) notify();
33
+ }
34
+ }
35
+ const socket = { current: {
36
+ open: openSocket,
37
+ path: () => SESSIONS_FEED_PATH,
38
+ onOpen: (revived) => {
39
+ sent &&= revived;
40
+ setFed(sent);
41
+ },
42
+ onClose: () => setFed(false),
43
+ onMessage: (data) => {
44
+ const listing = listingFrame(data);
45
+ if (!listing) return;
46
+ sent = true;
47
+ setFed(true);
48
+ onListing(listing);
49
+ for (const read of [...readers]) read(listing);
50
+ },
51
+ whenReachable: (now) => {
52
+ tryNow = now;
53
+ return () => {
54
+ tryNow = void 0;
55
+ };
56
+ },
57
+ heartbeat: (data) => {
58
+ if (hidden?.()) queueMicrotask(() => {
59
+ if (hidden()) leave();
60
+ });
61
+ return isHeartbeat(data);
62
+ }
63
+ } };
64
+ function open() {
65
+ if (!stop && openSocket && readers.size > 0 && writing === 0 && !hidden?.()) stop = holdSocket(socket, () => {});
66
+ }
67
+ function leave() {
68
+ if (stop) {
69
+ stop();
70
+ stop = void 0;
71
+ sent = false;
72
+ setFed(false);
73
+ }
74
+ }
75
+ /** Hands `reader` each listing until the returned call. */
76
+ function read(reader) {
77
+ readers.add(reader);
78
+ open();
79
+ return () => {
80
+ readers.delete(reader);
81
+ queueMicrotask(() => {
82
+ if (readers.size === 0) leave();
83
+ });
84
+ };
85
+ }
86
+ /** Leaves the socket until the returned call, while the page itself writes
87
+ * the listing or reads it again. A listing the platform sent before that
88
+ * would put back what it changed; another socket's first listing is asked
89
+ * for after it opened. The listing is polled for meanwhile. */
90
+ function pause() {
91
+ writing += 1;
92
+ leave();
93
+ let landed = false;
94
+ return () => {
95
+ if (!landed) {
96
+ landed = true;
97
+ writing -= 1;
98
+ open();
99
+ }
100
+ };
101
+ }
102
+ function watch(notify) {
103
+ watchers.add(notify);
104
+ return () => {
105
+ watchers.delete(notify);
106
+ };
107
+ }
108
+ /** Whether the listing comes over the socket, so that nothing need poll for it. */
109
+ function useFed() {
110
+ return useSyncExternalStore(watch, () => fed, () => false);
111
+ }
112
+ /** The platform answered, so a socket waiting to try again tries at once,
113
+ * and one left while the app was out of sight opens again. */
114
+ function reachable() {
115
+ open();
116
+ tryNow?.();
117
+ }
118
+ return {
119
+ read,
120
+ pause,
121
+ useFed,
122
+ reachable
123
+ };
124
+ }
125
+ export { SESSIONS_FEED_PATH, sessionsFeed };
@@ -115,16 +115,19 @@ export interface PwCodeMachineMenu {
115
115
  /** Picks a machine; the one picked already stays as it is. */
116
116
  pick: (id: string) => void;
117
117
  }
118
- export declare function machineMenu<M extends PwCodeStartMachine>(location: Pick<PwCodeStartLocation<M>, 'startable' | 'down' | 'machine' | 'pickMachine'>, t: Translate): PwCodeMachineMenu;
118
+ export declare function machineMenu<M extends PwCodeStartMachine>(location: Pick<PwCodeStartLocation<M>, 'startable' | 'down' | 'machine' | 'pickMachine'> & Partial<Pick<PwCodeStartLocation<M>, 'pending'>>, t: Translate): PwCodeMachineMenu;
119
119
  /** The chip naming the machine a session starts on, which opens the
120
120
  * `machineMenu`: the machine's name after a dot in the `success` tone, since
121
121
  * only a machine that answers can be chosen, or, until one is, a call to
122
122
  * choose one and no dot. While the machines are still being listed
123
- * (`finding`), it says so and opens nothing. `label` names the chip's action. */
124
- export declare function machineChip(machine: Pick<PwCodeStartMachine, 'name'> | undefined, t: Translate, finding?: boolean): {
123
+ * (`finding`), it says so and opens nothing; while the workspace a start
124
+ * waits for starts (`pending`), it says so and still opens the menu.
125
+ * `label` names the chip's action. */
126
+ export declare function machineChip(machine: Pick<PwCodeStartMachine, 'name'> | undefined, t: Translate, finding?: boolean, pending?: boolean): {
125
127
  text: string;
126
128
  label: string;
127
129
  dot: 'success' | null;
130
+ waiting: boolean;
128
131
  };
129
132
  /** A chat handed to a new session, while it loads or once it failed to. */
130
133
  export interface PwCodeStartHandoff {
package/dist/startPage.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { chatHandoffPrompt } from "./chatHandoff.js";
2
2
  import { paletteOptions } from "./command.js";
3
3
  import { loadErrorMessage } from "./loadError.js";
4
- import { isComputer } from "./machine.js";
4
+ import { isComputer, isWorkspace } from "./machine.js";
5
5
  import { runsClaude } from "./models.js";
6
6
  import { isActiveSession } from "./session.js";
7
7
  import { approvalToPart } from "./transcript.js";
@@ -97,15 +97,16 @@ function startCommands(palette, machine, t) {
97
97
  return paletteOptions(palette, runsClaude(machine) ? t("claude.choose") : void 0);
98
98
  }
99
99
  function machineMenu(location, t) {
100
- const picked = location.machine?.id;
101
- const startable = location.startable.map((m) => ({
100
+ const { pending } = location;
101
+ const picked = location.machine?.id ?? pending?.id;
102
+ const startable = [...pending ? [pending] : [], ...location.startable].map((m) => ({
102
103
  id: m.id,
103
104
  label: m.name,
104
- description: isComputer(m) ? t("machine.computer") : t("machine.resource"),
105
+ description: m === pending ? machineHint(m, t)?.text : machineDescription(m, t),
105
106
  checked: m.id === picked,
106
107
  disabled: false
107
108
  }));
108
- const down = location.down.map((m) => ({
109
+ const down = location.down.filter((m) => m !== pending).map((m) => ({
109
110
  id: m.id,
110
111
  label: m.name,
111
112
  description: machineHint(m, t)?.text,
@@ -121,29 +122,50 @@ function machineMenu(location, t) {
121
122
  }
122
123
  };
123
124
  }
125
+ /** What a machine is, and the pw it runs when its daemon said. */
126
+ function machineDescription(m, t) {
127
+ const kind = isWorkspace(m) ? t("machine.workspace") : isComputer(m) ? t("machine.computer") : t("machine.resource");
128
+ if (m.pwUpdate) return t("machine.withUpdate", { kind });
129
+ return m.pwVersion ? t("machine.withVersion", {
130
+ kind,
131
+ version: m.pwVersion
132
+ }) : kind;
133
+ }
124
134
  /** The chip naming the machine a session starts on, which opens the
125
135
  * `machineMenu`: the machine's name after a dot in the `success` tone, since
126
136
  * only a machine that answers can be chosen, or, until one is, a call to
127
137
  * choose one and no dot. While the machines are still being listed
128
- * (`finding`), it says so and opens nothing. `label` names the chip's action. */
129
- function machineChip(machine, t, finding = false) {
138
+ * (`finding`), it says so and opens nothing; while the workspace a start
139
+ * waits for starts (`pending`), it says so and still opens the menu.
140
+ * `label` names the chip's action. */
141
+ function machineChip(machine, t, finding = false, pending = false) {
130
142
  if (finding) {
131
143
  const text = t("start.findingMachines");
132
144
  return {
133
145
  text,
134
146
  label: text,
135
- dot: null
147
+ dot: null,
148
+ waiting: true
136
149
  };
137
150
  }
138
151
  const choose = t("start.chooseMachine");
139
- return machine ? {
152
+ if (machine) return {
140
153
  text: machine.name,
141
154
  label: choose,
142
- dot: "success"
143
- } : {
155
+ dot: "success",
156
+ waiting: false
157
+ };
158
+ if (pending) return {
159
+ text: t("start.workspaceStarting"),
160
+ label: choose,
161
+ dot: null,
162
+ waiting: true
163
+ };
164
+ return {
144
165
  text: choose,
145
166
  label: choose,
146
- dot: null
167
+ dot: null,
168
+ waiting: false
147
169
  };
148
170
  }
149
171
  /** How a start carries a chat handed to it: it waits until the chat has