@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,107 @@
1
+ import { usePwCodeTranslations } from "./messages.js";
2
+ import { isClaudeModel, modelLabel, useModelCatalog } from "./models.js";
3
+ // src/modelPicker.ts
4
+ /** The issue that keeps a model's connection from serving it, if any. */
5
+ function providerIssueOf(issues, model) {
6
+ if (!model.provider_name) return;
7
+ return issues.find((issue) => issue.provider_name === model.provider_name && (issue.provider_owner ?? "") === (model.provider_owner ?? ""));
8
+ }
9
+ function groupDescription(model, issue, reader, t) {
10
+ const owner = model.provider_owner;
11
+ return [owner && owner !== "org" && owner !== reader ? t("modelPicker.sharedBy", { owner }) : "", issue ? issue.status === "unauthorized" ? t("providerIssue.keyRejected") : t("providerIssue.unreachable") : ""].filter(Boolean).join(" · ") || void 0;
12
+ }
13
+ /** The platform's models grouped by provider, the id's prefix. A connection
14
+ * that cannot serve its models leaves them listed, disabled, and its group
15
+ * says why; models another user shares name them. */
16
+ function modelGroups(models, issues, reader, t) {
17
+ const groups = /* @__PURE__ */ new Map();
18
+ for (const model of models) {
19
+ const key = model.id.split("/")[0] ?? model.provider ?? "";
20
+ const issue = providerIssueOf(issues, model);
21
+ let group = groups.get(key);
22
+ if (!group) {
23
+ group = {
24
+ label: model.provider || key,
25
+ description: groupDescription(model, issue, reader, t),
26
+ items: []
27
+ };
28
+ groups.set(key, group);
29
+ }
30
+ group.items = [...group.items, {
31
+ value: model.id,
32
+ label: modelLabel(model.id, model.name),
33
+ disabled: !!issue
34
+ }];
35
+ }
36
+ return [...groups.values()];
37
+ }
38
+ /** Why the platform offers no model: still loading, failed, or none. */
39
+ function platformModelStatus(list, t) {
40
+ if (list.error) return t("modelPicker.failed");
41
+ return list.isLoading ? t("modelPicker.loading") : t("modelPicker.none");
42
+ }
43
+ var ACCOUNTS_CHOICE = "claude-code-accounts";
44
+ var REFRESH_CHOICE = "refresh";
45
+ /** One picker for the platform's models and the machine's Claude ones. A
46
+ * model picked is remembered with the allocation it bills; the Claude
47
+ * accounts choice opens them instead, and the refresh choice reads both
48
+ * lists again. Which model and allocation stand before a pick is the host's. */
49
+ function useModelPicker(api, { machine, sessionId, claudeReady, canStart, account, open, model, allocation, platform, reader, names, errorMessage, remember, onAccounts }) {
50
+ const t = usePwCodeTranslations("agents");
51
+ const words = usePwCodeTranslations("agentTranscript");
52
+ const catalog = useModelCatalog(api, {
53
+ machine,
54
+ sessionId,
55
+ claudeReady,
56
+ canStart,
57
+ model: model.value,
58
+ account,
59
+ open
60
+ });
61
+ const groups = modelGroups(platform.models, platform.providerIssues, reader, words);
62
+ if (platform.models.length === 0) groups.push({
63
+ label: t("claude.platformModels"),
64
+ description: platformModelStatus(platform, words),
65
+ items: []
66
+ });
67
+ const claudeModels = catalog.models;
68
+ if (claudeReady) groups.push({
69
+ label: t("claude.models"),
70
+ description: catalog.error ? errorMessage(catalog.error) : catalog.isLoading ? t("claude.loadingModels") : void 0,
71
+ items: [...claudeModels.map((entry) => ({
72
+ value: entry.id,
73
+ label: modelLabel(entry.id, entry.name)
74
+ })), {
75
+ value: ACCOUNTS_CHOICE,
76
+ label: t("claude.accounts")
77
+ }]
78
+ });
79
+ const id = model.value ?? "";
80
+ const listed = platform.models.find((m) => m.id === model.value) ?? claudeModels.find((m) => m.id === model.value);
81
+ return {
82
+ entries: [...groups, {
83
+ value: REFRESH_CHOICE,
84
+ label: t("claude.refreshModels")
85
+ }],
86
+ label: modelLabel(id, names?.[id] ?? listed?.name) || words("modelPicker.select"),
87
+ opened: catalog.request,
88
+ pick: (value) => {
89
+ if (value === ACCOUNTS_CHOICE) onAccounts();
90
+ else if (value === REFRESH_CHOICE) {
91
+ catalog.refresh();
92
+ platform.refresh();
93
+ } else if (value) {
94
+ remember(value, allocation.value);
95
+ model.onChange(value);
96
+ }
97
+ },
98
+ allocation: isClaudeModel(model.value) ? null : {
99
+ ...allocation,
100
+ onChange: (next) => {
101
+ if (model.value) remember(model.value, next);
102
+ allocation.onChange(next);
103
+ }
104
+ }
105
+ };
106
+ }
107
+ export { modelGroups, platformModelStatus, providerIssueOf, useModelPicker };
package/dist/notices.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { type PwCodeTranslator } from './messages.js';
2
2
  import type { CompactionNotice, GoalNotice, RecapNotice, TranscriptWords } from './transcript.js';
