@parallelworks/code 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +598 -113
  2. package/dist/accountApi.d.ts +31 -0
  3. package/dist/accountApi.js +182 -0
  4. package/dist/agentSwitcher.d.ts +109 -0
  5. package/dist/agentSwitcher.js +165 -0
  6. package/dist/ago.d.ts +3 -3
  7. package/dist/ago.js +10 -10
  8. package/dist/allocations.d.ts +41 -0
  9. package/dist/allocations.js +76 -0
  10. package/dist/api.d.ts +1080 -11
  11. package/dist/chatStrings.d.ts +188 -0
  12. package/dist/chatStrings.js +217 -0
  13. package/dist/claudeAccounts.d.ts +38 -1
  14. package/dist/claudeAccounts.js +98 -4
  15. package/dist/claudeApi.js +1 -1
  16. package/dist/claudeSignIn.d.ts +19 -1
  17. package/dist/claudeSignIn.js +12 -2
  18. package/dist/commandsApi.d.ts +11 -1
  19. package/dist/commandsApi.js +24 -5
  20. package/dist/createPwCodeApi.d.ts +44 -5
  21. package/dist/createPwCodeApi.js +18 -2
  22. package/dist/directories.d.ts +161 -0
  23. package/dist/directories.js +301 -0
  24. package/dist/goal.d.ts +89 -0
  25. package/dist/goal.js +164 -0
  26. package/dist/imageFit.d.ts +23 -0
  27. package/dist/imageFit.js +27 -0
  28. package/dist/images.d.ts +28 -0
  29. package/dist/images.js +38 -6
  30. package/dist/index.d.ts +27 -12
  31. package/dist/index.js +26 -12
  32. package/dist/loadError.d.ts +8 -0
  33. package/dist/loadError.js +19 -0
  34. package/dist/locales/en/agentTranscript.js +73 -12
  35. package/dist/locales/en/agents.js +71 -9
  36. package/dist/locales/en.d.ts +124 -8
  37. package/dist/locales/es/agentTranscript.js +73 -12
  38. package/dist/locales/es/agents.js +71 -9
  39. package/dist/locales/ja/agentTranscript.js +76 -15
  40. package/dist/locales/ja/agents.js +45 -120
  41. package/dist/locales/ko/agentTranscript.js +73 -12
  42. package/dist/locales/ko/agents.js +71 -9
  43. package/dist/locales/zh/agentTranscript.js +71 -10
  44. package/dist/locales/zh/agents.js +71 -9
  45. package/dist/machine.d.ts +2 -0
  46. package/dist/modelPicker.d.ts +79 -0
  47. package/dist/modelPicker.js +107 -0
  48. package/dist/notices.js +47 -19
  49. package/dist/platformDefaults.d.ts +22 -0
  50. package/dist/platformDefaults.js +30 -0
  51. package/dist/preferences.d.ts +78 -0
  52. package/dist/preferences.js +128 -0
  53. package/dist/pullRequestList.d.ts +10 -2
  54. package/dist/pullRequestList.js +41 -22
  55. package/dist/query.d.ts +6 -2
  56. package/dist/query.js +85 -10
  57. package/dist/session.d.ts +5 -2
  58. package/dist/session.js +12 -8
  59. package/dist/sessionActions.d.ts +11 -1
  60. package/dist/sessionActions.js +14 -6
  61. package/dist/sessionEvents.d.ts +8 -3
  62. package/dist/sessionEvents.js +10 -5
  63. package/dist/sessionGroups.d.ts +3 -2
  64. package/dist/sessionGroups.js +4 -3
  65. package/dist/sessionList.d.ts +57 -9
  66. package/dist/sessionList.js +74 -12
  67. package/dist/sessionScreen.d.ts +193 -0
  68. package/dist/sessionScreen.js +213 -0
  69. package/dist/sessionsApi.d.ts +13 -3
  70. package/dist/sessionsApi.js +88 -29
  71. package/dist/settingsApi.d.ts +3 -1
  72. package/dist/startPage.d.ts +153 -0
  73. package/dist/startPage.js +174 -0
  74. package/dist/startSession.d.ts +41 -7
  75. package/dist/startSession.js +26 -4
  76. package/dist/transcript.js +48 -15
  77. package/dist/types.d.ts +11 -1
  78. package/dist/useComposer.d.ts +25 -1
  79. package/dist/useComposer.js +54 -3
  80. package/dist/useComposerImages.d.ts +5 -0
  81. package/dist/useComposerImages.js +24 -1
  82. package/dist/useComposerPastes.d.ts +70 -0
  83. package/dist/useComposerPastes.js +130 -0
  84. package/dist/useConversation.d.ts +10 -1
  85. package/dist/useConversation.js +32 -5
  86. package/dist/useSubagent.d.ts +49 -3
  87. package/dist/useSubagent.js +70 -7
  88. package/dist/useTranscript.d.ts +23 -3
  89. package/dist/useTranscript.js +76 -19
  90. package/dist/wording.js +2 -2
  91. package/dist/workingDirectories.d.ts +31 -0
  92. package/dist/workingDirectories.js +25 -1
  93. package/locales/en/agentTranscript.json +67 -11
  94. package/locales/en/agents.json +68 -8
  95. package/locales/es/agentTranscript.json +67 -11
  96. package/locales/es/agents.json +68 -8
  97. package/locales/ja/agentTranscript.json +70 -14
  98. package/locales/ja/agents.json +68 -8
  99. package/locales/ko/agentTranscript.json +67 -11
  100. package/locales/ko/agents.json +68 -8
  101. package/locales/zh/agentTranscript.json +65 -9
  102. package/locales/zh/agents.json +68 -8
  103. package/package.json +6 -3
