@parallelworks/code 0.3.0 → 0.4.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 (103) hide show
  1. package/README.md +598 -113
  2. package/dist/accountApi.d.ts +31 -0
  3. package/dist/accountApi.js +182 -0
  4. package/dist/agentSwitcher.d.ts +109 -0
  5. package/dist/agentSwitcher.js +165 -0
  6. package/dist/ago.d.ts +3 -3
  7. package/dist/ago.js +10 -10
  8. package/dist/allocations.d.ts +41 -0
  9. package/dist/allocations.js +76 -0
  10. package/dist/api.d.ts +1080 -11
  11. package/dist/chatStrings.d.ts +188 -0
  12. package/dist/chatStrings.js +217 -0
  13. package/dist/claudeAccounts.d.ts +38 -1
  14. package/dist/claudeAccounts.js +98 -4
  15. package/dist/claudeApi.js +1 -1
  16. package/dist/claudeSignIn.d.ts +19 -1
  17. package/dist/claudeSignIn.js +12 -2
  18. package/dist/commandsApi.d.ts +11 -1
  19. package/dist/commandsApi.js +24 -5
  20. package/dist/createPwCodeApi.d.ts +44 -5
  21. package/dist/createPwCodeApi.js +18 -2
  22. package/dist/directories.d.ts +161 -0
  23. package/dist/directories.js +301 -0
  24. package/dist/goal.d.ts +89 -0
  25. package/dist/goal.js +164 -0
  26. package/dist/imageFit.d.ts +23 -0
  27. package/dist/imageFit.js +27 -0
  28. package/dist/images.d.ts +28 -0
  29. package/dist/images.js +38 -6
  30. package/dist/index.d.ts +27 -12
  31. package/dist/index.js +26 -12
  32. package/dist/loadError.d.ts +8 -0
  33. package/dist/loadError.js +19 -0
  34. package/dist/locales/en/agentTranscript.js +73 -12
  35. package/dist/locales/en/agents.js +71 -9
  36. package/dist/locales/en.d.ts +124 -8
  37. package/dist/locales/es/agentTranscript.js +73 -12
  38. package/dist/locales/es/agents.js +71 -9
  39. package/dist/locales/ja/agentTranscript.js +76 -15
  40. package/dist/locales/ja/agents.js +45 -120
  41. package/dist/locales/ko/agentTranscript.js +73 -12
  42. package/dist/locales/ko/agents.js +71 -9
  43. package/dist/locales/zh/agentTranscript.js +71 -10
  44. package/dist/locales/zh/agents.js +71 -9
  45. package/dist/machine.d.ts +2 -0
  46. package/dist/modelPicker.d.ts +79 -0
  47. package/dist/modelPicker.js +107 -0
  48. package/dist/notices.js +47 -19
  49. package/dist/platformDefaults.d.ts +22 -0
  50. package/dist/platformDefaults.js +30 -0
  51. package/dist/preferences.d.ts +78 -0
  52. package/dist/preferences.js +128 -0
  53. package/dist/pullRequestList.d.ts +10 -2
  54. package/dist/pullRequestList.js +41 -22
  55. package/dist/query.d.ts +6 -2
  56. package/dist/query.js +85 -10
  57. package/dist/session.d.ts +5 -2
  58. package/dist/session.js +12 -8
  59. package/dist/sessionActions.d.ts +11 -1
  60. package/dist/sessionActions.js +14 -6
  61. package/dist/sessionEvents.d.ts +8 -3
  62. package/dist/sessionEvents.js +10 -5
  63. package/dist/sessionGroups.d.ts +3 -2
  64. package/dist/sessionGroups.js +4 -3
  65. package/dist/sessionList.d.ts +57 -9
  66. package/dist/sessionList.js +74 -12
  67. package/dist/sessionScreen.d.ts +193 -0
  68. package/dist/sessionScreen.js +213 -0
  69. package/dist/sessionsApi.d.ts +13 -3
  70. package/dist/sessionsApi.js +88 -29
  71. package/dist/settingsApi.d.ts +3 -1
  72. package/dist/startPage.d.ts +153 -0
  73. package/dist/startPage.js +174 -0
  74. package/dist/startSession.d.ts +41 -7
  75. package/dist/startSession.js +26 -4
  76. package/dist/transcript.js +48 -15
  77. package/dist/types.d.ts +11 -1
  78. package/dist/useComposer.d.ts +25 -1
  79. package/dist/useComposer.js +54 -3
  80. package/dist/useComposerImages.d.ts +5 -0
  81. package/dist/useComposerImages.js +24 -1
  82. package/dist/useComposerPastes.d.ts +70 -0
  83. package/dist/useComposerPastes.js +130 -0
  84. package/dist/useConversation.d.ts +10 -1
  85. package/dist/useConversation.js +32 -5
  86. package/dist/useSubagent.d.ts +49 -3
  87. package/dist/useSubagent.js +70 -7
  88. package/dist/useTranscript.d.ts +23 -3
  89. package/dist/useTranscript.js +76 -19
  90. package/dist/wording.js +2 -2
  91. package/dist/workingDirectories.d.ts +31 -0
  92. package/dist/workingDirectories.js +25 -1
  93. package/locales/en/agentTranscript.json +67 -11
  94. package/locales/en/agents.json +68 -8
  95. package/locales/es/agentTranscript.json +67 -11
  96. package/locales/es/agents.json +68 -8
  97. package/locales/ja/agentTranscript.json +70 -14
  98. package/locales/ja/agents.json +68 -8
  99. package/locales/ko/agentTranscript.json +67 -11
  100. package/locales/ko/agents.json +68 -8
  101. package/locales/zh/agentTranscript.json +65 -9
  102. package/locales/zh/agents.json +68 -8
  103. package/package.json +6 -3
