@parallelworks/code 0.1.0 → 0.3.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 +171 -24
  2. package/dist/ago.d.ts +8 -0
  3. package/dist/ago.js +26 -0
  4. package/dist/api.d.ts +3547 -0
  5. package/dist/apiClient.d.ts +26 -0
  6. package/dist/apiClient.js +5 -0
  7. package/dist/base64.d.ts +3 -0
  8. package/dist/base64.js +15 -0
  9. package/dist/chatHandoff.d.ts +12 -0
  10. package/dist/chatHandoff.js +27 -0
  11. package/dist/claudeAccounts.d.ts +112 -0
  12. package/dist/claudeAccounts.js +234 -0
  13. package/dist/claudeApi.d.ts +27 -0
  14. package/dist/claudeApi.js +250 -0
  15. package/dist/claudeSignIn.d.ts +62 -0
  16. package/dist/claudeSignIn.js +239 -0
  17. package/dist/command.d.ts +47 -0
  18. package/dist/command.js +64 -0
  19. package/dist/commandsApi.d.ts +64 -0
  20. package/dist/commandsApi.js +267 -0
  21. package/dist/contextRow.d.ts +25 -0
  22. package/dist/contextRow.js +16 -0
  23. package/dist/createPwCodeApi.d.ts +696 -0
  24. package/dist/createPwCodeApi.js +33 -0
  25. package/dist/howSessionsAppear.d.ts +12 -0
  26. package/dist/howSessionsAppear.js +24 -0
  27. package/dist/index.d.ts +39 -3
  28. package/dist/index.js +38 -3
  29. package/dist/locales/en/agentTranscript.js +162 -0
  30. package/dist/locales/en/agents.js +380 -0
  31. package/dist/locales/en.d.ts +523 -0
  32. package/dist/locales/en.js +8 -0
  33. package/dist/locales/es/agentTranscript.js +162 -0
  34. package/dist/locales/es/agents.js +380 -0
  35. package/dist/locales/es.d.ts +3 -0
  36. package/dist/locales/es.js +8 -0
  37. package/dist/locales/ja/agentTranscript.js +162 -0
  38. package/dist/locales/ja/agents.js +380 -0
  39. package/dist/locales/ja.d.ts +3 -0
  40. package/dist/locales/ja.js +8 -0
  41. package/dist/locales/ko/agentTranscript.js +162 -0
  42. package/dist/locales/ko/agents.js +380 -0
  43. package/dist/locales/ko.d.ts +3 -0
  44. package/dist/locales/ko.js +8 -0
  45. package/dist/locales/zh/agentTranscript.js +162 -0
  46. package/dist/locales/zh/agents.js +380 -0
  47. package/dist/locales/zh.d.ts +3 -0
  48. package/dist/locales/zh.js +8 -0
  49. package/dist/machine.d.ts +51 -0
  50. package/dist/machine.js +60 -0
  51. package/dist/messages.d.ts +17 -0
  52. package/dist/messages.js +31 -0
  53. package/dist/models.d.ts +47 -0
  54. package/dist/models.js +49 -0
  55. package/dist/notices.d.ts +12 -0
  56. package/dist/notices.js +120 -0
  57. package/dist/pullRequest.d.ts +8 -0
  58. package/dist/pullRequest.js +29 -0
  59. package/dist/pullRequestList.d.ts +52 -0
  60. package/dist/pullRequestList.js +106 -0
  61. package/dist/query.d.ts +28 -0
  62. package/dist/query.js +25 -0
  63. package/dist/session.d.ts +75 -1
  64. package/dist/session.js +101 -1
  65. package/dist/sessionActions.d.ts +105 -0
  66. package/dist/sessionActions.js +178 -0
  67. package/dist/sessionEvents.d.ts +27 -0
  68. package/dist/sessionEvents.js +212 -0
  69. package/dist/sessionGroups.d.ts +49 -0
  70. package/dist/sessionGroups.js +72 -0
  71. package/dist/sessionHeader.d.ts +14 -0
  72. package/dist/sessionHeader.js +16 -0
  73. package/dist/sessionList.d.ts +134 -0
  74. package/dist/sessionList.js +271 -0
  75. package/dist/sessionsApi.d.ts +105 -0
  76. package/dist/sessionsApi.js +511 -0
  77. package/dist/settingsApi.d.ts +36 -0
  78. package/dist/settingsApi.js +151 -0
  79. package/dist/startSession.d.ts +138 -0
  80. package/dist/startSession.js +234 -0
  81. package/dist/terminalHandoffPanel.d.ts +30 -0
  82. package/dist/terminalHandoffPanel.js +33 -0
  83. package/dist/toolStrings.d.ts +4 -0
  84. package/dist/toolStrings.js +95 -0
  85. package/dist/transcript.d.ts +14 -1
  86. package/dist/transcript.js +55 -14
  87. package/dist/types.d.ts +20 -1
  88. package/dist/usageLimit.d.ts +8 -0
  89. package/dist/usageLimit.js +13 -0
  90. package/dist/useAwayRecap.d.ts +30 -0
  91. package/dist/useAwayRecap.js +75 -0
  92. package/dist/useComposer.d.ts +121 -0
  93. package/dist/useComposer.js +244 -0
  94. package/dist/useComposerImages.d.ts +66 -0
  95. package/dist/useComposerImages.js +195 -0
  96. package/dist/useConversation.d.ts +190 -0
  97. package/dist/useConversation.js +287 -0
  98. package/dist/useSubagent.d.ts +58 -0
  99. package/dist/useSubagent.js +149 -0
  100. package/dist/useTranscript.d.ts +4 -1
  101. package/dist/useTranscript.js +54 -11
  102. package/dist/wording.d.ts +43 -0
  103. package/dist/wording.js +101 -0
  104. package/dist/workingDirectories.d.ts +32 -0
  105. package/dist/workingDirectories.js +71 -0
  106. package/dist/worktreeChoice.d.ts +31 -0
  107. package/dist/worktreeChoice.js +38 -0
  108. package/locales/en/agentTranscript.json +154 -0
  109. package/locales/en/agents.json +366 -0
  110. package/locales/es/agentTranscript.json +154 -0
  111. package/locales/es/agents.json +366 -0
  112. package/locales/ja/agentTranscript.json +154 -0
  113. package/locales/ja/agents.json +366 -0
  114. package/locales/ko/agentTranscript.json +154 -0
  115. package/locales/ko/agents.json +366 -0
  116. package/locales/zh/agentTranscript.json +154 -0
  117. package/locales/zh/agents.json +366 -0
  118. package/package.json +24 -9