@@ -0,0 +1,78 @@
1
+ import { type EffortLevel, type PermissionMode } from '@parallelworks/ui/ai/headless';
2
+ import { type Dispatch, type SetStateAction } from 'react';
3
+ import type { SessionGroup } from './sessionGroups.js';
4
+ import type { PwCodeLastModel } from './startSession.js';
5
+ /** A choice kept in the reader's account, which every client reads and
6
+ * writes under `key`; `fallback` stands until one is saved. */
7
+ export interface PwCodePreference<T> {
8
+ key: string;
9
+ fallback: T;
10
+ }
11
+ /** A preference as `useState` returns it: its value, and its setter. */
12
+ export type PwCodePreferenceState<T> = readonly [T, Dispatch<SetStateAction<T>>];
13
+ /** The key a preference is saved under in the account, which refuses a dot. */
14
+ export declare function preferenceKey(key: string): string;
15
+ export declare const startModePreference: PwCodePreference<PermissionMode>;
16
+ /** Empty starts a session at the machine's own pw code setting. */
17
+ export declare const startEffortPreference: PwCodePreference<string>;
18
+ /** The id of the machine new sessions were last started on. */
19
+ export declare const startMachinePreference: PwCodePreference<string>;
20
+ /** Each machine's account, by machine id. */
21
+ export declare const startAccountPreference: PwCodePreference<Record<string, string>>;
22
+ export declare const lastModelPreference: PwCodePreference<PwCodeLastModel>;
23
+ /** The model an AI chat last picked, which cannot be a Claude model. */
24
+ export declare const chatModelPreference: PwCodePreference<string | null>;
25
+ /** The keys of the session list's folded sections, which `useSessionList`
26
+ * takes as `folded`. */
27
+ export declare const foldedGroupsPreference: PwCodePreference<string[]>;
28
+ /** Whether a folder tree shows hidden folders, a choice the platform's file
29
+ * browser shares. */
30
+ export declare const showHiddenPreference: PwCodePreference<boolean>;
31
+ /** The reader's session groups, kept per user: a copy kept on a shared
32
+ * device would otherwise go to whoever signs in next, or to a user being
33
+ * impersonated. */
34
+ export declare function sessionGroupsPreference(userId: string): PwCodePreference<SessionGroup[]>;
35
+ /** The mode new sessions start in. Bypass is never kept, as in pw code, so a
36
+ * later session never starts in it unasked. */
37
+ export declare function useStartModePreference([saved, save,]: PwCodePreferenceState<PermissionMode>): {
38
+ saved: PermissionMode;
39
+ remember: (mode: PermissionMode) => void;
40
+ };
41
+ /** The effort new sessions start at; empty, or a level no longer offered,
42
+ * starts them at the machine's own. */
43
+ export declare function useStartEffortPreference([saved, save,]: PwCodePreferenceState<string>): {
44
+ saved: EffortLevel | '';
45
+ remember: (effort: string) => void;
46
+ };
47
+ /** The machine picked last, which `useStartLocation` starts on while it can. */
48
+ export declare function useStartMachinePreference([saved, save,]: PwCodePreferenceState<string>): {
49
+ saved: string | undefined;
50
+ remember: (id: string) => void;
51
+ };
52
+ /** The Claude Code account new sessions on `machine` start on. Kept per
53
+ * machine, whose accounts are its own, so a pick here never changes the one
54
+ * pw code starts on there. */
55
+ export declare function useStartAccountPreference([accounts, save]: PwCodePreferenceState<Record<string, string>>, machine: string | undefined): {
56
+ saved: string | undefined;
57
+ remember: (account: string) => void;
58
+ };
59
+ /** What an open session's settings report, so new sessions start where the
60
+ * reader last set one: the mode and effort as they are picked, and the
61
+ * account once the machine takes it, kept for that machine. Each follows
62
+ * its start preference's own rule. */
63
+ export declare function useStartDefaultsFromSession(preferences: {
64
+ mode: PwCodePreferenceState<PermissionMode>;
65
+ effort: PwCodePreferenceState<string>;
66
+ account: PwCodePreferenceState<Record<string, string>>;
67
+ }, machine: string): {
68
+ onModePicked: (mode: PermissionMode) => void;
69
+ onEffortPicked: (effort: string) => void;
70
+ onAccountSaved: (account: string) => void;
71
+ };
72
+ /** The model last picked for a session, and the allocation it billed. Kept
73
+ * apart from the chat's model, which cannot be a Claude one; a Claude pick
74
+ * bills no allocation, so the platform one waits for the next pick. */
75
+ export declare function useLastModelPreference([last, setLast,]: PwCodePreferenceState<PwCodeLastModel>): {
76
+ last: PwCodeLastModel;
77
+ remember: (model: string, allocation: string | null | undefined) => void;
78
+ };
@@ -0,0 +1,128 @@
1
+ import { useCallback } from "react";
2
+ import { isEffortLevel } from "@parallelworks/ui/ai/headless";
3
+ // src/preferences.ts
4
+ /** The key a preference is saved under in the account, which refuses a dot. */
5
+ function preferenceKey(key) {
6
+ return key.replaceAll(".", ":");
7
+ }
8
+ var startModePreference = {
9
+ key: "agents:startMode",
10
+ fallback: "auto"
11
+ };
12
+ /** Empty starts a session at the machine's own pw code setting. */
13
+ var startEffortPreference = {
14
+ key: "agents:startEffort",
15
+ fallback: ""
16
+ };
17
+ /** The id of the machine new sessions were last started on. */
18
+ var startMachinePreference = {
19
+ key: "agents:startMachine",
20
+ fallback: ""
21
+ };
22
+ /** Each machine's account, by machine id. */
23
+ var startAccountPreference = {
24
+ key: "agents:startAccount",
25
+ fallback: {}
26
+ };
27
+ var lastModelPreference = {
28
+ key: "agents:lastModel",
29
+ fallback: {}
30
+ };
31
+ /** The model an AI chat last picked, which cannot be a Claude model. */
32
+ var chatModelPreference = {
33
+ key: "aiChat:model",
34
+ fallback: null
35
+ };
36
+ /** The keys of the session list's folded sections, which `useSessionList`
37
+ * takes as `folded`. */
38
+ var foldedGroupsPreference = {
39
+ key: "aiChatSidebarCollapsedGroups",
40
+ fallback: []
41
+ };
42
+ /** Whether a folder tree shows hidden folders, a choice the platform's file
43
+ * browser shares. */
44
+ var showHiddenPreference = {
45
+ key: "computeExplorer:showHidden",
46
+ fallback: false
47
+ };
48
+ var NO_GROUPS = [];
49
+ /** The reader's session groups, kept per user: a copy kept on a shared
50
+ * device would otherwise go to whoever signs in next, or to a user being
51
+ * impersonated. */
52
+ function sessionGroupsPreference(userId) {
53
+ return {
54
+ key: `agentsSessionGroups:${userId}`,
55
+ fallback: NO_GROUPS
56
+ };
57
+ }
58
+ /** The mode new sessions start in. Bypass is never kept, as in pw code, so a
59
+ * later session never starts in it unasked. */
60
+ function useStartModePreference([saved, save]) {
61
+ return {
62
+ saved,
63
+ remember: useCallback((mode) => {
64
+ if (mode !== "bypass-permissions") save(mode);
65
+ }, [save])
66
+ };
67
+ }
68
+ /** The effort new sessions start at; empty, or a level no longer offered,
69
+ * starts them at the machine's own. */
70
+ function useStartEffortPreference([saved, save]) {
71
+ const remember = useCallback((effort) => save(isEffortLevel(effort) ? effort : ""), [save]);
72
+ return {
73
+ saved: isEffortLevel(saved) ? saved : "",
74
+ remember
75
+ };
76
+ }
77
+ /** The machine picked last, which `useStartLocation` starts on while it can. */
78
+ function useStartMachinePreference([saved, save]) {
79
+ const remember = useCallback((id) => save(id), [save]);
80
+ return {
81
+ saved: typeof saved === "string" && saved ? saved : void 0,
82
+ remember
83
+ };
84
+ }
85
+ /** The Claude Code account new sessions on `machine` start on. Kept per
86
+ * machine, whose accounts are its own, so a pick here never changes the one
87
+ * pw code starts on there. */
88
+ function useStartAccountPreference([accounts, save], machine) {
89
+ const remember = useCallback((account) => {
90
+ if (machine) save((previous) => ({
91
+ ...previous,
92
+ [machine]: account
93
+ }));
94
+ }, [machine, save]);
95
+ const saved = machine ? accounts[machine] : void 0;
96
+ return {
97
+ saved: typeof saved === "string" ? saved : void 0,
98
+ remember
99
+ };
100
+ }
101
+ /** What an open session's settings report, so new sessions start where the
102
+ * reader last set one: the mode and effort as they are picked, and the
103
+ * account once the machine takes it, kept for that machine. Each follows
104
+ * its start preference's own rule. */
105
+ function useStartDefaultsFromSession(preferences, machine) {
106
+ const { remember: onModePicked } = useStartModePreference(preferences.mode);
107
+ const { remember: onEffortPicked } = useStartEffortPreference(preferences.effort);
108
+ const { remember: onAccountSaved } = useStartAccountPreference(preferences.account, machine);
109
+ return {
110
+ onModePicked,
111
+ onEffortPicked,
112
+ onAccountSaved
113
+ };
114
+ }
115
+ /** The model last picked for a session, and the allocation it billed. Kept
116
+ * apart from the chat's model, which cannot be a Claude one; a Claude pick
117
+ * bills no allocation, so the platform one waits for the next pick. */
118
+ function useLastModelPreference([last, setLast]) {
119
+ const remember = (model, allocation) => setLast((previous) => ({
120
+ model,
121
+ allocation: allocation || previous.allocation
122
+ }));
123
+ return {
124
+ last,
125
+ remember
126
+ };
127
+ }
128
+ export { chatModelPreference, foldedGroupsPreference, lastModelPreference, preferenceKey, sessionGroupsPreference, showHiddenPreference, startAccountPreference, startEffortPreference, startMachinePreference, startModePreference, useLastModelPreference, useStartAccountPreference, useStartDefaultsFromSession, useStartEffortPreference, useStartMachinePreference, useStartModePreference };
@@ -20,8 +20,10 @@ export declare function pullRequestStateOf(states: readonly {
20
20
  export declare function orderPullRequests(pullRequests: readonly LabeledPullRequest[], stateOf: PullRequestStateOf): LabeledPullRequest[];
21
21
  /** Whether each pull request folds into the merged-or-closed count rather than the open one. */
22
22
  export declare function pullRequestFoldGroups(ordered: readonly LabeledPullRequest[], stateOf: PullRequestStateOf): boolean[];
23
+ /** 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. */
24
+ export declare const FOLD_DONE_PULL_REQUESTS_FROM = 2;
23
25
  /** 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. */
24
- export declare function donePullRequestsToFold(ordered: readonly LabeledPullRequest[], stateOf: PullRequestStateOf, from: number): number;
26
+ export declare function donePullRequestsToFold(ordered: readonly LabeledPullRequest[], stateOf: PullRequestStateOf, from?: number): number;
25
27
  /** Folded pull requests count apart while open or draft and once merged or closed; `all` counts every one, for a line with room for nothing else. */
26
28
  export type PullRequestFoldGroup = 'open' | 'done' | 'all';
27
29
  export type PullRequestFold = {
@@ -37,6 +39,11 @@ export declare function foldPullRequests(ordered: readonly LabeledPullRequest[],
37
39
  export declare function pullRequestGroupState(group: readonly LabeledPullRequest[], stateOf: PullRequestStateOf): PullRequestState | undefined;
38
40
  /** Whether each pull request's state differs from the one before it, where a list marks the change. */
39
41
  export declare function pullRequestStateBreaks(pullRequests: readonly LabeledPullRequest[], stateOf: PullRequestStateOf): boolean[];
42
+ /** The tone a pull request's state shows in, as the forges color them: `done`
43
+ * is their purple for merged work. */
44
+ export type PullRequestTone = 'success' | 'muted' | 'done' | 'error';
45
+ export declare function pullRequestTone(state: PullRequestState): PullRequestTone;
46
+ type Translate = PwCodeTranslator<'agents'>;
40
47
  export interface PullRequestWords {
41
48
  /** A pull request's tooltip, naming its state once it is known. */
42
49
  title: (pr: string, state: string | undefined) => string;
@@ -49,4 +56,5 @@ export interface PullRequestWords {
49
56
  /** The control that lists a folded group. */
50
57
  showGroup: (group: Exclude<PullRequestFoldGroup, 'all'>, count: number) => string;
51
58
  }
52
- export declare function pullRequestWords(t: PwCodeTranslator<'agents'>): PullRequestWords;
59
+ export declare function pullRequestWords(t: Translate): PullRequestWords;
60
+ export {};
@@ -40,8 +40,10 @@ var isDone = (state) => state === "merged" || state === "closed";
40
40
  function pullRequestFoldGroups(ordered, stateOf) {
41
41
  return ordered.map(({ url }) => isDone(stateOf(url)));
42
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;
43
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. */
44
- function donePullRequestsToFold(ordered, stateOf, from) {
46
+ function donePullRequestsToFold(ordered, stateOf, from = 2) {
45
47
  const done = ordered.filter(({ url }) => isDone(stateOf(url))).length;
46
48
  const foldable = done === ordered.length ? done - 1 : done;
47
49
  return foldable >= from ? foldable : 0;
@@ -76,31 +78,48 @@ function pullRequestGroupState(group, stateOf) {
76
78
  function pullRequestStateBreaks(pullRequests, stateOf) {
77
79
  return pullRequests.map(({ url }, i) => i > 0 && stateRank(stateOf(url)) !== stateRank(stateOf(pullRequests[i - 1]?.url ?? "")));
78
80
  }
79
- var stateTitles = {
80
- open: "detail.pullRequestOpen",
81
- draft: "detail.pullRequestDraft",
82
- merged: "detail.pullRequestMerged",
83
- closed: "detail.pullRequestClosed"
84
- };
85
- var groupTitles = {
86
- open: "detail.pullRequestsMoreOpenTitle",
87
- done: "detail.pullRequestsMoreDoneTitle",
88
- all: "detail.pullRequestsMoreAllTitle"
89
- };
90
- var groupLabels = {
91
- open: "detail.pullRequestsShowMoreOpen",
92
- done: "detail.pullRequestsShowMoreDone"
81
+ var stateTones = {
82
+ open: "success",
83
+ draft: "muted",
84
+ merged: "done",
85
+ closed: "error"
93
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
+ }
94
116
  function pullRequestWords(t) {
95
117
  return {
96
- title: (pr, state) => t(isPullRequestState(state) ? stateTitles[state] : "detail.pullRequest", {
97
- pr,
98
- kind: pullRequestKind(pr)
99
- }),
118
+ title: (pr, state) => stateTitle(t, pr, state),
100
119
  state: (state) => t(`detail.pullRequestState.${state}`),
101
120
  more: (count) => t("detail.pullRequestsMore", { count }),
102
- groupTitle: (group, count) => t(groupTitles[group], { count }),
103
- showGroup: (group, count) => t(groupLabels[group], { count })
121
+ groupTitle: (group, count) => groupTitle(t, group, count),
122
+ showGroup: (group, count) => groupLabel(t, group, count)
104
123
  };
105
124
  }
106
- export { donePullRequestsToFold, foldPullRequests, isPullRequestState, labeledPullRequests, orderPullRequests, pullRequestFoldGroups, pullRequestGroupState, pullRequestStateBreaks, pullRequestStateOf, pullRequestWords };
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
@@ -20,6 +20,7 @@ export interface PwCodeSession {
20
20
  group?: string | undefined;
21
21
  /** Links to the pull requests the session opened or was pointed at. */
22
22
  pullRequests?: string[] | null | undefined;
23
+ createdAt?: string | undefined;
23
24
  updatedAt?: string | undefined;
24
25
  turnStartedAt?: string | undefined;
25
26
  workspace?: string | undefined;
@@ -62,12 +63,14 @@ export interface RecentDirectory {
62
63
  sessions: number;
63
64
  updatedAt: string;
64
65
  }
65
- /** The daemon offers no way to browse, so the machine's own sessions are the
66
- * only paths we can honestly suggest. */
66
+ /** The directories the machine's sessions worked in, newest first. */
67
67
  export declare function recentDirectories(sessions: readonly Pick<PwCodeSession, 'machineId' | 'workspace' | 'updatedAt'>[], machineId: string | undefined): RecentDirectory[];
68
68
  export declare function newestFirst<T extends {
69
69
  updatedAt?: string | undefined;
70
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[];
71
74
  /** An approval blocks the agent and goes first; a running turn is context;
72
75
  * everything else is what the reader last touched, newest first. */
73
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 };
@@ -3,6 +3,7 @@ import type { PwCodeApi } from './createPwCodeApi.js';
3
3
  import { type PwCodeMachine } from './machine.js';
4
4
  import type { PwCodeWorktreeRef } from './sessionHeader.js';
5
5
  type Session = Schemas['AgentSession'];
6
+ export declare const DELETE_KEYS: readonly ['Backspace', 'Delete'];
6
7
  /** The session the reader has open, if any. */
7
8
  export interface OpenSessionRef {
8
9
  machine?: string | undefined;
@@ -53,8 +54,17 @@ export interface SessionConfirmation<R> {
53
54
  /** Rejects with the machine's refusal, for the host to show while it still asks. */
54
55
  onConfirm: (removeWorktree?: string) => Promise<void>;
55
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;
56
66
  /** The session being renamed while the host's prompt for its name is up. */
57
- export interface SessionRename {
67
+ export interface SessionRename extends NamePromptWords {
58
68
  session: Session | null;
59
69
  name: string;
60
70
  setName: (name: string) => void;
@@ -6,6 +6,10 @@ import { useState } from "react";
6
6
  // src/sessionActions.ts
7
7
  var DELETE_KEYS = ["Backspace", "Delete"];
8
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
+ }
9
13
  function machineBlocked(machine, t) {
10
14
  return isMachineDown(machine) ? machineHint(machine, t)?.text : void 0;
11
15
  }
@@ -36,9 +40,9 @@ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarni
36
40
  setName("");
37
41
  };
38
42
  const confirmRename = async () => {
39
- const trimmed = name.trim();
40
- if (toRename === null || !trimmed) return;
41
- const refusal = await renameSession(toRename, trimmed).catch((thrown) => thrown);
43
+ const saved = nameToSave(name);
44
+ if (toRename === null || !saved) return;
45
+ const refusal = await renameSession(toRename, saved).catch((thrown) => thrown);
42
46
  if (refusal) {
43
47
  onRefusal(refusal);
44
48
  return;
@@ -130,7 +134,7 @@ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarni
130
134
  const midTurn = isMidTurn(session) ? t("sidebar.forkMidTurn") : void 0;
131
135
  return [
132
136
  rename,
133
- menuCommand(session.pinnedAt ? "unpin" : "pin", t(session.pinnedAt ? "sidebar.unpin" : "sidebar.pin"), () => togglePin(session), machineDown),
137
+ menuCommand(session.pinnedAt ? "unpin" : "pin", session.pinnedAt ? t("sidebar.unpin") : t("sidebar.pin"), () => togglePin(session), machineDown),
134
138
  menuCommand("fork", t("sidebar.fork"), () => fork(session), disabledReason ?? midTurn),
135
139
  ...worktree ? [menuCommand("leaveWorktree", t("sidebar.leaveWorktree"), () => requestLeaveWorktree(session, worktree), disabledReason ?? midTurn)] : [],
136
140
  ...isMidTurn(session) ? [menuCommand("stop", t("sidebar.stop"), () => stop(session), machineDown)] : [],
@@ -157,7 +161,11 @@ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarni
157
161
  name,
158
162
  setName,
159
163
  confirm: confirmRename,
160
- close: closeRename
164
+ close: closeRename,
165
+ title: t("sidebar.renameTitle"),
166
+ label: t("sidebar.renameLabel"),
167
+ placeholder: t("sidebar.renamePlaceholder"),
168
+ confirmLabel: t("sidebar.renameAction")
161
169
  },
162
170
  requestRename,
163
171
  requestDelete,
@@ -175,4 +183,4 @@ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarni
175
183
  archiveBlocked: (session) => sessionActionBlocked(session, machineById.get(session.machineId), t)
176
184
  };
177
185
  }
178
- export { menuCommand, useSessionActions };
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;