@parallelworks/code 0.2.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 (126) hide show
  1. package/README.md +602 -84
  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 +8 -0
  7. package/dist/ago.js +26 -0
  8. package/dist/allocations.d.ts +41 -0
  9. package/dist/allocations.js +76 -0
  10. package/dist/api.d.ts +1213 -66
  11. package/dist/base64.d.ts +3 -0
  12. package/dist/base64.js +15 -0
  13. package/dist/chatHandoff.d.ts +12 -0
  14. package/dist/chatHandoff.js +27 -0
  15. package/dist/chatStrings.d.ts +188 -0
  16. package/dist/chatStrings.js +217 -0
  17. package/dist/claudeAccounts.d.ts +149 -0
  18. package/dist/claudeAccounts.js +328 -0
  19. package/dist/claudeApi.js +1 -1
  20. package/dist/claudeSignIn.d.ts +80 -0
  21. package/dist/claudeSignIn.js +249 -0
  22. package/dist/commandsApi.d.ts +11 -1
  23. package/dist/commandsApi.js +24 -5
  24. package/dist/contextRow.d.ts +25 -0
  25. package/dist/contextRow.js +16 -0
  26. package/dist/createPwCodeApi.d.ts +52 -5
  27. package/dist/createPwCodeApi.js +20 -2
  28. package/dist/directories.d.ts +161 -0
  29. package/dist/directories.js +301 -0
  30. package/dist/goal.d.ts +89 -0
  31. package/dist/goal.js +164 -0
  32. package/dist/howSessionsAppear.d.ts +12 -0
  33. package/dist/howSessionsAppear.js +24 -0
  34. package/dist/imageFit.d.ts +23 -0
  35. package/dist/imageFit.js +27 -0
  36. package/dist/images.d.ts +28 -0
  37. package/dist/images.js +38 -6
  38. package/dist/index.d.ts +41 -3
  39. package/dist/index.js +40 -4
  40. package/dist/loadError.d.ts +8 -0
  41. package/dist/loadError.js +19 -0
  42. package/dist/locales/en/agentTranscript.js +75 -22
  43. package/dist/locales/en/agents.js +76 -14
  44. package/dist/locales/en.d.ts +129 -21
  45. package/dist/locales/es/agentTranscript.js +75 -22
  46. package/dist/locales/es/agents.js +76 -14
  47. package/dist/locales/ja/agentTranscript.js +78 -25
  48. package/dist/locales/ja/agents.js +49 -124
  49. package/dist/locales/ko/agentTranscript.js +75 -22
  50. package/dist/locales/ko/agents.js +76 -14
  51. package/dist/locales/zh/agentTranscript.js +73 -20
  52. package/dist/locales/zh/agents.js +76 -14
  53. package/dist/machine.d.ts +4 -0
  54. package/dist/modelPicker.d.ts +79 -0
  55. package/dist/modelPicker.js +107 -0
  56. package/dist/models.d.ts +47 -0
  57. package/dist/models.js +49 -0
  58. package/dist/notices.d.ts +2 -1
  59. package/dist/notices.js +75 -21
  60. package/dist/platformDefaults.d.ts +22 -0
  61. package/dist/platformDefaults.js +30 -0
  62. package/dist/preferences.d.ts +78 -0
  63. package/dist/preferences.js +128 -0
  64. package/dist/pullRequestList.d.ts +60 -0
  65. package/dist/pullRequestList.js +125 -0
  66. package/dist/query.d.ts +6 -2
  67. package/dist/query.js +85 -10
  68. package/dist/session.d.ts +10 -2
  69. package/dist/session.js +12 -8
  70. package/dist/sessionActions.d.ts +115 -0
  71. package/dist/sessionActions.js +186 -0
  72. package/dist/sessionEvents.d.ts +8 -3
  73. package/dist/sessionEvents.js +10 -5
  74. package/dist/sessionGroups.d.ts +50 -0
  75. package/dist/sessionGroups.js +73 -0
  76. package/dist/sessionHeader.d.ts +14 -0
  77. package/dist/sessionHeader.js +16 -0
  78. package/dist/sessionList.d.ts +182 -0
  79. package/dist/sessionList.js +333 -0
  80. package/dist/sessionScreen.d.ts +193 -0
  81. package/dist/sessionScreen.js +213 -0
  82. package/dist/sessionsApi.d.ts +13 -3
  83. package/dist/sessionsApi.js +90 -33
  84. package/dist/settingsApi.d.ts +38 -0
  85. package/dist/settingsApi.js +151 -0
  86. package/dist/startPage.d.ts +153 -0
  87. package/dist/startPage.js +174 -0
  88. package/dist/startSession.d.ts +172 -0
  89. package/dist/startSession.js +256 -0
  90. package/dist/terminalHandoffPanel.d.ts +30 -0
  91. package/dist/terminalHandoffPanel.js +33 -0
  92. package/dist/transcript.d.ts +2 -0
  93. package/dist/transcript.js +62 -26
  94. package/dist/types.d.ts +11 -1
  95. package/dist/usageLimit.d.ts +8 -0
  96. package/dist/usageLimit.js +13 -0
  97. package/dist/useAwayRecap.d.ts +30 -0
  98. package/dist/useAwayRecap.js +75 -0
  99. package/dist/useComposer.d.ts +145 -0
  100. package/dist/useComposer.js +295 -0
  101. package/dist/useComposerImages.d.ts +71 -0
  102. package/dist/useComposerImages.js +218 -0
  103. package/dist/useComposerPastes.d.ts +70 -0
  104. package/dist/useComposerPastes.js +130 -0
  105. package/dist/useConversation.d.ts +199 -0
  106. package/dist/useConversation.js +314 -0
  107. package/dist/useSubagent.d.ts +104 -0
  108. package/dist/useSubagent.js +212 -0
  109. package/dist/useTranscript.d.ts +23 -3
  110. package/dist/useTranscript.js +76 -19
  111. package/dist/wording.js +2 -2
  112. package/dist/workingDirectories.d.ts +63 -0
  113. package/dist/workingDirectories.js +95 -0
  114. package/dist/worktreeChoice.d.ts +31 -0
  115. package/dist/worktreeChoice.js +38 -0
  116. package/locales/en/agentTranscript.json +69 -21
  117. package/locales/en/agents.json +73 -13
  118. package/locales/es/agentTranscript.json +69 -21
  119. package/locales/es/agents.json +73 -13
  120. package/locales/ja/agentTranscript.json +72 -24
  121. package/locales/ja/agents.json +73 -13
  122. package/locales/ko/agentTranscript.json +69 -21
  123. package/locales/ko/agents.json +73 -13
  124. package/locales/zh/agentTranscript.json +67 -19
  125. package/locales/zh/agents.json +73 -13
  126. 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,5 +1,8 @@
