@hexdecimal16/nexo 0.4.13 → 0.4.15

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 (46) hide show
  1. package/README.md +3 -0
  2. package/cli/src/common.js +1 -1
  3. package/cli/src/main.js +17 -2
  4. package/core/src/engine/context-trim.js +39 -0
  5. package/core/src/engine/errors.js +9 -0
  6. package/core/src/engine/messages.js +14 -1
  7. package/core/src/engine/run.js +39 -8
  8. package/core/src/providers/claude-p.js +75 -19
  9. package/core/src/providers/codex-p.js +16 -3
  10. package/core/src/providers/kiro-p.js +34 -7
  11. package/core/src/session/mentions.js +32 -8
  12. package/core/src/session/session.js +17 -13
  13. package/package.json +1 -1
  14. package/sdk/src/index.js +2 -0
  15. package/store/src/migrations/010_memory_project_scope.sql +27 -0
  16. package/store/src/run-dir.js +10 -0
  17. package/tools/src/builtin.js +39 -8
  18. package/tools/src/images.js +174 -0
  19. package/tools/src/index.js +1 -0
  20. package/tui/src/app.js +51 -2
  21. package/tui/src/commands.js +1 -1
  22. package/tui/src/image-attachments.js +142 -0
  23. package/web/public/area.html +2 -2
  24. package/web/public/cost.html +1 -1
  25. package/web/public/index.html +6 -23
  26. package/web/public/judge.html +1 -1
  27. package/web/public/learning.html +1 -1
  28. package/web/public/lib/common-view.ts +1 -1
  29. package/web/public/lib/run-view.ts +1 -1
  30. package/web/public/lib/runs-view.ts +1 -1
  31. package/web/public/lib/span-view.ts +18 -1
  32. package/web/public/lib/theme.ts +1 -1
  33. package/web/public/optim.html +1 -1
  34. package/web/public/page.html +2 -2
  35. package/web/public/pages/area.ts +3 -3
  36. package/web/public/pages/companion.ts +1 -1
  37. package/web/public/pages/home.ts +104 -21
  38. package/web/public/pages/page.ts +1 -1
  39. package/web/public/pages/run.ts +8 -1
  40. package/web/public/run.html +2 -1
  41. package/web/public/runs.html +40 -0
  42. package/web/public/sessions.html +1 -1
  43. package/web/public/style.css +60 -9
  44. package/web/public/wikis.html +1 -1
  45. package/web/src/companion.js +2 -2
  46. package/web/public/home.html +0 -23
