@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,121 @@
1
+ import { PREVIEWS_BY_REF } from "./images.js";
2
+ // src/transcriptRead.ts
3
+ /** About how many history items the end of a transcript holds. */
4
+ var TAIL_ITEMS = 200;
5
+ /** How long the rest of a transcript may take before its end is shown without
6
+ * it: one that arrives whole is drawn once. */
7
+ var TAIL_GRACE_MS = 80;
8
+ var OLDER = ",\"older\":[";
9
+ function tailBefore(text, at) {
10
+ try {
11
+ return JSON.parse(`${text.slice(0, at)}}`).tail;
12
+ } catch {
13
+ return;
14
+ }
15
+ }
16
+ /** Reads a transcript answered tail first and resolves to its text. `onTail` is
17
+ * handed the tail once it has arrived, if the rest is still on its way a
18
+ * moment later. */
19
+ async function readTailFirst(stream, onTail) {
20
+ const reader = stream.getReader();
21
+ const decoder = new TextDecoder();
22
+ let text = "";
23
+ let from = 0;
24
+ let found = false;
25
+ let grace;
26
+ try {
27
+ for (;;) {
28
+ const { done, value } = await reader.read();
29
+ if (done) break;
30
+ text += decoder.decode(value, { stream: true });
31
+ while (!found) {
32
+ const at = text.indexOf(OLDER, from);
33
+ if (at < 0) {
34
+ from = Math.max(0, text.length - 10);
35
+ break;
36
+ }
37
+ const tail = tailBefore(text, at);
38
+ if (tail) {
39
+ found = true;
40
+ grace = setTimeout(() => onTail(tail), TAIL_GRACE_MS);
41
+ } else from = at + 1;
42
+ }
43
+ }
44
+ } finally {
45
+ clearTimeout(grace);
46
+ }
47
+ return text + decoder.decode();
48
+ }
49
+ /** Reads sessions' transcripts so the end of one can be shown while the rest
50
+ * of it arrives, which over a slow connection is most of the wait. */
51
+ function createTranscriptReads(client, previewsByRef) {
52
+ const tails = /* @__PURE__ */ new Map();
53
+ const listeners = /* @__PURE__ */ new Set();
54
+ const tell = () => {
55
+ for (const listener of listeners) listener();
56
+ };
57
+ const query = previewsByRef ? { previews: PREVIEWS_BY_REF } : {};
58
+ const readWhole = async (machine, id, aborts) => {
59
+ const { data, error } = await client.GET("/api/code/machines/{machine}/sessions/{id}", {
60
+ params: {
61
+ path: {
62
+ machine,
63
+ id
64
+ },
65
+ ...previewsByRef ? { query } : {}
66
+ },
67
+ ...aborts
68
+ });
69
+ if (error !== void 0) throw error;
70
+ return data;
71
+ };
72
+ return {
73
+ /** The end of the transcript being read under `name`, until the read ends. */
74
+ tail: (name) => tails.get(name),
75
+ subscribe: (listener) => {
76
+ listeners.add(listener);
77
+ return () => {
78
+ listeners.delete(listener);
79
+ };
80
+ },
81
+ /** The session, whole. `name` is what its end is kept under meanwhile. */
82
+ async read(machine, id, name, signal) {
83
+ const aborts = signal ? { signal } : {};
84
+ const { data, error, response } = await client.GET("/api/code/machines/{machine}/sessions/{id}/transcript", {
85
+ params: {
86
+ path: {
87
+ machine,
88
+ id
89
+ },
90
+ query: {
91
+ ...query,
92
+ tail: TAIL_ITEMS
93
+ }
94
+ },
95
+ parseAs: "stream",
96
+ ...aborts
97
+ });
98
+ if (error !== void 0) {
99
+ if (response.status !== 404 && response.status !== 405) throw error;
100
+ return readWhole(machine, id, aborts);
101
+ }
102
+ if (!data) return readWhole(machine, id, aborts);
103
+ try {
104
+ const text = await readTailFirst(data, (tail) => {
105
+ tails.set(name, tail);
106
+ tell();
107
+ });
108
+ const { tail, older } = JSON.parse(text);
109
+ return {
110
+ ...tail,
111
+ history: [...older ?? [], ...tail.history ?? []]
112
+ };
113
+ } finally {
114
+ setTimeout(() => {
115
+ if (tails.delete(name)) tell();
116
+ }, 0);
117
+ }
118
+ }
119
+ };
120
+ }
121
+ export { createTranscriptReads, readTailFirst };
package/dist/types.d.ts CHANGED
@@ -43,16 +43,22 @@ export interface PwCodeHistoryItem {
43
43
  turnEnd?: PwCodeTurnEnd;
44
44
  /** On an EditFile call: the line its hunk begins on, as a live tool_start carries it. */
45
45
  startLine?: number;
46
+ /** On a thinking item: how long the thought took, when the session recorded it. */
47
+ durationMs?: number;
46
48
  }
