@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
@@ -0,0 +1,218 @@
1
+ import { useCompactAgo } from "./ago.js";
2
+ import { paletteOptions } from "./command.js";
3
+ import { goalMark } from "./goal.js";
4
+ import { loadFailure } from "./loadError.js";
5
+ import { canStartHere } from "./machine.js";
6
+ import { usePwCodeTranslations } from "./messages.js";
7
+ import { isClaudeModel, pickerCommand, runsClaude } from "./models.js";
8
+ import { useLastReadAt } from "./sessionsApi.js";
9
+ import { reviewingCount } from "./transcript.js";
10
+ import { sessionStatusText } from "./wording.js";
11
+ import { useCallback, useState } from "react";
12
+ // src/sessionScreen.ts
13
+ /** A machine that does not answer outranks a session running in pw code elsewhere. */
14
+ function sessionBanner({ unreachable, liveElsewhere, machineName, staleFor, liveHost }, t) {
15
+ if (unreachable) return {
16
+ kind: "unreachable",
17
+ tone: "danger",
18
+ title: t("detail.unreachableTitle", {
19
+ machine: machineName,
20
+ when: staleFor
21
+ }),
22
+ body: t("detail.unreachableBody"),
23
+ action: t("detail.checkAgain")
24
+ };
25
+ if (liveElsewhere) {
26
+ const host = liveHost ?? "";
27
+ return {
28
+ kind: "liveElsewhere",
29
+ tone: "info",
30
+ title: t("detail.liveOn", { host }),
31
+ body: t("detail.liveElsewhereBody", { host }),
32
+ action: t("detail.refresh")
33
+ };
34
+ }
35
+ return null;
36
+ }
37
+ /** The goal loop's state, which stands apart from the session's: a paused
38
+ * goal leaves the turn it paused in running. Null without a goal. */
39
+ function goalLabel(goal, t) {
40
+ if (!goal?.active && !goal?.paused) return null;
41
+ const active = goal.active === true;
42
+ return {
43
+ ...goalMark(goal),
44
+ active,
45
+ text: active ? t("detail.goalActive") : t("detail.goalPaused")
46
+ };
47
+ }
48
+ /** The Claude Code account a Claude model runs as, pw code's `default` until
49
+ * one is chosen; null for any other model. */
50
+ function claudeAccountChip(model, account, t) {
51
+ if (!isClaudeModel(model)) return null;
52
+ const name = account || "default";
53
+ return {
54
+ account: name,
55
+ label: t("claude.selected", { account: name })
56
+ };
57
+ }
58
+ /** The composer's draft key. By the session rather than its machine: the
59
+ * screen follows a session to another login node, and the draft goes with it. */
60
+ function sessionDraftKey(sessionId, detail) {
61
+ return `agents:${detail?.id ?? sessionId}`;
62
+ }
63
+ /** The draft key of the composer that starts a session, one per reader. */
64
+ function newSessionDraftKey(username) {
65
+ return `agents:new:${username}`;
66
+ }
67
+ /** How long ago the transcript was last read, abbreviated, for the composer
68
+ * and banner to say how stale it is once the machine stops answering. */
69
+ function useStaleFor(detail, feedOpen) {
70
+ const { now, compactMinutes } = useCompactAgo();
71
+ const lastReadAt = useLastReadAt(detail, feedOpen);
72
+ return compactMinutes(lastReadAt ? Math.floor((now - lastReadAt.toMillis()) / 6e4) : 0);
73
+ }
74
+ /** The model a session runs: the one it reports while live, else the one
75
+ * read of it. */
76
+ function sessionModel(liveState, detail) {
77
+ return liveState?.model ?? detail?.model;
78
+ }
79
+ /** What an open session's settings pickers show and whether they can change. */
80
+ function sessionSettingsOptions(machine, conversation, composer) {
81
+ const { liveState, detail } = conversation;
82
+ return {
83
+ machine,
84
+ sessionId: detail?.id ?? "",
85
+ model: sessionModel(liveState, detail),
86
+ effort: liveState ? liveState.effort : detail?.effort,
87
+ allocation: liveState?.allocation ?? detail?.allocation,
88
+ claudeAccount: liveState?.claudeAccount ?? detail?.claudeAccount,
89
+ locked: composer.unreachable || composer.archived,
90
+ live: !!detail && composer.status !== "live_elsewhere"
91
+ };
92
+ }
93
+ /** Which of the composer's pickers is open; `/model` and `/claude-code` open
94
+ * one in place of being sent, and stay out of the transcript. */
95
+ function useSessionPicker() {
96
+ const [picker, setPicker] = useState(null);
97
+ return {
98
+ picker,
99
+ setPicker,
100
+ close: useCallback((panel) => setPicker((current) => current === panel ? null : current), []),
101
+ handleLocally: useCallback((typed) => {
102
+ const panel = pickerCommand(typed);
103
+ if (panel) setPicker(panel);
104
+ return !!panel;
105
+ }, []),
106
+ addsToTranscript: useCallback((typed) => !pickerCommand(typed), [])
107
+ };
108
+ }
109
+ /** A turn at work: when it started and what it has used so far. */
110
+ function workingActivity(transcript, tokens, word) {
111
+ return {
112
+ kind: "working",
113
+ startedAt: transcript?.turnStartedAt ?? null,
114
+ inputTokens: tokens?.inputTokens,
115
+ outputTokens: tokens?.outputTokens,
116
+ word
117
+ };
118
+ }
119
+ /** What the composer's activity line says: the feed reconnecting outranks a
120
+ * turn, and a turn waiting on a usage limit says so in place of working. */
121
+ function sessionActivity({ composer, transcript, liveState, claudeModel }, t, tTranscript) {
122
+ if (composer.reconnecting) return {
123
+ kind: "reconnecting",
124
+ text: t("detail.reconnecting")
125
+ };
126
+ if (!composer.working) return null;
127
+ if (transcript?.waitingForUsageLimit) return {
128
+ kind: "usageLimit",
129
+ resumeAt: transcript.usageLimitResumeAt,
130
+ offersAccounts: claudeModel
131
+ };
132
+ const reviewing = reviewingCount(transcript);
133
+ return workingActivity(transcript, liveState, composer.checkingGoal ? t("detail.checkingGoal") : reviewing ? tTranscript("transcript.reviewing", { count: reviewing }) : void 0);
134
+ }
135
+ /** What a machine allows of Claude Code, for its account panel and model picker. */
136
+ function claudeOnMachine(machine) {
137
+ return {
138
+ available: runsClaude(machine),
139
+ installed: machine?.claudeInstalled === true,
140
+ allowed: machine?.claudeCodeAllowed === true,
141
+ login: machine?.claudeLogin === true,
142
+ accountRemove: machine?.claudeAccountRemove === true && machine.remoteStart === true
143
+ };
144
+ }
145
+ /** An open session's screen around its transcript and composer: the banner,
146
+ * the activity line, the goal, what the transcript shows when it never
147
+ * loaded, the command menu and the settings row. The host reads the session
148
+ * (`api.useSessionDetail`, `api.useMachine`) and runs the conversation,
149
+ * composer and settings it passes here. */
150
+ function usePwCodeSessionScreen({ conversation, composer, read, machine, staleFor, settings, images, describeError }) {
151
+ const t = usePwCodeTranslations("agents");
152
+ const tTranscript = usePwCodeTranslations("agentTranscript");
153
+ const { detail, liveState, transcript, refetch } = conversation;
154
+ const { machine: info, recheck } = machine;
155
+ const claude = claudeOnMachine(info);
156
+ const retry = useCallback(() => void refetch(), [refetch]);
157
+ const banner = sessionBanner({
158
+ unreachable: composer.unreachable,
159
+ liveElsewhere: detail?.status === "live_elsewhere",
160
+ machineName: composer.machineName,
161
+ staleFor,
162
+ liveHost: detail?.liveHost
163
+ }, t);
164
+ const rechecks = banner?.kind === "unreachable";
165
+ const act = useCallback(() => {
166
+ if (rechecks) recheck();
167
+ refetch();
168
+ }, [
169
+ rechecks,
170
+ recheck,
171
+ refetch
172
+ ]);
173
+ const activity = sessionActivity({
174
+ composer,
175
+ transcript,
176
+ liveState,
177
+ claudeModel: claude.available && isClaudeModel(settings.model.value)
178
+ }, t, tTranscript);
179
+ return {
180
+ /** The session's state in a sentence, for a screen reader. */
181
+ statusText: composer.status ? sessionStatusText({
182
+ status: composer.status,
183
+ liveHost: detail?.liveHost,
184
+ approvals: composer.approvals
185
+ }, t) : "",
186
+ banner: banner && {
187
+ ...banner,
188
+ act
189
+ },
190
+ /** The transcript has yet to load for the first time. */
191
+ loading: read.isLoading && !detail && !conversation.endOnly,
192
+ /** Shown in place of a transcript that never loaded: why, or undefined
193
+ * for the host's own line. */
194
+ failed: loadFailure(read.error, !!detail, describeError),
195
+ retry,
196
+ /** Why the workspace's own settings, skills and hooks did not load. */
197
+ untrusted: detail?.workspaceUntrusted ? t("detail.untrusted") : null,
198
+ activity,
199
+ /** The turn waits at its account's usage limit, as the activity line
200
+ * says; not while the feed reconnects, which that line says instead. For
201
+ * `useClaudeAccountPanel`'s `waitingAtLimit`. */
202
+ waitingAtLimit: activity?.kind === "usageLimit",
203
+ goal: goalLabel(conversation.goal, t),
204
+ commands: paletteOptions(composer.palette, claude.available ? t("claude.choose") : void 0, t("detail.archiveCommand")),
205
+ showAuthor: conversation.all.some((m) => m.author),
206
+ /** A message may go without text while images go with it. */
207
+ allowEmpty: images.length > 0,
208
+ permission: {
209
+ mode: liveState?.permissionMode ?? detail?.permissionMode,
210
+ ceiling: info?.remoteMaxPermissionMode,
211
+ accepted: info?.permissionModes ?? void 0,
212
+ disabled: composer.composer.locked || settings.saving
213
+ },
214
+ claude,
215
+ canStart: !!info && canStartHere(info)
216
+ };
217
+ }
218
+ export { claudeAccountChip, claudeOnMachine, goalLabel, newSessionDraftKey, sessionActivity, sessionBanner, sessionDraftKey, sessionModel, sessionSettingsOptions, usePwCodeSessionScreen, useSessionPicker, useStaleFor, workingActivity };
@@ -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';
3
+ import { type KeyedMutator } from 'swr';
4
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,18 +38,40 @@ export type PwCodePasteUpload = {
37
38
  } | {
38
39
  unsupported: true;
39
40
  };