1
+ import { bytesToBase64 } from "./base64.js";
2
+ import { PREVIEWS_BY_REF } from "./images.js";
1
3
  import { createQuery } from "./query.js";
2
4
  import { machinesById } from "./machine.js";
5
+ import { labeledPullRequests } from "./pullRequestList.js";
3
6
  import { isSession, triageSessions } from "./session.js";
4
7
  import { approvalAnswerBody } from "./transcript.js";
5
8
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -15,6 +18,11 @@ var SUBAGENTS_REFRESH_MS = 1e3;
15
18
  function cachedCopyCurrent(listed, cached) {
16
19
  return !!listed && listed.status !== "running" && listed.status === cached.status && listed.messages === cached.messages && listed.updatedAt === cached.updatedAt;
17
20
  }
21
+ var SESSION_DETAIL_READ = {
22
+ revalidateIfStale: false,
23
+ revalidateOnFocus: false,
24
+ revalidateOnReconnect: false
25
+ };
18
26
  /** Whether this visit's own read has answered: a copy cached by an earlier
19
27
  * visit has not, until the read started on mounting lands. */
20
28
  function useReadThisVisit(data, isValidating, mutate) {
@@ -128,10 +136,7 @@ function pasteRefs(pastes) {
128
136
  })) } : {};
129
137
  }
130
138
  function utf8ToBase64(text) {
131
- const bytes = new TextEncoder().encode(text);
132
- let binary = "";
133
- for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
134
- return btoa(binary);
139
+ return bytesToBase64(new TextEncoder().encode(text));
135
140
  }
136
141
  function sameSession(a, b) {
137
142
  return isSession(a, b.machineId, b.id);
@@ -142,7 +147,7 @@ function sessionPath(s) {
142
147
  id: s.id
143
148
  } } };