47
49
  /** A preview of an image a message carried, base64-encoded; ref names the
48
50
  * full-size image when the daemon can serve it, and originalMime and
49
- * originalSize describe that image. */
51
+ * originalSize describe that image. Data is empty where the transcript was
52
+ * read with its previews left to their refs. */
50
53
  export interface PwCodeImage {
51
54
  mime: string;
52
55
  data: string;
53
56
  ref?: string;
54
57
  originalMime?: string;
55
58
  originalSize?: number;
59
+ /** The preview's size in pixels. */
60
+ width?: number;
61
+ height?: number;
56
62
  }
57
63
  /** An image the session saved, sent with the message that names its placeholder. */
58
64
  export interface PwCodeImageRef {
@@ -141,6 +147,8 @@ export interface PwCodeGoalStatus {
141
147
  paused?: boolean;
142
148
  /** An evaluation is in flight, which spends tokens with no turn to show. */
143
149
  checking?: boolean;
150
+ /** Time spent working toward it when the snapshot was taken; a pause stops it. */
151
+ elapsedMs?: number;
144
152
  }
145
153
  /** One step of a /goal loop, as the daemon files and announces it. */
146
154
  export interface PwCodeGoalProgress {
@@ -151,6 +159,8 @@ export interface PwCodeGoalProgress {
151
159
  err?: string;
152
160
  /** Set when a usage limit stopped the check; the goal is checked again then. */
153
161
  resumeAt?: string;
162
+ /** Set on a check-in: how long the check has waited on background work still running. */
163
+ waitedMs?: number;
154
164
  elapsedMs?: number;
155
165
  tokens?: number;
156
166
  }
@@ -1,19 +1,28 @@
1
- import type { MessagePaste } from '@parallelworks/ui/ai/headless';
1
+ import type { ChatMessage, MessagePaste } from '@parallelworks/ui/ai/headless';
2
2
  import type { Schemas } from './apiClient.js';
3
3
  import type { PwCodeApi } from './createPwCodeApi.js';
4
4
  import type { PwCodeConversation } from './useConversation.js';
5
- import type { PwCodeTakenImages } from './useComposerImages.js';
5
+ import { type PwCodeSavedImage, type PwCodeTakenImages } from './useComposerImages.js';
6
6
  /** The composer's history of sent prompts, as `@parallelworks/ui/ai`'s
7
7
  * `ComposerHistory` takes it. */
8
8
  export interface PwCodeComposerHistory {
9
9
  /** Composers with the same name share one history. */
10
10
  name: string;
11
+ /** What was sent before this tab, oldest first. */
12
+ seed?: readonly string[] | undefined;
11
13
  /** Text to forget, such as a command carrying a secret. */
12
14
  skip?: ((text: string) => boolean) | undefined;
13
15
  }
16
+ /** What the reader typed into a conversation, oldest first: not the recorded
17
+ * commands and `!` runs, nor what the main session told a subagent. */
18
+ export declare function typedPrompts(messages: readonly ChatMessage[]): string[];
14
19
  /** Per person, since someone else can sign in where the history is kept, and
15
- * without `/auth`, which can carry a key. */
16
- export declare function promptHistory(username: string): PwCodeComposerHistory;
20
+ * per conversation, such as a session or one of its subagents, so ↑ in one
21
+ * recalls only what was sent to it. Without `/auth`, which can carry a key. */
22
+ export declare function promptHistory(username: string, conversation?: {
23
+ id: string;
24
+ messages: readonly ChatMessage[] | undefined;
25
+ }): PwCodeComposerHistory;
17
26
  /** What a command printed, shown below the transcript under the command as typed. */
18
27
  export interface PwCodeCommandOutput {
19
28
  id: number;
@@ -49,6 +58,7 @@ export declare function usePwCodeComposer({ api, machine, sessionId, conversatio
49
58
  /** The images waiting to go with the next message, as `useComposerImages` holds them. */
50
59
  images?: {
51
60
  take: () => Promise<PwCodeTakenImages>;
61
+ restore: (saved: readonly PwCodeSavedImage[]) => void;
52
62
  taking: boolean;
53
63
  } | undefined;
54
64
  /** Typed text the host acts on itself, such as a command that opens one of
@@ -56,9 +66,9 @@ export declare function usePwCodeComposer({ api, machine, sessionId, conversatio
56
66
  handleLocally?: ((typed: string) => boolean) | undefined;
57
67
  /** Tells the reader something in passing, such as in a toast. */
58
68
  notify: (text: string) => void;
59
- /** Shows the session `/clear` started in place of this one. */
69
+ /** Shows the session `/clear` started in place of this one, while this screen is still open. */
60
70
  onCleared: (newId: string) => void;
61
- /** Leaves the session `/archive` archived. */
71
+ /** Leaves the session `/archive` archived, while this screen is still open. */
62
72
  onArchived: () => void;
63
73
  }): {
64
74
  /** Sends what was typed; false hands it back to the composer. */
@@ -74,6 +84,14 @@ export declare function usePwCodeComposer({ api, machine, sessionId, conversatio
74
84
  locked: boolean;
75
85
  disabled: boolean;
76
86
  };
87
+ /** The composer's `recall`: ↑ in it, or Edit under the queue, takes back what waits. */
88
+ recall: {
89
+ available: boolean;
90
+ take: () => Promise<{
91
+ text: string;
92
+ pastes: MessagePaste[] | undefined;
93
+ }[]>;
94
+ };
77
95
  /** Why nothing can be sent to the session at all, which a subagent's composer shows too. */
78
96
  sessionLock: {
79
97
  placeholder: string;
@@ -119,3 +137,18 @@ export declare function usePwCodeComposer({ api, machine, sessionId, conversatio
119
137
  };
120
138
  };
121
139
  export type PwCodeComposer = ReturnType<typeof usePwCodeComposer>;
140
+ /** Stops a composer's turn as `@parallelworks/ui/ai`'s session view does,
141
+ * for a host that draws its own composer: while what waits can come back
142
+ * (`recall.available`), `takeBack`, the composer's own take-back into its
143
+ * box, runs first, so none of it starts a turn once this one stops; then
144
+ * the turn stops, even when taking back failed. Resolves to what taking
145
+ * back threw, which the session view only logs.
146
+ * Takes `usePwCodeComposer`'s or `usePwCodeSubagent`'s result. */
147
+ export declare function stopTurn(composer: {
148
+ recall: {
149
+ available: boolean;
150
+ };
151
+ turn: {
152
+ stop: () => Promise<void>;
153
+ };
154
+ }, takeBack: () => Promise<unknown>): Promise<unknown>;
@@ -2,17 +2,33 @@ import { shellCommand } from "./command.js";
2
2
  import { isMachineDown } from "./machine.js";
3
3
  import { usePwCodeTranslations } from "./messages.js";
4
4
  import { bashRunning, liveSessionStatus, pendingApprovals, turnRunning } from "./transcript.js";
5
+ import { withoutAppendedImages } from "./useComposerImages.js";
6
+ import { useMounted } from "./useMounted.js";
5
7
  import { composerState, sessionLabel } from "./wording.js";
6
8
  import { useCallback, useEffect, useRef, useState } from "react";
7
9
  // src/useComposer.ts
10
+ /** What the reader typed into a conversation, oldest first: not the recorded
11
+ * commands and `!` runs, nor what the main session told a subagent. */
12
+ function typedPrompts(messages) {
13
+ return messages.flatMap((m) => m.role === "user" && m.content && !m.pseudo && !m.commandAnswer && !m.author ? [m.content] : []);
14
+ }
8
15
  /** Per person, since someone else can sign in where the history is kept, and
9
- * without `/auth`, which can carry a key. */
10
- function promptHistory(username) {
16
+ * per conversation, such as a session or one of its subagents, so ↑ in one
17
+ * recalls only what was sent to it. Without `/auth`, which can carry a key. */
18
+ function promptHistory(username, conversation) {
11
19
  return {
12
- name: `agents:${username}`,
20
+ name: conversation ? `agents:${username}:${conversation.id}` : `agents:${username}`,
21
+ seed: conversation?.messages && typedPrompts(conversation.messages),
13
22
  skip: (text) => /^\/auth(\s|$)/.test(text)
14
23
  };
15
24
  }
25
+ /** Typed text steers a running turn; what a command resolved to runs as a turn of its own, and comes back as typed. */
26
+ function resolvedDelivery(text, typed) {
27
+ return text === typed ? { steer: true } : {
28
+ steer: false,
29
+ typed
30
+ };
31
+ }
16
32
  function useCommandOutputs() {
17
33
  const [outputs, setOutputs] = useState([]);
18
34
  const seq = useRef(0);
@@ -38,7 +54,7 @@ function useCommandOutputs() {
38
54
  * elsewhere, or it waits on an approval. */
39
55
  function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo, feed, staleFor, images, handleLocally, notify, onCleared, onArchived }) {
40
56
  const t = usePwCodeTranslations("agents");
41
- const { session, detail, transcript, goal, sending, refetch, warn, showError, reached, deliver, noteShellRun } = conversation;
57
+ const { session, detail, transcript, goal, sending, refetch, warn, showError, reached, deliver, noteShellRun, queued, canRemoveQueued, takeBackPending } = conversation;
42
58
  const [shellRun, setShellRun] = useState(null);
43
59
  const delivering = useRef(null);
44
60
  const { palette, loading: paletteLoading, load: loadPalette } = api.usePalette(machine, sessionId);
@@ -57,6 +73,7 @@ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo,
57
73
  warn
58
74
  ]);
59
75
  const { archiveSession, archiveAfterTurn, stopSession } = api.useSessionMutations();
76
+ const mounted = useMounted();
60
77
  /** Resolves to the machine's refusal. A session archived once its turn ends stays open, and the machine says so in the transcript. */
61
78
  const archiveTyped = useCallback(async (s, waits) => {
62
79
  const { refusal, deferred } = waits ? await archiveAfterTurn(s) : {
@@ -65,12 +82,13 @@ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo,
65
82
  };
66
83
  if (!refusal && !deferred) {
67
84
  notify(t("detail.archived", { name: sessionLabel(s, t) }));
68
- onArchived();
85
+ if (mounted.current) onArchived();
69
86
  }
70
87
  return refusal;
71
88
  }, [
72
89
  archiveAfterTurn,
73
90
  archiveSession,
91
+ mounted,
74
92
  notify,
75
93
  onArchived,
76
94
  t
@@ -98,7 +116,9 @@ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo,
98
116
  onOutput: commandOutputs.add,
99
117
  onShellRun,
100
118
  onCompacted: () => void refetch(),
101
- onCleared,
119
+ onCleared: (newId) => {
120
+ if (mounted.current) onCleared(newId);
121
+ },
102
122
  onArchive: async () => {
103
123
  const waits = machineInfo?.archiveAfterTurn === true;
104
124
  if (running && !waits) {
@@ -123,7 +143,7 @@ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo,
123
143
  const refs = saved.map((i) => i.ref);
124
144
  const message = [text, ...refs.map((i) => i.placeholder).filter((p) => !text.includes(p))].filter(Boolean).join(" ");
125
145
  const delivery = deliver(message, {
126
- steer: text === typed,
146
+ ...resolvedDelivery(text, typed),
127
147
  pastes,
128
148
  images: refs,
129
149
  previews: saved.map((i) => i.preview)
@@ -144,6 +164,7 @@ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo,
144
164
  loadPalette,
145
165
  machine,
146
166
  machineInfo?.archiveAfterTurn,
167
+ mounted,
147
168
  onCleared,
148
169
  onShellRun,
149
170
  palette,
@@ -170,6 +191,27 @@ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo,
170
191
  session,
171
192
  stopSession
172
193
  ]);
194
+ const restoreImages = images?.restore;
195
+ /** Takes back what waits into the composer, as ↑ does in the terminal; one the model read meanwhile stays sent. */
196
+ const takeBack = useCallback(async () => {
197
+ const { taken, refusal } = await takeBackPending();
198
+ if (refusal) warn(refusal);
199
+ restoreImages?.(taken.flatMap(({ images = [], previews = [] }) => images.flatMap((ref, i) => {
200
+ const preview = previews[i];
201
+ return preview ? [{
202
+ ref,
203
+ preview
204
+ }] : [];
205
+ })));
206
+ return taken.map((m) => ({
207
+ text: withoutAppendedImages(m.text, m.images),
208
+ pastes: m.pastes
209
+ }));
210
+ }, [
211
+ restoreImages,
212
+ takeBackPending,
213
+ warn
214
+ ]);
173
215
  const status = detail ? liveSessionStatus(detail.status, transcript, goal) : null;
174
216
  const approvals = transcript ? pendingApprovals(transcript).map((p) => ({ kind: p.approvalKind })) : detail?.approvals;
175
217
  const unreachable = isMachineDown(machineInfo) && !feed.connected;
@@ -212,7 +254,12 @@ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo,
212
254
  },
213
255
  composer: {
214
256
  ...state,
215
- disabled: sending || !!images?.taking || state.locked
257
+ disabled: sending || !!images?.taking || state.locked || conversation.endOnly
258
+ },
259
+ /** The composer's `recall`: ↑ in it, or Edit under the queue, takes back what waits. */
260
+ recall: {
261
+ available: queued.some((m) => canRemoveQueued(m.id)),
262
+ take: takeBack
216
263
  },
217
264
  /** Why nothing can be sent to the session at all, which a subagent's composer shows too. */
218
265
  sessionLock: unreachable || archived || liveElsewhere ? state : null,
@@ -241,4 +288,21 @@ function usePwCodeComposer({ api, machine, sessionId, conversation, machineInfo,
241
288
  background
242
289
  };
243
290
  }
244
- export { promptHistory, useCommandOutputs, usePwCodeComposer };
291
+ /** Stops a composer's turn as `@parallelworks/ui/ai`'s session view does,
292
+ * for a host that draws its own composer: while what waits can come back
293
+ * (`recall.available`), `takeBack`, the composer's own take-back into its
294
+ * box, runs first, so none of it starts a turn once this one stops; then
295
+ * the turn stops, even when taking back failed. Resolves to what taking
296
+ * back threw, which the session view only logs.
297
+ * Takes `usePwCodeComposer`'s or `usePwCodeSubagent`'s result. */
298
+ async function stopTurn(composer, takeBack) {
299
+ let failure;
300
+ if (composer.recall.available) try {
301
+ await takeBack();
302
+ } catch (error) {
303
+ failure = error;
304
+ }
305
+ await composer.turn.stop();
306
+ return failure;
307
+ }
308
+ export { promptHistory, stopTurn, typedPrompts, useCommandOutputs, usePwCodeComposer };
@@ -31,6 +31,9 @@ export interface PwCodeTakenImages {
31
31
  }
32
32
  /** Numbers past every placeholder the texts name, as the terminal does. */
33
33
  export declare function nextImageSeq(texts: Iterable<string | null | undefined> | undefined, after: number): number;
34
+ /** The send appends the placeholders of images its text left out; a message
35
+ * taken back gives them back as images, so they leave its text. */
36
+ export declare function withoutAppendedImages(text: string, images: readonly PwCodeImageRef[] | undefined): string;
34
37
  /** Images stay with the reader until there is a session to save them with. */
35
38
  export declare function useComposerImages<F extends PwCodeImageFile>({ api, machine, sessionId, messages, onError, describeError, encode, preview, release, }: {
36
39
  api: Pick<PwCodeApi, 'saveImage'>;
@@ -61,6 +64,8 @@ export declare function useComposerImages<F extends PwCodeImageFile>({ api, mach
61
64
  remove: (key: string) => void;
62
65
  /** Empties the composer and resolves to the saved images; settling with false puts them back. */
63
66
  take: () => Promise<PwCodeTakenImages>;
67
+ /** Puts back the images a message taken back was sent with, already saved with the session. */
68
+ restore: (saved: readonly PwCodeSavedImage[]) => void;
64
69
  /** Saves the images added before there was a session; null once one failed, which `onError` was told. */
65
70
  saveTo: (machine: string, sessionId: string) => Promise<PwCodeImageRef[] | null>;
66
71
  };
@@ -1,4 +1,5 @@
1
1
  import { usePwCodeTranslations } from "./messages.js";
2
+ import { useMounted } from "./useMounted.js";
2
3
  import { IMAGE_PLACEHOLDER } from "./wording.js";
3
4
  import { useCallback, useEffect, useRef, useState } from "react";
4
5
  // src/useComposerImages.ts
@@ -23,6 +24,14 @@ function nextImageSeq(texts, after) {
23
24
  }
24
25
  return seq + 1;
25
26
  }
27
+ /** The send appends the placeholders of images its text left out; a message
28
+ * taken back gives them back as images, so they leave its text. */
29
+ function withoutAppendedImages(text, images) {
30
+ let rest = text;
31
+ for (const { placeholder } of (images ?? []).toReversed()) if (rest === placeholder) rest = "";
32
+ else if (rest.endsWith(` ${placeholder}`)) rest = rest.slice(0, -placeholder.length - 1);
33
+ return rest;
34
+ }
26
35
  /** Images stay with the reader until there is a session to save them with. */
27
36
  function useComposerImages({ api, machine, sessionId, messages, onError, describeError, encode, preview, release }) {
28
37
  const t = usePwCodeTranslations("agents");
@@ -72,11 +81,9 @@ function useComposerImages({ api, machine, sessionId, messages, onError, describ
72
81
  }
73
82
  };
74
83
  }, []);
75
- const mounted = useRef(false);
84
+ const mounted = useMounted();
76
85
  useEffect(() => {
77
- mounted.current = true;
78
86
  return () => {
79
- mounted.current = false;
80
87
  for (const image of imagesRef.current) releasePreview(image.previewUrl);
81
88
  };
82
89
  }, [releasePreview]);
@@ -188,8 +195,23 @@ function useComposerImages({ api, machine, sessionId, messages, onError, describ
188
195
  }
189
196
  }
190
197
  };
191
- }, [releasePreview]),
198
+ }, [mounted, releasePreview]),
199
+ restore: useCallback((saved) => {
200
+ if (saved.length === 0) return;
201
+ lastSeq.current = nextImageSeq(saved.map((s) => s.ref.placeholder), lastSeq.current) - 1;
202
+ const restored = saved.map((image) => {
203
+ const { placeholder } = image.ref;
204
+ uploads.current.set(placeholder, Promise.resolve(image));
205
+ return {
206
+ key: placeholder,
207
+ placeholder,
208
+ previewUrl: `data:${image.preview.mime};base64,${image.preview.data}`,
209
+ saved: true
210
+ };
211
+ });
212
+ setImages((current) => [...restored, ...current]);
213
+ }, []),
192
214
  saveTo
193
215
  };
194
216
  }
195
- export { IMAGE_MAX_BYTES, IMAGE_MAX_SIDE, IMAGE_READ_MAX_BYTES, IMAGE_TYPES, PwCodeImageTooLarge, nextImageSeq, useComposerImages };
217
+ export { IMAGE_MAX_BYTES, IMAGE_MAX_SIDE, IMAGE_READ_MAX_BYTES, IMAGE_TYPES, PwCodeImageTooLarge, nextImageSeq, useComposerImages, withoutAppendedImages };
@@ -0,0 +1,70 @@
1
+ import { type ComposerPastes, type MessagePaste, type PasteCard } from '@parallelworks/ui/ai/headless';
2
+ import type { Schemas } from './apiClient.js';
3
+ import type { PwCodeChatStrings } from './chatStrings.js';
4
+ import type { PwCodeApi } from './createPwCodeApi.js';
5
+ import type { PwCodeSessionState } from './types.js';
6
+ /** Where a session's large pastes are saved, and the size past which one is.
7
+ * A live session's own limit stands, and a live session that reports none
8
+ * predates paste uploads, so its pastes stay text. Before the session is
9
+ * live, the context window of the model read of it sets the limit once the
10
+ * platform's models have loaded; until then every paste stays text. */
11
+ export declare function useComposerPastes(api: Pick<PwCodeApi, 'uploadPaste'> & {
12
+ /** The package's, or a host's list it already holds. */
13
+ usePlatformModels: () => {
14
+ models: readonly Pick<Schemas['ModelEntry'], 'id' | 'context_window'>[];
15
+ };
16
+ }, { machine, sessionId, liveState, detail, describeError, }: {
17
+ machine: string;
18
+ sessionId: string;
19
+ /** What the session reported while live, as `usePwCodeConversation` holds it; null before. */
20
+ liveState: Pick<PwCodeSessionState, 'pasteInlineMaxBytes'> | null;
21
+ /** The session as `api.useSessionDetail` read it. */
22
+ detail: Pick<Schemas['AgentSessionDetail'], 'model'> | undefined;
23
+ /** A failed save in the reader's language. */
24
+ describeError: (error: unknown) => string;
25
+ }): ComposerPastes | undefined;
26
+ /** A send's share of the composer: the message, which names each saved
27
+ * paste after the text, and the pastes it names. */
28
+ export interface PwCodePasteSend {
29
+ text: string;
30
+ pastes: MessagePaste[];
31
+ /** Puts the text back before anything typed since, and the cards with it,
32
+ * after a send that failed. False, putting nothing back, once the composer
33
+ * is another or gone, so the host can keep the text as that one's draft. */
34
+ putBack: () => boolean;
35
+ }
36
+ export interface PwCodePasteCards {
37
+ /** The pastes waiting as cards, in the order they were pasted. */
38
+ cards: PasteCard[];
39
+ /** A card is still saving or failed to save, which holds the send back
40
+ * until it saves or is removed. */
41
+ blocking: boolean;
42
+ /** Takes a paste: true when it became a card, so the box leaves the text
43
+ * out. Otherwise the box takes it, its line endings made `\n` as
44
+ * `normalizeNewlines` makes them. */
45
+ paste: (text: string) => boolean;
46
+ remove: (key: string) => void;
47
+ /** Empties the box and the cards for a send; null, leaving both, while a
48
+ * card holds the send back. */
49
+ send: () => PwCodePasteSend | null;
50
+ }
51
+ /** A composer's paste cards, for a host that draws its own composer: a paste
52
+ * past the limit becomes a card that saves with the session and goes as its
53
+ * placeholder, and a new limit, such as another model's, moves pastes
54
+ * between the box and the cards. */
55
+ export declare function usePasteCards({ pastes, input, setInput, composer, }: {
56
+ /** As `useComposerPastes` gives them; undefined keeps every paste text. */
57
+ pastes: ComposerPastes | undefined;
58
+ /** What the box holds now. */
59
+ input: string;
60
+ setInput: (value: string) => void;
61
+ /** The composer the cards belong to, such as the session's draft key:
62
+ * another one starts with none. */
63
+ composer: string;
64
+ }): PwCodePasteCards;
65
+ /** A paste card's name, and the line under it: why it failed, else that it is
66
+ * saving, else its lines and size. */
67
+ export declare function pasteCardText(card: PasteCard, words: PwCodeChatStrings['paste']): {
68
+ title: string;
69
+ detail: string;
70
+ };
@@ -0,0 +1,125 @@
1
+ import { useMounted } from "./useMounted.js";
2
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
3
+ import { createPasteCards, joinPastes, pasteInlineMaxBytes } from "@parallelworks/ui/ai/headless";
4
+ import { formatBytes } from "@parallelworks/ui/headless";
5
+ // src/useComposerPastes.ts
6
+ /** Where a session's large pastes are saved, and the size past which one is.
7
+ * A live session's own limit stands, and a live session that reports none
8
+ * predates paste uploads, so its pastes stay text. Before the session is
9
+ * live, the context window of the model read of it sets the limit once the
10
+ * platform's models have loaded; until then every paste stays text. */
11
+ function useComposerPastes(api, { machine, sessionId, liveState, detail, describeError }) {
12
+ const { models } = api.usePlatformModels();
13
+ const contextWindow = models.find((m) => m.id === detail?.model)?.context_window;
14
+ const listedMax = models.length > 0 ? pasteInlineMaxBytes(contextWindow) : void 0;
15
+ const supported = !liveState || liveState.pasteInlineMaxBytes !== void 0;
16
+ const inlineMaxBytes = liveState ? liveState.pasteInlineMaxBytes : listedMax;
17
+ const { uploadPaste } = api;
18
+ const upload = useCallback((text) => uploadPaste(machine, sessionId, text, describeError), [
19
+ uploadPaste,
20
+ machine,
21
+ sessionId,
22
+ describeError
23
+ ]);
24
+ return useMemo(() => supported ? {
25
+ inlineMaxBytes,
26
+ upload
27
+ } : void 0, [
28
+ supported,
29
+ inlineMaxBytes,
30
+ upload
31
+ ]);
32
+ }
33
+ /** A composer's paste cards, for a host that draws its own composer: a paste
34
+ * past the limit becomes a card that saves with the session and goes as its
35
+ * placeholder, and a new limit, such as another model's, moves pastes
36
+ * between the box and the cards. */
37
+ function usePasteCards({ pastes, input, setInput, composer }) {
38
+ const [cards, setCards] = useState([]);
39
+ const latest = useRef({
40
+ pastes,
41
+ input,
42
+ setInput,
43
+ composer,
44
+ cards,
45
+ controller: null
46
+ });
47
+ latest.current = {
48
+ ...latest.current,
49
+ pastes,
50
+ input,
51
+ setInput,
52
+ composer
53
+ };
54
+ const cardsFor = (key) => {
55
+ const controller = createPasteCards({
56
+ pastes: () => latest.current.pastes,
57
+ input: () => latest.current.input,
58
+ setInput: (value) => {
59
+ if (latest.current.controller === controller) {
60
+ latest.current.input = value;
61
+ latest.current.setInput(value);
62
+ }
63
+ },
64
+ onCardsChange: (next) => {
65
+ if (latest.current.controller === controller) {
66
+ latest.current.cards = next;
67
+ setCards(next);
68
+ }
69
+ }
70
+ });
71
+ return {
72
+ composer: key,
73
+ controller
74
+ };
75
+ };
76
+ const [owned, setOwned] = useState(() => cardsFor(composer));
77
+ if (owned.composer !== composer) {
78
+ latest.current.cards = [];
79
+ setCards([]);
80
+ setOwned(cardsFor(composer));
81
+ }
82
+ const { controller } = owned;
83
+ latest.current.controller = controller;
84
+ const inlineMax = pastes?.inlineMaxBytes;
85
+ useEffect(() => {
86
+ if (inlineMax !== void 0) controller.applyInlineLimit(inlineMax);
87
+ }, [inlineMax, controller]);
88
+ const mounted = useMounted();
89
+ const send = useCallback(() => {
90
+ const { input: sent, composer: from, cards: taken } = latest.current;
91
+ if (taken.some((c) => !c.paste)) return null;
92
+ const saved = controller.takeCards();
93
+ latest.current.input = "";
94
+ latest.current.setInput("");
95
+ return {
96
+ text: joinPastes(sent, saved),
97
+ pastes: saved,
98
+ putBack: () => {
99
+ if (!mounted.current || latest.current.composer !== from) return false;
100
+ const typed = latest.current.input;
101
+ const value = [sent, typed].filter((text) => text.trim()).join("\n\n");
102
+ latest.current.input = value;
103
+ latest.current.setInput(value);
104
+ latest.current.controller?.returnCards(taken);
105
+ return true;
106
+ }
107
+ };
108
+ }, [controller, mounted]);
109
+ return {
110
+ cards,
111
+ blocking: cards.some((c) => !c.paste),
112
+ paste: controller.handleTextPaste,
113
+ remove: controller.removeCard,
114
+ send
115
+ };
116
+ }
117
+ /** A paste card's name, and the line under it: why it failed, else that it is
118
+ * saving, else its lines and size. */
119
+ function pasteCardText(card, words) {
120
+ return {
121
+ title: card.paste?.id ? `paste-${card.paste.id}.txt` : words.title,
122
+ detail: card.error ?? (card.paste ? `${words.lines(card.lines)} · ${formatBytes(card.bytes)}` : words.saving)
123
+ };
124
+ }
125
+ export { pasteCardText, useComposerPastes, usePasteCards };