@@ -0,0 +1,213 @@
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
+ return {
174
+ /** The session's state in a sentence, for a screen reader. */
175
+ statusText: composer.status ? sessionStatusText({
176
+ status: composer.status,
177
+ liveHost: detail?.liveHost,
178
+ approvals: composer.approvals
179
+ }, t) : "",
180
+ banner: banner && {
181
+ ...banner,
182
+ act
183
+ },
184
+ /** The transcript has yet to load for the first time. */
185
+ loading: read.isLoading && !detail,
186
+ /** Shown in place of a transcript that never loaded: why, or undefined
187
+ * for the host's own line. */
188
+ failed: loadFailure(read.error, !!detail, describeError),
189
+ retry,
190
+ /** Why the workspace's own settings, skills and hooks did not load. */
191
+ untrusted: detail?.workspaceUntrusted ? t("detail.untrusted") : null,
192
+ activity: sessionActivity({
193
+ composer,
194
+ transcript,
195
+ liveState,
196
+ claudeModel: claude.available && isClaudeModel(settings.model.value)
197
+ }, t, tTranscript),
198
+ goal: goalLabel(conversation.goal, t),
199
+ commands: paletteOptions(composer.palette, claude.available ? t("claude.choose") : void 0, t("detail.archiveCommand")),
200
+ showAuthor: conversation.all.some((m) => m.author),
201
+ /** A message may go without text while images go with it. */
202
+ allowEmpty: images.length > 0,
203
+ permission: {
204
+ mode: liveState?.permissionMode ?? detail?.permissionMode,
205
+ ceiling: info?.remoteMaxPermissionMode,
206
+ accepted: info?.permissionModes ?? void 0,
207
+ disabled: composer.composer.locked || settings.saving
208
+ },
209
+ claude,
210
+ canStart: !!info && canStartHere(info)
211
+ };
212
+ }
213
+ export { claudeAccountChip, claudeOnMachine, goalLabel, newSessionDraftKey, sessionActivity, sessionBanner, sessionDraftKey, sessionModel, sessionSettingsOptions, usePwCodeSessionScreen, useSessionPicker, useStaleFor, workingActivity };
@@ -1,7 +1,7 @@
1
1
  import type { ApprovalAnswerValue, MessagePaste } from '@parallelworks/ui/ai/headless';
2
2
  import { DateTime } from 'luxon';
3
3
  import type { KeyedMutator } from 'swr';
4
- import { type PwCodeApiError, type PwCodeClient, type PwCodeQuery, type PwCodeResult, type Schemas } from './apiClient.js';
4
+ import type { PwCodeApiError, PwCodeClient, PwCodeQuery, PwCodeResult, Schemas } from './apiClient.js';
5
5
  type Session = Schemas['AgentSession'];
6
6
  type SessionDetail = Schemas['AgentSessionDetail'];