144
149
  }
145
- function sessionsApi(client) {
150
+ function sessionsApi(client, { previewsByRef = false } = {}) {
146
151
  const useQuery = createQuery(client);
147
152
  /** Every session on every machine the reader can reach, with each machine's reachability. */
148
153
  function useSessions() {
@@ -159,14 +164,13 @@ function sessionsApi(client) {
159
164
  * A cached copy the listed row says the session has moved past stays hidden
160
165
  * until that fetch answers, so the newer turns don't land under the reader. */
161
166
  function useSessionDetail(machine, id, listed) {
162
- const { data, error, isLoading, isValidating, mutate } = useQuery("/api/code/machines/{machine}/sessions/{id}", { params: { path: {
163
- machine,
164
- id
165
- } } }, {
166
- revalidateIfStale: false,
167
- revalidateOnFocus: false,
168
- revalidateOnReconnect: false
169
- });
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);
170
174
  const [current] = useState(() => data !== void 0 && cachedCopyCurrent(listed, data));
171
175
  const answered = useReadThisVisit(data, isValidating, mutate);
172
176
  const hidden = !current && !answered;
@@ -198,10 +202,12 @@ function sessionsApi(client) {
198
202
  }, [shown, mutate]);
199
203
  return query;
200
204
  }
201
- /** A session's pull request states, as the sessions list has them so every
202
- * view of the session agrees, or its own read where the list has none. Each
203
- * read goes into the list at once. */
204
- 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);
205
211
  const { data: list, mutate } = useSessions();
206
212
  const { data } = usePullRequests(machine, id, urls, (read) => {
207
213
  if (patchPullRequestStates(list, machine, read) !== list) mutate((current) => patchPullRequestStates(current, machine, read), { revalidate: false });
@@ -304,7 +310,8 @@ function sessionsApi(client) {
304
310
  return error ? { refusal: error } : { left: data };
305
311
  }
306
312
  /** Each resolves to the daemon's refusal, or null once the list is patched,
307
- * 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. */
308
315
  function useSessionMutations() {
309
316
  const { mutate } = useSessions();
310
317
  const patched = useCallback(async (s, request, change) => {
@@ -316,6 +323,30 @@ function sessionsApi(client) {
316
323
  }, { revalidate: true });
317
324
  return null;
318
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]);
319
350
  return {
320
351
  deleteSession: useCallback(async (s, removeWorktree) => {
321
352
  const { error } = await client.DELETE("/api/code/machines/{machine}/sessions/{id}", removeWorktree ? { params: {
@@ -357,18 +388,18 @@ function sessionsApi(client) {
357
388
  deferred
358
389
  };
359
390
  }, [patched]),
360
- restoreSession: useCallback((s) => patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/archive", sessionPath(s)), ({ archivedAt: _, ...x }) => x), [patched]),
361
- 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) => ({
362
393
  ...x,
363
394
  pinnedAt: DateTime.now().toISO()
364
- })) : patched(s, client.DELETE("/api/code/machines/{machine}/sessions/{id}/pin", sessionPath(s)), ({ pinnedAt: _, ...x }) => x), [patched]),
365
- 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", {
366
397
  ...sessionPath(s),
367
398
  body: { group }
368
399
  }), (x) => ({
369
400
  ...x,
370
401
  group
371
- })) : 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]),
372
403
  stopSession: useCallback((s) => patched(s, client.POST("/api/code/machines/{machine}/sessions/{id}/stop", sessionPath(s)), (x) => x), [patched]),