3
+ /** When a usage limit resets, short enough for a row in a list of sessions. */
4
+ export declare function useResumeClock(): (at: string) => string;
3
5
  /** When a usage limit resets, as a session's notices name it. */
4
6
  export declare function useResumeTime(): (at: string) => string;
5
7
  export declare function useGoalNotice(): GoalNotice;
package/dist/notices.js CHANGED
@@ -1,10 +1,29 @@
1
+ import { goalElapsed } from "./goal.js";
1
2
  import { usePwCodeTranslations } from "./messages.js";
2
3
  import { useCallback, useMemo } from "react";
3
- import { DateTime } from "luxon";
4
4
  import { sanitizeLabel } from "@parallelworks/ui/ai/headless";
5
5
  import { useFormatter, useLocale } from "use-intl";
6
+ import { DateTime } from "luxon";
6
7
  import { formatDuration } from "@parallelworks/ui/headless";
7
8
  // src/notices.ts
9
+ /** The time of day on the day itself, with the weekday within a week and the date beyond. */
10
+ function nearTime(format, at, weekday) {
11
+ const days = Math.abs(Math.round(DateTime.now().startOf("day").diff(at.startOf("day"), "days").days));
12
+ return format.dateTime(at.toJSDate(), {
13
+ hour: "numeric",
14
+ minute: "2-digit",
15
+ ...days > 0 ? { weekday } : {},
16
+ ...days >= 7 ? {
17
+ month: "short",
18
+ day: "numeric"
19
+ } : {}
20
+ });
21
+ }
22
+ /** When a usage limit resets, short enough for a row in a list of sessions. */
23
+ function useResumeClock() {
24
+ const format = useFormatter();
25
+ return useCallback((at) => nearTime(format, DateTime.fromISO(at), "short"), [format]);
26
+ }
8
27
  /** When a usage limit resets, as a session's notices name it. */
9
28
  function useResumeTime() {
10
29
  const format = useFormatter();
@@ -22,13 +41,14 @@ function useGoalNotice() {
22
41
  if (p.resumeAt) return t("detail.goalUsageLimit", { time: resumeTime(p.resumeAt) });
23
42
  if (p.err) return t("detail.goalCheckFailed", { error: p.err });
24
43
  if (p.outcome === "achieved") return t("detail.goalAchieved", {
25
- elapsed: formatDuration(Math.floor((p.elapsedMs ?? 0) / 1e3) * 1e3, locale),
44
+ elapsed: goalElapsed(p.elapsedMs ?? 0, "panel", locale),
26
45
  turns: p.turns ?? 0,
27
46
  tokens: format.number(p.tokens ?? 0, {
28
47
  notation: "compact",
29
48
  maximumFractionDigits: 1
30
49
  })
31
50
  });
51
+ if (p.waitedMs) return t("detail.goalCheckin", { waited: formatDuration(Math.floor(p.waitedMs / 6e4) * 6e4, locale) });
32
52
  return t("detail.goalContinuing");
33
53
  }, [
34
54
  t,
@@ -61,6 +81,48 @@ function turnDuration(t, ms) {
61
81
  minutes: Math.floor(total / 60) % 60
62
82
  });
63
83
  }
