@andrioid/paseo-attention-span 0.6.0 → 0.6.1

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 (71) hide show
  1. package/OVERVIEW.md +3 -1
  2. package/client/attention-screen.tsx +61 -1174
  3. package/client/coverage-settings.tsx +5 -4
  4. package/client/data.ts +4 -2
  5. package/client/feedback.tsx +21 -25
  6. package/client/history.tsx +12 -50
  7. package/client/item-actions.ts +363 -0
  8. package/client/item-row.tsx +450 -0
  9. package/client/new-issue.tsx +244 -0
  10. package/client/next-up.tsx +22 -183
  11. package/client/pickers.tsx +237 -0
  12. package/client/session-menu.ts +3 -11
  13. package/client/sessions.ts +58 -57
  14. package/client/setup.tsx +2 -1
  15. package/client/sheet.tsx +92 -15
  16. package/client/ui.tsx +23 -14
  17. package/client/wrap-up.tsx +151 -85
  18. package/docs/architecture.md +22 -11
  19. package/docs/screenshots/desktop-dark-doing-acknowledge.png +0 -0
  20. package/docs/screenshots/desktop-dark-doing-clear.png +0 -0
  21. package/docs/screenshots/desktop-dark-doing-issue-sheet.png +0 -0
  22. package/docs/screenshots/desktop-dark-doing-reviewers.png +0 -0
  23. package/docs/screenshots/desktop-dark-doing-sheet.png +0 -0
  24. package/docs/screenshots/desktop-dark-doing-wrap-dirty.png +0 -0
  25. package/docs/screenshots/desktop-dark-doing-wrap-multi.png +0 -0
  26. package/docs/screenshots/desktop-dark-doing-wrap.png +0 -0
  27. package/docs/screenshots/desktop-dark-doing.png +0 -0
  28. package/docs/screenshots/desktop-dark-next-up-setup.png +0 -0
  29. package/docs/screenshots/desktop-dark-next-up.png +0 -0
  30. package/docs/screenshots/desktop-dark-settings.png +0 -0
  31. package/docs/screenshots/phone-dark-doing.png +0 -0
  32. package/docs/screenshots/phone-light-next-up-filtered.png +0 -0
  33. package/index.client.tsx +19 -0
  34. package/index.server.ts +43 -26
  35. package/package.json +2 -1
  36. package/requirements.yaml +8 -3
  37. package/server/actions.ts +2 -1
  38. package/server/archive.ts +146 -67
  39. package/server/archived.ts +12 -16
  40. package/server/changes.ts +34 -54
  41. package/server/classify.ts +142 -136
  42. package/server/feedback.ts +2 -6
  43. package/server/fetch.ts +262 -0
  44. package/server/fixture.ts +83 -14
  45. package/server/github-types.ts +3 -1
  46. package/server/markdown.ts +3 -1
  47. package/server/port.ts +46 -0
  48. package/server/queries.ts +33 -23
  49. package/server/service.ts +155 -272
  50. package/server/setup.ts +15 -14
  51. package/server/store.ts +94 -80
  52. package/server/update.ts +34 -13
  53. package/server/view.ts +16 -15
  54. package/shared/archive.ts +116 -13
  55. package/shared/attention.ts +50 -18
  56. package/shared/changes.ts +2 -1
  57. package/shared/config.ts +2 -6
  58. package/shared/drafting.ts +17 -0
  59. package/shared/feedback.ts +6 -5
  60. package/shared/format.ts +2 -1
  61. package/shared/history-report.ts +2 -1
  62. package/shared/item-sessions.ts +76 -0
  63. package/shared/item-view.ts +223 -0
  64. package/shared/linked-sessions.ts +59 -8
  65. package/shared/names.ts +17 -0
  66. package/shared/new-issue.ts +129 -0
  67. package/shared/next-up-filter.ts +137 -0
  68. package/shared/paging.ts +16 -0
  69. package/shared/rpc.ts +23 -10
  70. package/shared/setup.ts +3 -1
  71. package/shared/wrap-up.ts +20 -23
package/server/setup.ts CHANGED
@@ -1,16 +1,17 @@
1
1
  import { FIELD_ROLES } from "../shared/config";
2
2
  import type { ConfigStatus, CoverageCheck, CoverageKind, SetupStatus } from "../shared/setup";
3
- import { FIXTURE_MY_ORGS, FIXTURE_ORGS, FIXTURE_REPOS } from "./fixture";
4
- import { FIXTURE, graphql, runGh } from "./gh";
5
- import { loadConfig } from "./store";
3
+ import { graphql, runGh } from "./gh";
4
+ import type { Store } from "./store";
5
+
6
+ // What GitHub says, which previews answer from made-up data instead (fixtureAnswers in fixture.ts).
6
7
 
7
8
  // What the setup checklist needs [SET-01]. Asked only when Attention Span can't load.