373
404
  forkSession: useCallback(async (s) => {
374
405
  const { data, error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/fork", sessionPath(s));
@@ -405,6 +436,16 @@ function sessionsApi(client) {
405
436
  body
406
437
  });
407
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
+ }
408
449
  /** Takes back a message still queued behind the running turn. */
409
450
  function withdrawQueued(machine, id, turnId) {
410
451
  return client.DELETE("/api/code/machines/{machine}/sessions/{id}/queued/{turnId}", { params: { path: {
@@ -433,6 +474,16 @@ function sessionsApi(client) {
433
474
  body
434
475
  });
435
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
+ }
436
487
  /** Saves an image, base64-encoded, with the session; a message names it by
437
488
  * the path this resolves to. */
438
489
  function saveImage(machine, id, body) {
@@ -444,17 +495,21 @@ function sessionsApi(client) {
444
495
  body
445
496
  });
446
497
  }
447
- /** 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. */
448
499
  async function answerApproval(machine, sessionId, approvalId, answer) {
449
- const { error } = await client.POST("/api/code/machines/{machine}/sessions/{id}/approvals/{approvalId}", {
450
- params: { path: {
451
- machine,
452
- id: sessionId,
453
- approvalId
454
- } },
455
- body: approvalAnswerBody(answer)
456
- });
457
- 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
+ }
458
513
  }
459
514
  /** Closes a directory added for this session only; resolves to the daemon's refusal, or null once it is closed. */
460
515
  async function removeSessionDirectory(machine, sessionId, path) {
@@ -501,9 +556,11 @@ function sessionsApi(client) {
501
556
  createSession,
502
557
  sendMessage,
503
558
  steer,
559
+ withdrawDirection,
504
560
  withdrawQueued,
505
561
  messageSubagent,
506
562
  steerSubagent,
563
+ withdrawSubagentDirection,
507
564
  saveImage,
508
565
  answerApproval,
509
566
  removeSessionDirectory,
@@ -0,0 +1,38 @@
1
+ import type { BoundSetting, PermissionMode } from '@parallelworks/ui/ai/headless';
2
+ import type { PwCodeClient, PwCodeResult, Schemas } from './apiClient.js';
3
+ type SettingsBody = Schemas['AgentSessionSettingsBody'];
4
+ export interface PwCodeSessionSettingsOptions {
5
+ machine: string;
6
+ sessionId: string;
7
+ model: string | undefined;
8
+ effort?: string | undefined;
9
+ allocation: string | undefined;
10
+ claudeAccount?: string | undefined;
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. */
14
+ nativeAllocation?: string | null | undefined;
15
+ locked: boolean;
16
+ live: boolean;
17
+ onPatched: () => void;
18
+ onError: (error: unknown) => void;
19
+ /** Called as a mode is picked, before the machine answers. */
20
+ onModePicked?: ((mode: PermissionMode) => void) | undefined;
21
+ /** Called as an effort level is picked, before the machine answers. */
22
+ onEffortPicked?: ((effort: string) => void) | undefined;
23
+ /** Called once the machine takes an account; it refuses one it cannot use, such as one signed out. */
24
+ onAccountSaved?: ((account: string) => void) | undefined;
25
+ }
26
+ export interface PwCodeSessionSettings {
27
+ model: BoundSetting;
28
+ effort: BoundSetting;
29
+ allocation: BoundSetting;
30
+ account: BoundSetting;
31
+ setMode: (mode: PermissionMode) => void;
32
+ saving: boolean;
33
+ }
34
+ export declare function settingsApi(client: PwCodeClient): {
35
+ updateSessionSettings: (machine: string, id: string, body: SettingsBody) => Promise<PwCodeResult<Schemas['SessionState']>>;
36
+ useSessionSettings: ({ machine, sessionId, model, effort, allocation, claudeAccount, nativeAllocation, locked, live, onPatched, onError, onModePicked, onEffortPicked, onAccountSaved, }: PwCodeSessionSettingsOptions) => PwCodeSessionSettings;
37
+ };
38
+ export {};
@@ -0,0 +1,151 @@
1
+ import { useCallback, useRef, useState } from "react";
2
+ // src/settingsApi.ts
3
+ var isClaude = (model) => !!model?.startsWith("claude-code/");
4
+ function settingsApi(client) {
5
+ /** Changes what a live session runs as, answering with its new state. */
6
+ function updateSessionSettings(machine, id, body) {
7
+ return client.PATCH("/api/code/machines/{machine}/sessions/{id}/settings", {
8
+ params: { path: {
9
+ machine,
10
+ id
11
+ } },
12
+ body
13
+ });
14
+ }
15
+ /** The session's own model, effort, allocation, account and permission
16
+ * mode, for pickers that show and change them. A pick shows at once and
17
+ * goes back if the machine refuses it. A session that cannot take a change
18
+ * (not live yet, or unreachable) shows its pickers disabled rather than
19
+ * dropping a pick. */
20
+ function useSessionSettings({ machine, sessionId, model, effort, allocation, claudeAccount, nativeAllocation, locked, live, onPatched, onError, onModePicked, onEffortPicked, onAccountSaved }) {
21
+ const [inFlight, setInFlight] = useState(0);
22
+ const saving = inFlight > 0;
23
+ const platformAllocation = useRef(allocation || "");
24
+ if (!isClaude(model) && allocation) platformAllocation.current = allocation;
25
+ const [picked, setPicked] = useState(null);
26
+ const reported = [
27
+ model,
28
+ effort,
29
+ allocation,
30
+ claudeAccount
31
+ ].join("|");
32
+ const pick = picked?.over === reported ? picked : null;
33
+ const pickNext = (change) => setPicked((previous) => ({
34
+ ...previous?.over === reported ? previous : {},
35
+ ...change,
36
+ over: reported
37
+ }));
38
+ const patch = useCallback(async (body) => {
39
+ setInFlight((count) => count + 1);
40
+ let error;
41
+ try {
42
+ error = (await updateSessionSettings(machine, sessionId, body)).error;
43
+ } catch (thrown) {
44
+ error = thrown;
45
+ }
46
+ setInFlight((count) => count - 1);
47
+ if (error) {
48
+ setPicked(null);
49
+ onError(error);
50
+ return false;
51
+ }
52
+ onPatched();
53
+ return true;
54
+ }, [
55
+ machine,
56
+ sessionId,
57
+ onError,
58
+ onPatched
59
+ ]);
60
+ const shownModel = pick?.model ?? model;
61
+ const shownAllocation = pick?.allocation ?? allocation;
62
+ const disabled = !live || locked || saving;
63
+ const modelSetting = {
64
+ value: shownModel,
65
+ disabled,
66
+ onChange: (next) => {
67
+ const nextAllocation = isClaude(next) ? "" : shownAllocation || platformAllocation.current || nativeAllocation || "";
68
+ pickNext({
69
+ model: next,
70
+ allocation: nextAllocation
71
+ });
72
+ patch({
73
+ model: next,
74
+ ...nextAllocation || isClaude(next) ? { allocation: nextAllocation } : {}
75
+ });
76
+ }
77
+ };
78
+ const allocationSetting = {
79
+ value: shownAllocation,
80
+ disabled,
81
+ onChange: (next) => {
82
+ if (!shownModel) return;
83
+ pickNext({
84
+ model: shownModel,
85
+ allocation: next
86
+ });
87
+ patch({
88
+ model: shownModel,
89
+ allocation: next
90
+ });
91
+ }
92
+ };
93
+ const effortQueue = useRef({
94
+ sending: false,
95
+ next: null
96
+ });
97
+ const [sendingEffort, setSendingEffort] = useState(null);
98
+ const sendEffort = async (level) => {
99
+ const queue = effortQueue.current;
100
+ queue.next = level;
101
+ if (queue.sending) return;
102
+ queue.sending = true;
103
+ try {
104
+ while (queue.next !== null) {
105
+ const sending = queue.next;
106
+ queue.next = null;
107
+ await patch({ effort: sending });
108
+ }
109
+ } finally {
110
+ queue.sending = false;
111
+ setSendingEffort(null);
112
+ }
113
+ };
114
+ const effortSetting = {
115
+ value: sendingEffort ?? pick?.effort ?? effort ?? "",
116
+ disabled: !live || locked,
117
+ onChange: (next) => {
118
+ pickNext({ effort: next });
119
+ setSendingEffort(next);
120
+ onEffortPicked?.(next);
121
+ sendEffort(next);
122
+ }
123
+ };
124
+ const setMode = useCallback((mode) => {
125
+ onModePicked?.(mode);
126
+ patch({ permissionMode: mode });
127
+ }, [patch, onModePicked]);
128
+ return {
129
+ model: modelSetting,
130
+ effort: effortSetting,
131
+ allocation: allocationSetting,
132
+ account: {
133
+ value: pick?.claudeAccount ?? claudeAccount,
134
+ disabled,
135
+ onChange: (next) => {
136
+ pickNext({ claudeAccount: next });
137
+ patch({ claudeAccount: next }).then((saved) => {
138
+ if (saved) onAccountSaved?.(next);
139
+ });
140
+ }
141
+ },
142
+ setMode,
143
+ saving
144
+ };
145
+ }
146
+ return {
147
+ updateSessionSettings,
148
+ useSessionSettings
149
+ };
150
+ }
151
+ export { settingsApi };