@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,125 @@
1
+ import { pullRequestKind, pullRequestLabel } from "./pullRequest.js";
2
+ // src/pullRequestList.ts
3
+ var stateOrder = {
4
+ draft: 0,
5
+ open: 1,
6
+ merged: 2,
7
+ closed: 3
8
+ };
9
+ function isPullRequestState(state) {
10
+ return state !== void 0 && Object.hasOwn(stateOrder, state);
11
+ }
12
+ /** The URLs that are plain GitHub pull requests or GitLab merge requests, each with its `pullRequestLabel`. */
13
+ function labeledPullRequests(urls) {
14
+ return (urls ?? []).flatMap((url) => {
15
+ const pr = pullRequestLabel(url);
16
+ return pr ? [{
17
+ url,
18
+ pr
19
+ }] : [];
20
+ });
21
+ }
22
+ /** Reads a state from a session's pull request reads, or from the
23
+ * `pullRequestStates` a listed session carries. */
24
+ function pullRequestStateOf(states) {
25
+ if (Array.isArray(states)) return (url) => states.find((s) => s.url === url)?.state;
26
+ const byUrl = states;
27
+ return (url) => byUrl?.[url];
28
+ }
29
+ var stateRank = (state) => isPullRequestState(state) ? stateOrder[state] : stateOrder.open;
30
+ /** Drafts, then open, merged and closed pull requests, the newest first within each; one whose state is unknown counts as open. */
31
+ function orderPullRequests(pullRequests, stateOf) {
32
+ return pullRequests.map((pr, i) => ({
33
+ pr,
34
+ i,
35
+ rank: stateRank(stateOf(pr.url))
36
+ })).sort((a, b) => a.rank - b.rank || b.i - a.i).map(({ pr }) => pr);
37
+ }
38
+ var isDone = (state) => state === "merged" || state === "closed";
39
+ /** Whether each pull request folds into the merged-or-closed count rather than the open one. */
40
+ function pullRequestFoldGroups(ordered, stateOf) {
41
+ return ordered.map(({ url }) => isDone(stateOf(url)));
42
+ }
43
+ /** Once a listed session's row has this many merged and closed pull requests to fold, they fold into their count even when they fit. */
44
+ var FOLD_DONE_PULL_REQUESTS_FROM = 2;
45
+ /** How many of `ordered` fold whether or not they fit: its merged and closed ones, which come last, once there are `from` of them to fold; the first stays when every one is merged or closed. */
46
+ function donePullRequestsToFold(ordered, stateOf, from = 2) {
47
+ const done = ordered.filter(({ url }) => isDone(stateOf(url))).length;
48
+ const foldable = done === ordered.length ? done - 1 : done;
49
+ return foldable >= from ? foldable : 0;
50
+ }
51
+ /** `ordered` but its last `folded`, which fold into an open count and a merged-or-closed one; a group with none is left out. */
52
+ function foldPullRequests(ordered, folded, stateOf) {
53
+ const rest = ordered.slice(ordered.length - folded);
54
+ const groups = [{
55
+ group: "open",
56
+ pullRequests: rest.filter(({ url }) => !isDone(stateOf(url)))
57
+ }, {
58
+ group: "done",
59
+ pullRequests: rest.filter(({ url }) => isDone(stateOf(url)))
60
+ }];
61
+ return {
62
+ shown: ordered.slice(0, ordered.length - folded),
63
+ groups: groups.filter(({ pullRequests }) => pullRequests.length > 0)
64
+ };
65
+ }
66
+ var groupPrecedence = [
67
+ "open",
68
+ "draft",
69
+ "merged",
70
+ "closed"
71
+ ];
72
+ /** The state a folded group shows: open over draft, and merged over closed. */
73
+ function pullRequestGroupState(group, stateOf) {
74
+ const states = new Set(group.map(({ url }) => stateOf(url)));
75
+ return groupPrecedence.find((state) => states.has(state));
76
+ }
77
+ /** Whether each pull request's state differs from the one before it, where a list marks the change. */
78
+ function pullRequestStateBreaks(pullRequests, stateOf) {
79
+ return pullRequests.map(({ url }, i) => i > 0 && stateRank(stateOf(url)) !== stateRank(stateOf(pullRequests[i - 1]?.url ?? "")));
80
+ }
81
+ var stateTones = {
82
+ open: "success",
83
+ draft: "muted",
84
+ merged: "done",
85
+ closed: "error"
86
+ };
87
+ function pullRequestTone(state) {
88
+ return stateTones[state];
89
+ }
90
+ function stateTitle(t, pr, state) {
91
+ const values = {
92
+ pr,
93
+ kind: pullRequestKind(pr)
94
+ };
95
+ switch (state) {
96
+ case "open": return t("detail.pullRequestOpen", values);
97
+ case "draft": return t("detail.pullRequestDraft", values);
98
+ case "merged": return t("detail.pullRequestMerged", values);
99
+ case "closed": return t("detail.pullRequestClosed", values);
100
+ default: return t("detail.pullRequest", values);
101
+ }
102
+ }
103
+ function groupTitle(t, group, count) {
104
+ switch (group) {
105
+ case "open": return t("detail.pullRequestsMoreOpenTitle", { count });
106
+ case "done": return t("detail.pullRequestsMoreDoneTitle", { count });
107
+ case "all": return t("detail.pullRequestsMoreAllTitle", { count });
108
+ }
109
+ }
110
+ function groupLabel(t, group, count) {
111
+ switch (group) {
112
+ case "open": return t("detail.pullRequestsShowMoreOpen", { count });
113
+ case "done": return t("detail.pullRequestsShowMoreDone", { count });
114
+ }
115
+ }
116
+ function pullRequestWords(t) {
117
+ return {
118
+ title: (pr, state) => stateTitle(t, pr, state),
119
+ state: (state) => t(`detail.pullRequestState.${state}`),
120
+ more: (count) => t("detail.pullRequestsMore", { count }),
121
+ groupTitle: (group, count) => groupTitle(t, group, count),
122
+ showGroup: (group, count) => groupLabel(t, group, count)
123
+ };
124
+ }
125
+ export { FOLD_DONE_PULL_REQUESTS_FROM, donePullRequestsToFold, foldPullRequests, isPullRequestState, labeledPullRequests, orderPullRequests, pullRequestFoldGroups, pullRequestGroupState, pullRequestStateBreaks, pullRequestStateOf, pullRequestTone, pullRequestWords };
package/dist/query.d.ts CHANGED
@@ -23,6 +23,10 @@ export type ReadData<P extends ReadPath> = PwCodePaths[P] extends {
23
23
  /** A data hook over `client` that keys each read `[prefix, path, init]`, or
24
24
  * `null` to skip it, and fetches it, as swr-openapi's query hook does: a host
25
25
  * reading the same routes through `@parallelworks/client/swr` shares each
26
- * cache entry with it. It throws the client's error, so SWR keeps it. */
27
- export declare function createQuery(client: PwCodeClient): <P extends ReadPath>(path: P, init: ReadInit<P> | null, config?: SWRConfiguration<ReadData<P>, PwCodeApiError>) => SWRResponse<ReadData<P>, PwCodeApiError>;
26
+ * cache entry with it. It throws the client's error, so SWR keeps it.
27
+ *
28
+ * With `giveUpWhenLeft` a read still on its way when the hook stops showing
29
+ * its key is aborted, for a large read only this hook shows: the connection
30
+ * goes to what the reader moved on to. */
31
+ export declare function createQuery(client: PwCodeClient): <P extends ReadPath>(path: P, init: ReadInit<P> | null, config?: SWRConfiguration<ReadData<P>, PwCodeApiError>, giveUpWhenLeft?: boolean) => SWRResponse<ReadData<P>, PwCodeApiError>;
28
32
  export {};
package/dist/query.js CHANGED
@@ -1,25 +1,100 @@
1
1
  import "./apiClient.js";
2
- import { useCallback, useMemo } from "react";
3
- import useSWR from "swr";
2
+ import { useCallback, useEffect, useMemo, useRef } from "react";
3
+ import useSWR, { unstable_serialize, useSWRConfig } from "swr";
4
4
  // src/query.ts
5
+ /** What a read given up rejects with. It is no answer, so it is never shown
6
+ * and never retried. */
7
+ var GIVEN_UP = Object.freeze({});
8
+ /** Runs a hook's reads of a key so that each is aborted once the hook no
9
+ * longer shows that key, and then rejects with GIVEN_UP. */
10
+ function useGivingUp(shown) {
11
+ const reads = useRef(/* @__PURE__ */ new Map());
12
+ const showing = useRef(void 0);
13
+ useEffect(() => {
14
+ if (shown === void 0) return;
15
+ showing.current = shown;
16
+ const started = reads.current;
17
+ return () => {
18
+ showing.current = void 0;
19
+ queueMicrotask(() => {
20
+ if (showing.current !== shown) for (const read of started.get(shown) ?? []) read.abort();
21
+ });
22
+ };
23
+ }, [shown]);
24
+ return useCallback(async (name, run) => {
25
+ const read = new AbortController();
26
+ const started = reads.current.get(name) ?? /* @__PURE__ */ new Set();
27
+ reads.current.set(name, started.add(read));
28
+ try {
29
+ return await run(read.signal);
30
+ } catch (error) {
31
+ throw read.signal.aborted ? GIVEN_UP : error;
32
+ } finally {
33
+ started.delete(read);
34
+ }
35
+ }, []);
36
+ }
5
37
  /** A data hook over `client` that keys each read `[prefix, path, init]`, or
6
38
  * `null` to skip it, and fetches it, as swr-openapi's query hook does: a host
7
39
  * reading the same routes through `@parallelworks/client/swr` shares each
8
- * cache entry with it. It throws the client's error, so SWR keeps it. */
40
+ * cache entry with it. It throws the client's error, so SWR keeps it.
41
+ *
42
+ * With `giveUpWhenLeft` a read still on its way when the hook stops showing
43
+ * its key is aborted, for a large read only this hook shows: the connection
44
+ * goes to what the reader moved on to. */
9
45
  function createQuery(client) {
10
46
  const reader = client;
11
- return function useQuery(path, init, config) {
47
+ return function useQuery(path, init, config, giveUpWhenLeft = false) {
12
48
  const key = useMemo(() => init !== null ? [
13
49
  "api",
14
50
  path,
15
51
  init
16
52
  ] : null, [path, init]);
17
- const fetcher = useCallback(async ([, route, options]) => {
18
- const { data, error } = await reader.GET(route, options);
19
- if (error) throw error;
20
- return data;
21
- }, []);
22
- return useSWR(key, fetcher, config);
53
+ const leaving = useGivingUp(giveUpWhenLeft && key ? unstable_serialize(key) : void 0);
54
+ const fetcher = useCallback((read) => {
55
+ const [, route, options] = read;
56
+ const get = async (signal) => {
57
+ const { data, error } = await reader.GET(route, signal ? {
58
+ ...options,
59
+ signal
60
+ } : options);
61
+ if (error) throw error;
62
+ return data;
63
+ };
64
+ return giveUpWhenLeft ? leaving(unstable_serialize(read), get) : get();
65
+ }, [giveUpWhenLeft, leaving]);
66
+ const shared = useSWRConfig();
67
+ const retry = config?.shouldRetryOnError ?? shared.shouldRetryOnError;
68
+ const onError = config?.onError ?? shared.onError;
69
+ const answered = useMemo(() => giveUpWhenLeft ? {
70
+ ...config,
71
+ shouldRetryOnError: (error) => error !== GIVEN_UP && (typeof retry === "function" ? retry(error) : retry !== false),
72
+ onError: (error, ...rest) => {
73
+ if (error !== GIVEN_UP) onError?.(error, ...rest);
74
+ }
75
+ } : config, [
76
+ giveUpWhenLeft,
77
+ config,
78
+ retry,
79
+ onError
80
+ ]);
81
+ const response = useSWR(key, fetcher, answered);
82
+ if (!giveUpWhenLeft) return response;
83
+ return {
84
+ get data() {
85
+ return response.data;
86
+ },
87
+ get error() {
88
+ return response.error === GIVEN_UP ? void 0 : response.error;
89
+ },
90
+ get isValidating() {
91
+ return response.isValidating;
92
+ },
93
+ get isLoading() {
94
+ return response.isLoading;
95
+ },
96
+ mutate: response.mutate
97
+ };
23
98
  };
24
99
  }
25
100
  export { createQuery };
package/dist/session.d.ts CHANGED
@@ -15,6 +15,12 @@ export interface PwCodeSession {
15
15
  /** The host whose client holds the session, while one does. */
16
16
  liveHost?: string | undefined;
17
17
  archivedAt?: string | undefined;
18
+ pinnedAt?: string | undefined;
19
+ /** The id of the reader's group the session is in. */
20
+ group?: string | undefined;
21
+ /** Links to the pull requests the session opened or was pointed at. */
22
+ pullRequests?: string[] | null | undefined;
23
+ createdAt?: string | undefined;
18
24
  updatedAt?: string | undefined;
19
25
  turnStartedAt?: string | undefined;
20
26
  workspace?: string | undefined;
@@ -57,12 +63,14 @@ export interface RecentDirectory {
57
63
  sessions: number;
58
64
  updatedAt: string;
59
65
  }
60
- /** The daemon offers no way to browse, so the machine's own sessions are the
61
- * only paths we can honestly suggest. */
66
+ /** The directories the machine's sessions worked in, newest first. */
62
67
  export declare function recentDirectories(sessions: readonly Pick<PwCodeSession, 'machineId' | 'workspace' | 'updatedAt'>[], machineId: string | undefined): RecentDirectory[];
63
68
  export declare function newestFirst<T extends {
64
69
  updatedAt?: string | undefined;
65
70
  }>(items: readonly T[]): T[];
71
+ /** Live sessions update with every message, so ordering them by that would
72
+ * move a row out from under the reader's pointer; when each began holds still. */
73
+ export declare function newestCreatedFirst<T extends Pick<PwCodeSession, 'machineId' | 'id' | 'createdAt'>>(items: readonly T[]): T[];
66
74
  /** An approval blocks the agent and goes first; a running turn is context;
67
75
  * everything else is what the reader last touched, newest first. */
68
76
  export declare function triageSessions<S extends Pick<PwCodeSession, 'machineId' | 'status' | 'archivedAt' | 'updatedAt'>>(sessions: readonly S[], machineById: ReadonlyMap<string, Pick<PwCodeMachine, 'status'>>): {
package/dist/session.js CHANGED
@@ -65,8 +65,7 @@ function sessionVariant(status, machine, idle) {
65
65
  function needsYou(s, machine) {
66
66
  return !isArchived(s) && s.status === "awaiting_approval" && isConnected(machine);
67
67
  }
68
- /** The daemon offers no way to browse, so the machine's own sessions are the
69
- * only paths we can honestly suggest. */
68
+ /** The directories the machine's sessions worked in, newest first. */
70
69
  function recentDirectories(sessions, machineId) {
71
70
  if (!machineId) return [];
72
71
  const byPath = /* @__PURE__ */ new Map();
@@ -75,7 +74,7 @@ function recentDirectories(sessions, machineId) {
75
74
  const found = byPath.get(s.workspace);
76
75
  if (found) {
77
76
  found.sessions += 1;
78
- if (updatedMillis(s) > updatedMillis(found)) found.updatedAt = s.updatedAt ?? "";
77
+ if (millis(s.updatedAt) > millis(found.updatedAt)) found.updatedAt = s.updatedAt ?? "";
79
78
  continue;
80
79
  }
81
80
  byPath.set(s.workspace, {
@@ -89,12 +88,17 @@ function recentDirectories(sessions, machineId) {
89
88
  }
90
89
  /** An unparseable timestamp would make the comparator return NaN, which leaves
91
90
  * the sort order up to the engine. */
92
- function updatedMillis(item) {
93
- const millis = DateTime.fromISO(item.updatedAt ?? "").toMillis();
94
- return Number.isFinite(millis) ? millis : 0;
91
+ function millis(iso) {
92
+ const ms = DateTime.fromISO(iso ?? "").toMillis();
93
+ return Number.isFinite(ms) ? ms : 0;
95
94
  }
96
95
  function newestFirst(items) {
97
- return [...items].sort((a, b) => updatedMillis(b) - updatedMillis(a));
96
+ return [...items].sort((a, b) => millis(b.updatedAt) - millis(a.updatedAt));
97
+ }
98
+ /** Live sessions update with every message, so ordering them by that would
99
+ * move a row out from under the reader's pointer; when each began holds still. */
100
+ function newestCreatedFirst(items) {
101
+ return [...items].sort((a, b) => millis(b.createdAt) - millis(a.createdAt) || sessionKey(a).localeCompare(sessionKey(b)));
98
102
  }
99
103
  /** An approval blocks the agent and goes first; a running turn is context;
100
104
  * everything else is what the reader last touched, newest first. */
@@ -108,4 +112,4 @@ function triageSessions(sessions, machineById) {
108
112
  idle: rest.filter((s) => s.status !== "running")
109
113
  };
110
114
  }
111
- export { isActiveSession, isArchived, isMidTurn, isSession, needsYou, newestFirst, pathBasename, recentDirectories, sessionClock, sessionKey, sessionStatusVariant, sessionVariant, sharedStoreCopy, spansMachines, triageSessions, waitsOnAnswer };
115
+ export { isActiveSession, isArchived, isMidTurn, isSession, needsYou, newestCreatedFirst, newestFirst, pathBasename, recentDirectories, sessionClock, sessionKey, sessionStatusVariant, sessionVariant, sharedStoreCopy, spansMachines, triageSessions, waitsOnAnswer };
@@ -0,0 +1,115 @@
1
+ import type { Schemas } from './apiClient.js';
2
+ import type { PwCodeApi } from './createPwCodeApi.js';
3
+ import { type PwCodeMachine } from './machine.js';
4
+ import type { PwCodeWorktreeRef } from './sessionHeader.js';
5
+ type Session = Schemas['AgentSession'];
6
+ export declare const DELETE_KEYS: readonly ['Backspace', 'Delete'];
7
+ /** The session the reader has open, if any. */
8
+ export interface OpenSessionRef {
9
+ machine?: string | undefined;
10
+ sessionId?: string | undefined;
11
+ }
12
+ /** What a menu entry does, so a host can give it an icon of its own. */
13
+ export type SessionMenuAction = 'rename' | 'restore' | 'pin' | 'unpin' | 'fork' | 'leaveWorktree' | 'stop' | 'archive' | 'delete' | 'moveToGroup' | 'joinGroup' | 'moveToNewGroup' | 'renameGroup' | 'deleteGroup' | 'newSession' | 'newGroup';
14
+ export interface SessionMenuCommand {
15
+ action: SessionMenuAction;
16
+ label: string;
17
+ run: () => void;
18
+ /** Why it can't be chosen now, for a host that shows it disabled. */
19
+ disabledReason?: string | undefined;
20
+ /** The key a focused row takes for it, as `shortcuts` binds it. */
21
+ shortcut?: string | undefined;
22
+ destructive?: boolean | undefined;
23
+ /** An on/off choice, on while true. */
24
+ checked?: boolean | undefined;
25
+ }
26
+ export interface SessionSubmenu {
27
+ action: SessionMenuAction;
28
+ label: string;
29
+ disabledReason?: string | undefined;
30
+ items: SessionMenuItem[];
31
+ }
32
+ /** A menu as data, which a host draws with its own components. */
33
+ export type SessionMenuItem = SessionMenuCommand | SessionSubmenu | 'divider';
34
+ /** A key that acts on a session's row while it has focus. */
35
+ export interface SessionRowKey<R> {
36
+ keys: string | readonly string[];
37
+ run: (row: R) => void;
38
+ }
39
+ /** What the host asks the reader before an action. */
40
+ export interface SessionConfirmation<R> {
41
+ action: 'delete' | 'archive' | 'leaveWorktree';
42
+ session: Session;
43
+ title: string;
44
+ description: string;
45
+ confirmLabel: string;
46
+ destructive: boolean;
47
+ /** The host offers to remove the session's worktree too, and passes the
48
+ * root of the one the reader chose to remove to `onConfirm`. */
49
+ offersWorktreeRemoval: boolean;
50
+ /** The row the action takes out of the list, as the host passed it in. */
51
+ removes?: R | undefined;
52
+ /** Asked with a key pressed on the row, so the next press may answer it. */
53
+ fromKey?: boolean | undefined;
54
+ /** Rejects with the machine's refusal, for the host to show while it still asks. */
55
+ onConfirm: (removeWorktree?: string) => Promise<void>;
56
+ }
57
+ /** What a prompt for a name says. */
58
+ export interface NamePromptWords {
59
+ title: string;
60
+ label: string;
61
+ placeholder: string;
62
+ confirmLabel: string;
63
+ }
64
+ /** A name as typed, without the spaces around it; undefined when nothing else was typed. */
65
+ export declare function nameToSave(name: string): string | undefined;
66
+ /** The session being renamed while the host's prompt for its name is up. */
67
+ export interface SessionRename extends NamePromptWords {
68
+ session: Session | null;
69
+ name: string;
70
+ setName: (name: string) => void;
71
+ /** Saves the trimmed name and closes; a refusal goes to `onRefusal` and leaves it open. */
72
+ confirm: () => Promise<void>;
73
+ close: () => void;
74
+ }
75
+ export interface SessionActionsOptions<R> {
76
+ api: Pick<PwCodeApi, 'useSessionMutations' | 'leaveWorktree'>;
77
+ machineById: ReadonlyMap<string, PwCodeMachine>;
78
+ open: OpenSessionRef;
79
+ confirm: (request: SessionConfirmation<R>) => void;
80
+ /** A refusal of an action taken without asking, or what was thrown when the request failed. */
81
+ onRefusal: (refusal: unknown) => void;
82
+ onWarning: (message: string) => void;
83
+ /** Leaves the open session once it is deleted or archived. */
84
+ showStart: () => void;
85
+ /** Opens a session, as forking does with the copy. */
86
+ showSession: (session: Pick<Session, 'machineId' | 'id'>) => void;
87
+ }
88
+ export interface SessionActions<R> {
89
+ /** Given its row, a delete or archive names the row it removes, and the
90
+ * entries show the keys the row takes. Given its worktree, it offers to leave it. */
91
+ menu: (session: Session, row?: R, worktree?: PwCodeWorktreeRef) => SessionMenuItem[];
92
+ /** The keys skip what the menu disables, as choosing a disabled entry does. */
93
+ shortcuts: (session: Session) => SessionRowKey<R>[];
94
+ rename: SessionRename;
95
+ requestRename: (session: Session) => void;
96
+ requestDelete: (session: Session, row?: R, fromKey?: boolean) => void;
97
+ requestArchive: (session: Session, row?: R) => void;
98
+ requestLeaveWorktree: (session: Session, worktree: PwCodeWorktreeRef) => void;
99
+ restore: (session: Session) => void;
100
+ stop: (session: Session) => void;
101
+ togglePin: (session: Session) => void;
102
+ fork: (session: Session) => void;
103
+ /** `group` null takes the session out of its group. */
104
+ moveToGroup: (session: Session, group: string | null) => void;
105
+ /** Why the session's machine cannot record a group, if it cannot. */
106
+ groupBlocked: (session: Session) => string | undefined;
107
+ /** Why the session cannot be archived, if it cannot. */
108
+ archiveBlocked: (session: Session) => string | undefined;
109
+ }
110
+ export declare function menuCommand(action: SessionMenuAction, label: string, run: () => void, disabledReason?: string | undefined, shortcut?: string | undefined): SessionMenuCommand;
111
+ /** A session's actions and the flows behind them: the list is patched as
112
+ * soon as the daemon agrees, and deleting or archiving the open session
113
+ * shows the start rather than a transcript that is gone or shut down. */
114
+ export declare function useSessionActions<R = unknown>({ api, machineById, open, confirm, onRefusal, onWarning, showStart, showSession, }: SessionActionsOptions<R>): SessionActions<R>;
115
+ export {};
@@ -0,0 +1,186 @@
1
+ import { isMachineDown } from "./machine.js";
2
+ import { usePwCodeTranslations } from "./messages.js";
3
+ import { isArchived, isMidTurn, isSession } from "./session.js";
4
+ import { machineHint, sessionLabel, sessionStatusText } from "./wording.js";
5
+ import { useState } from "react";
6
+ // src/sessionActions.ts
7
+ var DELETE_KEYS = ["Backspace", "Delete"];
8
+ var ARCHIVE_KEY = "A";
9
+ /** A name as typed, without the spaces around it; undefined when nothing else was typed. */
10
+ function nameToSave(name) {
11
+ return name.trim() || void 0;
12
+ }
13
+ function machineBlocked(machine, t) {
14
+ return isMachineDown(machine) ? machineHint(machine, t)?.text : void 0;
15
+ }
16
+ /** The daemon refuses these for a session another host holds. */
17
+ function sessionActionBlocked(session, machine, t) {
18
+ if (isMachineDown(machine)) return machineBlocked(machine, t);
19
+ if (session.status === "live_elsewhere") return sessionStatusText(session, t);
20
+ }
21
+ function menuCommand(action, label, run, disabledReason, shortcut) {
22
+ return {
23
+ action,
24
+ label,
25
+ run,
26
+ ...disabledReason ? { disabledReason } : {},
27
+ ...shortcut ? { shortcut } : {}
28
+ };
29
+ }
30
+ /** A session's actions and the flows behind them: the list is patched as
31
+ * soon as the daemon agrees, and deleting or archiving the open session
32
+ * shows the start rather than a transcript that is gone or shut down. */
33
+ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarning, showStart, showSession }) {
34
+ const t = usePwCodeTranslations("agents");
35
+ const { archiveSession, deleteSession, forkSession, groupSession, pinSession, renameSession, restoreSession, stopSession } = api.useSessionMutations();
36
+ const [toRename, setToRename] = useState(null);
37
+ const [name, setName] = useState("");
38
+ const closeRename = () => {
39
+ setToRename(null);
40
+ setName("");
41
+ };
42
+ const confirmRename = async () => {
43
+ const saved = nameToSave(name);
44
+ if (toRename === null || !saved) return;
45
+ const refusal = await renameSession(toRename, saved).catch((thrown) => thrown);
46
+ if (refusal) {
47
+ onRefusal(refusal);
48
+ return;
49
+ }
50
+ closeRename();
51
+ };
52
+ const isOpen = (s) => isSession(s, open.machine, open.sessionId);
53
+ const report = (refusal) => {
54
+ if (refusal) onRefusal(refusal);
55
+ };
56
+ const settle = (action) => void action.then(report, report);
57
+ const requestRename = (s) => {
58
+ setName(s.name || s.autoName || "");
59
+ setToRename(s);
60
+ };
61
+ const requestDelete = (s, row, fromKey = false) => confirm({
62
+ action: "delete",
63
+ session: s,
64
+ title: t("sidebar.deleteTitle"),
65
+ description: t("sidebar.deleteBody", {
66
+ name: sessionLabel(s, t),
67
+ machine: machineById.get(s.machineId)?.name ?? ""
68
+ }),
69
+ confirmLabel: t("sidebar.deleteAction"),
70
+ destructive: true,
71
+ offersWorktreeRemoval: true,
72
+ removes: row,
73
+ fromKey,
74
+ onConfirm: async (removeWorktree) => {
75
+ const refusal = await deleteSession(s, removeWorktree);
76
+ if (refusal) throw refusal;
77
+ if (isOpen(s)) showStart();
78
+ }
79
+ });
80
+ const requestArchive = (s, row) => confirm({
81
+ action: "archive",
82
+ session: s,
83
+ title: t("sidebar.archiveTitle", { name: sessionLabel(s, t) }),
84
+ description: t("sidebar.archiveBody"),
85
+ confirmLabel: t("sidebar.archive"),
86
+ destructive: false,
87
+ offersWorktreeRemoval: false,
88
+ removes: row,
89
+ onConfirm: async () => {
90
+ const refusal = await archiveSession(s);
91
+ if (refusal) throw refusal;
92
+ if (isOpen(s)) showStart();
93
+ }
94
+ });
95
+ const requestLeaveWorktree = (s, worktree) => confirm({
96
+ action: "leaveWorktree",
97
+ session: s,
98
+ title: t("sidebar.leaveWorktreeTitle"),
99
+ description: t("sidebar.leaveWorktreeBody", { workspace: s.workspace }),
100
+ confirmLabel: t("sidebar.leaveWorktree"),
101
+ destructive: false,
102
+ offersWorktreeRemoval: true,
103
+ onConfirm: async (removeWorktree) => {
104
+ const { left, refusal } = await api.leaveWorktree(s, removeWorktree);
105
+ if (refusal) throw refusal;
106
+ worktree.refresh();
107
+ if (left?.outcome === "remove_failed") onWarning(t("sidebar.leaveWorktreeKept"));
108
+ }
109
+ });
110
+ const restore = (s) => settle(restoreSession(s));
111
+ const stop = (s) => settle(stopSession(s));
112
+ const togglePin = (s) => settle(pinSession(s, !s.pinnedAt));
113
+ const moveToGroup = (s, group) => settle(groupSession(s, group));
114
+ const fork = (s) => settle(forkSession(s).then(({ forked, refusal }) => {
115
+ if (forked) showSession(forked);
116
+ return refusal;
117
+ }));
118
+ const menu = (session, row, worktree) => {
119
+ const machine = machineById.get(session.machineId);
120
+ const disabledReason = sessionActionBlocked(session, machine, t);
121
+ const machineDown = machineBlocked(machine, t);
122
+ const rowKey = (key) => row === void 0 ? void 0 : key;
123
+ const rename = menuCommand("rename", t("sidebar.renameAction"), () => requestRename(session), disabledReason);
124
+ const remove = {
125
+ ...menuCommand("delete", t("sidebar.deleteAction"), () => requestDelete(session, row), disabledReason, rowKey(DELETE_KEYS[0])),
126
+ destructive: true
127
+ };
128
+ if (isArchived(session)) return [
129
+ menuCommand("restore", t("sidebar.restore"), () => restore(session), machineDown),
130
+ rename,
131
+ "divider",
132
+ remove
133
+ ];
134
+ const midTurn = isMidTurn(session) ? t("sidebar.forkMidTurn") : void 0;
135
+ return [
136
+ rename,
137
+ menuCommand(session.pinnedAt ? "unpin" : "pin", session.pinnedAt ? t("sidebar.unpin") : t("sidebar.pin"), () => togglePin(session), machineDown),
138
+ menuCommand("fork", t("sidebar.fork"), () => fork(session), disabledReason ?? midTurn),
139
+ ...worktree ? [menuCommand("leaveWorktree", t("sidebar.leaveWorktree"), () => requestLeaveWorktree(session, worktree), disabledReason ?? midTurn)] : [],
140
+ ...isMidTurn(session) ? [menuCommand("stop", t("sidebar.stop"), () => stop(session), machineDown)] : [],
141
+ menuCommand("archive", t("sidebar.archive"), () => requestArchive(session, row), disabledReason, rowKey(ARCHIVE_KEY)),
142
+ "divider",
143
+ remove
144
+ ];
145
+ };
146
+ const shortcuts = (session) => {
147
+ if (sessionActionBlocked(session, machineById.get(session.machineId), t)) return [];
148
+ return [{
149
+ keys: DELETE_KEYS,
150
+ run: (row) => requestDelete(session, row, true)
151
+ }, ...isArchived(session) ? [] : [{
152
+ keys: ARCHIVE_KEY,
153
+ run: (row) => requestArchive(session, row)
154
+ }]];
155
+ };
156
+ return {
157
+ menu,
158
+ shortcuts,
159
+ rename: {
160
+ session: toRename,
161
+ name,
162
+ setName,
163
+ confirm: confirmRename,
164
+ close: closeRename,
165
+ title: t("sidebar.renameTitle"),
166
+ label: t("sidebar.renameLabel"),
167
+ placeholder: t("sidebar.renamePlaceholder"),
168
+ confirmLabel: t("sidebar.renameAction")
169
+ },
170
+ requestRename,
171
+ requestDelete,
172
+ requestArchive,
173
+ requestLeaveWorktree,
174
+ restore,
175
+ stop,
176
+ togglePin,
177
+ fork,
178
+ moveToGroup,
179
+ groupBlocked: (session) => {
180
+ const machine = machineById.get(session.machineId);
181
+ return machineBlocked(machine, t) ?? (machine?.sessionGroups ? void 0 : t("sidebar.groupsNeedUpdate", { machine: machine?.name ?? "" }));
182
+ },
183
+ archiveBlocked: (session) => sessionActionBlocked(session, machineById.get(session.machineId), t)
184
+ };
185
+ }
186
+ export { DELETE_KEYS, menuCommand, nameToSave, useSessionActions };
@@ -10,14 +10,19 @@ export interface PwCodeSocketOptions {
10
10
  * frames are applied as they arrive. */
11
11
  hidden?: (() => boolean) | undefined;
12
12
  }
13
- /** The path a session's event feed is served at, resuming after frame `after`. */
14
- export declare function sessionEventsPath(machine: string, id: string, after: number): string;
13
+ /** The path a session's event feed is served at, resuming after frame `after`.
14
+ * With `previewsByRef` the images a tool read come without their previews,
15
+ * which the host loads by URL: a preview is tens of kilobytes, and over a slow
16
+ * connection what the session says next waits behind it. */
17
+ export declare function sessionEventsPath(machine: string, id: string, after: number, previewsByRef?: boolean): string;
15
18
  /** Frames after which the list of subagents may read differently: one started
16
19
  * or ended, one asked for or got an approval, or a turn began or closed. */
17
20
  export declare function changesSubagents(ev: StreamEvent): boolean;
18
21
  /** `machines` with each one in `fed` that the listing lost counted as connected. */
19
22
  export declare function reachedByFeed(machines: Machine[], fed: ReadonlySet<string>): Machine[];
20
- export declare function sessionEvents({ openSocket, hidden }: PwCodeSocketOptions): {
23
+ export declare function sessionEvents({ openSocket, hidden, previewsByRef, }: PwCodeSocketOptions & {
24
+ previewsByRef?: boolean | undefined;
25
+ }): {
21
26
  useSessionEvents: (machine: string, id: string, cursor: (() => number) | undefined, onEvent: (event: StreamEvent) => void) => {
22
27
  connected: boolean;
23
28
  disconnected: boolean;