84
+ /** A monitor's line: the first line an event's script printed, or how the monitor ended. */
85
+ function monitorLine(t, n, name) {
86
+ const elapsed = turnDuration(t, n.elapsedMs ?? 0);
87
+ switch (n.ended) {
88
+ case "exited": return n.exitCode ? t("detail.monitorFailed", {
89
+ name,
90
+ code: n.exitCode
91
+ }) : t("detail.monitorEnded", { name });
92
+ case "expired": return t("detail.monitorExpired", {
93
+ name,
94
+ elapsed,
95
+ count: n.events ?? 0
96
+ });
97
+ case "flooded": return t("detail.monitorFlooded", {
98
+ name,
99
+ elapsed
100
+ });
101
+ default: return t("detail.monitorEvent", {
102
+ name,
103
+ line: n.preview
104
+ });
105
+ }
106
+ }
107
+ /** The line a background agent's report, a command's end or a monitor's notice enters the conversation with. */
108
+ function deliveryLine(t, n) {
109
+ const name = sanitizeLabel(n.description) || n.id;
110
+ if (n.monitor) return monitorLine(t, n, name);
111
+ if (n.interim) return t("detail.subagentMessage", { name });
112
+ if (n.shell) return n.exitCode ? t("detail.commandFailed", {
113
+ name,
114
+ code: n.exitCode
115
+ }) : t("detail.commandCompleted", { name });
116
+ const outcome = n.failed ? "failed" : "finished";
117
+ return n.elapsedMs ? t("detail.agentEndedAfter", {
118
+ name,
119
+ outcome,
120
+ elapsed: turnDuration(t, n.elapsedMs)
121
+ }) : t("detail.agentEnded", {
122
+ name,
123
+ outcome
124
+ });
125
+ }
64
126
  /** The session's own lines: what a goal step opens to, how a turn ended,
65
127
  * which plan a /plan showed, and how a background task reported back. */
66
128
  function useTranscriptWords() {
@@ -74,41 +136,14 @@ function useTranscriptWords() {
74
136
  }),
75
137
  turnEnd: (te, verb, waiting) => {
76
138
  if (waiting) return t("detail.turnEndWaiting", { count: te.pendingAgents ?? 0 });
77
- const ended = DateTime.fromISO(te.endedAt);
78
- const days = Math.floor(DateTime.now().startOf("day").diff(ended.startOf("day"), "days").days);
79
- const time = format.dateTime(ended.toJSDate(), {
80
- hour: "numeric",
81
- minute: "2-digit",
82
- ...days > 0 ? { weekday: "long" } : {},
83
- ...days >= 7 ? {
84
- month: "short",
85
- day: "numeric"
86
- } : {}
87
- });
88
139
  return t("detail.turnEnd", {
89
140
  verb,
90
141
  duration: turnDuration(t, te.durationMs),
91
- time
142
+ time: nearTime(format, DateTime.fromISO(te.endedAt), "long")
92
143
  });
93
144
  },
94
145
  planAnswer: (path, opened) => opened ? t("detail.planOpened", { path }) : path,