@@ -0,0 +1,105 @@
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
+ /** The session the reader has open, if any. */
7
+ export interface OpenSessionRef {
8
+ machine?: string | undefined;
9
+ sessionId?: string | undefined;
10
+ }
11
+ /** What a menu entry does, so a host can give it an icon of its own. */
12
+ export type SessionMenuAction = 'rename' | 'restore' | 'pin' | 'unpin' | 'fork' | 'leaveWorktree' | 'stop' | 'archive' | 'delete' | 'moveToGroup' | 'joinGroup' | 'moveToNewGroup' | 'renameGroup' | 'deleteGroup' | 'newSession' | 'newGroup';
13
+ export interface SessionMenuCommand {
14
+ action: SessionMenuAction;
15
+ label: string;
16
+ run: () => void;
17
+ /** Why it can't be chosen now, for a host that shows it disabled. */
18
+ disabledReason?: string | undefined;
19
+ /** The key a focused row takes for it, as `shortcuts` binds it. */
20
+ shortcut?: string | undefined;
21
+ destructive?: boolean | undefined;
22
+ /** An on/off choice, on while true. */
23
+ checked?: boolean | undefined;
24
+ }
25
+ export interface SessionSubmenu {
26
+ action: SessionMenuAction;
27
+ label: string;
28
+ disabledReason?: string | undefined;
29
+ items: SessionMenuItem[];
30
+ }
31
+ /** A menu as data, which a host draws with its own components. */
32
+ export type SessionMenuItem = SessionMenuCommand | SessionSubmenu | 'divider';
33
+ /** A key that acts on a session's row while it has focus. */
34
+ export interface SessionRowKey<R> {
35
+ keys: string | readonly string[];
36
+ run: (row: R) => void;
37
+ }
38
+ /** What the host asks the reader before an action. */
39
+ export interface SessionConfirmation<R> {
40
+ action: 'delete' | 'archive' | 'leaveWorktree';
41
+ session: Session;
42
+ title: string;
43
+ description: string;
44
+ confirmLabel: string;
45
+ destructive: boolean;
46
+ /** The host offers to remove the session's worktree too, and passes the
47
+ * root of the one the reader chose to remove to `onConfirm`. */
48
+ offersWorktreeRemoval: boolean;
49
+ /** The row the action takes out of the list, as the host passed it in. */
50
+ removes?: R | undefined;
51
+ /** Asked with a key pressed on the row, so the next press may answer it. */
52
+ fromKey?: boolean | undefined;
53
+ /** Rejects with the machine's refusal, for the host to show while it still asks. */
54
+ onConfirm: (removeWorktree?: string) => Promise<void>;
55
+ }
56
+ /** The session being renamed while the host's prompt for its name is up. */
57
+ export interface SessionRename {
58
+ session: Session | null;
59
+ name: string;
60
+ setName: (name: string) => void;
61
+ /** Saves the trimmed name and closes; a refusal goes to `onRefusal` and leaves it open. */
62
+ confirm: () => Promise<void>;
63
+ close: () => void;
64
+ }
65
+ export interface SessionActionsOptions<R> {
66
+ api: Pick<PwCodeApi, 'useSessionMutations' | 'leaveWorktree'>;
67
+ machineById: ReadonlyMap<string, PwCodeMachine>;
68
+ open: OpenSessionRef;
69
+ confirm: (request: SessionConfirmation<R>) => void;
70
+ /** A refusal of an action taken without asking, or what was thrown when the request failed. */
71
+ onRefusal: (refusal: unknown) => void;
72
+ onWarning: (message: string) => void;
73
+ /** Leaves the open session once it is deleted or archived. */
74
+ showStart: () => void;
75
+ /** Opens a session, as forking does with the copy. */
76
+ showSession: (session: Pick<Session, 'machineId' | 'id'>) => void;
77
+ }
78
+ export interface SessionActions<R> {
79
+ /** Given its row, a delete or archive names the row it removes, and the
80
+ * entries show the keys the row takes. Given its worktree, it offers to leave it. */
81
+ menu: (session: Session, row?: R, worktree?: PwCodeWorktreeRef) => SessionMenuItem[];
82
+ /** The keys skip what the menu disables, as choosing a disabled entry does. */
83
+ shortcuts: (session: Session) => SessionRowKey<R>[];
84
+ rename: SessionRename;
85
+ requestRename: (session: Session) => void;
86
+ requestDelete: (session: Session, row?: R, fromKey?: boolean) => void;
87
+ requestArchive: (session: Session, row?: R) => void;
88
+ requestLeaveWorktree: (session: Session, worktree: PwCodeWorktreeRef) => void;
89
+ restore: (session: Session) => void;
90
+ stop: (session: Session) => void;
91
+ togglePin: (session: Session) => void;
92
+ fork: (session: Session) => void;
93
+ /** `group` null takes the session out of its group. */
94
+ moveToGroup: (session: Session, group: string | null) => void;
95
+ /** Why the session's machine cannot record a group, if it cannot. */
96
+ groupBlocked: (session: Session) => string | undefined;
97
+ /** Why the session cannot be archived, if it cannot. */
98
+ archiveBlocked: (session: Session) => string | undefined;
99
+ }
100
+ export declare function menuCommand(action: SessionMenuAction, label: string, run: () => void, disabledReason?: string | undefined, shortcut?: string | undefined): SessionMenuCommand;
101
+ /** A session's actions and the flows behind them: the list is patched as
102
+ * soon as the daemon agrees, and deleting or archiving the open session
103
+ * shows the start rather than a transcript that is gone or shut down. */
104
+ export declare function useSessionActions<R = unknown>({ api, machineById, open, confirm, onRefusal, onWarning, showStart, showSession, }: SessionActionsOptions<R>): SessionActions<R>;
105
+ export {};
@@ -0,0 +1,178 @@
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
+ function machineBlocked(machine, t) {
10
+ return isMachineDown(machine) ? machineHint(machine, t)?.text : void 0;
11
+ }
12
+ /** The daemon refuses these for a session another host holds. */
13
+ function sessionActionBlocked(session, machine, t) {
14
+ if (isMachineDown(machine)) return machineBlocked(machine, t);
15
+ if (session.status === "live_elsewhere") return sessionStatusText(session, t);
16
+ }
17
+ function menuCommand(action, label, run, disabledReason, shortcut) {
18
+ return {
19
+ action,
20
+ label,
21
+ run,
22
+ ...disabledReason ? { disabledReason } : {},
23
+ ...shortcut ? { shortcut } : {}
24
+ };
25
+ }
26
+ /** A session's actions and the flows behind them: the list is patched as
27
+ * soon as the daemon agrees, and deleting or archiving the open session
28
+ * shows the start rather than a transcript that is gone or shut down. */
29
+ function useSessionActions({ api, machineById, open, confirm, onRefusal, onWarning, showStart, showSession }) {
30
+ const t = usePwCodeTranslations("agents");
31
+ const { archiveSession, deleteSession, forkSession, groupSession, pinSession, renameSession, restoreSession, stopSession } = api.useSessionMutations();
32
+ const [toRename, setToRename] = useState(null);
33
+ const [name, setName] = useState("");
34
+ const closeRename = () => {
35
+ setToRename(null);
36
+ setName("");
37
+ };
38
+ const confirmRename = async () => {
39
+ const trimmed = name.trim();
40
+ if (toRename === null || !trimmed) return;
41
+ const refusal = await renameSession(toRename, trimmed).catch((thrown) => thrown);
42
+ if (refusal) {
43
+ onRefusal(refusal);
44
+ return;
45
+ }
46
+ closeRename();
47
+ };
48
+ const isOpen = (s) => isSession(s, open.machine, open.sessionId);
49
+ const report = (refusal) => {
50
+ if (refusal) onRefusal(refusal);
51
+ };
52
+ const settle = (action) => void action.then(report, report);
53
+ const requestRename = (s) => {
54
+ setName(s.name || s.autoName || "");
55
+ setToRename(s);
56
+ };
57
+ const requestDelete = (s, row, fromKey = false) => confirm({
58
+ action: "delete",
59
+ session: s,
60
+ title: t("sidebar.deleteTitle"),
61
+ description: t("sidebar.deleteBody", {
62
+ name: sessionLabel(s, t),
63
+ machine: machineById.get(s.machineId)?.name ?? ""
64
+ }),
65
+ confirmLabel: t("sidebar.deleteAction"),
66
+ destructive: true,
67
+ offersWorktreeRemoval: true,
68
+ removes: row,
69
+ fromKey,
70
+ onConfirm: async (removeWorktree) => {
71
+ const refusal = await deleteSession(s, removeWorktree);
72
+ if (refusal) throw refusal;
73
+ if (isOpen(s)) showStart();
74
+ }
75
+ });
76
+ const requestArchive = (s, row) => confirm({
77
+ action: "archive",
78
+ session: s,
79
+ title: t("sidebar.archiveTitle", { name: sessionLabel(s, t) }),
80
+ description: t("sidebar.archiveBody"),
81
+ confirmLabel: t("sidebar.archive"),
82
+ destructive: false,
83
+ offersWorktreeRemoval: false,
84
+ removes: row,
85
+ onConfirm: async () => {
86
+ const refusal = await archiveSession(s);
87
+ if (refusal) throw refusal;
88
+ if (isOpen(s)) showStart();
89
+ }
90
+ });
91
+ const requestLeaveWorktree = (s, worktree) => confirm({
92
+ action: "leaveWorktree",
93
+ session: s,
94
+ title: t("sidebar.leaveWorktreeTitle"),
95
+ description: t("sidebar.leaveWorktreeBody", { workspace: s.workspace }),
96
+ confirmLabel: t("sidebar.leaveWorktree"),
97
+ destructive: false,
98
+ offersWorktreeRemoval: true,
99
+ onConfirm: async (removeWorktree) => {
100
+ const { left, refusal } = await api.leaveWorktree(s, removeWorktree);
101
+ if (refusal) throw refusal;
102
+ worktree.refresh();
103
+ if (left?.outcome === "remove_failed") onWarning(t("sidebar.leaveWorktreeKept"));
104
+ }
105
+ });
106
+ const restore = (s) => settle(restoreSession(s));
107
+ const stop = (s) => settle(stopSession(s));
108
+ const togglePin = (s) => settle(pinSession(s, !s.pinnedAt));
109
+ const moveToGroup = (s, group) => settle(groupSession(s, group));
110
+ const fork = (s) => settle(forkSession(s).then(({ forked, refusal }) => {
111
+ if (forked) showSession(forked);
112
+ return refusal;
113
+ }));
114
+ const menu = (session, row, worktree) => {
115
+ const machine = machineById.get(session.machineId);
116
+ const disabledReason = sessionActionBlocked(session, machine, t);
117
+ const machineDown = machineBlocked(machine, t);
118
+ const rowKey = (key) => row === void 0 ? void 0 : key;
119
+ const rename = menuCommand("rename", t("sidebar.renameAction"), () => requestRename(session), disabledReason);
120
+ const remove = {
121
+ ...menuCommand("delete", t("sidebar.deleteAction"), () => requestDelete(session, row), disabledReason, rowKey(DELETE_KEYS[0])),
122
+ destructive: true
123
+ };
124
+ if (isArchived(session)) return [
125
+ menuCommand("restore", t("sidebar.restore"), () => restore(session), machineDown),
126
+ rename,
127
+ "divider",
128
+ remove
129
+ ];
130
+ const midTurn = isMidTurn(session) ? t("sidebar.forkMidTurn") : void 0;
131
+ return [
132
+ rename,
133
+ menuCommand(session.pinnedAt ? "unpin" : "pin", t(session.pinnedAt ? "sidebar.unpin" : "sidebar.pin"), () => togglePin(session), machineDown),
134
+ menuCommand("fork", t("sidebar.fork"), () => fork(session), disabledReason ?? midTurn),
135
+ ...worktree ? [menuCommand("leaveWorktree", t("sidebar.leaveWorktree"), () => requestLeaveWorktree(session, worktree), disabledReason ?? midTurn)] : [],
136
+ ...isMidTurn(session) ? [menuCommand("stop", t("sidebar.stop"), () => stop(session), machineDown)] : [],
137
+ menuCommand("archive", t("sidebar.archive"), () => requestArchive(session, row), disabledReason, rowKey(ARCHIVE_KEY)),
138
+ "divider",
139
+ remove
140
+ ];
141
+ };
142
+ const shortcuts = (session) => {
143
+ if (sessionActionBlocked(session, machineById.get(session.machineId), t)) return [];
144
+ return [{
145
+ keys: DELETE_KEYS,
146
+ run: (row) => requestDelete(session, row, true)
147
+ }, ...isArchived(session) ? [] : [{
148
+ keys: ARCHIVE_KEY,
149
+ run: (row) => requestArchive(session, row)
150
+ }]];
151
+ };
152
+ return {
153
+ menu,
154
+ shortcuts,
155
+ rename: {
156
+ session: toRename,
157
+ name,
158
+ setName,
159
+ confirm: confirmRename,
160
+ close: closeRename
161
+ },
162
+ requestRename,
163
+ requestDelete,
164
+ requestArchive,
165
+ requestLeaveWorktree,
166
+ restore,
167
+ stop,
168
+ togglePin,
169
+ fork,
170
+ moveToGroup,
171
+ groupBlocked: (session) => {
172
+ const machine = machineById.get(session.machineId);
173
+ return machineBlocked(machine, t) ?? (machine?.sessionGroups ? void 0 : t("sidebar.groupsNeedUpdate", { machine: machine?.name ?? "" }));
174
+ },
175
+ archiveBlocked: (session) => sessionActionBlocked(session, machineById.get(session.machineId), t)
176
+ };
177
+ }
178
+ export { menuCommand, useSessionActions };
@@ -0,0 +1,27 @@
1
+ import type { Schemas } from './apiClient.js';
2
+ type StreamEvent = Schemas['AgentStreamEvent'];
3
+ type Machine = Schemas['AgentMachine'];
4
+ export interface PwCodeSocketOptions {
5
+ /** Opens a WebSocket to `path` on the platform's host, signed in as the API
6
+ * client is. Resolving asynchronously lets a host fetch a token first. Each
7
+ * reconnect calls it again, with the path resuming after the last frame. */
8
+ openSocket?: ((path: string) => WebSocket | Promise<WebSocket>) | undefined;
9
+ /** Whether the app is out of sight, where animation frames do not run, so
10
+ * frames are applied as they arrive. */
11
+ hidden?: (() => boolean) | undefined;
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;
15
+ /** Frames after which the list of subagents may read differently: one started
16
+ * or ended, one asked for or got an approval, or a turn began or closed. */
17
+ export declare function changesSubagents(ev: StreamEvent): boolean;
18
+ /** `machines` with each one in `fed` that the listing lost counted as connected. */
19
+ export declare function reachedByFeed(machines: Machine[], fed: ReadonlySet<string>): Machine[];
20
+ export declare function sessionEvents({ openSocket, hidden }: PwCodeSocketOptions): {
21
+ useSessionEvents: (machine: string, id: string, cursor: (() => number) | undefined, onEvent: (event: StreamEvent) => void) => {
22
+ connected: boolean;
23
+ disconnected: boolean;
24
+ };
25
+ useFedMachines: () => ReadonlySet<string>;
26
+ };
27
+ export {};
@@ -0,0 +1,212 @@
1
+ import { isConnected } from "./machine.js";
2
+ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
3
+ // src/sessionEvents.ts
4
+ var INITIAL_RETRY_MS = 1e3;
5
+ var MAX_RETRY_MS = 3e4;
6
+ var SOCKET_OPEN = 1;
7
+ var SOCKET_CLOSED = 3;
8
+ /** The path a session's event feed is served at, resuming after frame `after`. */
9
+ function sessionEventsPath(machine, id, after) {
10
+ return `/ws/code/machines/${encodeURIComponent(machine)}/sessions/${encodeURIComponent(id)}/events?after=${after}`;
11
+ }
12
+ /** Frames after which the list of subagents may read differently: one started
13
+ * or ended, one asked for or got an approval, or a turn began or closed. */
14
+ function changesSubagents(ev) {
15
+ return ev.type === "subagent_start" || ev.type === "subagent_end" || ev.type === "approval_request" || ev.type === "approval_resolved" || ev.type === "user_message" || ev.type === "done" || ev.type === "error";
16
+ }
17
+ /** `machines` with each one in `fed` that the listing lost counted as connected. */
18
+ function reachedByFeed(machines, fed) {
19
+ const lost = (m) => fed.has(m.id) && !isConnected(m);
20
+ if (!machines.some(lost)) return machines;
21
+ return machines.map((m) => {
22
+ if (!lost(m)) return m;
23
+ const { error: _, ...reached } = m;
24
+ return {
25
+ ...reached,
26
+ status: "connected"
27
+ };
28
+ });
29
+ }
30
+ /** Holds one socket open while `enabled`, reopening it with backoff after it
31
+ * drops, and from scratch whenever `connectionKey` changes. */
32
+ function useReconnectingSocket({ open, path, connectionKey, enabled, onOpen, onMessage, onClose }) {
33
+ const [connected, setConnected] = useState(false);
34
+ const latest = useRef({
35
+ open,
36
+ path,
37
+ onOpen,
38
+ onMessage,
39
+ onClose
40
+ });
41
+ latest.current = {
42
+ open,
43
+ path,
44
+ onOpen,
45
+ onMessage,
46
+ onClose
47
+ };
48
+ useEffect(() => {
49
+ if (!enabled || !latest.current.open) return;
50
+ let stopped = false;
51
+ let socket = null;
52
+ let attempts = 0;
53
+ let timer;
54
+ const retry = () => {
55
+ const delay = Math.min(INITIAL_RETRY_MS * 2 ** attempts, MAX_RETRY_MS);
56
+ attempts += 1;
57
+ timer = setTimeout(connect, delay);
58
+ };
59
+ const failed = () => {
60
+ if (stopped) return;
61
+ latest.current.onClose();
62
+ retry();
63
+ };
64
+ const attach = (ws) => {
65
+ if (stopped) {
66
+ ws.close();
67
+ return;
68
+ }
69
+ socket = ws;
70
+ const opened = () => {
71
+ if (socket !== ws) return;
72
+ attempts = 0;
73
+ setConnected(true);
74
+ latest.current.onOpen();
75
+ };
76
+ const closed = () => {
77
+ if (socket !== ws) return;
78
+ socket = null;
79
+ setConnected(false);
80
+ latest.current.onClose();
81
+ if (!stopped) retry();
82
+ };
83
+ ws.addEventListener("open", opened);
84
+ ws.addEventListener("message", (event) => {
85
+ if (socket === ws) latest.current.onMessage(event.data);
86
+ });
87
+ ws.addEventListener("close", closed);
88
+ if (ws.readyState === SOCKET_OPEN) opened();
89
+ else if (ws.readyState === SOCKET_CLOSED) closed();
90
+ };
91
+ function connect() {
92
+ timer = void 0;
93
+ const opener = latest.current.open;
94
+ if (!opener) return;
95
+ let made;
96
+ try {
97
+ made = opener(latest.current.path());
98
+ } catch {
99
+ failed();
100
+ return;
101
+ }
102
+ if ("then" in made) made.then(attach, failed);
103
+ else attach(made);
104
+ }
105
+ connect();
106
+ return () => {
107
+ stopped = true;
108
+ clearTimeout(timer);
109
+ const ws = socket;
110
+ socket = null;
111
+ ws?.close();
112
+ setConnected(false);
113
+ };
114
+ }, [enabled, connectionKey]);
115
+ return connected;
116
+ }
117
+ function sessionEvents({ openSocket, hidden }) {
118
+ const openFeeds = /* @__PURE__ */ new Map();
119
+ const listeners = /* @__PURE__ */ new Set();
120
+ let fedMachines = /* @__PURE__ */ new Set();
121
+ function countFeed(machine, by) {
122
+ const open = (openFeeds.get(machine) ?? 0) + by;
123
+ const fed = open > 0;
124
+ if (fed) openFeeds.set(machine, open);
125
+ else openFeeds.delete(machine);
126
+ if (fed !== fedMachines.has(machine)) {
127
+ fedMachines = new Set(openFeeds.keys());
128
+ for (const notify of listeners) notify();
129
+ }
130
+ }
131
+ function subscribe(notify) {
132
+ listeners.add(notify);
133
+ return () => {
134
+ listeners.delete(notify);
135
+ };
136
+ }
137
+ /** The machines a session feed is open to. */
138
+ function useFedMachines() {
139
+ return useSyncExternalStore(subscribe, () => fedMachines);
140
+ }
141
+ /** The transcript owns the cursor; this only reconnects from it. Frames are
142
+ * applied once per animation frame: the backlog a reconnect catches up on
143
+ * arrives in a burst, and rendering each frame of it plays the turn back. */
144
+ function useSessionEvents(machine, id, cursor, onEvent) {
145
+ const key = `${machine}/${id}`;
146
+ const [feed, setFeed] = useState(null);
147
+ const pending = useRef([]);
148
+ const frame = useRef(null);
149
+ const onEventRef = useRef(onEvent);
150
+ onEventRef.current = onEvent;
151
+ const flush = useCallback(() => {
152
+ if (frame.current !== null) {
153
+ cancelAnimationFrame(frame.current);
154
+ frame.current = null;
155
+ }
156
+ const frames = pending.current;
157
+ pending.current = [];
158
+ for (const ev of frames) onEventRef.current(ev);
159
+ }, []);
160
+ useEffect(() => () => {
161
+ if (frame.current !== null) {
162
+ cancelAnimationFrame(frame.current);
163
+ frame.current = null;
164
+ }
165
+ pending.current = [];
166
+ }, [key]);
167
+ const connected = useReconnectingSocket({
168
+ open: openSocket,
169
+ path: () => sessionEventsPath(machine, id, cursor?.() ?? 0),
170
+ connectionKey: key,
171
+ enabled: cursor !== void 0,
172
+ onOpen: () => setFeed({
173
+ key,
174
+ open: true
175
+ }),
176
+ onClose: () => {
177
+ flush();
178
+ setFeed({
179
+ key,
180
+ open: false
181
+ });
182
+ },
183
+ onMessage: (data) => {
184
+ let parsed;
185
+ try {
186
+ parsed = JSON.parse(String(data));
187
+ } catch {
188
+ return;
189
+ }
190
+ pending.current.push(parsed);
191
+ if (hidden?.()) flush();
192
+ else if (frame.current === null) frame.current = requestAnimationFrame(flush);
193
+ }
194
+ });
195
+ const open = feed?.key === key ? feed.open : void 0;
196
+ const reading = connected && open === true;
197
+ useEffect(() => {
198
+ if (!reading) return;
199
+ countFeed(machine, 1);
200
+ return () => countFeed(machine, -1);
201
+ }, [reading, machine]);
202
+ return {
203
+ connected: reading,
204
+ disconnected: open === false
205
+ };
206
+ }
207
+ return {
208
+ useSessionEvents,
209
+ useFedMachines
210
+ };
211
+ }
212
+ export { changesSubagents, reachedByFeed, sessionEvents, sessionEventsPath };
@@ -0,0 +1,49 @@
1
+ import { type Dispatch, type SetStateAction } from 'react';
2
+ import { type PwCodeMachine } from './machine.js';
3
+ import { type PwCodeSession } from './session.js';
4
+ /** A group the reader made. Its name is theirs, so the host keeps it with
5
+ * their preferences; which group a session is in is on the session, kept by
6
+ * its machine's daemon. */
7
+ export interface SessionGroup {
8
+ id: string;
9
+ name: string;
10
+ }
11
+ export interface ListedGroup<S = PwCodeSession> {
12
+ group: SessionGroup;
13
+ sessions: S[];
14
+ waiting: number;
15
+ running: number;
16
+ }
17
+ type Grouped = Pick<PwCodeSession, 'machineId' | 'status' | 'liveHost' | 'archivedAt' | 'group'>;
18
+ type Machines = ReadonlyMap<string, Pick<PwCodeMachine, 'status'>>;
19
+ export declare function patchGroup(groups: readonly SessionGroup[], id: string, patch: Partial<Omit<SessionGroup, 'id'>>): SessionGroup[];
20
+ /** The reader's group a session is in. One naming a group since deleted is in none. */
21
+ export declare function groupOf(groups: readonly SessionGroup[], session: Pick<PwCodeSession, 'group'>): SessionGroup | undefined;
22
+ /** A turn is running on a machine that still answers. */
23
+ export declare function isWorking(session: Pick<PwCodeSession, 'status'>, machine: Pick<PwCodeMachine, 'status'> | undefined): boolean;
24
+ /** Sessions as a group lists them: what waits on the reader, then what is
25
+ * live, then the rest, with how many wait and how many are working. */
26
+ export declare function inFlightFirst<S extends Grouped>(sessions: readonly S[], machineById: Machines): {
27
+ sessions: S[];
28
+ waiting: number;
29
+ running: number;
30
+ };
31
+ /** Each group's sessions, and the ones in none. Archived sessions stay with
32
+ * the archive. */
33
+ export declare function listGroups<S extends Grouped>(groups: readonly SessionGroup[], sessions: readonly S[], machineById: Machines): {
34
+ listed: ListedGroup<S>[];
35
+ ungrouped: S[];
36
+ };
37
+ export interface SessionGroups {
38
+ groups: SessionGroup[];
39
+ create: (name: string) => SessionGroup;
40
+ patch: (id: string, change: Partial<Omit<SessionGroup, 'id'>>) => void;
41
+ remove: (id: string) => void;
42
+ }
43
+ /** The reader's groups, over state the host keeps for them, as `useState`
44
+ * returns it. `newId` names a group as it is made. */
45
+ export declare function useSessionGroups([groups, setGroups]: readonly [
46
+ SessionGroup[],
47
+ Dispatch<SetStateAction<SessionGroup[]>>
48
+ ], newId: () => string): SessionGroups;
49
+ export {};
@@ -0,0 +1,72 @@
1
+ import { isMachineDown } from "./machine.js";
2
+ import { isActiveSession, isArchived, needsYou } from "./session.js";
3
+ import { useCallback, useMemo } from "react";
4
+ // src/sessionGroups.ts
5
+ function patchGroup(groups, id, patch) {
6
+ return groups.map((g) => g.id === id ? {
7
+ ...g,
8
+ ...patch
9
+ } : g);
10
+ }
11
+ /** The reader's group a session is in. One naming a group since deleted is in none. */
12
+ function groupOf(groups, session) {
13
+ return session.group ? groups.find((g) => g.id === session.group) : void 0;
14
+ }
15
+ /** A turn is running on a machine that still answers. */
16
+ function isWorking(session, machine) {
17
+ return session.status === "running" && !isMachineDown(machine);
18
+ }
19
+ /** Sessions as a group lists them: what waits on the reader, then what is
20
+ * live, then the rest, with how many wait and how many are working. */
21
+ function inFlightFirst(sessions, machineById) {
22
+ const waiting = sessions.filter((s) => needsYou(s, machineById.get(s.machineId)));
23
+ const rest = sessions.filter((s) => !waiting.includes(s));
24
+ const live = rest.filter(isActiveSession);
25
+ return {
26
+ sessions: [
27
+ ...waiting,
28
+ ...live,
29
+ ...rest.filter((s) => !isActiveSession(s))
30
+ ],
31
+ waiting: waiting.length,
32
+ running: live.filter((s) => isWorking(s, machineById.get(s.machineId))).length
33
+ };
34
+ }
35
+ /** Each group's sessions, and the ones in none. Archived sessions stay with
36
+ * the archive. */
37
+ function listGroups(groups, sessions, machineById) {
38
+ const grouped = (s) => isArchived(s) ? void 0 : groupOf(groups, s);
39
+ return {
40
+ listed: groups.map((group) => ({
41
+ group,
42
+ ...inFlightFirst(sessions.filter((s) => grouped(s) === group), machineById)
43
+ })),
44
+ ungrouped: sessions.filter((s) => !grouped(s))
45
+ };
46
+ }
47
+ /** The reader's groups, over state the host keeps for them, as `useState`
48
+ * returns it. `newId` names a group as it is made. */
49
+ function useSessionGroups([groups, setGroups], newId) {
50
+ const create = useCallback((name) => {
51
+ const group = {
52
+ id: newId(),
53
+ name
54
+ };
55
+ setGroups((current) => [...current, group]);
56
+ return group;
57
+ }, [setGroups, newId]);
58
+ const patch = useCallback((id, change) => setGroups((current) => patchGroup(current, id, change)), [setGroups]);
59
+ const remove = useCallback((id) => setGroups((current) => current.filter((g) => g.id !== id)), [setGroups]);
60
+ return useMemo(() => ({
61
+ groups,
62
+ create,
63
+ patch,
64
+ remove
65
+ }), [
66
+ groups,
67
+ create,
68
+ patch,
69
+ remove
70
+ ]);
71
+ }
72
+ export { groupOf, inFlightFirst, isWorking, listGroups, patchGroup, useSessionGroups };
@@ -0,0 +1,14 @@
1
+ /** The worktree a session works in, as its actions take it, and a way to read it again. */
2
+ export type PwCodeWorktreeRef = {
3
+ root: string;
4
+ refresh: () => void;
5
+ };
6
+ /** The worktree `useSessionWorktree` read, read again whenever the live
7
+ * session reports it moved; undefined while the session works where it
8
+ * launched. */
9
+ export declare function useFollowedWorktree(worktree: {
10
+ data?: {
11
+ root?: string | undefined;
12
+ } | undefined;
13
+ mutate: () => Promise<unknown>;
14
+ }, liveWorktree: string | undefined): PwCodeWorktreeRef | undefined;
@@ -0,0 +1,16 @@
1
+ import { useEffect } from "react";
2
+ // src/sessionHeader.ts
3
+ /** The worktree `useSessionWorktree` read, read again whenever the live
4
+ * session reports it moved; undefined while the session works where it
5
+ * launched. */
6
+ function useFollowedWorktree(worktree, liveWorktree) {
7
+ const { data, mutate } = worktree;
8
+ useEffect(() => {
9
+ mutate();
10
+ }, [liveWorktree, mutate]);
11
+ return data?.root ? {
12
+ root: data.root,
13
+ refresh: () => void mutate()
14
+ } : void 0;
15
+ }
16
+ export { useFollowedWorktree };