@@ -0,0 +1,142 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { homedir } from "node:os";
3
+ import { basename, extname } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { describeImage, IMAGE_EXTENSIONS, withAttachedImagesNote, isImageFile, loadImageFile, prepareImage } from "../../tools/src/index.js";
6
+ /**
7
+ * A path token starting at a word boundary: single- or double-quoted, or unquoted with backslash-escaped spaces, the
8
+ * forms terminals use when a file is dragged in (iTerm and Terminal escape, Ghostty and VS Code quote).
9
+ */
10
+ const PATH_TOKEN = /(^|\s)('[^'\n]+'|"[^"\n]+"|(?:\\.|[^\s\\'"])+)/g;
11
+ function unquote(token) {
12
+ if ((token.startsWith("'") && token.endsWith("'")) || (token.startsWith('"') && token.endsWith('"')))
13
+ return token.slice(1, -1);
14
+ return token.replace(/\\(.)/g, "$1");
15
+ }
16
+ /** The absolute file path a token names, or null: only absolute, `~/` and `file://` paths count, so typed words never do. */
17
+ function tokenPath(token) {
18
+ const raw = unquote(token);
19
+ let path;
20
+ if (raw.startsWith("file://")) {
21
+ try {
22
+ path = fileURLToPath(raw);
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ else if (raw.startsWith("~/"))
29
+ path = `${homedir()}${raw.slice(1)}`;
30
+ else if (raw.startsWith("/") || /^[A-Za-z]:[\\/]/.test(raw))
31
+ path = raw;
32
+ else
33
+ return null;
34
+ return IMAGE_EXTENSIONS.includes(extname(path).toLowerCase()) ? path : null;
35
+ }
36
+ /** Image files named by dropped or pasted paths in `text`, in order. Paths to missing or non-image files are left out. */
37
+ export function findDroppedImagePaths(text, isImage = isImageFile) {
38
+ const out = [];
39
+ for (const match of text.matchAll(PATH_TOKEN)) {
40
+ const token = match[2];
41
+ const path = tokenPath(token);
42
+ if (!path || !isImage(path))
43
+ continue;
44
+ const start = (match.index ?? 0) + match[1].length;
45
+ out.push({ start, end: start + token.length, path });
46
+ }
47
+ return out;
48
+ }
49
+ const MARKER = /\[Image #(\d+)\]/g;
50
+ export const imageMarker = (n) => `[Image #${n}]`;
51
+ /**
52
+ * Images attached to the draft. Each one gets a `[Image #n]` marker in the editor; a submitted message carries the
53
+ * images whose markers it still contains, in the order they appear, so deleting a marker drops its image. Attachments
54
+ * live as long as the TUI, so a message recalled from history or put back from the queue keeps its images.
55
+ */
56
+ export class ImageAttachments {
57
+ byId = new Map();
58
+ next = 1;
59
+ add(loaded, name) {
60
+ const id = this.next++;
61
+ this.byId.set(id, { image: loaded.image, label: describeImage(name, loaded) });
62
+ return imageMarker(id);
63
+ }
64
+ /** Attaches an image file and returns its marker. Throws for an unreadable or non-image file. */
65
+ attachFile(path) {
66
+ return this.add(loadImageFile(path), basename(path));
67
+ }
68
+ /** Attaches image bytes (a clipboard image) and returns its marker. */
69
+ attachBytes(bytes, name) {
70
+ return this.add(prepareImage(bytes), name);
71
+ }
72
+ /**
73
+ * Replaces every dropped image path in `text` with its marker. Returns null when there is none, so the editor is
74
+ * left alone; `failed` lists paths that looked like images but could not be read.
75
+ */
76
+ replaceDroppedPaths(text) {
77
+ const dropped = findDroppedImagePaths(text);
78
+ if (dropped.length === 0)
79
+ return null;
80
+ let out = "";
81
+ let at = 0;
82
+ const attached = [];
83
+ const failed = [];
84
+ for (const d of dropped) {
85
+ out += text.slice(at, d.start);
86
+ try {
87
+ const marker = this.attachFile(d.path);
88
+ out += marker;
89
+ attached.push(marker);
90
+ }
91
+ catch {
92
+ out += text.slice(d.start, d.end);
93
+ failed.push(d.path);
94
+ }
95
+ at = d.end;
96
+ }
97
+ out += text.slice(at);
98
+ return attached.length > 0 || failed.length > 0 ? { text: out, attached, failed } : null;
99
+ }
100
+ /** The images a message's markers refer to, in order (a repeated marker counts once), with a line naming each. */
101
+ resolve(text) {
102
+ const images = [];
103
+ const labels = [];
104
+ const seen = new Set();
105
+ for (const match of text.matchAll(MARKER)) {
106
+ const id = Number(match[1]);
107
+ const attachment = this.byId.get(id);
108
+ if (!attachment || seen.has(id))
109
+ continue;
110
+ seen.add(id);
111
+ images.push(attachment.image);
112
+ labels.push(`${imageMarker(id)} ${attachment.label}`);
113
+ }
114
+ return { images, labels };
115
+ }
116
+ }
117
+ /** The message sent for a draft with images: the text as typed, plus a line saying which image each marker is. */
118
+ export const withImageLabels = withAttachedImagesNote;
119
+ /**
120
+ * The image on the system clipboard as PNG bytes, or null when there is none or no clipboard tool is available:
121
+ * AppleScript on macOS, wl-paste or xclip on Linux.
122
+ */
123
+ export function readClipboardImage() {
124
+ const run = (command, args) => {
125
+ try {
126
+ const out = execFileSync(command, args, { stdio: ["ignore", "pipe", "ignore"], maxBuffer: 200 * 1024 * 1024, timeout: 10_000 });
127
+ return out.length > 0 ? out : null;
128
+ }
129
+ catch {
130
+ return null;
131
+ }
132
+ };
133
+ if (process.platform === "darwin") {
134
+ const out = run("osascript", ["-e", "try", "-e", "the clipboard as «class PNGf»", "-e", "end try"]);
135
+ const hex = out?.toString("utf8").match(/«data PNGf([0-9A-Fa-f]+)»/)?.[1];
136
+ return hex ? Buffer.from(hex, "hex") : null;
137
+ }
138
+ if (process.platform === "linux") {
139
+ return run("wl-paste", ["--no-newline", "--type", "image/png"]) ?? run("xclip", ["-selection", "clipboard", "-t", "image/png", "-o"]);
140
+ }
141
+ return null;
142
+ }
@@ -12,9 +12,9 @@
12
12
  </head>
13
13
  <body>
14
14
  <a class="skip" href="#main">Skip to content</a>
15
- <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/home.html" aria-current="page">Home</a><a href="/">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
15
+ <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/">Home</a><a href="/runs.html">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
16
16
  <main id="main" tabindex="-1">
17
- <p class="muted"><a href="/home.html">&larr; Home</a></p>
17
+ <p class="muted"><a href="/">&larr; Home</a></p>
18
18
  <h1 id="area-title">Area</h1>
19
19
  <div id="error"></div>
20
20
  <div id="area"></div>
@@ -12,7 +12,7 @@
12
12
  </head>
13
13
  <body>
14
14
  <a class="skip" href="#main">Skip to content</a>
15
- <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/home.html">Home</a><a href="/">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
15
+ <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/">Home</a><a href="/runs.html">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
16
16
  <main id="main" tabindex="-1">
17
17
  <h1>Cost</h1>
18
18
  <form id="cost-form" class="filters">
@@ -4,37 +4,20 @@
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
6
  <meta name="nexo-token" content="{{NEXO_TOKEN}}">
7
- <title>nexo · runs</title>
7
+ <title>nexo · home</title>
8
8
  <link rel="stylesheet" href="/style.css">
9
9
  <script type="module" src="/lib/theme.ts"></script>
10
10
  <script type="module" src="/pages/companion.ts"></script>
11
- <script type="module" src="/pages/runs.ts"></script>
11
+ <script type="module" src="/pages/home.ts"></script>
12
12
  </head>
13
13
  <body>
14
14
  <a class="skip" href="#main">Skip to content</a>
15
- <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/home.html">Home</a><a href="/">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
15
+ <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/">Home</a><a href="/runs.html">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
16
16
  <main id="main" tabindex="-1">
17
- <h1>Runs</h1>
18
- <div id="session-filter"></div>
19
- <div class="tabs" role="tablist">
20
- <button type="button" role="tab" data-tab="all" aria-selected="true">All runs</button>
21
- <button type="button" role="tab" data-tab="review" aria-selected="false">Review queue</button>
22
- </div>
23
- <form id="filters" class="filters">
24
- <label>Status <select name="status" id="status-filter"><option value="">any</option></select></label>
25
- <label>Skill <input name="skill" type="text" placeholder="any"></label>
26
- <label>Since <input name="since" type="date"></label>
27
- <label>Scored <select name="scored"><option value="">any</option><option value="true">scored</option><option value="false">not scored</option></select></label>
28
- <button type="submit">Apply</button>
29
- </form>
17
+ <div class="home-head"><h1 id="greeting">Home</h1><p class="home-date" id="home-date"></p></div>
30
18
  <div id="error"></div>
31
- <div class="table-wrap">
32
- <table class="runs">
33
- <thead><tr><th>Started (UTC)</th><th>Instruction</th><th>Skill</th><th>Status</th><th>Model</th><th class="num">Duration</th><th class="num">Cost</th><th>Score</th><th>Verdict</th></tr></thead>
34
- <tbody id="runs-body"></tbody>
35
- </table>
36
- </div>
37
- <div id="pager"></div>
19
+ <input id="home-search" class="home-search" type="search" placeholder="Search areas, wikis, recent activity and decisions" aria-label="Search">
20
+ <div id="home"><p class="muted">Loading…</p></div>
38
21
  </main>
39
22
  </body>
40
23
  </html>
@@ -12,7 +12,7 @@
12
12
  </head>
13
13
  <body>
14
14
  <a class="skip" href="#main">Skip to content</a>
15
- <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/home.html">Home</a><a href="/">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
15
+ <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/">Home</a><a href="/runs.html">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
16
16
  <main id="main" tabindex="-1">
17
17
  <h1>Judge calibration</h1>
18
18
  <div id="error"></div>
@@ -12,7 +12,7 @@
12
12
  </head>
13
13
  <body>
14
14
  <a class="skip" href="#main">Skip to content</a>
15
- <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/home.html">Home</a><a href="/">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
15
+ <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/">Home</a><a href="/runs.html">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
16
16
  <main id="main" tabindex="-1">
17
17
  <h1>Learning</h1>
18
18
  <div id="error"></div>
@@ -7,7 +7,7 @@ export function runLink(id: string): string {
7
7
 
8
8
  /** The runs list filtered to one session's turns. */
9
9
  export function sessionLink(sessionId: string): string {
10
- return `/?session=${encodeURIComponent(sessionId)}`;
10
+ return `/runs.html?session=${encodeURIComponent(sessionId)}`;
11
11
  }
12
12
 
13
13
  const STATUS_GLYPH = new Map([
@@ -29,7 +29,7 @@ export function renderRunHeader(detail: RunDetailResponse, nowMs: number): SafeH
29
29
  const { run, runJson } = detail;
30
30
  const model = runJson?.model;
31
31
  return html`<header class="run-header ${stateClass(run.status)}">
32
- <div class="crumbs">${run.parentRunId ? html`<a href="${runLink(run.parentRunId)}">← parent run ${shortId(run.parentRunId)}</a>` : html`<a href="/">← runs</a>`}</div>
32
+ <div class="crumbs">${run.parentRunId ? html`<a href="${runLink(run.parentRunId)}">← parent run ${shortId(run.parentRunId)}</a>` : html`<a href="/runs.html">← runs</a>`}</div>
33
33
  <h1>${truncate(run.instruction.split("\n")[0] ?? "", 200)}</h1>
34
34
  <div class="facts">
35
35
  ${statusBadge(run.status)} ${verdictBadge(run.verdict)}
@@ -68,7 +68,7 @@ export function renderRunRows(runs: RunSummary[], nowMs: number): SafeHtml {
68
68
  /** The active session filter, with a link back to all runs; empty without one. */
69
69
  export function renderSessionFilter(sessionId: string, title: string | null): SafeHtml {
70
70
  if (!sessionId) return html``;
71
- return html`<p class="session-filter">Turns of session <a class="mono" href="${sessionLink(sessionId)}">${title || sessionId}</a> <span class="muted mono">${sessionId}</span> · <a href="/">show all runs</a></p>`;
71
+ return html`<p class="session-filter">Turns of session <a class="mono" href="${sessionLink(sessionId)}">${title || sessionId}</a> <span class="muted mono">${sessionId}</span> · <a href="/runs.html">show all runs</a></p>`;
72
72
  }
73
73
 
74
74
  /** On the default view (all tabs, no session filter) chat turns are not listed; a muted line points to the Sessions page. */
@@ -1,6 +1,7 @@
1
1
  import type { Span, SpanNode } from "./api-types.ts";
2
2
  import { statusBadge } from "./common-view.ts";
3
3
  import { durationMs, formatDuration, formatUsd, shortId } from "./format.ts";
4
+ import { filePath } from "./files-view.ts";
4
5
  import { html, prettyJson, type SafeHtml } from "./html.ts";
5
6
 
6
7
  export function findSpan(roots: SpanNode[], id: string): SpanNode | undefined {
@@ -55,7 +56,22 @@ function renderContentBlocks(content: unknown): SafeHtml {
55
56
  })}`;
56
57
  }
57
58
 
58
- const SHOWN_ATTRS = new Set(["content", "args", "result", "reason", "trigger", "instruction", "errorMessage", "firstChunkMs", "firstTextMs"]);
59
+ const SHOWN_ATTRS = new Set(["content", "args", "result", "reason", "trigger", "instruction", "errorMessage", "firstChunkMs", "firstTextMs", "images"]);
60
+
61
+ /** Paths of the images a span saved in its run folder (`attrs.images`): a run's attached inputs or a tool's returned images. */
62
+ export function spanImages(span: Span): string[] {
63
+ const images = span.attrs.images;
64
+ return Array.isArray(images) ? images.filter((p): p is string => typeof p === "string") : [];
65
+ }
66
+
67
+ /** Thumbnails of images in a run folder; each opens full size in a new tab. */
68
+ export function renderImageStrip(runId: string, paths: readonly string[], label: string): SafeHtml {
69
+ if (paths.length === 0) return html``;
70
+ return html`<div class="msg msg-images"><div class="msg-label">${label}</div><div class="image-strip">${paths.map((p) => {
71
+ const src = filePath(runId, p);
72
+ return html`<a href="${src}" target="_blank" rel="noopener noreferrer" title="${p}"><img class="thumb" alt="${p}" src="${src}" loading="lazy"></a>`;
73
+ })}</div></div>`;
74
+ }
59
75
 
60
76
  /** Fields, messages, tool input and output, and remaining attributes of one span. */
61
77
  export function renderSpanDetail(span: Span, attrsTruncated: boolean, nowMs: number): SafeHtml {
@@ -87,6 +103,7 @@ export function renderSpanDetail(span: Span, attrsTruncated: boolean, nowMs: num
87
103
  ${a.content !== undefined ? renderContentBlocks(a.content) : ""}
88
104
  ${a.args !== undefined ? html`<div class="msg msg-tool"><div class="msg-label">input</div><pre>${prettyJson(a.args)}</pre></div>` : ""}
89
105
  ${typeof a.result === "string" ? html`<div class="msg msg-result"><div class="msg-label">output</div><pre>${a.result}</pre></div>` : ""}
106
+ ${renderImageStrip(span.runId, spanImages(span), span.kind === "run" ? "attached images" : "images returned")}
90
107
  ${span.payloadRef ? html`<p class="note">Full payload stored in ${fileButton(span.runId, span.payloadRef, span.payloadRef)}</p>` : ""}
91
108
  ${Object.keys(rest).length ? html`<details><summary>attributes</summary><pre>${prettyJson(rest)}</pre></details>` : ""}
92
109
  </div>`;
@@ -20,7 +20,7 @@ function apply(choice: Choice): void {
20
20
 
21
21
  function markActive(nav: Element): void {
22
22
  const path = location.pathname;
23
- const target = path === '/' || path === '/index.html' || path === '/run.html' ? '/' : path;
23
+ const target = path === '/index.html' ? '/' : path === '/run.html' ? '/runs.html' : path;
24
24
  for (const a of nav.querySelectorAll('a:not(.brand)')) {
25
25
  if (a.getAttribute('href') === target) a.setAttribute('aria-current', 'page');
26
26
  }
@@ -12,7 +12,7 @@
12
12
  </head>
13
13
  <body>
14
14
  <a class="skip" href="#main">Skip to content</a>
15
- <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/home.html">Home</a><a href="/">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
15
+ <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/">Home</a><a href="/runs.html">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
16
16
  <main id="main" tabindex="-1">
17
17
  <h1>Optimization</h1>
18
18
  <div id="error"></div>
@@ -12,9 +12,9 @@
12
12
  </head>
13
13
  <body>
14
14
  <a class="skip" href="#main">Skip to content</a>
15
- <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/home.html">Home</a><a href="/">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
15
+ <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/">Home</a><a href="/runs.html">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
16
16
  <main id="main" tabindex="-1">
17
- <p class="muted" id="page-crumbs"><a href="/home.html">Home</a></p>
17
+ <p class="muted" id="page-crumbs"><a href="/">Home</a></p>
18
18
  <h1 id="page-title">Page</h1>
19
19
  <p class="muted" id="page-meta"></p>
20
20
  <div id="error"></div>
@@ -27,7 +27,7 @@ function render(d: Home, id: string): void {
27
27
  const a = d.areas.find((x) => x.id === id);
28
28
  if (!a) {
29
29
  title.textContent = "Area not found";
30
- box.innerHTML = html`<p class="muted">No active area "${id}". <a href="/home.html">Back to Home</a>.</p>`.value;
30
+ box.innerHTML = html`<p class="muted">No active area "${id}". <a href="/">Back to Home</a>.</p>`.value;
31
31
  return;
32
32
  }
33
33
  title.textContent = a.name;
@@ -38,11 +38,11 @@ function render(d: Home, id: string): void {
38
38
  const pages = a.wikis.reduce((n, w) => n + w.pageCount, 0);
39
39
  const wikis = a.wikis.map((w) => html`<a class="area-card" href="/page.html?path=${encodeURIComponent(`${w.path}/index.html`)}"><strong>${w.name}</strong><span class="muted">${String(w.pageCount)} pages</span>${w.summary ? html`<span class="area-card-text">${w.summary}</span>` : ""}</a>`);
40
40
  const timeline = feed.map((f) => {
41
- const link = f.sessionId ? html`<a href="/?session=${encodeURIComponent(f.sessionId)}">session</a>` : html`<a href="/run.html?id=${encodeURIComponent(f.runId)}">run</a>`;
41
+ const link = f.sessionId ? html`<a href="/runs.html?session=${encodeURIComponent(f.sessionId)}">session</a>` : html`<a href="/run.html?id=${encodeURIComponent(f.runId)}">run</a>`;
42
42
  return html`<li><time>${formatTime(f.at)}${f.wiki ? ` · ${f.wiki}` : ""}</time>${f.text}${f.verified ? "" : html` <span class="home-tag">unverified</span>`} ${pageLinks(f)} ${link}</li>`;
43
43
  });
44
44
  const decisionCards = decisions.map((x) => html`<div class="area-decision"><strong>${x.choice}</strong>${x.reason ? html`<span class="muted">Because ${x.reason}</span>` : ""}<time class="muted">${formatTime(x.at)}</time></div>`);
45
- const rows = sessions.map((s) => html`<tr><td><a href="/?session=${encodeURIComponent(s.id)}">${s.title || s.id}</a></td><td class="mono muted">${s.cwd}</td><td class="muted">${formatTime(s.updatedAt)}</td></tr>`);
45
+ const rows = sessions.map((s) => html`<tr><td><a href="/runs.html?session=${encodeURIComponent(s.id)}">${s.title || s.id}</a></td><td class="mono muted">${s.cwd}</td><td class="muted">${formatTime(s.updatedAt)}</td></tr>`);
46
46
  box.innerHTML = html`<p class="home-note">${a.scope}</p>
47
47
  <div class="area-stats">${stat(a.wikis.length, "wikis")}${stat(pages, "pages")}${stat(a.recent, "filed this week")}${stat(decisions.length, "decisions")}</div>
48
48
  <section><h2>Wikis</h2>${wikis.length > 0 ? html`<div class="area-grid">${wikis}</div>` : empty("No wikis in this area yet.")}</section>
@@ -219,7 +219,7 @@ function render(state: CompanionState, reviewCount: number): void {
219
219
  const first = state.running[0];
220
220
  if (first) action(state.running.length > 1 ? `Watch the oldest of ${state.running.length} running runs` : "Watch the running run", runLink(first.id));
221
221
  if (state.lastFailed) action("Open the last failure", runLink(state.lastFailed.id));
222
- if (reviewCount > 0) action(`Review queue (${reviewCount})`, "/?tab=review");
222
+ if (reviewCount > 0) action(`Review queue (${reviewCount})`, "/runs.html?tab=review");
223
223
  if (state.latest && state.latest !== state.lastFailed) action("Open the latest run", runLink(state.latest.id));
224
224
  action("Where the money went", "/cost.html");
225
225
  }
@@ -1,5 +1,7 @@
1
- import { renderError } from "../lib/common-view.ts";
2
- import { formatTime } from "../lib/format.ts";
1
+ // Home: what is running and what needs you, the life areas as tiles, and one timeline of filed work and decisions.
2
+ import type { RunListResponse } from "../lib/api-types.ts";
3
+ import { renderError, runLink, sessionLink } from "../lib/common-view.ts";
4
+ import { formatTime, truncate } from "../lib/format.ts";
3
5
  import { html, type SafeHtml } from "../lib/html.ts";
4
6
  import { asErrorBody, el, getJson } from "./api.ts";
5
7
 
@@ -9,14 +11,53 @@ interface HomeFeedItem { at: string; text: string; areaId: string | null; wiki:
9
11
  interface HomeDecision { at: string; choice: string; reason: string; areaId: string | null; wiki: string | null; sessionId: string | null; runId: string }
10
12
  interface HomeSession { id: string; title: string; cwd: string; updatedAt: string; areaId: string | null }
11
13
  interface Home { areas: HomeArea[]; proposed: { id: string; name: string }[]; unsorted: number; feed: HomeFeedItem[]; decisions: HomeDecision[]; sessions: HomeSession[] }
14
+ interface ReviewItem { runId: string; instruction: string; status: string; score: number | null; startedAt: string }
15
+ interface Entry { at: string; kind: "done" | "decision"; body: SafeHtml; meta: SafeHtml; text: string }
12
16
 
17
+ const HUES = 6;
13
18
  const box = el<HTMLDivElement>("#home");
14
19
  const errorBox = el<HTMLDivElement>("#error");
15
20
  const search = el<HTMLInputElement>("#home-search");
21
+ const greeting = el<HTMLHeadingElement>("#greeting");
22
+ const dateLine = el<HTMLParagraphElement>("#home-date");
16
23
  let data: Home | null = null;
24
+ let running: RunListResponse["runs"] = [];
25
+ let review: ReviewItem[] = [];
17
26
 
18
27
  const hit = (q: string, ...parts: (string | null | undefined)[]) => !q || parts.some((p) => (p ?? "").toLowerCase().includes(q));
19
28
  const areaName = (id: string | null) => data?.areas.find((a) => a.id === id)?.name ?? "unsorted";
29
+ const hueOf = (id: string | null): string => {
30
+ const i = data ? data.areas.findIndex((a) => a.id === id) : -1;
31
+ return i < 0 ? "none" : String(i % HUES);
32
+ };
33
+ const chip = (id: string | null): SafeHtml => html`<span class="chip" data-hue="${hueOf(id)}">${areaName(id)}</span>`;
34
+ const dayKey = (d: Date): string => `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
35
+ const clock = (iso: string): string => new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
36
+
37
+ function dayLabel(d: Date): string {
38
+ const today = new Date();
39
+ const yesterday = new Date();
40
+ yesterday.setDate(today.getDate() - 1);
41
+ if (dayKey(d) === dayKey(today)) return "Today";
42
+ if (dayKey(d) === dayKey(yesterday)) return "Yesterday";
43
+ return d.toLocaleDateString(undefined, { weekday: "long", day: "numeric", month: "short" });
44
+ }
45
+
46
+ function ago(iso: string): string {
47
+ const m = Math.round((Date.now() - Date.parse(iso)) / 60_000);
48
+ if (!(m >= 0)) return formatTime(iso);
49
+ if (m < 1) return "just now";
50
+ if (m < 60) return `${m}m ago`;
51
+ const h = Math.round(m / 60);
52
+ return h < 24 ? `${h}h ago` : `${Math.round(h / 24)}d ago`;
53
+ }
54
+
55
+ function header(): void {
56
+ const now = new Date();
57
+ const h = now.getHours();
58
+ greeting.textContent = h < 12 ? "Good morning" : h < 18 ? "Good afternoon" : "Good evening";
59
+ dateLine.textContent = now.toLocaleDateString(undefined, { weekday: "long", day: "numeric", month: "long", year: "numeric" });
60
+ }
20
61
 
21
62
  function pageLinks(f: { pages?: string[]; wiki: string | null; areaId: string | null }): SafeHtml {
22
63
  const pages = (f.pages ?? []).filter((p) => p.endsWith(".html") && p.includes("/") && !p.includes(".."));
@@ -24,37 +65,66 @@ function pageLinks(f: { pages?: string[]; wiki: string | null; areaId: string |
24
65
  return f.wiki && f.areaId ? html`<a class="feed-page" href="/page.html?path=${encodeURIComponent(`${f.areaId}/${f.wiki}/index.html`)}">${f.wiki}</a>` : html``;
25
66
  }
26
67
 
27
- function feedItem(f: HomeFeedItem): SafeHtml {
28
- const link = f.sessionId ? html`<a href="/?session=${encodeURIComponent(f.sessionId)}">session</a>` : html`<a href="/run.html?id=${encodeURIComponent(f.runId)}">run</a>`;
29
- return html`<li><span class="muted mono">${formatTime(f.at)}</span> ${f.text}${f.verified ? "" : html` <span class="home-tag">unverified</span>`} <span class="muted">· ${areaName(f.areaId)}${f.wiki ? ` · ${f.wiki}` : ""}</span> ${pageLinks(f)} ${link}</li>`;
68
+ function panel(title: SafeHtml | string, count: number | null, state: string, items: SafeHtml[], empty: string): SafeHtml {
69
+ return html`<section class="today-panel" data-state="${state}"><h2><span>${title}</span>${count === null ? "" : html`<span class="today-count">${String(count)}</span>`}</h2>${items.length > 0 ? html`<ul class="today-list">${items}</ul>` : html`<p class="today-empty">${empty}</p>`}</section>`;
30
70
  }
31
71
 
32
- function list(items: SafeHtml[], empty: string): SafeHtml {
33
- return items.length > 0 ? html`<ul class="home-list">${items}</ul>` : html`<p class="muted">${empty}</p>`;
72
+ function strip(d: Home, q: string): SafeHtml {
73
+ const live = running.filter((r) => hit(q, r.instruction));
74
+ const runItems = live.slice(0, 4).map((r) => html`<li class="live"><a href="${runLink(r.id)}">${truncate(r.instruction, 90)}</a></li>`);
75
+ const proposals = d.proposed.length > 0 ? [html`<li>${String(d.proposed.length)} proposed area${d.proposed.length === 1 ? "" : "s"} to approve: ${d.proposed.map((p) => p.name).join(", ")}. Run <code>nexo areas list</code>.</li>`] : [];
76
+ const toReview = review.filter((r) => hit(q, r.instruction)).slice(0, 4).map((r) => html`<li><a href="${runLink(r.runId)}">${truncate(r.instruction, 80)}</a> <span class="muted">${r.score === null ? "unscored" : `score ${Math.round(r.score * 100) / 100}`}</span></li>`);
77
+ const needs = review.length + d.proposed.length;
78
+ const sessions = d.sessions.filter((s) => hit(q, s.title, s.cwd, areaName(s.areaId))).slice(0, 4).map((s) => html`<li><a href="${sessionLink(s.id)}">${truncate(s.title || s.id, 70)}</a> <span class="muted">${ago(s.updatedAt)}</span></li>`);
79
+ return html`${panel("Running", live.length, live.length > 0 ? "running" : "idle", runItems, "No runs in progress.")}${panel(html`<a href="/runs.html?tab=review">Needs you</a>`, needs, needs > 0 ? "attention" : "idle", [...proposals, ...toReview], "Nothing waiting for a verdict or an approval.")}${panel("Pick up", null, "idle", sessions, "No recent sessions.")}`;
34
80
  }
35
81
 
36
- function areaCard(a: HomeArea): SafeHtml {
37
- return html`<a class="home-area" href="/area.html?id=${encodeURIComponent(a.id)}"><strong>${a.name}</strong> <span class="muted">${String(a.recent)} this week · ${String(a.wikis.length)} wikis</span><span class="home-scope muted">${a.scope}</span></a>`;
82
+ function tile(d: Home, a: HomeArea): SafeHtml {
83
+ const week = Array.from({ length: 7 }, (_, k) => {
84
+ const day = new Date();
85
+ day.setDate(day.getDate() - (6 - k));
86
+ const key = dayKey(day);
87
+ return d.feed.filter((f) => f.areaId === a.id && dayKey(new Date(f.at)) === key).length;
88
+ });
89
+ const total = week.reduce((s, n) => s + n, 0);
90
+ const cells = week.map((n) => html`<span data-level="${String(Math.min(n, 3))}"></span>`);
91
+ const wikis = [...a.wikis].sort((x, y) => y.pageCount - x.pageCount).slice(0, 4).map((w) => html`<li><a href="/page.html?path=${encodeURIComponent(`${w.path}/index.html`)}">${w.name}</a></li>`);
92
+ return html`<article class="tile" data-hue="${hueOf(a.id)}"><h3><a href="/area.html?id=${encodeURIComponent(a.id)}">${a.name}</a></h3><p class="tile-scope">${a.scope}</p>${wikis.length > 0 ? html`<ul class="tile-wikis" aria-label="Wikis">${wikis}</ul>` : html`<p class="tile-scope">No wikis yet.</p>`}<div class="tile-foot"><span>${String(a.recent)} this week · ${String(a.wikis.length)} ${a.wikis.length === 1 ? "wiki" : "wikis"}</span><span class="week" role="img" aria-label="${`${total} tasks filed in the last 7 days`}" title="Tasks filed per day, last 7 days">${cells}</span></div></article>`;
93
+ }
94
+
95
+ function timeline(d: Home, q: string): SafeHtml {
96
+ const entries: Entry[] = [
97
+ ...d.feed.map((f): Entry => {
98
+ const link = f.sessionId ? html`<a href="${sessionLink(f.sessionId)}">session</a>` : html`<a href="${runLink(f.runId)}">run</a>`;
99
+ return { at: f.at, kind: "done", text: `${f.text} ${f.wiki ?? ""} ${areaName(f.areaId)}`, body: html`${f.text}${f.verified ? "" : html` <span class="home-tag">unverified</span>`}`, meta: html`${chip(f.areaId)} ${pageLinks(f)} ${link}` };
100
+ }),
101
+ ...d.decisions.map((x): Entry => ({ at: x.at, kind: "decision", text: `${x.choice} ${x.reason} ${x.wiki ?? ""} ${areaName(x.areaId)}`, body: html`<span class="tl-kind">Decided</span> <strong>${x.choice}</strong>${x.reason ? ` because ${x.reason}` : ""}`, meta: html`${chip(x.areaId)}${x.wiki ? html` <span>${x.wiki}</span>` : ""}` })),
102
+ ]
103
+ .filter((e) => hit(q, e.text))
104
+ .sort((a, b) => Date.parse(b.at) - Date.parse(a.at))
105
+ .slice(0, 40);
106
+ if (entries.length === 0) return html`<p class="muted">${q ? "Nothing in the timeline matches." : "No activity yet. Each finished task adds a line here after it is scored."}</p>`;
107
+ const days: { label: string; items: Entry[] }[] = [];
108
+ for (const e of entries) {
109
+ const label = dayLabel(new Date(e.at));
110
+ const last = days[days.length - 1];
111
+ if (last && last.label === label) last.items.push(e);
112
+ else days.push({ label, items: [e] });
113
+ }
114
+ return html`${days.map((g) => html`<div class="tl-day"><h3>${g.label}</h3><ol class="tl">${g.items.map((e) => html`<li data-kind="${e.kind}"><time datetime="${e.at}">${clock(e.at)}</time><div class="tl-body">${e.body}<div class="tl-meta">${e.meta}</div></div></li>`)}</ol></div>`)}`;
38
115
  }
39
116
 
40
117
  function render(): void {
41
118
  if (!data) return;
42
119
  const d = data;
43
120
  const q = search.value.trim().toLowerCase();
44
- const feed = d.feed.filter((f) => hit(q, f.text, f.wiki, areaName(f.areaId)));
45
- const decisions = d.decisions.filter((x) => hit(q, x.choice, x.reason, x.wiki, areaName(x.areaId)));
46
- const areas = d.areas.filter((a) => hit(q, a.name, a.scope, ...a.wikis.map((w) => `${w.name} ${w.summary ?? ""}`)) || (q !== "" && feed.some((f) => f.areaId === a.id)));
47
- const sessions = d.sessions.filter((s) => hit(q, s.title, s.cwd, areaName(s.areaId)));
48
- const pending = d.proposed.length > 0 ? html`<p class="home-note">${String(d.proposed.length)} proposed area(s) waiting for approval: ${d.proposed.map((p) => p.name).join(", ")}. Run <code>nexo areas list</code>.</p>` : "";
49
- const decisionItems = decisions.slice(0, 20).map((x) => html`<li><span class="muted mono">${formatTime(x.at)}</span> <strong>${x.choice}</strong>${x.reason ? html` <span class="muted">because ${x.reason}</span>` : ""} <span class="muted">· ${areaName(x.areaId)}</span></li>`);
50
- const sessionItems = sessions.map((s) => html`<li><a href="/?session=${encodeURIComponent(s.id)}">${s.title || s.id}</a> <span class="muted">${s.cwd} · ${formatTime(s.updatedAt)}</span></li>`);
51
- box.innerHTML = html`${pending}
52
- <section><h2>Areas</h2><div class="home-areas">${areas.map((a) => areaCard(a))}</div></section>
53
- <section><h2>Recent</h2>${list(feed.slice(0, 20).map(feedItem), "No activity yet. Each finished task adds a line here after it is scored.")}</section>
54
- <section><h2>Decisions</h2>${list(decisionItems, "No decisions recorded yet.")}</section>
55
- <section><h2>Recent sessions</h2>${list(sessionItems, "No sessions.")}</section>`.value;
121
+ const areas = d.areas.filter((a) => hit(q, a.name, a.scope, ...a.wikis.map((w) => `${w.name} ${w.summary ?? ""}`)) || (q !== "" && d.feed.some((f) => f.areaId === a.id && hit(q, f.text))));
122
+ box.innerHTML = html`<div class="today">${strip(d, q)}</div>
123
+ <section><h2>Areas</h2>${areas.length > 0 ? html`<div class="tiles">${areas.map((a) => tile(d, a))}</div>` : html`<p class="muted">No areas match.</p>`}</section>
124
+ <section class="tl-wrap"><h2>Timeline</h2>${timeline(d, q)}</section>`.value;
56
125
  }
57
126
 
127
+ header();
58
128
  search.addEventListener("input", render);
59
129
  getJson<Home>("/api/home")
60
130
  .then((d) => {
@@ -62,5 +132,18 @@ getJson<Home>("/api/home")
62
132
  render();
63
133
  })
64
134
  .catch((error) => {
135
+ box.innerHTML = "";
65
136
  errorBox.innerHTML = renderError(asErrorBody(error)).value;
66
137
  });
138
+ getJson<RunListResponse>("/api/runs?limit=25")
139
+ .then((r) => {
140
+ running = r.runs.filter((x) => x.status === "running");
141
+ render();
142
+ })
143
+ .catch(() => undefined);
144
+ getJson<{ items: ReviewItem[] }>("/api/review-queue?limit=5")
145
+ .then((r) => {
146
+ review = r.items;
147
+ render();
148
+ })
149
+ .catch(() => undefined);
@@ -49,7 +49,7 @@ function mount(page: HomePage): void {
49
49
 
50
50
  const path = new URLSearchParams(location.search).get("path") ?? "";
51
51
  const [area = "", folder = ""] = path.split("/");
52
- crumbs.replaceChildren(link("Home", "/home.html"), " / ", link(area, `/area.html?id=${encodeURIComponent(area)}`), " / ", link(folder, `/page.html?path=${encodeURIComponent(`${area}/${folder}/index.html`)}`));
52
+ crumbs.replaceChildren(link("Home", "/"), " / ", link(area, `/area.html?id=${encodeURIComponent(area)}`), " / ", link(folder, `/page.html?path=${encodeURIComponent(`${area}/${folder}/index.html`)}`));
53
53
  getJson<HomePage>(`/api/home/page?path=${encodeURIComponent(path)}`)
54
54
  .then((page) => {
55
55
  titleEl.textContent = page.title;
@@ -14,12 +14,14 @@ import { html, type SafeHtml } from "../lib/html.ts";
14
14
  import { createPoller } from "../lib/poller.ts";
15
15
  import { renderChildren, renderFeedbackForm, renderInjectedMemories, renderRunHeader, shouldPoll } from "../lib/run-view.ts";
16
16
  import { renderEscalations, renderScores } from "../lib/score-view.ts";
17
- import { findSpan, renderSpanDetail, renderSpanTree } from "../lib/span-view.ts";
17
+ import { findSpan, renderImageStrip, renderSpanDetail, renderSpanTree, spanImages } from "../lib/span-view.ts";
18
18
  import { renderTimeline, timelineRows } from "../lib/timeline.ts";
19
19
  import { asErrorBody, el, getJson, getText, postJson } from "./api.ts";
20
20
 
21
21
  const runId = new URLSearchParams(location.search).get("id") ?? "";
22
22
  const header = el<HTMLElement>("#header");
23
+ const imagesSection = el<HTMLElement>("#sec-images");
24
+ const inputImages = el<HTMLElement>("#input-images");
23
25
  const review = el<HTMLElement>("#review");
24
26
  const scores = el<HTMLElement>("#scores");
25
27
  const escalations = el<HTMLElement>("#escalations");
@@ -144,6 +146,11 @@ async function load(): Promise<boolean> {
144
146
  setHtml(injected, renderInjectedMemories(run.injectedMemories, run.run.id));
145
147
  setHtml(children, renderChildren(run.children, now, readOnly ?? null, run.childFeedback));
146
148
  roots = spans.roots;
149
+ // The run span holds the images sent with the instruction.
150
+ const attached = roots.find((r) => r.span.kind === "run")?.span;
151
+ const attachedPaths = attached ? spanImages(attached) : [];
152
+ imagesSection.hidden = attachedPaths.length === 0;
153
+ setHtml(inputImages, renderImageStrip(runId, attachedPaths, `${attachedPaths.length} sent with the instruction`));
147
154
  setHtml(timeline, renderTimeline(timelineRows(roots, now), selectedSpanId));
148
155
  setHtml(tree, html`${spans.truncated ? html`<p class="warn">This run has ${spans.total} spans; only the earliest are shown.</p>` : ""}${renderSpanTree(roots, now, 2, selectedSpanId)}`);
149
156
  restoreState(state);
@@ -12,11 +12,12 @@
12
12
  </head>
13
13
  <body>
14
14
  <a class="skip" href="#main">Skip to content</a>
15
- <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/home.html">Home</a><a href="/">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
15
+ <nav class="top" aria-label="Primary"><a href="/" class="brand">nexo</a><a href="/">Home</a><a href="/runs.html">Runs</a><a href="/sessions.html">Sessions</a><a href="/cost.html">Cost</a><a href="/learning.html">Learning</a><a href="/judge.html">Judge</a><a href="/optim.html">Optimization</a></nav>
16
16
  <main id="main" tabindex="-1">
17
17
  <nav class="run-nav" aria-label="Run sections"><a href="#sec-timeline">Timeline</a><a href="#sec-spans">Spans</a><a href="#sec-scores">Scores</a><a href="#sec-memories">Memories</a><a href="#sec-subagents">Subagents</a><a href="#sec-files">Files</a><a href="#sec-review">Review</a></nav>
18
18
  <div id="error"></div>
19
19
  <div id="header"></div>
20
+ <section id="sec-images" hidden><h2>Attached images</h2><div id="input-images"></div></section>
20
21
  <section id="sec-timeline"><h2>Timeline</h2><div id="timeline"></div></section>
21
22
  <section class="split" id="sec-spans">
22
23
  <div><h2>Spans</h2><div id="tree"></div></div>