40
- export declare function sessionsApi(client: PwCodeClient): {
41
+ export interface PwCodeSessionOptions {
42
+ /** Whether the host shows an image from its URL on the platform's API, signed
43
+ * in as the API client is, as a browser on the platform's origin does. Set,
44
+ * a session's transcript is read with each image's preview left to its ref,
45
+ * and the preview is loaded from there when it is drawn: previews are most
46
+ * of what a transcript with pictures weighs. */
47
+ previewsByRef?: boolean | undefined;
48
+ /** Whether the host's `fetch` hands over a response's body as it arrives
49
+ * (`response.body`), as a browser's does. Set, a session's transcript is
50
+ * read end first, and the end of the conversation is drawn while the rest
51
+ * arrives: over a slow connection the transcript is most of the wait. A
52
+ * host without it, such as React Native's own fetch, reads the session
53
+ * whole. */
54
+ transcriptEndFirst?: boolean | undefined;
55
+ }
56
+ export declare function sessionsApi(client: PwCodeClient, { previewsByRef, transcriptEndFirst, }?: PwCodeSessionOptions,
57
+ /** Told the machines of each listing that answers. */
58
+ listed?: (machines: Schemas['AgentMachine'][]) => void,
59
+ /** The listing as the platform sends it over a socket, for a host that opens them. */
60
+ feed?: SessionsFeed): {
41
61
  useSessions: () => PwCodeQuery<SessionsResponse>;
42
62
  useWaitingSessionCount: (enabled: boolean) => number;
43
63
  useSessionDetail: (machine: string, id: string, listed: Session | undefined) => {
44
64
  data: SessionDetail | undefined;
65
+ /** The session with only the end of its history, while the rest of the
66
+ * transcript is still arriving and there is nothing else to show. */
67
+ preview: SessionDetail | undefined;
45
68
  error: PwCodeApiError | undefined;
46
69
  isLoading: boolean;
47
70
  mutate: KeyedMutator<SessionDetail>;
48
71
  fresh: boolean;
49
72
  };
50
73
  usePullRequests: (machine: string, id: string, urls: string[], onRead?: (read: PullRequest[]) => void) => PwCodeQuery<Schemas['AgentPullRequests']>;
51
- useSessionPullRequestStates: (machine: string, id: string, urls: string[]) => {
74
+ useSessionPullRequestStates: (machine: string, id: string, pullRequests: readonly string[] | null | undefined) => {
52
75
  url: string;
53
76
  state: string | undefined;
54
77
  }[] | undefined;
@@ -67,6 +90,7 @@ export declare function sessionsApi(client: PwCodeClient): {
67
90
  };
68
91
  stopSubagent: (machine: string, id: string, subId: string) => Promise<unknown>;
69
92
  stopAllSubagents: (machine: string, id: string) => Promise<unknown>;
93
+ dismissSubagent: (machine: string, id: string, subId: string) => Promise<unknown>;
70
94
  useSessionWorktree: (s: Session | undefined) => PwCodeQuery<Schemas['AgentSessionWorktree']>;
71
95
  leaveWorktree: (s: Session, removeRoot?: string) => Promise<{
72
96
  left?: Schemas['AgentWorktreeLeft'];
@@ -94,9 +118,11 @@ export declare function sessionsApi(client: PwCodeClient): {
94
118
  createSession: (machine: string, body: Schemas['CreateSessionBody']) => Promise<PwCodeResult<SessionDetail>>;
95
119
  sendMessage: (machine: string, id: string, body: Schemas['SendMessageBody']) => Promise<PwCodeResult<Schemas['AgentMessageAccepted']>>;
96
120
  steer: (machine: string, id: string, body: Schemas['AgentDirectionBody']) => Promise<PwCodeResult<Schemas['AgentDirectionDelivered']>>;
121
+ withdrawDirection: (machine: string, id: string, ids: string[]) => Promise<PwCodeResult<Schemas['AgentDirectionWithdrawn']>>;
97
122
  withdrawQueued: (machine: string, id: string, turnId: string) => Promise<PwCodeResult<undefined>>;
98
123
  messageSubagent: (machine: string, id: string, subId: string, body: Schemas['SendMessageBody']) => Promise<PwCodeResult<Schemas['AgentMessageAccepted']>>;
99
124
  steerSubagent: (machine: string, id: string, subId: string, body: Schemas['AgentDirectionBody']) => Promise<PwCodeResult<Schemas['AgentDirectionDelivered']>>;
125
+ withdrawSubagentDirection: (machine: string, id: string, subId: string, ids: string[]) => Promise<PwCodeResult<Schemas['AgentDirectionWithdrawn']>>;
100
126
  saveImage: (machine: string, id: string, body: Schemas['AgentImageBody']) => Promise<PwCodeResult<Schemas['AgentImageSaved']>>;
101
127
  answerApproval: (machine: string, sessionId: string, approvalId: string, answer: ApprovalAnswerValue) => Promise<unknown>;
102
128
  removeSessionDirectory: (machine: string, sessionId: string, path: string) => Promise<unknown>;
@@ -1,10 +1,16 @@
1
+ import "./apiClient.js";
1
2
  import { bytesToBase64 } from "./base64.js";
3
+ import { PREVIEWS_BY_REF } from "./images.js";
2
4
  import { createQuery } from "./query.js";
3
5
  import { machinesById } from "./machine.js";
6
+ import { labeledPullRequests } from "./pullRequestList.js";
4
7
  import { isSession, triageSessions } from "./session.js";
5
8
  import { approvalAnswerBody } from "./transcript.js";
6
- 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";
7
12
  import { DateTime } from "luxon";
13
+ import { toApiError } from "@parallelworks/problem";
8
14
  // src/sessionsApi.ts
9
15
  var SESSIONS_REFRESH_MS = 5e3;
10
16
  var WAITING_REFRESH_MS = 3e4;
@@ -16,6 +22,12 @@ var SUBAGENTS_REFRESH_MS = 1e3;
16
22
  function cachedCopyCurrent(listed, cached) {
17
23
  return !!listed && listed.status !== "running" && listed.status === cached.status && listed.messages === cached.messages && listed.updatedAt === cached.updatedAt;
18
24
  }
25
+ var SESSION_DETAIL = "/api/code/machines/{machine}/sessions/{id}";
26
+ var SESSION_DETAIL_READ = {
27
+ revalidateIfStale: false,
28
+ revalidateOnFocus: false,
29
+ revalidateOnReconnect: false
30
+ };
19
31
  /** Whether this visit's own read has answered: a copy cached by an earlier
20
32
  * visit has not, until the read started on mounting lands. */
21
33
  function useReadThisVisit(data, isValidating, mutate) {
@@ -140,15 +152,73 @@ function sessionPath(s) {
140
152
  id: s.id
141
153
  } } };
142
154
  }
143
- function sessionsApi(client) {
155
+ function sessionsApi(client, { previewsByRef = false, transcriptEndFirst = false } = {}, listed, feed) {
144
156
  const useQuery = createQuery(client);
157
+ const transcripts = createTranscriptReads(client, previewsByRef);
158
+ const useFed = feed?.useFed ?? (() => false);
159
+ /** The listing, asked for again every `every` ms while no socket sends it.
160
+ * `live` holds that socket open. */
161
+ function useListing(enabled, every, live = false) {
162
+ const { onErrorRetry } = useSWRConfig();
163
+ const fed = useFed();
164
+ const config = useMemo(() => ({
165
+ refreshInterval: fed ? 0 : every,
166
+ onSuccess: (listing) => {
167
+ listed?.(listing.machines ?? []);
168
+ feed?.reachable();
169
+ },
170
+ onErrorRetry: (error, key, swr, revalidate, attempt) => {
171
+ if (toApiError(error).code === "network") {
172
+ setTimeout(() => void revalidate(attempt), SESSIONS_REFRESH_MS);
173
+ return;
174
+ }
175
+ onErrorRetry(error, key, swr, revalidate, attempt);
176
+ }
177
+ }), [
178
+ every,
179
+ fed,
180
+ onErrorRetry
181
+ ]);
182
+ const response = useQuery("/api/code/sessions", enabled ? void 0 : null, config);
183
+ const { mutate } = response;
184
+ useEffect(() => {
185
+ if (!live || !enabled || !feed) return;
186
+ return feed.read((listing) => void mutate(listing, { revalidate: false }));
187
+ }, [
188
+ live,
189
+ enabled,
190
+ mutate
191
+ ]);
192
+ return {
193
+ get data() {
194
+ return response.data;
195
+ },
196
+ get error() {
197
+ return response.error;
198
+ },
199
+ get isValidating() {
200
+ return response.isValidating;
201
+ },
202
+ get isLoading() {
203
+ return response.isLoading;
204
+ },
205
+ mutate: useCallback(async (...args) => {
206
+ const landed = feed?.pause();
207
+ try {
208
+ return await mutate(...args);
209
+ } finally {
210
+ landed?.();
211
+ }
212
+ }, [mutate])
213
+ };
214
+ }
145
215
  /** Every session on every machine the reader can reach, with each machine's reachability. */
146
216
  function useSessions() {
147
- return useQuery("/api/code/sessions", void 0, { refreshInterval: SESSIONS_REFRESH_MS });
217
+ return useListing(true, SESSIONS_REFRESH_MS, true);
148
218
  }
149
219
  /** Every listing asks each machine, so an app-wide count polls slower; the list's own poll keeps it current beside the list. */
150
220
  function useWaitingSessionCount(enabled) {
151
- const { data } = useQuery("/api/code/sessions", enabled ? void 0 : null, { refreshInterval: WAITING_REFRESH_MS });
221
+ const { data } = useListing(enabled, WAITING_REFRESH_MS);
152
222
  return useMemo(() => data ? triageSessions(data.sessions ?? [], machinesById(data.machines ?? [])).blocked.length : 0, [data]);
153
223
  }
154
224
  /** `fresh` once this visit has fetched the session: a copy cached by an earlier
@@ -157,19 +227,30 @@ function sessionsApi(client) {
157
227
  * A cached copy the listed row says the session has moved past stays hidden
158
228
  * until that fetch answers, so the newer turns don't land under the reader. */
159
229
  function useSessionDetail(machine, id, listed) {
160
- const { data, error, isLoading, isValidating, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}", { params: { path: {
161
- machine,
162
- id
163
- } } }, {
164
- revalidateIfStale: false,
165
- revalidateOnFocus: false,
166
- revalidateOnReconnect: false
167
- });
230
+ const init = useMemo(() => {
231
+ return { params: {
232
+ path: {
233
+ machine,
234
+ id
235
+ },
236
+ ...previewsByRef ? { query: { previews: PREVIEWS_BY_REF } } : {}
237
+ } };
238
+ }, [machine, id]);
239
+ const read = useCallback((name, signal) => transcripts.read(machine, id, name, signal), [machine, id]);
240
+ const { data, error, isLoading, isValidating, mutate } = useQuery(SESSION_DETAIL, init, SESSION_DETAIL_READ, true, transcriptEndFirst ? read : void 0);
241
+ const name = useMemo(() => unstable_serialize([
242
+ "api",
243
+ SESSION_DETAIL,
244
+ init
245
+ ]), [init]);
246
+ const tail = useSyncExternalStore(transcripts.subscribe, () => transcripts.tail(name), () => void 0);
168
247
  const [current] = useState(() => data !== void 0 && cachedCopyCurrent(listed, data));
169
248
  const answered = useReadThisVisit(data, isValidating, mutate);
170
249
  const hidden = !current && !answered;
250
+ const shown = hidden ? void 0 : data;
171
251
  return {
172
- data: hidden ? void 0 : data,
252
+ data: shown,
253
+ preview: shown === void 0 ? tail : void 0,
173
254
  error,
174
255
  isLoading: isLoading || hidden,
175
256
  mutate,
@@ -196,10 +277,12 @@ function sessionsApi(client) {
196
277
  }, [shown, mutate]);
197
278
  return query;
198
279
  }
199
- /** A session's pull request states, as the sessions list has them so every
200
- * view of the session agrees, or its own read where the list has none. Each
201
- * read goes into the list at once. */
202
- function useSessionPullRequestStates(machine, id, urls) {
280
+ /** The states of the session's `pullRequests` that are pull or merge requests
281
+ * (`labeledPullRequests`), as the sessions list has them so every view of
282
+ * the session agrees, or its own read where the list has none. Each read
283
+ * goes into the list at once. */
284
+ function useSessionPullRequestStates(machine, id, pullRequests) {
285
+ const urls = labeledPullRequests(pullRequests).map(({ url }) => url);
203
286
  const { data: list, mutate } = useSessions();
204
287
  const { data } = usePullRequests(machine, id, urls, (read) => {
205
288
  if (patchPullRequestStates(list, machine, read) !== list) mutate((current) => patchPullRequestStates(current, machine, read), { revalidate: false });
@@ -275,6 +358,18 @@ function sessionsApi(client) {
275
358
  return thrown;
276
359
  }
277
360
  }
361
+ async function dismissSubagent(machine, id, subId) {
362
+ try {
363
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/dismiss", { params: { path: {
364
+ machine,
365
+ id,
366
+ subId
367
+ } } });
368
+ return error ?? null;
369
+ } catch (thrown) {
370
+ return thrown;
371
+ }
372
+ }
278
373
  async function stopAllSubagents(machine, id) {
279
374
  try {
280
375
  const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/stop-all", { params: { path: {
@@ -302,7 +397,8 @@ function sessionsApi(client) {
302
397
  return error ? { refusal: error } : { left: data };
303
398
  }
304
399
  /** Each resolves to the daemon's refusal, or null once the list is patched,
305
- * which happens at once so the row does not linger until the next poll. */
400
+ * which happens at once so the row does not linger until the next poll. A
401
+ * pin, a group and a restore show before the machine answers. */
306
402
  function useSessionMutations() {
307
403
  const { mutate } = useSessions();
308
404
  const patched = useCallback(async (s, request, change) => {
@@ -314,6 +410,30 @@ function sessionsApi(client) {
314
410
  }, { revalidate: true });
315
411
  return null;
316
412
  }, [mutate]);
413
+ const patchedAtOnce = useCallback(async (s, request, change) => {
414
+ const refused = {};
415
+ try {
416
+ await mutate(async () => {
417
+ const { error } = await request;
418
+ if (error) {
419
+ refused.error = error;
420
+ throw error;
421
+ }
422
+ }, {
423
+ optimisticData: (_read, shown) => shown && {
424
+ ...shown,
425
+ sessions: (shown.sessions ?? []).map((x) => sameSession(x, s) ? change(x) : x)
426
+ },
427
+ populateCache: false,
428
+ rollbackOnError: true,
429
+ revalidate: true
430
+ });
431
+ } catch (thrown) {
432
+ if ("error" in refused) return refused.error;
433
+ throw thrown;
434
+ }
435
+ return null;
436
+ }, [mutate]);
317
437
  return {
318
438
  deleteSession: useCallback(async (s, removeWorktree) => {
319
439
  const { error } = await client.DELETE("/api/code/machines/{machine}/sessions/{id}", removeWorktree ? { params: {
@@ -355,18 +475,18 @@ function sessionsApi(client) {
355
475
  deferred
356
476
  };
357
477
  }, [patched]),
358
- restoreSession: useCallback((s) => patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/archive", sessionPath(s)), ({ archivedAt: _, ...x }) => x), [patched]),
359
- pinSession: useCallback((s, pinned) => pinned ? patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), (x) => ({
478
+ restoreSession: useCallback((s) => patchedAtOnce(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/archive", sessionPath(s)), ({ archivedAt: _, ...x }) => x), [patchedAtOnce]),
479
+ pinSession: useCallback((s, pinned) => pinned ? patchedAtOnce(s, client.POST("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), (x) => ({
360
480
  ...x,
361
481
  pinnedAt: DateTime.now().toISO()
362
- })) : patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), ({ pinnedAt: _, ...x }) => x), [patched]),
363
- groupSession: useCallback((s, group) => group ? patched(s, client.PUT("/api/code/machines/{machine}/sessions/{id}/group", {
482
+ })) : patchedAtOnce(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), ({ pinnedAt: _, ...x }) => x), [patchedAtOnce]),
483
+ groupSession: useCallback((s, group) => group ? patchedAtOnce(s, client.PUT("/api/code/machines/{machine}/sessions/{id}/group", {
364
484
  ...sessionPath(s),
365
485
  body: { group }
366
486
  }), (x) => ({
367
487
  ...x,
368
488
  group
369
- })) : patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/group", sessionPath(s)), ({ group: _, ...x }) => x), [patched]),
489
+ })) : patchedAtOnce(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/group", sessionPath(s)), ({ group: _, ...x }) => x), [patchedAtOnce]),
370
490
  stopSession: useCallback((s) => patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/stop", sessionPath(s)), (x) => x), [patched]),
371
491
  forkSession: useCallback(async (s) => {
372
492
  const { data, error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/fork", sessionPath(s));
@@ -403,6 +523,16 @@ function sessionsApi(client) {
403
523
  body
404
524
  });
405
525
  }
526
+ /** Takes back steered text the model has not read, by the ids steering answered with. */
527
+ function withdrawDirection(machine, id, ids) {
528
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/direction/withdraw", {
529
+ params: { path: {
530
+ machine,
531
+ id
532
+ } },
533
+ body: { ids }
534
+ });
535
+ }
406
536
  /** Takes back a message still queued behind the running turn. */
407
537
  function withdrawQueued(machine, id, turnId) {
408
538
  return client.DELETE("/api/code/machines/{machine}/sessions/{id}/queued/{turnId}", { params: { path: {
@@ -431,6 +561,16 @@ function sessionsApi(client) {
431
561
  body
432
562
  });
433
563
  }
564
+ function withdrawSubagentDirection(machine, id, subId, ids) {
565
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/direction/withdraw", {
566
+ params: { path: {
567
+ machine,
568
+ id,
569
+ subId
570
+ } },
571
+ body: { ids }
572
+ });
573
+ }
434
574
  /** Saves an image, base64-encoded, with the session; a message names it by
435
575
  * the path this resolves to. */
436
576
  function saveImage(machine, id, body) {
@@ -442,17 +582,21 @@ function sessionsApi(client) {
442
582
  body
443
583
  });
444
584
  }
445
- /** Resolves to the daemon's refusal, or null once the answer is accepted. */
585
+ /** Resolves to the daemon's refusal, or what was thrown when it did not answer, or null once the answer is accepted. */
446
586
  async function answerApproval(machine, sessionId, approvalId, answer) {
447
- const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/approvals/{approvalId}", {
448
- params: { path: {
449
- machine,
450
- id: sessionId,
451
- approvalId
452
- } },
453
- body: approvalAnswerBody(answer)
454
- });
455
- return error ?? null;
587
+ try {
588
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/approvals/{approvalId}", {
589
+ params: { path: {
590
+ machine,
591
+ id: sessionId,
592
+ approvalId
593
+ } },
594
+ body: approvalAnswerBody(answer)
595
+ });
596
+ return error ?? null;
597
+ } catch (thrown) {
598
+ return thrown;
599
+ }
456
600
  }
457
601
  /** Closes a directory added for this session only; resolves to the daemon's refusal, or null once it is closed. */
458
602
  async function removeSessionDirectory(machine, sessionId, path) {
@@ -493,15 +637,18 @@ function sessionsApi(client) {
493
637
  useSubagentDetail,
494
638
  stopSubagent,
495
639
  stopAllSubagents,
640
+ dismissSubagent,
496
641
  useSessionWorktree,
497
642
  leaveWorktree,
498
643
  useSessionMutations,
499
644
  createSession,
500
645
  sendMessage,
501
646
  steer,
647
+ withdrawDirection,
502
648
  withdrawQueued,
503
649
  messageSubagent,
504
650
  steerSubagent,
651
+ withdrawSubagentDirection,
505
652
  saveImage,
506
653
  answerApproval,
507
654
  removeSessionDirectory,
@@ -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 {};