8
- export async function setupStatus(): Promise<SetupStatus> {
9
- return { gh: FIXTURE ? { found: true, login: "me", error: null } : await ghStatus(), config: await configStatus() };
9
+ export async function setupStatus(store: Pick<Store, "loadConfig">, gh: () => Promise<SetupStatus["gh"]>): Promise<SetupStatus> {
10
+ return { gh: await gh(), config: await configStatus(store) };
10
11
  }
11
12
 
12
13
  // `gh api user` answers both questions at once: is gh there, and who is it signed in as.
13
- async function ghStatus(): Promise<SetupStatus["gh"]> {
14
+ export async function ghStatus(): Promise<SetupStatus["gh"]> {
14
15
  try {
15
16
  const { code, stdout, stderr } = await runGh(["api", "user", "--jq", ".login"]);
16
17
  const login = stdout.trim();
@@ -20,9 +21,9 @@ async function ghStatus(): Promise<SetupStatus["gh"]> {
20
21
  }
21
22
  }
22
23
 
23
- export async function configStatus(): Promise<ConfigStatus> {
24
+ export async function configStatus(store: Pick<Store, "loadConfig">): Promise<ConfigStatus> {
24
25
  try {
25
- const { orgs, repos, nextUp, followThreads } = await loadConfig();
26
+ const { orgs, repos, nextUp, followThreads } = await store.loadConfig();
26
27
  const fields = Object.fromEntries(FIELD_ROLES.flatMap((role) => (nextUp[role] === undefined ? [] : [[role, nextUp[role]?.field ?? null]])));
27
28
  return { error: null, orgs, repos, nextUp: { mine: nextUp.mine, orgs: nextUp.orgs, repos: nextUp.repos }, fields, followThreads };
28
29
  } catch (error) {
@@ -32,21 +33,21 @@ export async function configStatus(): Promise<ConfigStatus> {
32
33
 
33
34
  // The orgs I belong to, for Next up's org picker [NXT-04]. Only these can be picked.
34
35
  export async function myOrgs(): Promise<string[]> {
35
- if (FIXTURE) return FIXTURE_MY_ORGS;
36
36
  const { viewer } = await graphql<{ viewer: { organizations: { nodes: { login: string }[] } } }>("{ viewer { organizations(first: 100) { nodes { login } } } }");
37
37
  return viewer.organizations.nodes.map((org) => org.login).sort((a, b) => a.localeCompare(b));
38
38
  }
39
39
 
40
40
  // An org or repo is checked on GitHub before it's saved, so a typo shows right away [SRC-02].
41
41
  // Pasted GitHub URLs are accepted. The exact name GitHub returns is what gets saved.
42
- export async function checkCoverage(kind: CoverageKind, input: string): Promise<CoverageCheck> {
42
+ export async function checkCoverage(kind: CoverageKind, input: string, lookUp: typeof coverageOnGitHub): Promise<CoverageCheck> {
43
43
  const name = input.trim().replace(/^(https?:\/\/)?github\.com\//i, "").replace(/\/+$/, "");
44
44
  if (kind === "org" && !/^[\w.-]+$/.test(name)) return { name: null, error: "Use the organization's name, like acme" };
45
45
  if (kind === "repo" && !/^[\w.-]+\/[\w.-]+$/.test(name)) return { name: null, error: "Use owner/name, like acme/shop" };
46
- if (FIXTURE) {
47
- const known = (kind === "org" ? FIXTURE_ORGS : FIXTURE_REPOS).find((candidate) => candidate.toLowerCase() === name.toLowerCase());
48
- return known ? { name: known, error: null } : { name: null, error: `${name} wasn't found on GitHub` };
49
- }
46
+ return lookUp(kind, name);
47
+ }
48
+
49
+ // GitHub's exact name for an org or repo, or why it isn't one [SRC-02].
50
+ export async function coverageOnGitHub(kind: CoverageKind, name: string): Promise<CoverageCheck> {
50
51
  const { code, stdout, stderr } = await runGh(["api", kind === "org" ? `users/${name}` : `repos/${name}`, "--jq", kind === "org" ? ".login + \" \" + .type" : ".full_name"]);
51
52
  if (code !== 0) return { name: null, error: /404|Not Found/i.test(stderr) ? `${name} wasn't found on GitHub, or gh's account can't see it` : stderr.trim() || `gh exited with ${code}` };
52
53
  if (kind === "repo") return { name: stdout.trim(), error: null };
package/server/store.ts CHANGED
@@ -3,18 +3,18 @@ import { homedir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { z } from "zod";
5
5
  import { type Attention, type HistoryFilter, type Item, type RememberedGroups, type SectionId, SECTIONS } from "../shared/attention";
6
- import { AttentionConfig, FIELD_ROLES, type FieldRole, sameField } from "../shared/config";
6
+ import { AttentionConfig, FIELD_ROLES, type FieldRole } from "../shared/config";
7
+ import type { KeptRow } from "../shared/archive";
7
8
  import type { OthersChange } from "../shared/changes";
8
9
  import { type ChangeLedger, EMPTY_LEDGER } from "./changes";
9
10
  import type { Pending } from "./view";
11
+ import { sameName } from "../shared/names";
10
12
 
11
- // Local files in ~/.config/paseo-attention-span/ [PRIV-01].
13
+ // Local files in ~/.config/paseo-attention-span/ [PRIV-01], or a folder chosen by environment variable.
12
14
  const CHOSEN_DIR = process.env.PASEO_ATTENTION_SPAN_DIR ?? process.env.PASEO_GITHUB_ATTENTION_DIR;
13
15
  export const DIR = CHOSEN_DIR ?? join(homedir(), ".config", "paseo-attention-span");
14
- // Where they lived while the plugin was called "GitHub attention".
15
- const OLD_DIR = join(homedir(), ".config", "paseo-github-attention");
16
- const CONFIG = join(DIR, "config.json");
17
- const STATE = join(DIR, "state.json");
16
+ // Where they lived while the plugin was called "GitHub attention"; a chosen folder has none.
17
+ export const OLD_DIR = CHOSEN_DIR ? undefined : join(homedir(), ".config", "paseo-github-attention");
18
18
 
19
19
  const knownSections = (items: unknown): boolean => Array.isArray(items) && items.every((item) => Object.hasOwn(SECTIONS, (item as Item)?.section));
20
20
 
@@ -31,6 +31,8 @@ export const State = z.object({
31
31
  projectFilter: z.array(z.string()).default([]),
32
32
  // Reviewed and Changed by others shown in each of History's weeks; none means finished only [HIS-07].
33
33
  historyFilter: z.array(z.enum(["reviewed", "changed"])).default([]).catch([] as HistoryFilter[]),
34
+ // The device's IANA time zone, which History's weeks follow; the last device to send one wins. UTC until then [HIS-01].
35
+ timeZone: z.string().nullable().default(null).catch(null),
34
36
  // The update notice put off with Not now, by the version it offered [UPD-01].
35
37
  skippedUpdate: z.string().nullable().default(null).catch(null),
36
38
  // What others did to my work, kept until Got it or an archive and for History [HIS-06, HIS-07, ATT-22].
@@ -48,6 +50,10 @@ export const State = z.object({
48
50
  // Key -> the keys of the stack or issue group it was last seen in, and when, so Wrap up still knows a merged PR's open
49
51
  // siblings after History lists it on its own [ATT-22, ATT-04].
50
52
  groups: z.record(z.string(), z.object({ keys: z.array(z.string()), at: z.string() })).default({}).catch({}) satisfies z.ZodType<RememberedGroups>,
53
+ // Wrap up rows whose sessions were archived but whose worktree stayed, until it goes or is dismissed [ATT-22].
54
+ kept: z.array(z.custom<KeptRow>((value) => typeof (value as KeptRow)?.workspaceId === "string" && typeof (value as KeptRow)?.itemKey === "string")).default([]).catch([]),
55
+ // The repository and agent profile the New issue sheet last started with [ISS-01].
56
+ newIssue: z.object({ repo: z.string().nullable().default(null), profileId: z.string().nullable().default(null) }).default({ repo: null, profileId: null }).catch({ repo: null, profileId: null }),
51
57
  // My Paseo projects' GitHub repos when last listed, for refreshes before the app has connected [NXT-08].
52
58
  projectRepos: z.array(z.string()).default([]),
53
59
  // The last fetch of each feed. A cache from an older version is dropped rather than shown wrong, like one with an item in a
@@ -66,12 +72,6 @@ export const State = z.object({
66
72
  });
67
73
  export type State = z.infer<typeof State>;
68
74
 
69
- // Moves the old folder over once, unless a folder is chosen by environment variable.
70
- export async function moveOldFiles(): Promise<void> {
71
- if (CHOSEN_DIR || (await exists(DIR)) || !(await exists(OLD_DIR))) return;
72
- await rename(OLD_DIR, DIR);
73
- }
74
-
75
75
  async function exists(path: string): Promise<boolean> {
76
76
  return stat(path).then(
77
77
  () => true,
@@ -88,81 +88,95 @@ async function readJson(path: string): Promise<unknown> {
88
88
  }
89
89
  }
90
90
 
91
- export async function loadConfig(): Promise<AttentionConfig> {
92
- const parsed = AttentionConfig.safeParse(await readJson(CONFIG));
93
- if (!parsed.success) throw new Error(`${CONFIG} is invalid: ${parsed.error.message}`);
94
- return parsed.data;
95
- }
91
+ // The files in `dir`. `oldDir` is moved over once, before `dir` exists.
92
+ export function createStore(dir: string, oldDir?: string) {
93
+ const config = join(dir, "config.json");
94
+ const state = join(dir, "state.json");
96
95
 
97
- // Where an issue repo's code lives, chosen on the screen [SES-07].
98
- export function saveCodeRepo(issueRepo: string, codeRepo: string): Promise<AttentionConfig> {
99
- return updateConfig((file) => {
100
- const existing = file.codeRepos && typeof file.codeRepos === "object" ? (file.codeRepos as Record<string, unknown>) : {};
101
- const codeRepos = Object.fromEntries(Object.entries(existing).filter(([issues]) => issues.toLowerCase() !== issueRepo.toLowerCase()));
102
- return { ...file, codeRepos: { ...codeRepos, [issueRepo]: codeRepo } };
103
- });
104
- }
96
+ async function moveOldFiles(): Promise<void> {
97
+ if (!oldDir || (await exists(dir)) || !(await exists(oldDir))) return;
98
+ await rename(oldDir, dir);
99
+ }
105
100
 
106
- // The orgs and repos chosen in settings [SRC-02].
107
- export function saveCoverage(orgs: string[], repos: string[]): Promise<AttentionConfig> {
108
- return updateConfig((file) => ({ ...file, orgs, repos }));
109
- }
101
+ async function loadConfig(): Promise<AttentionConfig> {
102
+ const parsed = AttentionConfig.safeParse(await readJson(config));
103
+ if (!parsed.success) throw new Error(`${config} is invalid: ${parsed.error.message}`);
104
+ return parsed.data;
105
+ }
110
106
 
111
- // Where Next up looks, chosen in settings [NXT-04]. The fields and the rest of nextUp are kept.
112
- export function saveNextUpSources(sources: Pick<AttentionConfig["nextUp"], "mine" | "orgs" | "repos">): Promise<AttentionConfig> {
113
- return updateConfig((file) => {
114
- const nextUp = file.nextUp && typeof file.nextUp === "object" ? (file.nextUp as Record<string, unknown>) : {};
115
- return { ...file, nextUp: { ...nextUp, ...sources } };
116
- });
117
- }
107
+ // Where an issue repo's code lives, chosen on the screen [SES-07].
108
+ function saveCodeRepo(issueRepo: string, codeRepo: string): Promise<AttentionConfig> {
109
+ return updateConfig((file) => {
110
+ const existing = file.codeRepos && typeof file.codeRepos === "object" ? (file.codeRepos as Record<string, unknown>) : {};
111
+ const codeRepos = Object.fromEntries(Object.entries(existing).filter(([issues]) => !sameName(issues, issueRepo)));
112
+ return { ...file, codeRepos: { ...codeRepos, [issueRepo]: codeRepo } };
113
+ });
114
+ }
118
115
 
119
- // Which org issue fields Next up uses, from settings [NXT-04]: null turns one off, a role left out is kept as it is.
120
- // A field kept as it was keeps its order.
121
- export function saveNextUpFields(fields: Partial<Record<FieldRole, string | null>>): Promise<AttentionConfig> {
122
- return updateConfig((file) => {
123
- const nextUp = file.nextUp && typeof file.nextUp === "object" ? (file.nextUp as Record<string, unknown>) : {};
124
- const chosen = Object.fromEntries(
125
- FIELD_ROLES.filter((role) => fields[role] !== undefined).map((role) => {
126
- const before = nextUp[role] as { field?: unknown } | null | undefined;
127
- const field = fields[role]!;
128
- return [role, field === null ? null : before && typeof before.field === "string" && sameField(before.field, field) ? { ...before, field } : { field }];
129
- }),
130
- );
131
- return { ...file, nextUp: { ...nextUp, ...chosen } };
132
- });
133
- }
116
+ // The orgs and repos chosen in settings [SRC-02].
117
+ function saveCoverage(orgs: string[], repos: string[]): Promise<AttentionConfig> {
118
+ return updateConfig((file) => ({ ...file, orgs, repos }));
119
+ }
134
120
 
135
- // Whether replies on others' threads count without a tag, from settings [ATT-17].
136
- export function saveFollowThreads(followThreads: boolean): Promise<AttentionConfig> {
137
- return updateConfig((file) => ({ ...file, followThreads }));
138
- }
121
+ // Where Next up looks, chosen in settings [NXT-04]. The fields and the rest of nextUp are kept.
122
+ function saveNextUpSources(sources: Pick<AttentionConfig["nextUp"], "mine" | "orgs" | "repos">): Promise<AttentionConfig> {
123
+ return updateConfig((file) => {
124
+ const nextUp = file.nextUp && typeof file.nextUp === "object" ? (file.nextUp as Record<string, unknown>) : {};
125
+ return { ...file, nextUp: { ...nextUp, ...sources } };
126
+ });
127
+ }
139
128
 
140
- // What the screen writes changes only its own keys; everything else in the file is kept as it is.
141
- // A file that doesn't read or parse is left alone.
142
- async function updateConfig(change: (file: Record<string, unknown>) => Record<string, unknown>): Promise<AttentionConfig> {
143
- const raw = await readJson(CONFIG);
144
- const current = AttentionConfig.safeParse(raw);
145
- if (!current.success) throw new Error(`${CONFIG} is invalid: ${current.error.message}`);
146
- const next = change(raw as Record<string, unknown>);
147
- const parsed = AttentionConfig.safeParse(next);
148
- if (!parsed.success) throw new Error(`${CONFIG} is invalid: ${parsed.error.message}`);
149
- await writeAtomically(CONFIG, `${JSON.stringify(next, null, 2)}\n`);
150
- return parsed.data;
151
- }
129
+ // Which org issue fields Next up uses, from settings [NXT-04]: null turns one off, a role left out is kept as it is.
130
+ // A field kept as it was keeps its order.
131
+ function saveNextUpFields(fields: Partial<Record<FieldRole, string | null>>): Promise<AttentionConfig> {
132
+ return updateConfig((file) => {
133
+ const nextUp = file.nextUp && typeof file.nextUp === "object" ? (file.nextUp as Record<string, unknown>) : {};
134
+ const chosen = Object.fromEntries(
135
+ FIELD_ROLES.filter((role) => fields[role] !== undefined).map((role) => {
136
+ const before = nextUp[role] as { field?: unknown } | null | undefined;
137
+ const field = fields[role]!;
138
+ return [role, field === null ? null : before && typeof before.field === "string" && sameName(before.field, field) ? { ...before, field } : { field }];
139
+ }),
140
+ );
141
+ return { ...file, nextUp: { ...nextUp, ...chosen } };
142
+ });
143
+ }
152
144
 
153
- async function writeAtomically(path: string, content: string): Promise<void> {
154
- await mkdir(DIR, { recursive: true });
155
- const temporary = `${path}.${process.pid}.tmp`;
156
- await writeFile(temporary, content);
157
- await rename(temporary, path);
158
- }
145
+ // Whether replies on others' threads count without a tag, from settings [ATT-17].
146
+ function saveFollowThreads(followThreads: boolean): Promise<AttentionConfig> {
147
+ return updateConfig((file) => ({ ...file, followThreads }));
148
+ }
159
149
 
160
- export async function loadState(): Promise<State> {
161
- const parsed = State.safeParse(await readJson(STATE).catch(() => ({})));
162
- // A cache that no longer parses (e.g. after an update) is simply dropped.
163
- return parsed.success ? parsed.data : State.parse({});
164
- }
150
+ // What the screen writes changes only its own keys; everything else in the file is kept as it is.
151
+ // A file that doesn't read or parse is left alone.
152
+ async function updateConfig(change: (file: Record<string, unknown>) => Record<string, unknown>): Promise<AttentionConfig> {
153
+ const raw = await readJson(config);
154
+ const current = AttentionConfig.safeParse(raw);
155
+ if (!current.success) throw new Error(`${config} is invalid: ${current.error.message}`);
156
+ const next = change(raw as Record<string, unknown>);
157
+ const parsed = AttentionConfig.safeParse(next);
158
+ if (!parsed.success) throw new Error(`${config} is invalid: ${parsed.error.message}`);
159
+ await writeAtomically(config, `${JSON.stringify(next, null, 2)}\n`);
160
+ return parsed.data;
161
+ }
162
+
163
+ async function writeAtomically(path: string, content: string): Promise<void> {
164
+ await mkdir(dir, { recursive: true });
165
+ const temporary = `${path}.${process.pid}.tmp`;
166
+ await writeFile(temporary, content);
167
+ await rename(temporary, path);
168
+ }
169
+
170
+ async function loadState(): Promise<State> {
171
+ const parsed = State.safeParse(await readJson(state).catch(() => ({})));
172
+ // A cache that no longer parses (e.g. after an update) is simply dropped.
173
+ return parsed.success ? parsed.data : State.parse({});
174
+ }
175
+
176
+ async function saveState(saved: State): Promise<void> {
177
+ await writeAtomically(state, JSON.stringify(saved, null, 2));
178
+ }
165
179
 
166
- export async function saveState(state: State): Promise<void> {
167
- await writeAtomically(STATE, JSON.stringify(state, null, 2));
180
+ return { moveOldFiles, loadConfig, saveCodeRepo, saveCoverage, saveNextUpSources, saveNextUpFields, saveFollowThreads, loadState, saveState };
168
181
  }
182
+ export type Store = ReturnType<typeof createStore>;
package/server/update.ts CHANGED
@@ -2,7 +2,6 @@ import { execFile, spawn } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import { type UpdateNotice, updateNotice } from "../shared/update";
4
4
  import { ourInstall } from "./feedback";
5
- import { FIXTURE } from "./gh";
6
5
 
7
6
  const run = promisify(execFile);
8
7
 
@@ -11,7 +10,15 @@ const EVERY_MS = 12 * 60 * 60 * 1000;
11
10
  // A check that failed (offline, an older Paseo) is tried again sooner.
12
11
  const RETRY_MS = 60 * 60 * 1000;
13
12
 
14
- // Previews have nothing to update; PASEO_ATTENTION_SPAN_FIXTURE_UPDATE=1 makes one up to show the notice.
13
+ // How updates reach Paseo: asking what `paseo plugin update` would install, and installing it. `install` reports a failure
14
+ // through `failed`; a success restarts this process.
15
+ export interface UpdatePaseo {
16
+ check(): Promise<UpdateNotice | null>;
17
+ install(notice: UpdateNotice, failed: (error: string) => void): void;
18
+ }
19
+
20
+ // Previews have nothing to update; PASEO_ATTENTION_SPAN_FIXTURE_UPDATE=1 makes one up to show the notice, and Update shows
21
+ // how a failure looks.
15
22
  const FIXTURE_UPDATE: UpdateNotice = {
16
23
  id: "attention-span",
17
24
  current: "0.4.3",
@@ -25,6 +32,11 @@ const FIXTURE_UPDATE: UpdateNotice = {
25
32
  // Asks Paseo itself, so the answer is what `paseo plugin update` would install: a registry install's
26
33
  // reviewed pin, npm's latest, or a Git remote's HEAD. Directory installs are never updated, so they say nothing.
27
34
  export class UpdateCheck {
35
+ constructor(
36
+ private readonly paseo: UpdatePaseo,
37
+ private readonly now: () => number = Date.now,
38
+ ) {}
39
+
28
40
  private last: { at: number; ttl: number; notice: UpdateNotice | null } | null = null;
29
41
  private inFlight: Promise<UpdateNotice | null> | null = null;
30
42
  // Why the last Update failed. A successful one restarts this process, so nothing needs remembering then.
@@ -36,13 +48,13 @@ export class UpdateCheck {
36
48
  }
37
49
 
38
50
  private cached(): Promise<UpdateNotice | null> {
39
- if (this.last && Date.now() - this.last.at < this.last.ttl) return Promise.resolve(this.last.notice);
40
- this.inFlight ??= check()
51
+ if (this.last && this.now() - this.last.at < this.last.ttl) return Promise.resolve(this.last.notice);
52
+ this.inFlight ??= this.paseo.check()
41
53
  .then(
42
- (notice) => (this.last = { at: Date.now(), ttl: EVERY_MS, notice }),
54
+ (notice) => (this.last = { at: this.now(), ttl: EVERY_MS, notice }),
43
55
  (error) => {
44
56
  console.error("Checking for an Attention Span update failed:", (error as Error).message);
45
- return (this.last = { at: Date.now(), ttl: RETRY_MS, notice: null });
57
+ return (this.last = { at: this.now(), ttl: RETRY_MS, notice: null });
46
58
  },
47
59
  )
48
60
  .then((last) => last.notice)
@@ -57,27 +69,36 @@ export class UpdateCheck {
57
69
  const notice = await this.cached();
58
70
  if (!notice || notice.latest !== latest) throw new Error(`${latest} isn't the update on offer any more. Check again.`);
59
71
  this.failed = null;
60
- // Previews show how a failed update looks.
61
- if (FIXTURE) return void (this.failed = { latest, error: "Previews don't update." });
72
+ this.paseo.install(notice, (error) => (this.failed = { latest, error }));
73
+ }
74
+ }
75
+
76
+ export const fixtureUpdates: UpdatePaseo = {
77
+ check: async () => (process.env.PASEO_ATTENTION_SPAN_FIXTURE_UPDATE === "1" ? FIXTURE_UPDATE : null),
78
+ install: (_, failed) => failed("Previews don't update."),
79
+ };
80
+
81
+ export const paseoUpdates: UpdatePaseo = {
82
+ check,
83
+ install(notice, failed) {
62
84
  const cli = process.env.PASEO_CLI || "paseo";
63
85
  const child = spawn(cli, ["plugin", "update", notice.id, ...notice.args, "--json", ...home()], { detached: true, stdio: ["ignore", "pipe", "pipe"] });
64
86
  let output = "";
65
87
  child.stdout.on("data", (chunk) => (output += chunk));
66
88
  child.stderr.on("data", (chunk) => (output += chunk));
67
- child.on("error", (error) => (this.failed = { latest, error: error.message }));
89
+ child.on("error", (error) => failed(error.message));
68
90
  child.on("close", (code) => {
69
91
  const error = failure(notice.id, output, code);
70
92
  if (error) {
71
93
  console.error("Updating Attention Span failed:", error);
72
- this.failed = { latest, error };
94
+ failed(error);
73
95
  }
74
96
  });
75
97
  child.unref();
76
- }
77
- }
98
+ },
99
+ };
78
100
 
79
101
  async function check(): Promise<UpdateNotice | null> {
80
- if (FIXTURE) return process.env.PASEO_ATTENTION_SPAN_FIXTURE_UPDATE === "1" ? FIXTURE_UPDATE : null;
81
102
  const ours = ourInstall();
82
103
  if (!ours) return null;
83
104
  // Paseo gives its plugins the path of its CLI and its home, so this asks the daemon the plugin runs in.
package/server/view.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { type Attention, type AttentionView, type Chip, type FeedId, type FeedStatus, type HistoryFilter, type Item, type NextUpIssue, type Section, SECTION_ORDER, SECTIONS, type TabId, type WaitingGroup } from "../shared/attention";
1
+ import { type Attention, type AttentionView, baseItem, type Chip, type FeedId, type FeedStatus, type HistoryFilter, type Item, type NextUpIssue, type Section, SECTION_ORDER, SECTIONS, type TabId, type WaitingGroup } from "../shared/attention";
2
2
  import type { AttentionConfig } from "../shared/config";
3
+ import type { KeptRow } from "../shared/archive";
4
+ import type { NewIssueInfo } from "../shared/new-issue";
3
5
  import { workChip, workKind } from "../shared/work";
4
6
  import { type ChangeLedger, changeItems, EMPTY_LEDGER, handedKeys } from "./changes";
5
7
  import { historySince } from "./queries";
@@ -14,6 +16,8 @@ export interface ViewMeta {
14
16
  groups?: Record<string, string[]>;
15
17
  config: AttentionConfig;
16
18
  pending: number;
19
+ newIssue: NewIssueInfo;
20
+ kept?: KeptRow[];
17
21
  }
18
22
 
19
23
  // What a tap on GitHub changed, shown until a fetch can show it for itself [FRESH-02].
@@ -50,23 +54,17 @@ export function doneItem(source: Item | NextUpIssue, closedAt: string, notPlanne
50
54
  const kind = "kind" in source ? source.kind : "issue";
51
55
  // Labels come with the next History fetch; until then the issue type and title prefix tell what kind of work it was [HIS-04].
52
56
  const work = workKind({ type: "type" in source ? source.type : undefined, title });
57
+ const base = baseItem({ key, section: "done", kind, repo, number, title, url });
58
+ // A PR keeps its branch, so a session left on it finds its Wrap up row before History is fetched again [ATT-22].
59
+ const head = "target" in source && source.target.headRefName ? { headRefName: source.target.headRefName } : {};
53
60
  return {
54
- key,
55
- section: "done",
56
- kind,
57
- draft: false,
58
- repo,
59
- number,
60
- title,
61
- url,
61
+ ...base,
62
+ target: { ...base.target, ...head },
62
63
  chips: [...(work ? [workChip(work)] : []), ...(notPlanned ? [{ text: "not planned", tone: "neutral" as const }] : [])],
63
64
  ...(work ? { work } : {}),
64
65
  ...(notPlanned ? { notPlanned: true as const } : {}),
65
- actions: [],
66
66
  // Not planned issues list their PRs on their own, as classifyHistory does [HIS-03].
67
67
  children: "children" in source && !notPlanned ? source.children.map((child) => ({ ...child, draft: false, chips: [], attention: false })) : [],
68
- target: { kind, repo, number, title, url },
69
- othersActivityAt: "1970-01-01T00:00:00Z",
70
68
  closedAt,
71
69
  };
72
70
  }
@@ -100,7 +98,7 @@ export function isDismissed(item: Item, dismissed: State["dismissed"]): boolean
100
98
  // Waiting by who it waits on, so I know whom to nudge: whoever blocks the most first, ties by the longest wait, then bots, who
101
99
  // can't be nudged, and last the work no person holds up. Each one's work oldest first; the screen lifts work with an active
102
100
  // session. My PRs in Doing that wait on whom I asked are here too, so nudging them is one list [WAI-01, WAI-03, PRS-15].
103
- export function waitingGroups(items: Item[]): WaitingGroup[] {
101
+ function waitingGroups(items: Item[]): WaitingGroup[] {
104
102
  const oldest = (list: Item[]) => list.map((item) => item.wait?.since ?? "").sort()[0] ?? "";
105
103
  const people = new Map<string, WaitingGroup>();
106
104
  const nobody: Item[] = [];
@@ -130,7 +128,10 @@ export function waitingGroups(items: Item[]): WaitingGroup[] {
130
128
  // Waiting's work: its own sections, and my PRs in Doing while they wait on someone I asked [WAI-01, PRS-15].
131
129
  const inWaiting = (item: Item) => SECTIONS[item.section].tab === "waiting" || (SECTIONS[item.section].tab === "doing" && !!item.wait && !!item.waitingOn?.length);
132
130
 
133
- export function buildView(attention: Attention | null, history: Item[], dismissed: State["dismissed"], meta: ViewMeta, ledger: ChangeLedger = EMPTY_LEDGER, now = new Date()): AttentionView {
131
+ export function buildView(attention: Attention | null, fetched: Item[], dismissed: State["dismissed"], meta: ViewMeta, ledger: ChangeLedger = EMPTY_LEDGER, now = new Date(), timeZone = "UTC"): AttentionView {
132
+ // History's weeks in the device's time zone; what a fetch from before a new week began has that's older is left out [HIS-01].
133
+ const since = historySince(now, meta.config.historyWeeks, timeZone);
134
+ const history = fetched.filter((item) => !item.closedAt || Date.parse(item.closedAt) >= Date.parse(since));
134
135
  const items = [...(attention?.items ?? []), ...history];
135
136
  // A PR that left my hands isn't my finished work, even once its new owner merges it [HIS-06].
136
137
  const handed = handedKeys(ledger);
@@ -139,7 +140,7 @@ export function buildView(attention: Attention | null, history: Item[], dismisse
139
140
  .map((item) => (item.section === "done" && item.children.some((child) => handed.has(child.key)) ? { ...item, children: item.children.filter((child) => !handed.has(child.key)) } : item));
140
141
  // Notes on what others did, what was cleared into a week, and finished work a live refresh saw first; never dismissed,
141
142
  // only cleared with Got it or an archive [HIS-06, HIS-07, ATT-22].
142
- const changes = changeItems(ledger, now, meta.config.mentionDays, historySince(now, meta.config.historyWeeks));
143
+ const changes = changeItems(ledger, now, meta.config.mentionDays, since);
143
144
  // History's daily fetch has the richer item; one seen live fills in until then, so a merge or close shows in its week now.
144
145
  const knownDone = new Set(visible.filter((item) => SECTIONS[item.section].tab === "history" && item.section === "done").flatMap((item) => [item.key, ...item.children.map((child) => child.key)]));
145
146
  const liveFinished = changes.finished.filter((item) => !knownDone.has(item.key));
package/shared/archive.ts CHANGED
@@ -1,37 +1,140 @@
1
- import type { AttentionView, WrapItem } from "./attention";
1
+ import { z } from "zod";
2
+ import type { AttentionView, Item, WrapItem } from "./attention";
2
3
 
3
- // Archiving a Wrap up row's sessions [ATT-22]. The screen names the row; the server checks, archives and acknowledges.
4
+ // Archiving a Wrap up row's sessions [ATT-22]. The screen names the row; the server checks, archives and acknowledges. The
5
+ // confirm sheet is shaped like Paseo's own "Archive workspace" one, so the two read alike.
4
6
 
5
- // A session with work archiving could lose, as the confirm sheet names it: "2 uncommitted files and 1 unpushed commit on
6
- // branch". `unknown` when git and Paseo couldn't both say; the sheet says so instead.
7
+ // A session with work archiving could lose, as the confirm sheet names it. `unknown` when git and Paseo couldn't both say;
8
+ // the sheet says so instead.
7
9
  export interface UnsavedSession {
8
10
  agentId: string;
9
11
  title: string | null;
10
12
  branch?: string;
13
+ // Uncommitted files, counted where git or a preview could count them; else just that there are some.
11
14
  files?: number;
15
+ uncommitted?: true;
16
+ // Lines added and deleted in tracked files, as Paseo's sheet counts them; untracked files count as files only.
17
+ added?: number;
18
+ deleted?: number;
12
19
  commits?: number;
13
20
  unknown?: true;
21
+ // The terminals of a worktree archiving removes, by name: Paseo closes them with it.
22
+ terminals?: string[];
14
23
  }
15
24
 
16
- // What an archive request names: the row's item, its sessions, and the keys whose changes success acknowledges.
17
- export interface ArchiveTarget {
18
- itemKey: string;
19
- agentIds: string[];
20
- keys: string[];
25
+ // Paseo's own reading of a session's worktree, for when git can't be asked: null or missing where it couldn't tell. Previews
26
+ // add the counts and terminals Paseo can't give them.
27
+ export interface WorktreeReading {
28
+ dirty?: boolean | null;
29
+ ahead?: number | null;
30
+ branch?: string;
31
+ files?: number;
32
+ lines?: { added: number; deleted: number };
33
+ terminals?: string[];
34
+ }
35
+
36
+ // What archiving a session would lose, from Paseo's reading: null when it says both that nothing is uncommitted and that
37
+ // nothing is ahead. Clean needs both answers; either one missing makes it unknown [ATT-22]. A preview's terminals come along.
38
+ export function unsavedOf(session: Pick<UnsavedSession, "agentId" | "title">, reading: WorktreeReading | undefined): UnsavedSession | null {
39
+ const dirty = reading?.dirty ?? null;
40
+ const ahead = reading?.ahead ?? null;
41
+ const terminals = reading?.terminals ?? [];
42
+ if (dirty === false && ahead === 0) return null;
43
+ return {
44
+ agentId: session.agentId,
45
+ title: session.title,
46
+ ...(reading?.branch ? { branch: reading.branch } : {}),
47
+ ...(reading?.files ? { files: reading.files } : dirty ? { uncommitted: true as const } : {}),
48
+ ...(dirty && reading?.lines ? { added: reading.lines.added, deleted: reading.lines.deleted } : {}),
49
+ ...(ahead ? { commits: ahead } : {}),
50
+ ...(dirty === null || ahead === null ? { unknown: true as const } : {}),
51
+ ...(terminals.length ? { terminals } : {}),
52
+ };
53
+ }
54
+
55
+ const count = (n: number, what: string) => `${n} ${what}${n === 1 ? "" : "s"}`;
56
+
57
+ // "2 uncommitted files and 1 unpushed commit on split-invoice-pdf": what's known to be unsaved, in one line, as the multi
58
+ // sheet's session list says it.
59
+ export function unsavedWords(unsaved: UnsavedSession): string {
60
+ const parts = [
61
+ ...(unsaved.files ? [count(unsaved.files, "uncommitted file")] : unsaved.uncommitted ? ["uncommitted changes"] : []),
62
+ ...(unsaved.commits ? [count(unsaved.commits, "unpushed commit")] : []),
63
+ ];
64
+ const what = parts.join(" and ") || "unsaved changes";
65
+ return unsaved.branch ? `${what} on ${unsaved.branch}` : what;
66
+ }
67
+
68
+ // A session's lines on the confirm sheet, in Paseo's words: "Uncommitted changes: 2 files (+12 −3)", "1 unpushed commit",
69
+ // then the terminals archiving closes [ATT-22].
70
+ export function sheetLines(unsaved: UnsavedSession): string[] {
71
+ const { files, added, deleted, commits, terminals = [] } = unsaved;
72
+ const lines = added || deleted ? ` (+${added ?? 0} −${deleted ?? 0})` : "";
73
+ return [
74
+ ...(unsaved.unknown ? ["Couldn't check for unsaved changes"] : []),
75
+ ...(files ? [`Uncommitted changes: ${count(files, "file")}${lines}`] : unsaved.uncommitted ? [`Uncommitted changes${lines}`] : []),
76
+ ...(commits ? [count(commits, "unpushed commit")] : []),
77
+ ...(terminals.length ? [`Closes ${terminals.length === 1 ? "terminal" : "terminals"}: ${terminals.join(", ")}`] : []),
78
+ ];
21
79
  }
22
80
 
81
+ // What an archive request names: the row's item, its sessions, and the keys whose changes success acknowledges. The item's
82
+ // place and title, so a row that lingers with its worktree can still say what it was.
83
+ export const ArchiveTarget = z.object({
84
+ itemKey: z.string(),
85
+ agentIds: z.array(z.string()),
86
+ keys: z.array(z.string()),
87
+ title: z.string(),
88
+ repo: z.string(),
89
+ number: z.number(),
90
+ kind: z.enum(["pr", "issue"]),
91
+ });
92
+ export type ArchiveTarget = z.infer<typeof ArchiveTarget>;
93
+
23
94
  export const archiveTarget = (item: WrapItem): ArchiveTarget => ({
24
95
  itemKey: item.wrap.itemKey,
25
96
  agentIds: item.wrap.sessions.map((session) => session.id),
26
97
  keys: item.wrap.keys,
98
+ title: item.title,
99
+ repo: item.repo,
100
+ number: item.number,
101
+ kind: item.kind,
27
102
  });
28
103
 
29
- // What archiving answers. A refusal keeps the row and says why, or names the unsaved work to confirm. `warning`: the
30
- // sessions were archived, but a worktree that should have gone stayed, and why.
104
+ // Why a worktree stayed after its sessions were archived [ATT-22]: another item's session still lives in it, a terminal
105
+ // opened while archiving, or Paseo wouldn't remove it.
106
+ export type KeptReason = "session" | "terminal" | "refused";
107
+
108
+ export interface KeptWorktree {
109
+ workspaceId: string;
110
+ // As Paseo's sidebar names it: the workspace's title, else its branch.
111
+ name: string;
112
+ reason: KeptReason;
113
+ // The session's title, the terminals' names, or Paseo's error.
114
+ detail: string;
115
+ // The session that kept it, for Open session.
116
+ agentId?: string;
117
+ // The row's sessions that lived in it, so the server knows which row it was.
118
+ sessionIds: string[];
119
+ }
120
+
121
+ // A kept worktree as Wrap up shows it, with the row it came from; in state.json until the worktree goes or it's dismissed.
122
+ export type KeptRow = Omit<KeptWorktree, "sessionIds"> & Pick<Item, "repo" | "number" | "title" | "kind"> & { itemKey: string; at: string };
123
+
124
+ // Why it stayed, short: the archive mark and the row's button say the rest. "Fix flaky test still in it" [ATT-22].
125
+ export function keptText(kept: Pick<KeptWorktree, "reason" | "detail">): string {
126
+ if (kept.reason === "session") return `${kept.detail} still in it`;
127
+ if (kept.reason === "terminal") return `${kept.detail} opened meanwhile`;
128
+ return `Paseo: ${kept.detail}`;
129
+ }
130
+
131
+ // What archiving answers. A refusal keeps the row and says why, or names the unsaved work and open terminals to confirm,
132
+ // with the terminals' ids for the confirm to send back and the worktrees that would go, by name, for the sheet's title.
133
+ // Success says which worktrees stayed, and why.
31
134
  export type ArchiveResult =
32
- | { ok: true; warning?: string }
135
+ | { ok: true; kept: KeptWorktree[] }
33
136
  | { ok: false; reason: "working"; message: string }
34
- | { ok: false; reason: "unsaved"; sessions: UnsavedSession[] };
137
+ | { ok: false; reason: "unsaved"; sessions: UnsavedSession[]; terminals: string[]; leaving: string[] };
35
138
 
36
139
  // The answer the screen gets: the result, with the list after it.
37
140
  export type ArchiveOutcome = ArchiveResult & { view: AttentionView };