95
- deliveryLine: (n) => {
96
- const name = sanitizeLabel(n.description) || n.id;
97
- if (n.interim) return t("detail.subagentMessage", { name });
98
- if (n.shell) return n.exitCode ? t("detail.commandFailed", {
99
- name,
100
- code: n.exitCode
101
- }) : t("detail.commandCompleted", { name });
102
- const outcome = n.failed ? "failed" : "finished";
103
- return n.elapsedMs ? t("detail.agentEndedAfter", {
104
- name,
105
- outcome,
106
- elapsed: turnDuration(t, n.elapsedMs)
107
- }) : t("detail.agentEnded", {
108
- name,
109
- outcome
110
- });
111
- },
146
+ deliveryLine: (n) => deliveryLine(t, n),
112
147
  allowDirectory: ({ path, subtree }) => subtree ? tTranscript("transcript.allowDirectoryTree", { path }) : tTranscript("transcript.allowDirectoryOnly", { path }),
113
148
  mainConversation: t("switcher.main")
114
149
  }), [
@@ -117,4 +152,4 @@ function useTranscriptWords() {
117
152
  format
118
153
  ]);
119
154
  }
120
- export { turnDuration, useCompactionNotice, useGoalNotice, useRecapNotice, useResumeTime, useTranscriptWords };
155
+ export { turnDuration, useCompactionNotice, useGoalNotice, useRecapNotice, useResumeClock, useResumeTime, useTranscriptWords };
@@ -0,0 +1,22 @@
1
+ import type { PwCodePlatformModels } from './accountApi.js';
2
+ import type { Schemas } from './apiClient.js';
3
+ import type { PwCodeApi } from './createPwCodeApi.js';
4
+ /** The platform model and allocation the AI chat selects, for a host with no
5
+ * chat to take them from. They fit `useStartModel`'s `platform`, and the
6
+ * allocation `useSessionSettings`'s `nativeAllocation`. */
7
+ export interface PwCodePlatformDefaults {
8
+ /** The platform's models, as `useModelPicker`'s `platform` takes them. */
9
+ list: PwCodePlatformModels;
10
+ /** The models once they load; undefined while they load or when they failed to. */
11
+ models: Schemas['ModelEntry'][] | undefined;
12
+ /** The chat model last chosen while the list still offers it, else the
13
+ * first whose provider has no issue, else the first; null until the list loads. */
14
+ model: string | null;
15
+ /** The allocation `model` bills: the first it can charge, once the
16
+ * allocations load; none for a model that bills none. */
17
+ allocation: string | null;
18
+ }
19
+ export declare function usePlatformDefaults(api: Pick<PwCodeApi, 'usePlatformModels' | 'useAllocations'>, { stored, }: {
20
+ /** The chat model last chosen, saved under `chatModelPreference`. */
21
+ stored: string | null | undefined;
22
+ }): PwCodePlatformDefaults;
@@ -0,0 +1,30 @@
1
+ import { aiAllocations, allocationProblem, billsAllocation } from "./allocations.js";
2
+ import { useMemo } from "react";
3
+ import { defaultAllocation, defaultModel } from "@parallelworks/ui/ai/headless";
4
+ // src/platformDefaults.ts
5
+ function usePlatformDefaults(api, { stored }) {
6
+ const list = api.usePlatformModels();
7
+ const model = defaultModel({
8
+ models: list.models,
9
+ providerIssues: list.providerIssues,
10
+ current: null,
11
+ stored: stored ?? null
12
+ });
13
+ const { data } = api.useAllocations(billsAllocation(model));
14
+ const allocations = useMemo(() => data ? aiAllocations(data).map((a) => ({
15
+ name: a.name,
16
+ total: a.total,
17
+ disabled: allocationProblem(a, false) !== null
18
+ })) : void 0, [data]);
19
+ return {
20
+ list,
21
+ models: list.loaded && !list.error ? list.models : void 0,
22
+ model,
23
+ allocation: defaultAllocation({
24
+ model,
25
+ allocations,
26
+ current: null
27
+ })
28
+ };
29
+ }
30
+ export { usePlatformDefaults };
@@ -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,13 @@ 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,
32
+ /** Reads the key some other way than a GET of `path`; `name` is the key,
33
+ * serialized. It throws what the client answered with. */
34
+ readWith?: (name: string, signal: AbortSignal | undefined) => Promise<ReadData<P>>) => SWRResponse<ReadData<P>, PwCodeApiError>;
28
35
  export {};