7
7
  type SessionsResponse = Schemas['AgentSessionsResponse'];
@@ -37,7 +37,15 @@ export type PwCodePasteUpload = {
37
37
  } | {
38
38
  unsupported: true;
39
39
  };
40
- export declare function sessionsApi(client: PwCodeClient): {
40
+ export interface PwCodeSessionOptions {
41
+ /** Whether the host shows an image from its URL on the platform's API, signed
42
+ * in as the API client is, as a browser on the platform's origin does. Set,
43
+ * a session's transcript is read with each image's preview left to its ref,
44
+ * and the preview is loaded from there when it is drawn: previews are most
45
+ * of what a transcript with pictures weighs. */
46
+ previewsByRef?: boolean | undefined;
47
+ }
48
+ export declare function sessionsApi(client: PwCodeClient, { previewsByRef }?: PwCodeSessionOptions): {
41
49
  useSessions: () => PwCodeQuery<SessionsResponse>;
42
50
  useWaitingSessionCount: (enabled: boolean) => number;
43
51
  useSessionDetail: (machine: string, id: string, listed: Session | undefined) => {
@@ -48,7 +56,7 @@ export declare function sessionsApi(client: PwCodeClient): {
48
56
  fresh: boolean;
49
57
  };
50
58
  usePullRequests: (machine: string, id: string, urls: string[], onRead?: (read: PullRequest[]) => void) => PwCodeQuery<Schemas['AgentPullRequests']>;
51
- useSessionPullRequestStates: (machine: string, id: string, urls: string[]) => {
59
+ useSessionPullRequestStates: (machine: string, id: string, pullRequests: readonly string[] | null | undefined) => {
52
60
  url: string;
53
61
  state: string | undefined;
54
62
  }[] | undefined;
@@ -94,9 +102,11 @@ export declare function sessionsApi(client: PwCodeClient): {
94
102
  createSession: (machine: string, body: Schemas['CreateSessionBody']) => Promise<PwCodeResult<SessionDetail>>;
95
103
  sendMessage: (machine: string, id: string, body: Schemas['SendMessageBody']) => Promise<PwCodeResult<Schemas['AgentMessageAccepted']>>;
96
104
  steer: (machine: string, id: string, body: Schemas['AgentDirectionBody']) => Promise<PwCodeResult<Schemas['AgentDirectionDelivered']>>;
105
+ withdrawDirection: (machine: string, id: string, ids: string[]) => Promise<PwCodeResult<Schemas['AgentDirectionWithdrawn']>>;
97
106
  withdrawQueued: (machine: string, id: string, turnId: string) => Promise<PwCodeResult<undefined>>;
98
107
  messageSubagent: (machine: string, id: string, subId: string, body: Schemas['SendMessageBody']) => Promise<PwCodeResult<Schemas['AgentMessageAccepted']>>;
99
108
  steerSubagent: (machine: string, id: string, subId: string, body: Schemas['AgentDirectionBody']) => Promise<PwCodeResult<Schemas['AgentDirectionDelivered']>>;
109
+ withdrawSubagentDirection: (machine: string, id: string, subId: string, ids: string[]) => Promise<PwCodeResult<Schemas['AgentDirectionWithdrawn']>>;
100
110
  saveImage: (machine: string, id: string, body: Schemas['AgentImageBody']) => Promise<PwCodeResult<Schemas['AgentImageSaved']>>;
101
111
  answerApproval: (machine: string, sessionId: string, approvalId: string, answer: ApprovalAnswerValue) => Promise<unknown>;
102
112
  removeSessionDirectory: (machine: string, sessionId: string, path: string) => Promise<unknown>;
@@ -1,6 +1,8 @@
1
1
  import { bytesToBase64 } from "./base64.js";
2
+ import { PREVIEWS_BY_REF } from "./images.js";
2
3
  import { createQuery } from "./query.js";
3
4
  import { machinesById } from "./machine.js";
5
+ import { labeledPullRequests } from "./pullRequestList.js";
4
6
  import { isSession, triageSessions } from "./session.js";
5
7
  import { approvalAnswerBody } from "./transcript.js";
6
8
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -16,6 +18,11 @@ var SUBAGENTS_REFRESH_MS = 1e3;
16
18
  function cachedCopyCurrent(listed, cached) {
17
19
  return !!listed && listed.status !== "running" && listed.status === cached.status && listed.messages === cached.messages && listed.updatedAt === cached.updatedAt;
18
20
  }
21
+ var SESSION_DETAIL_READ = {
22
+ revalidateIfStale: false,
23
+ revalidateOnFocus: false,
24
+ revalidateOnReconnect: false
25
+ };
19
26
  /** Whether this visit's own read has answered: a copy cached by an earlier
20
27
  * visit has not, until the read started on mounting lands. */
21
28
  function useReadThisVisit(data, isValidating, mutate) {
@@ -140,7 +147,7 @@ function sessionPath(s) {
140
147
  id: s.id
141
148
  } } };
142
149
  }
143
- function sessionsApi(client) {
150
+ function sessionsApi(client, { previewsByRef = false } = {}) {
144
151
  const useQuery = createQuery(client);
145
152
  /** Every session on every machine the reader can reach, with each machine's reachability. */
146
153
  function useSessions() {
@@ -157,14 +164,13 @@ function sessionsApi(client) {
157
164
  * A cached copy the listed row says the session has moved past stays hidden
158
165
  * until that fetch answers, so the newer turns don't land under the reader. */
159
166
  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
- });
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);
168
174
  const [current] = useState(() => data !== void 0 && cachedCopyCurrent(listed, data));
169
175
  const answered = useReadThisVisit(data, isValidating, mutate);
170
176
  const hidden = !current && !answered;
@@ -196,10 +202,12 @@ function sessionsApi(client) {
196
202
  }, [shown, mutate]);
197
203
  return query;
198
204
  }
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) {
205
+ /** The states of the session's `pullRequests` that are pull or merge requests
206
+ * (`labeledPullRequests`), as the sessions list has them so every view of
207
+ * the session agrees, or its own read where the list has none. Each read
208
+ * goes into the list at once. */
209
+ function useSessionPullRequestStates(machine, id, pullRequests) {
210
+ const urls = labeledPullRequests(pullRequests).map(({ url }) => url);
203
211
  const { data: list, mutate } = useSessions();
204
212
  const { data } = usePullRequests(machine, id, urls, (read) => {
205
213
  if (patchPullRequestStates(list, machine, read) !== list) mutate((current) => patchPullRequestStates(current, machine, read), { revalidate: false });
@@ -302,7 +310,8 @@ function sessionsApi(client) {
302
310
  return error ? { refusal: error } : { left: data };
303
311
  }
304
312
  /** 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. */
313
+ * which happens at once so the row does not linger until the next poll. A
314
+ * pin, a group and a restore show before the machine answers. */
306
315
  function useSessionMutations() {
307
316
  const { mutate } = useSessions();
308
317
  const patched = useCallback(async (s, request, change) => {
@@ -314,6 +323,30 @@ function sessionsApi(client) {
314
323
  }, { revalidate: true });
315
324
  return null;
316
325
  }, [mutate]);
326
+ const patchedAtOnce = useCallback(async (s, request, change) => {
327
+ const refused = {};
328
+ try {
329
+ await mutate(async () => {
330
+ const { error } = await request;
331
+ if (error) {
332
+ refused.error = error;
333
+ throw error;
334
+ }
335
+ }, {
336
+ optimisticData: (_read, shown) => shown && {
337
+ ...shown,
338
+ sessions: (shown.sessions ?? []).map((x) => sameSession(x, s) ? change(x) : x)
339
+ },
340
+ populateCache: false,
341
+ rollbackOnError: true,
342
+ revalidate: true
343
+ });
344
+ } catch (thrown) {
345
+ if ("error" in refused) return refused.error;
346
+ throw thrown;
347
+ }
348
+ return null;
349
+ }, [mutate]);
317
350
  return {
318
351
  deleteSession: useCallback(async (s, removeWorktree) => {
319
352
  const { error } = await client.DELETE("/api/code/machines/{machine}/sessions/{id}", removeWorktree ? { params: {
@@ -355,18 +388,18 @@ function sessionsApi(client) {
355
388
  deferred
356
389
  };
357
390
  }, [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) => ({
391
+ restoreSession: useCallback((s) => patchedAtOnce(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/archive", sessionPath(s)), ({ archivedAt: _, ...x }) => x), [patchedAtOnce]),
392
+ pinSession: useCallback((s, pinned) => pinned ? patchedAtOnce(s, client.POST("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), (x) => ({
360
393
  ...x,
361
394
  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", {
395
+ })) : patchedAtOnce(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), ({ pinnedAt: _, ...x }) => x), [patchedAtOnce]),
396
+ groupSession: useCallback((s, group) => group ? patchedAtOnce(s, client.PUT("/api/code/machines/{machine}/sessions/{id}/group", {
364
397
  ...sessionPath(s),
365
398
  body: { group }
366
399
  }), (x) => ({
367
400
  ...x,
368
401
  group
369
- })) : patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/group", sessionPath(s)), ({ group: _, ...x }) => x), [patched]),
402
+ })) : patchedAtOnce(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/group", sessionPath(s)), ({ group: _, ...x }) => x), [patchedAtOnce]),
370
403
  stopSession: useCallback((s) => patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/stop", sessionPath(s)), (x) => x), [patched]),
371
404
  forkSession: useCallback(async (s) => {
372
405
  const { data, error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/fork", sessionPath(s));
@@ -403,6 +436,16 @@ function sessionsApi(client) {
403
436
  body
404
437
  });
405
438
  }
439
+ /** Takes back steered text the model has not read, by the ids steering answered with. */
440
+ function withdrawDirection(machine, id, ids) {
441
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/direction/withdraw", {
442
+ params: { path: {
443
+ machine,
444
+ id
445
+ } },
446
+ body: { ids }
447
+ });
448
+ }
406
449
  /** Takes back a message still queued behind the running turn. */
407
450
  function withdrawQueued(machine, id, turnId) {
408
451
  return client.DELETE("/api/code/machines/{machine}/sessions/{id}/queued/{turnId}", { params: { path: {
@@ -431,6 +474,16 @@ function sessionsApi(client) {
431
474
  body
432
475
  });
433
476
  }
477
+ function withdrawSubagentDirection(machine, id, subId, ids) {
478
+ return client.POST("/api/code/machines/{machine}/sessions/{id}/subagents/{subId}/direction/withdraw", {
479
+ params: { path: {
480
+ machine,
481
+ id,
482
+ subId
483
+ } },
484
+ body: { ids }
485
+ });
486
+ }
434
487
  /** Saves an image, base64-encoded, with the session; a message names it by
435
488
  * the path this resolves to. */
436
489
  function saveImage(machine, id, body) {
@@ -442,17 +495,21 @@ function sessionsApi(client) {
442
495
  body
443
496
  });
444
497
  }
445
- /** Resolves to the daemon's refusal, or null once the answer is accepted. */
498
+ /** Resolves to the daemon's refusal, or what was thrown when it did not answer, or null once the answer is accepted. */
446
499
  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;
500
+ try {
501
+ const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/approvals/{approvalId}", {
502
+ params: { path: {
503
+ machine,
504
+ id: sessionId,
505
+ approvalId
506
+ } },
507
+ body: approvalAnswerBody(answer)
508
+ });
509
+ return error ?? null;
510
+ } catch (thrown) {
511
+ return thrown;
512
+ }
456
513
  }
457
514
  /** Closes a directory added for this session only; resolves to the daemon's refusal, or null once it is closed. */
458
515
  async function removeSessionDirectory(machine, sessionId, path) {
@@ -499,9 +556,11 @@ function sessionsApi(client) {
499
556
  createSession,
500
557
  sendMessage,
501
558
  steer,
559
+ withdrawDirection,
502
560
  withdrawQueued,
503
561
  messageSubagent,
504
562
  steerSubagent,
563
+ withdrawSubagentDirection,
505
564
  saveImage,
506
565
  answerApproval,
507
566
  removeSessionDirectory,
@@ -8,7 +8,9 @@ export interface PwCodeSessionSettingsOptions {
8
8
  effort?: string | undefined;
9
9
  allocation: string | undefined;
10
10
  claudeAccount?: string | undefined;
11
- /** Billed by a switch to a model the platform bills, while the session has had no allocation of its own. */
11
+ /** Billed by a switch to a model the platform bills, while the session has
12
+ * had no allocation of its own: the host's selected one, such as its
13
+ * chat's, or `usePlatformDefaults`'s. */
12
14
  nativeAllocation?: string | null | undefined;
13
15
  locked: boolean;
14
16
  live: boolean;
@@ -0,0 +1,153 @@
1
+ import type { ApprovalAnswerValue, ApprovalPart } from '@parallelworks/ui/ai/headless';
2
+ import { type PwCodeHandoffChat } from './chatHandoff.js';
3
+ import { type PwCodePalette, type PwCodeSlashCommand } from './command.js';
4
+ import type { PwCodeApi } from './createPwCodeApi.js';
5
+ import { type PwCodeMachine } from './machine.js';
6
+ import type { PwCodeTranslator } from './messages.js';
7
+ import { runsClaude } from './models.js';
8
+ import { type PwCodeSession } from './session.js';
9
+ import type { PwCodeStartLocation, PwCodeStartMachine } from './startSession.js';
10
+ import { type TranscriptWords } from './transcript.js';
11
+ import type { PwCodeApprovalRequest } from './types.js';
12
+ import { sessionStateText } from './wording.js';
13
+ type Translate = PwCodeTranslator<'agents'>;
14
+ /** As many sessions as a new chat offers starters, so the page fits. */
15
+ export declare const START_SHORTLIST = 4;
16
+ /** The sessions a start page offers to pick back up: the live ones, then the
17
+ * idle ones, each newest first as `triageSessions` orders them. */
18
+ export declare function startShortlist<S>(triage: {
19
+ active: readonly S[];
20
+ idle: readonly S[];
21
+ }, size?: number): S[];
22
+ /** A shortlisted session that is live shows a mark named by its state, which
23
+ * nothing else on its row spells out; one at rest shows none. */
24
+ export declare function shortlistMark(session: Parameters<typeof sessionStateText>[0], machine: Pick<PwCodeMachine, 'status'> | undefined, t: Translate): {
25
+ label: string;
26
+ } | null;
27
+ /** When a session began waiting on the reader: its first pending question,
28
+ * else its last change. */
29
+ export declare function waitingSince(s: Pick<PwCodeSession, 'updatedAt'> & {
30
+ approvals?: readonly Pick<PwCodeApprovalRequest, 'createdAt'>[] | null;
31
+ }): string | undefined;
32
+ /** What a session waiting on the reader asks, answerable where it is listed,
33
+ * or, when the listing carries none of its questions, `inSession`: a line
34
+ * sending the reader into the session to answer. */
35
+ export declare function waitingQuestions(s: {
36
+ approvals?: readonly PwCodeApprovalRequest[] | null;
37
+ }, words: Pick<TranscriptWords, 'allowDirectory'>, t: Translate): {
38
+ questions: ApprovalPart[];
39
+ inSession: string | null;
40
+ };
41
+ /** A start page around its composer, from the listing `api.useSessions` reads. */
42
+ export interface PwCodeStartScreen {
43
+ /** The listing has yet to answer. */
44
+ loading: boolean;
45
+ /** Shown in place of the page while the listing never loaded, since an
46
+ * empty one would read as having no sessions: why, or undefined for the
47
+ * host's own line. */
48
+ failed: {
49
+ message: string | undefined;
50
+ } | null;
51
+ /** Otherwise no machine lets a session start here, and the host says so.
52
+ * A machine not answering keeps it: such a machine reports starting off,
53
+ * so the menu says why rather than sending the reader to that setting. */
54
+ showComposer: boolean;
55
+ /** Nothing is listed, so the host explains how sessions appear (`howSessionsAppear`). */
56
+ explainEmpty: boolean;
57
+ /** Answers a listed session's question, then reads the listing again;
58
+ * resolves to the refusal in `describeError`'s words, or null. */
59
+ answer: (session: Pick<PwCodeSession, 'machineId' | 'id'>, approvalId: string, value: ApprovalAnswerValue) => Promise<string | null>;
60
+ }
61
+ export declare function useStartScreen(api: Pick<PwCodeApi, 'useSessions' | 'answerApproval'>, { location, describeError, }: {
62
+ location: {
63
+ startable: readonly unknown[];
64
+ down: readonly unknown[];
65
+ };
66
+ /** Words a refusal or failure for the reader. */
67
+ describeError: (error: unknown) => string;
68
+ }): PwCodeStartScreen;
69
+ /** What a start page's address asks for: a session to open, named by the
70
+ * link pw code's /rc prints, or a chat to hand to a new session. */
71
+ export interface PwCodeStartSearch {
72
+ session?: string | undefined;
73
+ fromChat?: string | undefined;
74
+ }
75
+ /** The start page's parameters from its parsed query; any that is not a
76
+ * single string is left out. */
77
+ export declare function startSearch(search: Record<string, unknown>): PwCodeStartSearch;
78
+ /** How a link to a session stands: still being looked for, or missing from
79
+ * the listing; null without one. */
80
+ export type PwCodeSessionLinkState = 'resolving' | 'missing' | null;
81
+ /** Follows a link that names only a session, since the machine listed with
82
+ * it is not known where the link was printed: once the listing names the
83
+ * session, `open` takes it to the session. */
84
+ export declare function useSessionLink<S extends Pick<PwCodeSession, 'id'>>(session: string | undefined, listing: {
85
+ sessions: readonly S[];
86
+ loading: boolean;
87
+ }, open: (found: S) => void): PwCodeSessionLinkState;
88
+ /** The card over the composer while a link to a session is followed: news
89
+ * while it is looked for, a warning once the listing lacks it. Null without
90
+ * a link. */
91
+ export declare function sessionLinkNotice(state: PwCodeSessionLinkState, session: string | undefined, t: Translate): {
92
+ text: string;
93
+ tone: 'neutral' | 'warning';
94
+ } | null;
95
+ /** The commands a new session's composer offers: the directory's palette,
96
+ * led by the Claude Code account choice on a machine where Claude Code
97
+ * runs. Archiving needs a session, so it is not offered. */
98
+ export declare function startCommands(palette: PwCodePalette | null, machine: Parameters<typeof runsClaude>[0], t: Translate): PwCodeSlashCommand[];
99
+ /** A machine as the start page's menu offers it. */
100
+ export interface PwCodeMachineChoice {
101
+ id: string;
102
+ label: string;
103
+ /** A computer or a resource, or for one not answering, why. */
104
+ description: string | undefined;
105
+ checked: boolean;
106
+ disabled: boolean;
107
+ }
108
+ /** The machines a session can start on, then the ones not answering, each
109
+ * saying why, so a missing machine can be traced. With both, the ones not
110
+ * answering go under `downLabel`; with one kind only, it stands alone. */
111
+ export interface PwCodeMachineMenu {
112
+ startable: PwCodeMachineChoice[];
113
+ down: PwCodeMachineChoice[];
114
+ downLabel: string | undefined;
115
+ /** Picks a machine; the one picked already stays as it is. */
116
+ pick: (id: string) => void;
117
+ }
118
+ export declare function machineMenu<M extends PwCodeStartMachine>(location: Pick<PwCodeStartLocation<M>, 'startable' | 'down' | 'machine' | 'pickMachine'>, t: Translate): PwCodeMachineMenu;
119
+ /** The chip naming the machine a session starts on, which opens the
120
+ * `machineMenu`: the machine's name after a dot in the `success` tone, since
121
+ * only a machine that answers can be chosen, or, until one is, a call to
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): {
125
+ text: string;
126
+ label: string;
127
+ dot: 'success' | null;
128
+ };
129
+ /** A chat handed to a new session, while it loads or once it failed to. */
130
+ export interface PwCodeStartHandoff {
131
+ conversation: PwCodeHandoffChat | undefined;
132
+ error: unknown;
133
+ }
134
+ /** How a start carries a chat handed to it: it waits until the chat has
135
+ * arrived, since starting sooner would quietly leave it behind, then sends
136
+ * the chat after what was typed. A chat that failed to load holds nothing
137
+ * back. */
138
+ export declare function chatHandoffStart(handoff: PwCodeStartHandoff | undefined, t: Translate,
139
+ /** Words a failure for the reader. */
140
+ describeError: (error: unknown) => string): {
141
+ waiting: boolean;
142
+ firstPrompt: ((typed: string) => string) | undefined;
143
+ /** The composer's placeholder; once the chat has arrived, it asks what to do with it. */
144
+ placeholder: string;
145
+ /** The card above the composer naming the chat, or saying it is loading
146
+ * or why it failed to, which is a warning; null without a chat. */
147
+ notice: {
148
+ text: string;
149
+ failed: boolean;
150
+ tone: 'neutral' | 'warning';
151
+ } | null;
152
+ };
153
+ export {};