diff --git a/README.md b/README.md index 926b7267..d8ad88c7 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ A few features depend on the local VS Code language model and are hidden in canv | Page | Description | | ------------------ | ------------------------------------------------------------------------------------- | | **Dashboard** | Practice scores with week-over-week trends, daily activity chart, top workspace stats | -| **Timeline** | Autonomy lanes per day or week, waits on you, and session families with verdicts | +| **Timeline** | Autonomy lanes per day, week or chosen range, waits on you, families with verdicts | | **Coding Moments** | Screenshot gallery from AI coding sessions with story reels and workspace filtering | ### Measure diff --git a/docs/content/observe/timeline.md b/docs/content/observe/timeline.md index dbe8a1c5..f3f2daf6 100644 --- a/docs/content/observe/timeline.md +++ b/docs/content/observe/timeline.md @@ -6,30 +6,47 @@ description: "When your agents worked, when they waited on you, and how your del # Timeline -The Timeline shows each day or week of AI coding as lanes, one per session: when the agent was working, when it was stopped for you, who sent every turn, and which sessions started which. A third view, **Families**, looks at each piece of delegated work as a whole: what it cost, where you stepped in, and how wide it fanned out. Every sentence on the page states what your logs show; it never guesses why. +The Timeline shows each day, week or chosen range of days of AI coding as lanes, one per session: when the agent was working, when it was stopped for you, who sent every turn, and which sessions started which. A fourth view, **Families**, looks at each piece of delegated work as a whole: what it cost, where you stepped in, and how wide it fanned out. Every sentence on the page states what your logs show; it never guesses why. ![Timeline View](/screenshots/screen-timeline.png) -Pick **Day**, **Week** or **Families** at the top. Step between active days or weeks with **‹ ›**, or with the **←** and **→** keys while the Timeline has focus (not the sidebar, a button or a text field). Click a lane, then use **↑** and **↓** to move between lanes; in the Families list they move between families. Family headers, impact rows and the sessions of a family open with **Enter** or **Space**. The workspace and harness filters in the sidebar, and the date range, apply to every view. +Pick **Day**, **Week**, **Range** or **Families** at the top. Step between active days or weeks with **‹ ›**, or with the **←** and **→** keys while the Timeline has focus (not the sidebar, a button or a text field); in the Range view they move the range by its own length. Click a lane, then use **↑** and **↓** to move between lanes; in the Families list they move between families. Family headers, impact rows and the sessions of a family open with **Enter** or **Space**. The workspace and harness filters in the sidebar, and the date range, apply to every view. + +## Picking dates + +Click the date at the top to open a calendar: + +![Picking a range in the calendar](/screenshots/screen-timeline-range.png) + +- A dot marks each day with activity, larger on the busiest days; hover a day to see its turns and agent hours. Days outside the date range loaded in the sidebar can't be picked, and **‹ ›** move between the months that hold them. +- **A day** opens that day, or the week holding it in the Week view. **Today** opens today when it's loaded (while picking a range, it shows today's month). +- **A range**: pick the first day, then the last. The **Range** view shows those days, both included, up to 92 days; a longer range is cut to its first 92 days, and the page says so. **Last 7 days**, **Last 30 days** and **This month** pick a range ending today, kept within the loaded days. +- Keyboard: **←** **→** move a day, **↑** **↓** a week, **Page Up** and **Page Down** a month, **Home** and **End** to the week's first and last day; **Enter** picks, **Esc** closes. Focus stays in the calendar while it's open, and returns to the date when it closes. + +A range is drawn whole: its axis marks every 6 hours over two or three days, each day up to two weeks, every other day up to a month, then each Monday. The lanes, KPIs, callouts, impact table and the strip's highlight all describe the range. Over more than a month the lanes get dense, and the page suggests picking fewer days. + +The view is kept by its dates, so reopening the dashboard shows it again, also a picked day with no activity. In a browser, the address holds it as a link that opens the Timeline at that view, for example `#view=range&from=2026-11-10&to=2026-11-17` (also `#view=day&date=…`, `#view=week&date=…` and `#view=families`). A linked range is kept within the loaded days; one with no loaded day opens the Day view. ## Definitions +**How these numbers are measured**, under the lanes, sums up these rules; this section and [How sessions are linked](#how-sessions-are-linked) give them in full. + | Term | Rule | |---|---| | Your input | A prompt you typed, or your answer to a question or a permission prompt, at the time you answered: when Copilot's own record of your answer (`human_response.recorded`) was logged, else when the question's result was. A turn counts as typed by you when the harness marked it as neither automated nor sent by another session | | Stopped for you | A turn waiting on a question or a permission prompt, answered or not. That time is never that turn's agent time; another turn of the same session can keep working meanwhile | -| Agent time | Per session: the time from each prompt to the turn's last logged agent activity, less the time that turn was stopped for you, merged where turns overlap. A turn with no logged duration adds nothing (its work isn't measured). A day or week counts the part inside it | +| Agent time | Per session: the time from each prompt to the turn's last logged agent activity, less the time that turn was stopped for you, merged where turns overlap. A turn with no logged duration adds nothing (its work isn't measured). A day, week or range counts the part inside it | | Waiting on you | Per session: the gaps from the end of its work (or of a question still open after it) to your next typed prompt, from 2 to 120 minutes (inferred waits: the log only shows the agent had stopped), plus every question and permission prompt you answered, from the request to its result (the tool's clock: the result can come a little after your answer), counted once where they overlap. Then summed over sessions: when a coordinator and its child both wait on one question, both count (session-minutes, not minutes of your attention). A question Copilot recorded your answer to before the question itself was logged has no measurable start: its answer counts, but no waiting time. A wait ending exactly at midnight belongs to the day before. A wait is counted on the day it started; its time counts on the days it covers. Gaps longer than 2 hours are time away, not waiting | | Longest unattended | Per family: from one of your inputs anywhere in the family (each decision once: a relayed answer paired with the child's own record of it is one input, at the child's time), for as long as the family's measured agent work kept running (pauses of at most 2 minutes don't end it), until the work stopped or your next input anywhere in the family, whichever came first. Every member counts, also those the filters hide or that have no turn in the range | | Peak parallel sessions | The most sessions doing agent work at the same time, and when | Questions are Copilot `ask_user` calls, questions a coordinator relayed to you from a child session, and Claude Code `AskUserQuestion` calls. An answer counts when the log shows one: a result from you, also when it was logged in the same millisecond as the question. An interrupted question stops the agent but isn't an answer; a question or permission prompt with no result logged stops it, unanswered, until the next event the harness logged after it (any line, in Copilot events and Claude Code transcripts alike), unless a Copilot `human_response.recorded` record says you answered it: then it stops the agent until that record, and counts as answered then. That record dates your answer also when a result was logged: in real logs the result comes from a few milliseconds to minutes later, and the record can even come before the question's own entry, so the result's time would move your answer, and a family's verdict, to the wrong day. A day that lies wholly inside a stop you didn't answer isn't an active day for the session, even when the turn goes on after it. Permission prompts count as yours only when the log shows a person decided them: a decision a policy made (`host_policy`, `unattended_fallback`) isn't a request to you, and when an older Copilot build logs no decision source, the prompt stops the agent but isn't counted as an answer. A relayed question is counted once: in the child that asked it when a session the relaying one started (directly or through its children) logged its own answer to it, each relayed answer pairing with one such answer; otherwise in the session that relayed it. The pair is found by the request both logged (the relay's `request_id` and the child's record of your answer) first; without one, by the nearest answer to a question within 10 seconds that isn't known to be for another request. Pairs are found once over the whole log, so a range that leaves out the child's answer still knows the relay delivered it: a paired relay is no answer and no input of the relaying session on any day. The time it stopped that session's agent is still that session's waiting, and makes the session active in the days it covers, like any stop; a relay that took no time adds nothing. An answer in an unrelated session, or to a permission prompt, never stands in for a relayed one. An answer is a point in time: it counts on its day even at midnight, and even when nothing else happened that day, also when the turn it belongs to started on another day. When a day holds only answers and no waiting time, the callout says which took no measurable time (question, result and answer at the same moment), which ended a wait that began earlier, and which had no waiting time measured in the period (recorded before the question was logged, or after its result). A Copilot session whose only logged activity is your answer to a permission prompt has no turn; the Timeline shows it as a lane with that wait, and other tabs don't count it. -Every interval is built over the whole log first, then clipped: to the date range, then to the day or week. So a range gives the same per-day values as its days one at a time, and the summary export of a day matches the Day view. Times (agent time, waiting) and counts of things that start (turns, typed prompts, waits that started, answers) add up from days to the week; peaks, longest stretches, distinct sessions and percentages don't. Work and waits outside the range never count; the turns just outside it that a total needs (the last input before it, a turn running into it, the next prompt after it) are read, never counted as turns. Days are local calendar days, so a daylight-saving day has 23 or 25 hours. +Every interval is built over the whole log first, then clipped: to the date range, then to the day, week or range shown (half-open: from its first midnight up to, not including, the midnight after its last day). So a range gives the same per-day values as its days one at a time, and the summary export of a day, or of the dates of a Range view, matches that view. Times (agent time, waiting) and counts of things that start (turns, typed prompts, waits that started, answers) add up from days to a week or a range; peaks, longest stretches, distinct sessions and percentages don't. Work and waits outside the range never count; the turns just outside it that a total needs (the last input before it, a turn running into it, the next prompt after it) are read, never counted as turns. Days are local calendar days, so a daylight-saving day has 23 or 25 hours, and a range over one has an hour less or more. ## What happened, in three callouts -Each day or week starts with three findings: +Each day, week or range starts with three findings: - **Unattended work**: the family with the longest unattended stretch, and how long it was. It names the coordinator, or, when the coordinator isn't shown, the family it belongs to. - **Where credits went**: the share of the shown credits used by child sessions, the child that used most, and the prompts you typed into it and the questions or permission prompts you answered in it, or that none was recorded. @@ -37,16 +54,18 @@ Each day or week starts with three findings: ## Day strip -The strip shows every active day in range, before the lane filters: days with a turn, agent work, waiting on you or an answer you gave, stacked as prompts you typed and automated turns. A day that holds only an answer (one logged at midnight, for example) is listed with an empty bar. Switch it to **Agent hours** to see agent working time per day. Click a day to open it in the current view. In the Week view, the selected week is highlighted. +The strip, right under the filters, lists every active day in range so you can pick one: days with a turn, agent work, waiting on you or an answer you gave, stacked as prompts you typed and automated turns. A day that holds only an answer (one logged at midnight, for example) is listed with an empty bar. Switch it to **Agent hours** to see agent working time per day. Click a day to open it in the current view; in the Range view, a click opens that day in the Day view. In the Week and Range views, the days shown are highlighted. + +With a filter on, the bars, their tooltips and the calendar's dots count only the sessions the filters show, each day judged as the Day view judges it: a session counts on a day when its lane that day passes the filters. A day with none keeps its place with an empty bar. The strip's total is that of the day or range shown, the same as its KPIs; in the Week view, that of the selected day. ## Lanes -Each lane is one session with activity in the day or week: a turn, agent work, waiting on you or an answer. It is labelled with the name you gave the session, its role (coordinator, child, grandchild, or descendant with its depth), its repository (never a path; Xcode logs none, since its workspace name is the conversation's title), and its harness and model. Unnamed sessions read *Untitled … session N* with their date. +Each lane is one session with activity in the day, week or range: a turn, agent work, waiting on you or an answer. It is labelled with the name you gave the session, its role (coordinator, child, grandchild, or descendant with its depth), its repository (never a path; Xcode logs none, since its workspace name is the conversation's title), and its harness and model. Unnamed sessions read *Untitled … session N* with their date. -- **Bars** show when the agent was working, clipped to the day or week. **Light hatching** shows a session waiting for your next prompt; **dense hatching** shows a turn stopped for your answer. +- **Bars** show when the agent was working, clipped to the day, week or range. **Light hatching** shows a session waiting for your next prompt; **dense hatching** shows a turn stopped for your answer. - **Markers** show who sent each turn: ● you, ◆ another agent or session, ○ autopilot, ■ compaction or the harness. - A small badge counts the **sub-agent launches** a turn recorded: Copilot sub-agent runs, Claude Code `Agent` or `Task` calls, and Codex `spawn_agent` calls. -- In **Session tree** grouping, child sessions sit under the session that started them, with a dashed connector: from when the parent requested them, when its `create_session` call logged it (the child's own log begins a little later, by up to a minute), else from their first activity shown, and to their nearest shown ancestor when the parent is hidden. A child whose parent isn't drawn above it says why: *parent hidden by a filter*, *parent not active this day*, or *parent outside this range or the sidebar selection*; it adds *linked to its nearest shown ancestor* when the connector skips a hidden parent. Each family has a header with its typed and automated turns, agent time, credits and share; click it to collapse the family. **Flat** lists the lanes by start time. +- In **Session tree** grouping, child sessions sit under the session that started them, with a dashed connector: from when the parent requested them, when its `create_session` call logged it (the child's own log begins a little later, by up to a minute), else from their first activity shown, and to their nearest shown ancestor when the parent is hidden. A child whose parent isn't drawn above it says why: *parent hidden by a filter*, *parent not active this day* (or *this week*, *in this range*), or *parent outside this range or the sidebar selection*; it adds *linked to its nearest shown ancestor* when the connector skips a hidden parent. Each family has a header with its typed and automated turns, agent time, credits and share; click it to collapse the family. **Flat** lists the lanes by start time. - **Color** lanes by family or by harness. Use the filters above the lanes to show one harness, search a repository or model, or keep only families, sessions you typed in, sessions that waited on you, sessions that used sub-agents, or sessions with more than one turn. The KPIs, callouts and the impact table then describe the shown sessions; the longest unattended stretch still follows the whole family. The selection stays on a lane you can see. @@ -55,7 +74,22 @@ Use the filters above the lanes to show one harness, search a repository or mode **Impact by session family** ranks the day's families by credits, with typed and automated turns, agent time and the longest unattended stretch; bars compare each family with the largest. Click a row to select the family's coordinator, or its top session shown when the coordinator isn't. -Click a lane to see its details: role and direct parent, branch, harness, model and time span, typed and automated turns, agent time and credits in the day or week, sub-agent launches, and every turn that started in it with its time, sender, its own agent time and the time it was stopped for you. No prompt or response body is shown; a name you gave the session can contain the same words. Links open the parent session, the fork source, the first child, the family in the Families view, and **Context Health › Prompt Cache** (and **Token Types** when token reporting is on). +Click a lane to see its details: role and direct parent, branch, harness, model and time span, typed and automated turns, agent time and credits in the day, week or range, sub-agent launches, and every turn that started in it with its time, sender, its own agent time and the time it was stopped for you. Links open the parent session, the fork source, the first child, the family in the Families view, and **Context Health › Prompt Cache** (and **Token Types** when token reporting is on). + +### Prompts and questions + +**Show prompts and questions**, in the lane's details, is off until you turn it on. It shows the text behind the lane's day, week or range, in time order: + +![A lane's prompts and questions](/screenshots/screen-timeline-text.png) + +- **Each turn**: the message that started it (what you typed, or what a coordinator, relay or autopilot sent), and the end of the agent's reply in the turn: its own messages, never the code it wrote to files, its reasoning or a tool's output. Compaction summaries and harness messages aren't shown; the agent's reply to a harness message is. +- **Questions**: what the agent asked, with its choices and what it said just before, and your answer and how long you took. A relayed question shows the child's question and your reply. +- **Permission prompts**: what was requested (the command, path, URL, tool or extension), the kind of request, the agent's stated reason, and the decision. Decisions a policy made aren't requests to you, so they aren't listed. +- **Waits for your next prompt**: how long the agent waited, and the end of the reply it waited after. + +Click a hatched wait on a lane, or focus it and press **Enter** or **Space**, to jump to it and highlight it. The highlight lasts until you open a lane another way or the Timeline reloads. Copilot App and Copilot CLI log all of these; Claude Code logs its `AskUserQuestion` questions and your answers; other harnesses show the turns' messages. + +The text is read again from that session's log on this machine when you open the lane, and only for that lane and its day, week or range. A lane that lists more than 50,000 turns in a range shows no text; pick fewer days to read it. A background worker reads the log, keeps only the turns, questions and permission prompts the lane shows, and scrubs them, so nothing else of the session reaches the page. The Timeline's data, the `@aicoach` chat tool and the summary export never carry it, and nothing of it leaves the page. Credentials are replaced with `[secret]` before the text leaves the worker, so the page never receives them: private keys, well-known token formats (GitHub, AWS, Google, OpenAI, Anthropic, Slack, npm, GitLab, Stripe and others), JWTs, `Authorization` headers, connection-string keys and passwords, `key = value` pairs in env files, JSON, YAML and query strings when the name ends in a word such as password, secret, token or API key (`DB_PASSWORD`, `clientSecret`), credential flags (`--token`, `--password`, `-u user:password`, `-u user -p password`), long random-looking or hex keys, a password named in prose (`change the password to …`), your answer to a question that asks for a password, token or key, a lone word you send right after the agent asks for one, and, on a line that mentions a password, token or key, any long run of letters and digits. Links, email addresses, your home folder (as `~`) and your names (as `[name]`) are replaced too, and long text is cut. A compaction shows no text: neither its summary nor the reply that holds it. This covers those patterns; it isn't a guarantee that text you or an agent wrote holds nothing private. **Mask names** hides the section. Your choice is kept for the panel; turn it off to see only counts and timings. The tooltips on the toggle and on **Mask names** say what each one shows and hides. ## Families @@ -88,9 +122,9 @@ Claude Code sub-agents are part of their parent session's lane. ## Names, credits and privacy - **Names and branches** come from Copilot App and Copilot CLI (`workspace.yaml`). Only names the file marks as given by you (`user_named: true`) are shown, and not even those when they repeat your first prompt or its first words, however few (a name that ends inside a word of the prompt doesn't repeat it): an automatic title often is your prompt, so it and any name of unknown origin read *Untitled … session N*. Before a name, branch, repository or model is shown, links, email addresses, drive, network and absolute paths (quoted ones whole; an unquoted one with spaces up to its first word with a file extension, else up to the next path or the end of the clause), your OS account name and your GitHub handle are removed. An OS account name shorter than three characters is left as it is, since it would match ordinary words; a signed-in GitHub handle of any length is still removed as a branch's first word. A branch loses a first word that is your signed-in GitHub handle; your OS account name in a branch reads `[name]` where it stands, so the branch never passes for its topic alone. Generic account names such as `vscode`, `node` or `root` are ordinary words and stay. A repository named only after you reads *personal repository*. This covers the patterns above; it isn't a guarantee that free text you typed into a name holds nothing personal. -- **Mask names** replaces session names with *Session N*, hides branches, replaces repositories and every model name with letters (*Repository A*, *Model A*; a model name can be a deployment you named, even behind a provider's prefix), and clears and turns off both search boxes while it is on. It covers the Timeline page only: the sidebar still shows the workspace you picked, and the summary export isn't masked. +- **Mask names** replaces session names with *Session N*, hides branches, replaces repositories and every model name with letters (*Repository A*, *Model A*; a model name can be a deployment you named, even behind a provider's prefix), hides the prompts and questions in the lane's details, and clears and turns off both search boxes while it is on. It covers the Timeline page only: the sidebar still shows the workspace you picked, and the summary export isn't masked. - **Copilot CLI or Copilot App**: `workspace.yaml` `client_name` tells them apart. Without that file the log holds no client field, and such a session is labelled *Copilot App*. - **Credits** are the AI credits Copilot App and Copilot CLI log for each model call, sub-agents included. Other harnesses show time and turns. -- The dashboard runs locally from your session logs, read-only. The Timeline adds no prompt text of its own: names that repeat a first prompt are withheld (above), but a name you gave holds whatever words you typed into it. +- The dashboard runs locally from your session logs, read-only. The lanes, cards, callouts and the Families view show no prompt text; only **Show prompts and questions** in a lane's details does, for that lane. Names that repeat a first prompt are withheld (above), but a name you gave holds whatever words you typed into it. Ask `@aicoach` about autonomy and delegation: the `aiEngineerCoach_timeline` tool returns the same KPIs, callouts and family verdicts for the chat model to read, with session and repository names always masked and no branches; the Timeline page is where names appear. It checks that dates are real calendar dates and reports the range you asked for apart from the days it found. The summary export adds an **Autonomy and Delegation** section with counts only. diff --git a/docs/static/screenshots/screen-timeline-range.png b/docs/static/screenshots/screen-timeline-range.png new file mode 100644 index 00000000..c27ceee1 Binary files /dev/null and b/docs/static/screenshots/screen-timeline-range.png differ diff --git a/docs/static/screenshots/screen-timeline-text.png b/docs/static/screenshots/screen-timeline-text.png new file mode 100644 index 00000000..7729fea9 Binary files /dev/null and b/docs/static/screenshots/screen-timeline-text.png differ diff --git a/docs/static/screenshots/screen-timeline.png b/docs/static/screenshots/screen-timeline.png index 2d7c361d..5f17110a 100644 Binary files a/docs/static/screenshots/screen-timeline.png and b/docs/static/screenshots/screen-timeline.png differ diff --git a/src/core/analyzer-timeline.test.ts b/src/core/analyzer-timeline.test.ts index a62b2714..a229d479 100644 --- a/src/core/analyzer-timeline.test.ts +++ b/src/core/analyzer-timeline.test.ts @@ -82,7 +82,8 @@ describe('TimelineAnalyzer', () => { const data = createAnalyzer([session]).getTimelineData({ fromDate: '2024-03-15', toDate: '2024-03-15' }, ctx); expect(data.sessions).toHaveLength(1); expect(data.sessions[0]).toMatchObject({ id: 's1', repo: 'shop', harness: 'Copilot App', parent: -1, via: null }); - expect(data.sessions[0].turns).toEqual([ + expect(data.sessions[0].turns.every(t => typeof t.id === 'string')).toBe(true); + expect(data.sessions[0].turns.map(({ id: _id, ...turn }) => turn)).toEqual([ { t: at(10), d: 600_000, k: 'you', sub: 0, comp: false, cr: 2.5, tok: 1000 }, { t: at(10, 20), d: 0, k: 'autopilot', sub: 1, comp: false, cr: 0, tok: 0, noDuration: true }, ]); diff --git a/src/core/analyzer-timeline.ts b/src/core/analyzer-timeline.ts index 5210fee5..a960c18b 100644 --- a/src/core/analyzer-timeline.ts +++ b/src/core/analyzer-timeline.ts @@ -13,6 +13,7 @@ import { toDateStr, isoWeek } from './helpers'; import { AnalyzerBase } from './analyzer-base'; import type { EditLocIndex } from './edit-loc-diff'; import { harnessLabel, scrubBranch, scrubLabel, scrubRepository, type ScrubContext } from './session-labels'; +import { turnIdentity } from './fork-ownership'; import { localScrubContext } from './session-workspace-meta'; import { resolveParentLinks, type ParentLink } from './timeline-links'; import { addDays, dayStart, prepareTimeline } from './timeline-model'; @@ -69,6 +70,7 @@ function timelineTurn(r: SessionRequest, paired: RelayPairs, origin?: Map { expect(await loadCacheData()).toBeNull(); clearCache(); }); + + it('re-parses a version 32 cache, whose Copilot waits beside editor chats took a later question reusing an answered one’s ID for answered', async () => { + clearCache(); + const editor = makeSession(); + const cli = createSession({ + sessionId: 'cli-beside-editor', workspaceId: 'ws1', workspaceName: 'workspace', harness: 'GitHub Copilot CLI', + requests: [createRequest({ requestId: 'r1', timestamp: 1, messageText: 'go', responseText: '', + userWaits: [{ start: 2, end: 3, kind: 'question', answered: true, answeredAt: 3 }, { start: 5, end: 6, kind: 'question', answered: true, answeredAt: 3 }] })], + }); + const result: ParseResult = { + workspaces: new Map(), sessions: [editor, cli], editLocIndex: new Map(), + sessionSourceIndex: new Map([[cli.sessionId, { kind: 'cli-events', filePath: '/logs/ws1/copilot/events.jsonl', workspaceId: 'ws1', workspaceName: 'workspace', harness: 'GitHub Copilot CLI' }]]), + }; + await saveCacheData(result, { '/logs/ws1': { chatCount: 1, chatMaxMtime: 1, editCount: 0, editMaxMtime: 0 } }); + await flushCacheWrites(); + expect((await loadCacheData())?.result.sessions.length).toBe(2); + const metaFile = path.join(getCacheDir(), 'meta.json'); + fs.writeFileSync(metaFile, JSON.stringify({ ...JSON.parse(fs.readFileSync(metaFile, 'utf-8')) as object, version: 32 })); + expect(await loadCacheData()).toBeNull(); + clearCache(); + }); }); describe('computeDirMetas', () => { diff --git a/src/core/cache.ts b/src/core/cache.ts index 2558fecb..5127550e 100644 --- a/src/core/cache.ts +++ b/src/core/cache.ts @@ -14,10 +14,11 @@ import * as fs from 'fs'; import * as path from 'path'; import { Worker } from 'worker_threads'; -import { Session, Workspace } from './types'; +import { Session, Workspace, type TimelineSessionText, type TimelineTextScope, type TimelineTextSuperseded } from './types'; import { EditLoc, EditLocIndex } from './edit-loc-diff'; import { warnCore } from './log'; -import { loadSessionDetails } from './session-image-loader'; +import { loadSessionDetails, loadSessionTimelineText } from './session-image-loader'; +import type { ScrubContext } from './session-labels'; import { stripSingleSession } from './parser-shared'; import { getCacheDir } from './cache-paths'; import { isCacheWriteWorkerResult, removeStaleTempFiles, writeCacheFiles, type CacheWritePayload } from './cache-write'; @@ -72,8 +73,10 @@ const cacheMetaPath = (): string => path.join(getCacheDir(), 'meta.json'); /** Bump when a parser change alters what a cached session holds. 32: Copilot waits keep the time of your answer's own * record and the request it answered (`answeredAt`, `requestId`); sessions from Copilot logs beside editor chats are - * cached with their workspace, and an older entry would date their answers by the result. */ -const CACHE_VERSION = 32; + * cached with their workspace, and an older entry would date their answers by the result. 33: a record of your answer + * marks only the question it answered, not a later one that reused its tool call ID. 34: nor a question a record for + * another request was logged before. */ +const CACHE_VERSION = 34; /** Refuse to JSON.parse cache files beyond these sizes: a corrupted (or * tampered) cache must degrade to a full re-parse, not OOM the host. */ @@ -472,11 +475,7 @@ export function stripSessionsForMemory(sessions: Session[]): void { */ export async function loadSessionFromDisk(sessionId: string): Promise { try { - let source = memoryCache?.result.sessionSourceIndex.get(sessionId); - if (!source) { - const cached = await loadCacheData(); - source = cached?.result.sessionSourceIndex.get(sessionId); - } + const source = await sessionSource(sessionId); if (!source) return null; return await loadSessionDetails(source, sessionId); @@ -485,3 +484,21 @@ export async function loadSessionFromDisk(sessionId: string): Promise { + return memoryCache?.result.sessionSourceIndex.get(sessionId) ?? (await loadCacheData())?.result.sessionSourceIndex.get(sessionId); +} + +/** One Timeline lane's text, read again from its log and scrubbed in the parse worker (see `TimelineTextRequest`). */ +export async function loadTimelineTextFromDisk( + sessionId: string, scope: TimelineTextScope, labels: ScrubContext, kept?: string[], +): Promise { + try { + const source = await sessionSource(sessionId); + if (!source) return null; + return await loadSessionTimelineText({ type: 'timeline-text', source, sessionId, scope, labels, ...(kept ? { kept } : {}) }); + } catch (error) { + warnCore('cache', `Could not read the Timeline text of session ${sessionId}`, error); + return null; + } +} diff --git a/src/core/fork-ownership.ts b/src/core/fork-ownership.ts index 6074d05c..9847c1e0 100644 --- a/src/core/fork-ownership.ts +++ b/src/core/fork-ownership.ts @@ -142,12 +142,16 @@ export function withInheritedTurnsRemoved(sessions: readonly Session[]): Session }; }); } +/** A turn's identity that stays the same while its session is still being written: its prompt's event, else its + * request (a Copilot request ID is its latest reply's, so it changes as the turn gains messages). */ +export const turnIdentity = (r: Pick): string => r.userEventId || r.requestId; + /** A session re-read in full (for its detail view) with the same turns the analysis kept: a fork's copied turns stay * counted once, in their source. `analyzed` is the session as the analyzer holds it. */ export function withAnalyzedTurns(full: Session, analyzed: Session | null): Session { if (!analyzed?.inheritedTurns) return full; - const kept = new Set(analyzed.requests.map(r => r.requestId)); - const requests = full.requests.filter(r => kept.has(r.requestId)); + const kept = new Set(analyzed.requests.map(turnIdentity)); + const requests = full.requests.filter(r => kept.has(turnIdentity(r))); return { ...full, requests, requestCount: requests.length, inheritedTurns: analyzed.inheritedTurns, ...(analyzed.forkedFromId ? { forkedFromId: analyzed.forkedFromId } : {}), diff --git a/src/core/parse-worker.ts b/src/core/parse-worker.ts index 1521995e..6a6cdf12 100644 --- a/src/core/parse-worker.ts +++ b/src/core/parse-worker.ts @@ -17,7 +17,7 @@ import { getParseWarningCounts, getParseWarnings, setCuriosityDetector } from '. import { detectCuriosity } from './curiosity'; import { installRuntimeDebugHooks, runtimeDebug } from './runtime-debug'; import { createTelemetrySampler } from './worker-telemetry'; -import { extractSourceImages, loadSourceSession, type SessionSourceRequest } from './session-images'; +import { extractSourceImages, loadSourceSessionDetail, loadTimelineText, type SessionSourceRequest, type TimelineTextRequest } from './session-images'; interface ParseWorkerRequest { logsDirs?: string[]; @@ -75,10 +75,26 @@ function isAckMessage(msg: unknown): msg is AckMessage { /** Set by the streaming step to receive chunk acks from the parent. */ let onAck: ((seq: number) => void) | null = null; +const isStringArray = (value: unknown): value is string[] => Array.isArray(value) && value.every(item => typeof item === 'string'); +const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value); + +/** A Timeline text request's scope, kept turns and scrub labels. */ +function isTimelineTextFields(candidate: Partial): boolean { + const { scope, labels } = candidate; + return typeof scope === 'object' && scope !== null && isFiniteNumber(scope.from) && isFiniteNumber(scope.to) + && Array.isArray(scope.turns) && scope.turns.every(t => typeof t === 'object' && t !== null && isFiniteNumber(t.t) + && (t.id === undefined || typeof t.id === 'string')) + && (candidate.kept === undefined || isStringArray(candidate.kept)) + && typeof labels === 'object' && labels !== null && isStringArray(labels.names) + && (labels.home === undefined || typeof labels.home === 'string') && (labels.handles === undefined || isStringArray(labels.handles)); +} + function isSessionSourceRequest(value: object): value is SessionSourceRequest { const candidate = value as Partial; const source = candidate.source; - return (candidate.type === 'session-detail' || (candidate.type === 'session-images' && typeof candidate.requestId === 'string' + return (candidate.type === 'session-detail' + || (candidate.type === 'timeline-text' && isTimelineTextFields(candidate)) + || (candidate.type === 'session-images' && typeof candidate.requestId === 'string' && (candidate.userEventId === undefined || typeof candidate.userEventId === 'string') && (candidate.requestIndex === undefined || (Number.isSafeInteger(candidate.requestIndex) && candidate.requestIndex >= 0)))) && typeof candidate.sessionId === 'string' @@ -99,13 +115,16 @@ function onMessage(handler: (msg: ParseWorkerRequest) => void | Promise): onAck?.(raw.seq); return; } - if (typeof raw === 'object' && raw !== null && 'type' in raw && (raw.type === 'session-images' || raw.type === 'session-detail')) { + if (typeof raw === 'object' && raw !== null && 'type' in raw + && (raw.type === 'session-images' || raw.type === 'session-detail' || raw.type === 'timeline-text')) { try { if (!isSessionSourceRequest(raw)) throw new Error('Invalid session source request'); if (raw.type === 'session-images') { send({ type: 'session-images', images: extractSourceImages(raw.source, raw.sessionId, raw.requestId, raw) }); + } else if (raw.type === 'timeline-text') { + send({ type: 'timeline-text', text: loadTimelineText(raw) }); } else { - send({ type: 'session-detail', session: loadSourceSession(raw.source, raw.sessionId) }); + send({ type: 'session-detail', session: loadSourceSessionDetail(raw.source, raw.sessionId) }); } } catch (error) { send({ type: 'error', message: error instanceof Error ? error.message : String(error) }); diff --git a/src/core/parser-claude.test.ts b/src/core/parser-claude.test.ts index 1c3139fb..14c72aff 100644 --- a/src/core/parser-claude.test.ts +++ b/src/core/parser-claude.test.ts @@ -168,7 +168,7 @@ describe('parseClaudeSessions', () => { const request = parseClaudeSessions(projectsDir)[0].sessions[0].requests[0]; const ms = Date.parse; expect(request.userWaits).toEqual([ - { start: ms('2025-06-15T10:00:05Z'), end: ms('2025-06-15T10:04:05Z'), kind: 'question', answered: true }, + { start: ms('2025-06-15T10:00:05Z'), end: ms('2025-06-15T10:04:05Z'), kind: 'question', answered: true, text: { answer: 'User answered: B' } }, { start: ms('2025-06-15T10:04:10Z'), end: ms('2025-06-15T10:04:11Z'), kind: 'question', answered: false }, { start: ms('2025-06-15T10:04:20Z'), end: ms('2025-06-15T10:04:20Z'), kind: 'question', answered: false }, ]); @@ -176,6 +176,30 @@ describe('parseClaudeSessions', () => { }); }); + it('keeps the agent’s own text apart from the file contents its write tools wrote', () => { + withProjectsDir('s.jsonl', [ + makeUser('write it'), + makeAssistant('I will write the file.', '2025-06-15T10:00:01Z'), + makeToolAssistant('Write', { file_path: '/p/a.ts', content: 'export const x = 1;' }, '2025-06-15T10:00:02Z', 't1'), + { type: 'user', timestamp: '2025-06-15T10:00:03Z', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok' }] } }, + ], (projectsDir) => { + const request = parseClaudeSessions(projectsDir)[0].sessions[0].requests[0]; + expect(request.responseText).toContain('export const x = 1;'); + expect(request.replyText).toBe('I will write the file.'); + }); + }); + + it('logs an empty reply, not the file contents, for a turn that only wrote a file', () => { + withProjectsDir('s.jsonl', [ + makeUser('write it'), + makeToolAssistant('Write', { file_path: '/p/a.ts', content: 'export const x = 1;' }, '2025-06-15T10:00:02Z', 't1'), + { type: 'user', timestamp: '2025-06-15T10:00:03Z', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 't1', content: 'ok' }] } }, + ], (projectsDir) => { + const request = parseClaudeSessions(projectsDir)[0].sessions[0].requests[0]; + expect([request.responseText.includes('export const x = 1;'), request.replyText]).toEqual([true, '']); + }); + }); + it('marks a turn logged with its own queue or API records as logged live, and a fork’s copied turn not', () => { withProjectsDir('s.jsonl', [ { type: 'queue-operation', timestamp: '2025-06-15T10:00:00Z', sessionId: 'sess-1', operation: 'enqueue' }, @@ -222,6 +246,23 @@ describe('parseClaudeSessions', () => { } }); + it('keeps an AskUserQuestion call’s questions, options, your answer and what the agent said before it', () => { + withProjectsDir('s.jsonl', [ + makeUser('plan it', '2025-06-15T10:00:00Z'), + makeAssistant('Two ways to do this.', '2025-06-15T10:00:03Z'), + makeToolAssistant('AskUserQuestion', { + questions: [{ question: 'Which approach?', header: 'Approach', options: [{ label: 'Rewrite', description: 'x' }, { label: 'Patch' }], multiSelect: false }], + }, '2025-06-15T10:00:05Z', 'q1'), + { type: 'user', timestamp: '2025-06-15T10:01:00Z', sessionId: 'sess-1', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'q1', content: [{ type: 'text', text: 'User has answered your questions: "Which approach?"="Patch"' }] }] } }, + makeAssistant('done', '2025-06-15T10:02:00Z'), + ], (projectsDir) => { + const [wait] = parseClaudeSessions(projectsDir)[0].sessions[0].requests[0].userWaits ?? []; + expect(wait.text).toEqual({ + ask: 'Which approach?', choices: ['Rewrite', 'Patch'], before: 'Two ways to do this.', answer: 'User has answered your questions: "Which approach?"="Patch"', + }); + }); + }); + it('keeps a fork that holds only copied turns, from its transcript to the Sessions list', () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-fork-copies-only-')); try { @@ -282,7 +323,7 @@ describe('parseClaudeSessions', () => { const waits = parseClaudeSessions(projectsDir)[0].sessions[0].requests.map(r => r.userWaits); expect(waits).toEqual([ [{ start: ms('2025-06-15T10:00:05Z'), end: ms('2025-06-15T10:03:00Z'), kind: 'question', answered: false }], - [{ start: ms('2025-06-15T10:03:05Z'), end: ms('2025-06-15T10:06:00Z'), kind: 'question', answered: true }], + [{ start: ms('2025-06-15T10:03:05Z'), end: ms('2025-06-15T10:06:00Z'), kind: 'question', answered: true, text: { answer: 'User answered: B' } }], undefined, ]); }); diff --git a/src/core/parser-claude.ts b/src/core/parser-claude.ts index 332a17df..9c185753 100644 --- a/src/core/parser-claude.ts +++ b/src/core/parser-claude.ts @@ -18,7 +18,7 @@ import * as fs from 'fs'; import * as path from 'path'; import { createHash } from 'crypto'; -import { CompactionEvent, Session, SessionRequest, UserWait } from './types'; +import { CompactionEvent, Session, SessionRequest, UserWait, UserWaitText } from './types'; import { assertTrustedPath, MAX_FILE_SIZE, createRequest, createSession, detectDevcontainerFromRequests, extractSkillNameFromPath, recordFailedFile, recordSkippedLines } from './parser-shared'; import { extractReasoningEffortFromModelId } from './helpers'; import { warnCore } from './log'; @@ -119,6 +119,8 @@ interface ClaudeAssistantData { nextIndex: number; lastTs: number | null; assistantTexts: string[]; + /** The agent's own text blocks, without the code its write tools wrote (`assistantTexts` holds both). */ + replyTexts: string[]; toolsUsed: string[]; editedFiles: string[]; referencedFiles: string[]; @@ -553,6 +555,25 @@ function toolResultHasContent(block: ClaudeContentBlock): boolean { && (typeof (c as { text?: unknown }).text !== 'string' || (c as { text: string }).text.trim() !== '')); } +function toolResultText(block: ClaudeContentBlock): string { + const content = (block as { content?: unknown }).content; + if (typeof content === 'string') return content.trim(); + if (!Array.isArray(content)) return ''; + return content.map(c => (isRecord(c) && typeof c.text === 'string' ? c.text : '')).filter(Boolean).join('\n').trim(); +} + +/** An `AskUserQuestion` call's questions and options, your answer (its result) and what the agent said before it. */ +function askUserQuestionText(input: unknown, answer: string | undefined, before: string | undefined): UserWaitText | undefined { + const questions = isRecord(input) && Array.isArray(input.questions) ? input.questions.filter(isRecord) : []; + const ask = questions.map(q => (typeof q.question === 'string' ? q.question.trim() : '')).filter(Boolean).join('\n'); + const choices = questions.flatMap((q): unknown[] => (Array.isArray(q.options) ? q.options : [])) + .map(o => (isRecord(o) && typeof o.label === 'string' ? o.label : '')).filter(Boolean); + const text: UserWaitText = { + ...(ask ? { ask } : {}), ...(choices.length ? { choices } : {}), ...(answer ? { answer } : {}), ...(before?.trim() ? { before: before.trim() } : {}), + }; + return Object.keys(text).length ? text : undefined; +} + /** The stream of a line's response: a sub-agent's for a sidechain line, and for any line of a sub-agent's transcript, * marked or not. Read for every line of a request's responses, and for its prompt, so the request's own chain agrees * with their prompt-cache streams. */ @@ -563,7 +584,7 @@ function claudeStream(line: ClaudeLine, cacheState: ClaudeCacheState): 'main' | /** Every `AskUserQuestion` result in the transcript, by its call ID, with when it came and whether it holds an answer. * A result can come after your next prompt, so the whole transcript is read once, not only the asking turn. */ interface ClaudeQuestionResults { - results: Map; + results: Map; /** Each line's own timestamp or the next one logged after it: where an unanswered question's stop ends. */ nextTs: (number | null)[]; } @@ -574,7 +595,7 @@ function indexClaudeQuestionResults(lines: ClaudeLine[]): ClaudeQuestionResults if (line.type !== 'assistant') continue; for (const block of toContentArray(line.message?.content)) if (block.type === 'tool_use' && block.name === 'AskUserQuestion' && block.id) asked.add(block.id); } - const results = new Map(); + const results = new Map(); const nextTs = new Array(lines.length).fill(null); if (asked.size === 0) return { results, nextTs }; let next: number | null = null; @@ -582,16 +603,19 @@ function indexClaudeQuestionResults(lines: ClaudeLine[]): ClaudeQuestionResults next = getTimestamp(lines[i].timestamp) ?? next; nextTs[i] = next; } - for (const line of lines) { - if (line.type !== 'user') continue; - for (const block of toContentArray(line.message?.content)) { - if (block.type !== 'tool_result' || !block.tool_use_id || !asked.has(block.tool_use_id) || results.has(block.tool_use_id)) continue; - results.set(block.tool_use_id, { ts: getTimestamp(line.timestamp), answered: block.is_error !== true && toolResultHasContent(block) }); - } - } + for (const line of lines) if (line.type === 'user') noteQuestionResults(line, asked, results); return { results, nextTs }; } +/** The first result of each asked question in a user line: when it came, whether you answered and what you said. */ +function noteQuestionResults(line: ClaudeLine, asked: Set, results: ClaudeQuestionResults['results']): void { + for (const block of toContentArray(line.message?.content)) { + if (block.type !== 'tool_result' || !block.tool_use_id || !asked.has(block.tool_use_id) || results.has(block.tool_use_id)) continue; + const answered = block.is_error !== true && toolResultHasContent(block); + results.set(block.tool_use_id, { ts: getTimestamp(line.timestamp), answered, text: answered ? toolResultText(block) : '' }); + } +} + /** Assistant data of the request whose prompt is the user line at `userIndex`. */ function collectClaudeAssistantData( lines: ClaudeLine[], @@ -606,6 +630,7 @@ function collectClaudeAssistantData( nextIndex: startIndex, lastTs, assistantTexts: [], + replyTexts: [], toolsUsed: [], editedFiles: [], referencedFiles: [], @@ -641,13 +666,17 @@ function collectClaudeAssistantData( for (const block of toContentArray(next.message?.content)) { if (block.type === 'text' && block.text) { data.assistantTexts.push(block.text); + data.replyTexts.push(block.text); continue; } if (block.type === 'tool_use' && block.name === 'AskUserQuestion' && block.id && assistantTs) { // Answered or not, the question stopped the agent: until its result, or, with none logged, the next line. const result = questions.results.get(block.id); const end = result?.ts ?? questions.nextTs[i + 1] ?? assistantTs; - if (end >= assistantTs) data.userWaits.push({ start: assistantTs, end, kind: 'question', answered: result?.answered ?? false }); + if (end >= assistantTs) { + const text = askUserQuestionText(block.input, result?.text, data.replyTexts[data.replyTexts.length - 1]); + data.userWaits.push({ start: assistantTs, end, kind: 'question', answered: result?.answered ?? false, ...(text ? { text } : {}) }); + } } const incomplete = !!block.id && !toolResults.completed.has(block.id); const failed = incomplete || (!!block.id && toolResults.failed.has(block.id)); @@ -1293,6 +1322,7 @@ function buildClaudeRequest( timestamp: userTs, messageText: getClaudeUserText(line), responseText: assistantData.assistantTexts.join('\n'), + replyText: assistantData.replyTexts.join('\n'), agentName: 'Claude', agentMode: 'agent', modelId: assistantData.model, diff --git a/src/core/parser-codex-extra.test.ts b/src/core/parser-codex-extra.test.ts index f77efd29..63f9f68b 100644 --- a/src/core/parser-codex-extra.test.ts +++ b/src/core/parser-codex-extra.test.ts @@ -376,7 +376,35 @@ describe('parseCodexSessions extra coverage', () => { expect(session.requests[0].responseText).toBe('just reasoning'); }); + }); + + describe('the reply the Timeline shows', () => { + it('keeps its reasoning out of the reply the Timeline shows', () => { + const session = parseSingleSession([ + { type: 'session_meta', payload: { id: 'sess-reply-text', cwd: '/Users/me/project' } }, + { type: 'event_msg', timestamp: '2025-06-15T10:00:00Z', payload: { type: 'user_message', message: 'explain' } }, + { type: 'event_msg', timestamp: '2025-06-15T10:00:01Z', payload: { type: 'agent_reasoning', text: 'thinking' } }, + { type: 'response_item', timestamp: '2025-06-15T10:00:02Z', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'answer' }] } }, + { type: 'event_msg', timestamp: '2025-06-15T10:00:10Z', payload: { type: 'user_message', message: 'again' } }, + { type: 'event_msg', timestamp: '2025-06-15T10:00:11Z', payload: { type: 'agent_reasoning', text: 'just reasoning' } }, + ]); + + expect(session.requests.map(r => [r.responseText, r.replyText])).toEqual([['thinking\nanswer', 'answer'], ['just reasoning', '']]); + }); + + it('shows a reply logged both as an event and as a response item once', () => { + const session = parseSingleSession([ + { type: 'session_meta', payload: { id: 'sess-reply-twice', cwd: '/Users/me/project' } }, + { type: 'event_msg', timestamp: '2025-06-15T10:00:00Z', payload: { type: 'user_message', message: 'explain' } }, + { type: 'event_msg', timestamp: '2025-06-15T10:00:01Z', payload: { type: 'assistant_message', content: 'answer' } }, + { type: 'response_item', timestamp: '2025-06-15T10:00:01Z', payload: { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'answer' }] } }, + ]); + + expect(session.requests[0].replyText).toBe('answer'); + }); + }); + describe('end reasons', () => { it('leaves endReason as unknown when any request has a response', () => { const session = parseSingleSession([ { type: 'session_meta', payload: { id: 'sess-end-reason-response', cwd: '/Users/me/project' } }, diff --git a/src/core/parser-codex.ts b/src/core/parser-codex.ts index b32696aa..571c5c53 100644 --- a/src/core/parser-codex.ts +++ b/src/core/parser-codex.ts @@ -89,6 +89,10 @@ interface CodexParseState { hasUserMessageEvent: boolean; imageScan?: CodexImageScan; currentAssistantTexts: string[]; + /** The agent's own messages this turn, without its reasoning: the reply the Timeline shows. Codex can log one both as an + * event and as a response item, so each source is kept apart and the reply is read from one. */ + currentReplyTexts: string[]; + currentReplyItems: string[]; currentToolsUsed: string[]; investigationDelegations: ('research' | 'explore')[]; webDomains: string[]; @@ -235,6 +239,8 @@ function createCodexState(initialModel: string, editLocIndex?: EditLocIndex): Co hasUserResponseItem: false, hasUserMessageEvent: false, currentAssistantTexts: [], + currentReplyTexts: [], + currentReplyItems: [], currentToolsUsed: [], investigationDelegations: [], webDomains: [], @@ -327,6 +333,11 @@ function commitCodexEdit(state: CodexParseState, pending: PendingCodexEdit): voi state.currentEditedFiles.push(...pending.editedFiles); } +/** The turn's reply, from its response items when it logged any, else from its events: never both, so once. */ +function codexReply(state: CodexParseState): string { + return (state.currentReplyItems.length ? state.currentReplyItems : state.currentReplyTexts).join('\n'); +} + function flushCodexTurn(state: CodexParseState, defaultModel: string): void { const hasResponse = state.imageScan ? state.imageScan.hasAssistantText : state.currentAssistantTexts.length > 0; if (!state.currentUserMessage && state.currentImageCount === 0 && !hasResponse) return; @@ -361,6 +372,7 @@ function flushCodexTurn(state: CodexParseState, defaultModel: string): void { timestamp: state.turnStartTs, messageText: state.currentUserMessage, responseText, + replyText: codexReply(state), answerEvidence: state.answerEvidence, isCanceled: state.turnCanceled, agentName: 'Codex', @@ -435,6 +447,8 @@ function resetCodexTurn(state: CodexParseState): void { state.hasUserResponseItem = false; state.hasUserMessageEvent = false; state.currentAssistantTexts = []; + state.currentReplyTexts = []; + state.currentReplyItems = []; state.currentToolsUsed = []; state.investigationDelegations = []; state.webDomains = []; @@ -631,6 +645,7 @@ function handleAssistantMessageEvent(payload: Record, state: Co const content = payload.content; if (typeof content === 'string') { state.currentAssistantTexts.push(content); + state.currentReplyTexts.push(content); if (content.trim()) state.answerEvidence = payload.phase === 'final' ? 'final' : payload.phase == null ? 'legacy' : 'missing'; } } @@ -814,6 +829,7 @@ function handleAssistantResponseItem(payload: Record, state: Co for (const item of extractContentItems(payload.content)) { if (item.type === 'output_text' && item.text) { state.currentAssistantTexts.push(item.text); + state.currentReplyItems.push(item.text); if (item.text.trim()) state.answerEvidence = payload.phase === 'final' || payload.channel === 'final' ? 'final' : payload.phase == null && payload.channel == null ? 'legacy' : 'missing'; } diff --git a/src/core/parser-opencode.test.ts b/src/core/parser-opencode.test.ts index cecbf1b7..292e5fb4 100644 --- a/src/core/parser-opencode.test.ts +++ b/src/core/parser-opencode.test.ts @@ -194,6 +194,23 @@ describe('parseOpenCodeSessions', () => { ); }); + it('keeps the agent’s own text as its reply, apart from the code a write tool wrote', () => { + const user = { id: 'u1', sessionID: 's-reply', role: 'user', time: { created: 1700000000000 }, summary: { title: 'write it' } }; + const assistant = (id: string) => ({ id, sessionID: 's-reply', role: 'assistant', parentID: 'u1', time: { created: 1700000001000, completed: 1700000002000 }, modelID: 'm' }); + const write = (messageID: string) => ({ id: 'w-' + messageID, sessionID: 's-reply', messageID, type: 'tool', tool: 'write', state: { status: 'completed', input: { filePath: '/p/a.ts', content: 'export const x = 1;' } } }); + const replyOf = (parts: (Record & { id: string; messageID: string })[], ids: string[]) => { + let out: [boolean, string | undefined] = [false, undefined]; + withStorage({ id: 's-reply', directory: '/p', time: { created: 1700000000000 } }, [user, ...ids.map(assistant)], (storageDir) => { + const request = parseOpenCodeSessions(storageDir)[0].requests[0]; + out = [request.responseText.includes('export const x = 1;'), request.replyText]; + }, parts); + return out; + }; + expect(replyOf([{ id: 't1', sessionID: 's-reply', messageID: 'a1', type: 'text', text: 'Writing it.' }, write('a1')], ['a1'])).toEqual([true, 'Writing it.']); + // A turn that only wrote a file has no reply of its own. + expect(replyOf([write('a1')], ['a1'])).toEqual([true, '']); + }); + it('uses a present empty summary diff as authoritative zero edits', () => { withStorage( { id: 'sess-reverted', directory: '/Users/me/proj', time: { created: 1700000000000 } }, diff --git a/src/core/parser-opencode.ts b/src/core/parser-opencode.ts index e9bba5e4..2fbbb30f 100644 --- a/src/core/parser-opencode.ts +++ b/src/core/parser-opencode.ts @@ -101,6 +101,8 @@ interface OcPart { interface OpenCodeAssistantData { responseText: string; + /** The assistant's own text parts, without the code its write tools wrote (which `responseText` also holds). */ + replyText: string; toolsUsed: string[]; editedFiles: string[]; referencedFiles: string[]; @@ -351,6 +353,7 @@ function collectAssistantData( ): OpenCodeAssistantData { const data: OpenCodeAssistantData = { responseText: '', + replyText: '', toolsUsed: [], editedFiles: [], referencedFiles: [], @@ -384,6 +387,7 @@ function collectAssistantData( for (const part of parts) applyOpenCodePart(part, data, textParts); } data.responseText = textParts.join('\n'); + data.replyText = assistantMessages.flatMap(message => (partsByMsg.get(message.id) || []).filter(part => part.type === 'text' && part.text).map(part => part.text!)).join('\n'); return data; } @@ -437,6 +441,7 @@ function buildOpenCodeRequest( messageText: getOpenCodeUserText(msg, partsByMsg), variableKinds: imageCount > 0 ? { image: imageCount } : {}, responseText: assistantData.responseText, + replyText: assistantData.replyText, agentName: msg.agent || 'OpenCode', agentMode: msg.agent || 'build', modelId: assistantData.modelId, diff --git a/src/core/parser-shared.ts b/src/core/parser-shared.ts index f8a6faa6..551fa951 100644 --- a/src/core/parser-shared.ts +++ b/src/core/parser-shared.ts @@ -428,8 +428,12 @@ export function stripSingleSession(session: Session): void { r.messageText = r.messageText.substring(0, MEMORY_PREVIEW_CHARS); } r.responseText = ''; + delete r.replyText; if (r.todoSnapshot) r.todoSnapshot = null; + // What a question or permission prompt asked, and your answer: read again with the session when it is opened. + for (const w of r.userWaits ?? []) delete w.text; } + for (const w of session.userWaits ?? []) delete w.text; } const DEVCONTAINER_PATH_RE = /(?:^|[\s=:"'`])\/workspaces\//; diff --git a/src/core/parser-vscode-cli.test.ts b/src/core/parser-vscode-cli.test.ts index 22bfd77f..7261822d 100644 --- a/src/core/parser-vscode-cli.test.ts +++ b/src/core/parser-vscode-cli.test.ts @@ -12,7 +12,7 @@ import * as path from 'path'; import { afterEach, describe, it, expect, beforeEach } from 'vitest'; import { EditLocIndex } from './edit-loc-diff'; import { parseCLIEventsFile, parseCLIEventsFileAsync } from './parser-vscode-cli'; -import { getParseWarningCounts, resetParseWarnings, setCuriosityDetector } from './parser-shared'; +import { getParseWarningCounts, resetParseWarnings, setCuriosityDetector, stripSingleSession } from './parser-shared'; import { detectCuriosity } from './curiosity'; import { CuriosityAnalyzer } from './analyzer-curiosity'; import { runDetectors, runEmitters } from './detector-registry'; @@ -484,14 +484,84 @@ describe('session families and credits (Copilot CLI and Copilot App)', () => { const ms = (iso: string) => Date.parse(iso); // Every request stops the agent; only an answer from you is `answered`. A policy decision isn't a request to you. expect(session?.requests[0].userWaits).toEqual([ - { start: ms(at(1)), end: ms(at(6)), kind: 'question', answered: true }, + { start: ms(at(1)), end: ms(at(6)), kind: 'question', answered: true, text: { answer: 'yes' } }, { start: ms(at(7)), end: ms(at(8)), kind: 'question', answered: false }, - { start: ms(at(9)), end: ms(at(12)), kind: 'relay', answered: true }, - { start: ms(at(14)), end: ms(at(14, 2)), kind: 'permission', answered: false }, - { start: ms(at(15)), end: ms(at(17)), kind: 'permission', answered: true }, + { start: ms(at(9)), end: ms(at(12)), kind: 'relay', answered: true, text: { answer: 'b' } }, + { start: ms(at(14)), end: ms(at(14, 2)), kind: 'permission', answered: false, text: { answer: 'approved' } }, + { start: ms(at(15)), end: ms(at(17)), kind: 'permission', answered: true, text: { answer: 'approved' } }, // The record of your answer dates it, apart from the result. - { start: ms(at(18)), end: ms(at(19)), kind: 'permission', answered: true, answeredAt: ms(at(19)) }, - { start: ms(at(21)), end: ms(at(24)), kind: 'permission', answered: true }, + { start: ms(at(18)), end: ms(at(19)), kind: 'permission', answered: true, answeredAt: ms(at(19)), text: { answer: 'approved' } }, + { start: ms(at(21)), end: ms(at(24)), kind: 'permission', answered: true, text: { answer: 'denied-interactively-by-user' } }, + ]); + }); + + it('keeps what a question, relay or permission prompt asked and what you answered, until the session is stripped', () => { + const at = (m: number) => new Date(Date.UTC(2026, 9, 1, 10, m)).toISOString(); + const session = parseCLIEventsFile(writeEvents([ + { type: 'session.start', data: { sessionId: COORD } }, + { type: 'user.message', timestamp: at(0), data: { content: 'go' } }, + { type: 'assistant.message', timestamp: at(1), data: { content: 'Two databases fit.' } }, + { type: 'tool.execution_start', timestamp: at(2), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Which DB?', choices: ['A', 'B'] } } }, + { type: 'tool.execution_complete', timestamp: at(5), data: { toolCallId: 'q1', success: true, result: { content: 'User selected: B' } } }, + { type: 'permission.requested', timestamp: at(6), data: { requestId: 'p1', permissionRequest: { kind: 'shell', fullCommandText: 'npm test', intention: 'Run the tests' } } }, + { type: 'permission.completed', timestamp: at(7), data: { requestId: 'p1', decisionSource: 'human_response', result: { kind: 'approved' } } }, + { type: 'tool.execution_start', timestamp: at(8), data: { toolName: 'relay_session_input', toolCallId: 'r1', arguments: { context: 'Child asks', project_session_id: 'p' } } }, + { type: 'tool.execution_complete', timestamp: at(9), data: { toolCallId: 'r1', success: true, result: { content: JSON.stringify({ question: 'Deploy now?', outcome: 'answered_here', answer: 'Not yet' }) } } }, + // The answer text can come only in the human_response record. + { type: 'tool.execution_start', timestamp: at(10), data: { toolName: 'ask_user', toolCallId: 'q2', arguments: { question: 'Name?' } } }, + { type: 'tool.execution_complete', timestamp: at(11), data: { toolCallId: 'q2', success: true, result: { content: '' } } }, + { type: 'human_response.recorded', timestamp: at(11), data: { toolCallId: 'q2', response: { answer: 'Ada' } } }, + { type: 'permission.requested', timestamp: at(12), data: { requestId: 'p2', permissionRequest: { kind: 'mcp', serverName: 'github', toolTitle: 'Create issue' } } }, + { type: 'permission.completed', timestamp: at(13), data: { requestId: 'p2', decisionSource: 'human_response', result: { kind: 'denied-interactively-by-user' } } }, + { type: 'assistant.message', timestamp: at(14), data: { content: 'done' } }, + ]), 'ws', 'ws'); + expect(session?.requests[0].userWaits?.map(w => [w.kind, w.answered, w.text])).toEqual([ + ['question', true, { ask: 'Which DB?', choices: ['A', 'B'], before: 'Two databases fit.', answer: 'B' }], + ['permission', true, { ask: 'npm test', tool: 'shell', intention: 'Run the tests', answer: 'approved' }], + ['relay', true, { ask: 'Deploy now?', before: 'Two databases fit.', answer: 'Not yet' }], + ['question', true, { ask: 'Name?', before: 'Two databases fit.', answer: 'Ada' }], + ['permission', true, { ask: 'github: Create issue', tool: 'mcp', answer: 'denied-interactively-by-user' }], + ]); + // The analyzers hold sessions without it: the detail view reads it again from the log. + stripSingleSession(session!); + expect(session?.requests[0].userWaits?.some(w => w.text)).toBe(false); + }); + + it('gives a recorded answer only to the question it answered, not to a later one that reused its tool call ID', () => { + const at = (m: number) => new Date(Date.UTC(2026, 9, 1, 10, m)).toISOString(); + const session = parseCLIEventsFile(writeEvents([ + { type: 'session.start', data: { sessionId: COORD } }, + { type: 'user.message', timestamp: at(0), data: { content: 'go' } }, + { type: 'tool.execution_start', timestamp: at(2), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Ship it?' } } }, + { type: 'human_response.recorded', timestamp: at(3), data: { toolCallId: 'q1', response: { answer: 'yes' } } }, + { type: 'tool.execution_complete', timestamp: at(3), data: { toolCallId: 'q1', success: true, result: { content: '' } } }, + { type: 'tool.execution_start', timestamp: at(5), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Tag it?' } } }, + { type: 'tool.execution_complete', timestamp: at(6), data: { toolCallId: 'q1', success: false } }, + { type: 'tool.execution_start', timestamp: at(7), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Notify?' } } }, + { type: 'assistant.message', timestamp: at(8), data: { content: 'done' } }, + ]), 'ws', 'ws'); + expect(session?.requests[0].userWaits?.map(w => [w.text?.ask, w.text?.answer])).toEqual([['Ship it?', 'yes'], ['Tag it?', undefined], ['Notify?', undefined]]); + // Nor its record that you answered (code from #381, hardened here): only the first was answered. + expect(session?.requests[0].userWaits?.map(w => [w.answered, w.answeredAt])).toEqual([[true, Date.parse(at(3))], [false, undefined], [false, undefined]]); + }); + + it('keeps a recorded answer for a later request that reused the tool call ID, even when it comes before that question', () => { + const at = (m: number) => new Date(Date.UTC(2026, 9, 1, 10, m)).toISOString(); + const session = parseCLIEventsFile(writeEvents([ + { type: 'session.start', data: { sessionId: COORD } }, + { type: 'user.message', timestamp: at(0), data: { content: 'go' } }, + { type: 'tool.execution_start', timestamp: at(2), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Ship it?' } } }, + { type: 'human_response.recorded', timestamp: at(3), data: { toolCallId: 'q1', requestId: 'r1', response: { answer: 'yes' } } }, + { type: 'tool.execution_complete', timestamp: at(3), data: { toolCallId: 'q1', success: true, result: { content: '' } } }, + // The second question's record is logged before its own start entry. + { type: 'human_response.recorded', timestamp: at(5), data: { toolCallId: 'q1', requestId: 'r2', response: { answer: 'no' } } }, + { type: 'tool.execution_start', timestamp: at(5), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Tag it?' } } }, + { type: 'tool.execution_complete', timestamp: at(7), data: { toolCallId: 'q1', success: true, result: { content: '' } } }, + { type: 'assistant.message', timestamp: at(8), data: { content: 'done' } }, + ]), 'ws', 'ws'); + expect(session?.requests[0].userWaits?.map(w => [w.text?.ask, w.text?.answer, w.answered, w.answeredAt, w.requestId])).toEqual([ + ['Ship it?', 'yes', true, Date.parse(at(3)), 'r1'], + ['Tag it?', 'no', true, Date.parse(at(5)), 'r2'], ]); }); @@ -513,7 +583,8 @@ describe('session families and credits (Copilot CLI and Copilot App)', () => { const ms = (iso: string) => Date.parse(iso); // Overlapping requests stay separate: each is its own answer, and the model unions their time. expect(session?.requests.map(r => r.userWaits)).toEqual([ - [{ start: ms(at(1)), end: ms(at(11)), kind: 'permission', answered: true, answeredAt: ms(at(13)) }, { start: ms(at(2)), end: ms(at(12)), kind: 'question', answered: true }], + [{ start: ms(at(1)), end: ms(at(11)), kind: 'permission', answered: true, answeredAt: ms(at(13)), text: { answer: 'approved' } }, + { start: ms(at(2)), end: ms(at(12)), kind: 'question', answered: true, text: { answer: 'ok' } }], undefined, ]); }); diff --git a/src/core/parser-vscode-cli.ts b/src/core/parser-vscode-cli.ts index 44673343..85f7b531 100644 --- a/src/core/parser-vscode-cli.ts +++ b/src/core/parser-vscode-cli.ts @@ -35,7 +35,7 @@ import { } from './edit-tool-diff'; import { recordedTools, recordedToolFiles, recordedInvestigation, recordedWebDomains } from './curiosity-activity'; import { imageReferencesFromAttachments, imageReferencesFromVariables, imageRequestIndex, type ImageReference, type ImageRequestMatch } from './image-data'; -import type { NonHumanKind, UserWait } from './types'; +import type { NonHumanKind, UserWait, UserWaitText } from './types'; import { cliNonHumanKind, cliRelaySenderId } from './parser-turn-kinds'; import { NANO_AIU_PER_AI_CREDIT } from './github-app-issue-credit-model'; import { readCliClient, readCliWorkspaceMeta } from './session-workspace-meta'; @@ -66,6 +66,8 @@ interface TurnState { userTs: string | null; agentMode: string; responseChunks: string[]; + /** The agent's own messages, without the code that edits wrote (which `responseChunks` also holds). */ + agentMessages: string[]; toolNames: Set; investigationDelegations: Set<'research' | 'explore'>; webDomains: Set; @@ -150,6 +152,8 @@ interface CLIParseState { humanRequestIds: Map; /** Keys with a `human_response.recorded` event. */ humanResponses: Map; + /** The answer text a `human_response.recorded` event logged, by key. */ + humanAnswers: Map; /** Waits answered before the first turn; the first turn takes them. */ earlyWaits: UserWait[]; } @@ -166,6 +170,7 @@ function freshTurn(userMsg: string, userTs: string | null, agentMode: string, re userTs, agentMode, responseChunks: [], + agentMessages: [], toolNames: new Set(), investigationDelegations: new Set(), webDomains: new Set(), @@ -269,6 +274,7 @@ function flushTurn(state: CLIParseState): void { const respTs = turn.lastAssistantTs ? new Date(turn.lastAssistantTs).getTime() : null; const firstProgress = turn.firstToolTs && msgTs ? turn.firstToolTs - msgTs : null; const responseText = turn.responseChunks.filter(Boolean).join('\n\n'); + const replyText = turn.agentMessages.filter(Boolean).join('\n\n'); const requestId = turn.lastAssistantId || `${state.sessionId}:cli:${state.requests.length}`; const request = createRequest({ @@ -278,6 +284,7 @@ function flushTurn(state: CLIParseState): void { timestamp: msgTs, messageText: turn.userMsg, responseText, + replyText, agentName: harnessName(state), agentMode: turn.agentMode || 'agent', modelId: turn.modelId || state.currentModelId, @@ -360,11 +367,15 @@ interface OpenUserWait { nextTs?: number; /** The relayed request's ID (`relay_session_input`'s `request_id`). */ requestId?: string; + text?: UserWaitText; } -function openUserWait(state: CLIParseState, key: string, start: number | null, wait: Pick): void { +function openUserWait(state: CLIParseState, key: string, start: number | null, wait: Pick): void { if (start !== null && key && !key.endsWith(':')) { - state.openWaits.set(key, { start, kind: wait.kind, owner: state.turn ? state.requests.length : -1, ...(wait.requestId ? { requestId: wait.requestId } : {}) }); + state.openWaits.set(key, { + start, kind: wait.kind, owner: state.turn ? state.requests.length : -1, + ...(wait.requestId ? { requestId: wait.requestId } : {}), ...(wait.text ? { text: wait.text } : {}), + }); } } @@ -375,36 +386,119 @@ function waitRequestId(state: CLIParseState, key: string, open: OpenUserWait): P return requestId ? { requestId } : {}; } +/** A text field when it holds something. */ +function textField(key: K, value: UserWaitText[K] | undefined): Partial { + if (value === undefined || value === '' || (Array.isArray(value) && value.length === 0)) return {}; + const field: Partial = { [key]: value }; + return field; +} + +/** The agent's last message in the turn in progress: what it said before it stopped. */ +function lastAgentMessage(state: CLIParseState): string | undefined { + const chunks = state.turn?.agentMessages.filter(c => c.trim()); + return chunks?.length ? chunks[chunks.length - 1] : undefined; +} + +/** An `ask_user` question with its choices, or a relayed question's context, and what the agent said before it. */ +function questionText(args: Record, relay: boolean, state: CLIParseState): UserWaitText { + const choices = Array.isArray(args.choices) ? args.choices.filter((c): c is string => typeof c === 'string') : undefined; + return { + ...textField('ask', str(relay ? args.context : args.question).trim()), + ...textField('choices', choices), + ...textField('before', lastAgentMessage(state)), + }; +} + +/** Your answer in a question tool's result: Copilot's `User selected: …`/`User responded: …`, or a relay's `answer` + * (with the child's question). Nothing for a failed or interrupted call. */ +function questionAnswerText(data: Record): UserWaitText { + if (data.success === false) return {}; + const result = recordValue(data.result); + const content = str(result?.content ?? data.result).trim(); + if (content.startsWith('{')) { + try { + const parsed: unknown = JSON.parse(content); + if (isRecord(parsed)) return { ...textField('ask', str(parsed.question).trim()), ...textField('answer', str(parsed.answer).trim()) }; + } catch { + return textField('answer', content); + } + } + return textField('answer', content.replace(/^User (selected|responded):\s*/, '')); +} + +/** What a permission prompt asked for: the command, path, URL or extension capability, the kind of request and the + * agent's stated intention. */ +function permissionText(data: Record): UserWaitText { + const request = recordValue(data.permissionRequest) ?? recordValue(data.promptRequest) ?? {}; + const capabilities = Array.isArray(request.capabilities) ? request.capabilities.filter((c): c is string => typeof c === 'string') : []; + const extension = str(request.extensionName) ? `${str(request.extensionName)}${capabilities.length ? `: ${capabilities.join(', ')}` : ''}` : ''; + const mcp = str(request.serverName) ? `${str(request.serverName)}: ${str(request.toolTitle) || str(request.toolName)}` : ''; + const ask = [request.fullCommandText, request.path, request.fileName, request.url, mcp, request.toolName, extension].map(v => str(v).trim()).find(Boolean); + const intention = str(request.intention).trim() || str(request.toolDescription).trim(); + return { ...textField('ask', ask), ...textField('tool', str(request.kind)), ...textField('intention', intention) }; +} + /** The question or permission prompt `key` was resolved at `end`. The turn was stopped on it either way, so it is * kept, even at zero duration; it is `answered` with evidence that you answered (the result, or a * `human_response.recorded` event for it, which can come before or after). A decision a policy made (`automatic`) * stopped nothing a person was asked about and is dropped. */ -function closeUserWait(state: CLIParseState, key: string, end: number | null, answered: boolean, automatic = false): void { +function closeUserWait(state: CLIParseState, key: string, end: number | null, answered: boolean, automatic = false, result: UserWaitText = {}): void { const open = key ? state.openWaits.get(key) : undefined; if (!open) return; state.openWaits.delete(key); + // A recorded answer belongs to this wait alone: a later one that reuses its key starts without it. + const { answeredAt, requestId, recorded } = takeHumanResponse(state, key, open); if (end === null || end < open.start || automatic) return; - const answeredAt = state.humanResponses.get(key); + const text = { ...open.text, ...result, ...(recorded !== undefined && !result.answer ? { answer: recorded } : {}) }; const wait: UserWait = { - start: open.start, end, kind: open.kind, answered: answered || state.humanResponses.has(key), ...(answeredAt != null ? { answeredAt } : {}), - ...waitRequestId(state, key, open), + start: open.start, end, kind: open.kind, answered: answered || answeredAt !== undefined, ...(answeredAt != null ? { answeredAt } : {}), + ...requestId, ...(Object.keys(text).length ? { text } : {}), }; state.closedWaits.set(key, wait); attachUserWait(state, wait, open.owner); } +/** The record of your answer to the wait `key`, taken as the wait closes. `answeredAt` is undefined without a record, + * null when the record has no time. */ +function takeHumanResponse(state: CLIParseState, key: string, open: OpenUserWait): { answeredAt: number | null | undefined; requestId: Partial; recorded: string | undefined } { + const out = { + answeredAt: state.humanResponses.has(key) ? state.humanResponses.get(key) ?? null : undefined, + requestId: waitRequestId(state, key, open), + recorded: state.humanAnswers.get(key), + }; + state.humanResponses.delete(key); + state.humanRequestIds.delete(key); + state.humanAnswers.delete(key); + return out; +} + +/** The closed wait a record of your answer on `key` belongs to: none while a wait is open on the key, or when the record + * is for another request than the closed wait's (a later wait reusing the key, logged before that wait's own entry). */ +function closedWaitFor(state: CLIParseState, key: string, requestId: string): UserWait | undefined { + if (state.openWaits.has(key)) return undefined; + const closed = state.closedWaits.get(key); + return closed && !(requestId && closed.requestId && closed.requestId !== requestId) ? closed : undefined; +} + +/** A record of your answer goes to the wait still open on its key, kept until that closes; else to the wait it + * closed (it can come before or after the result). A record for another request than the closed wait's is kept for + * the later wait it belongs to (`closedWaitFor`). */ function recordHumanResponse(data: Record, state: CLIParseState, at: number | null): void { + const answer = str(recordValue(data.response)?.answer).trim(); for (const key of [str(data.toolCallId), data.requestId ? `permission:${str(data.requestId)}` : '']) { if (!key) continue; - if (!state.humanResponses.has(key)) state.humanResponses.set(key, at); const requestId = key === str(data.toolCallId) ? str(data.requestId) : ''; - if (requestId && !state.humanRequestIds.has(key)) state.humanRequestIds.set(key, requestId); - const wait = state.closedWaits.get(key); + const wait = closedWaitFor(state, key, requestId); if (wait) { wait.answered = true; if (wait.answeredAt === undefined && at !== null) wait.answeredAt = at; if (requestId && wait.kind === 'question') wait.requestId ??= requestId; + if (answer && !wait.text?.answer) wait.text = { ...wait.text, answer }; + continue; } + if (!state.humanResponses.has(key)) state.humanResponses.set(key, at); + if (requestId && !state.humanRequestIds.has(key)) state.humanRequestIds.set(key, requestId); + if (answer) state.humanAnswers.set(key, answer); } } @@ -614,7 +708,10 @@ function handleToolExecutionStart(ev: CLIEvent, state: CLIParseState): void { noteSessionToolCall(state, data, eventTime(ev)); if (isToolNamed(toolName, QUESTION_TOOLS)) { const relay = isToolNamed(toolName, ['relay_session_input']); - openUserWait(state, str(data.toolCallId), eventTime(ev), { kind: relay ? 'relay' : 'question', requestId: relay ? str(recordValue(data.arguments)?.request_id) : '' }); + openUserWait(state, str(data.toolCallId), eventTime(ev), { + kind: relay ? 'relay' : 'question', requestId: relay ? str(recordValue(data.arguments)?.request_id) : '', + text: questionText(recordValue(data.arguments) ?? {}, relay, state), + }); } const turn = state.turn; if (!turn) return; @@ -752,7 +849,7 @@ function handleToolExecutionComplete(ev: CLIEvent, state: CLIParseState): void { const data = ev.data || {}; recordStartedSessions(data, state); const toolCallId = str(data.toolCallId); - closeUserWait(state, toolCallId, eventTime(ev), questionAnswered(data)); + if (state.openWaits.has(toolCallId)) closeUserWait(state, toolCallId, eventTime(ev), questionAnswered(data), false, questionAnswerText(data)); const turn = state.turn; if (!turn) return; const pending = toolCallId ? turn.pendingToolEdits.get(toolCallId) : undefined; @@ -797,7 +894,10 @@ function handleAssistantMessage(ev: CLIEvent, state: CLIParseState): void { } else if (turn.answerEvidence === 'legacy') turn.answerEvidence = 'missing'; } - if (content) turn.responseChunks.push(content); + if (content) { + turn.responseChunks.push(content); + turn.agentMessages.push(content); + } turn.lastAssistantTs = ev.timestamp || turn.lastAssistantTs; turn.lastAssistantId = str(ev.id) || turn.lastAssistantId; @@ -923,10 +1023,11 @@ function handleCliEvent(ev: CLIEvent, state: CLIParseState, wsId: string): void handleToolExecutionComplete(ev, state); return; case 'permission.requested': - openUserWait(state, `permission:${str(ev.data?.requestId)}`, eventTime(ev), { kind: 'permission' }); + openUserWait(state, `permission:${str(ev.data?.requestId)}`, eventTime(ev), { kind: 'permission', text: permissionText(ev.data || {}) }); return; case 'permission.completed': - closeUserWait(state, `permission:${str(ev.data?.requestId)}`, eventTime(ev), permissionDecidedByYou(ev.data || {}), permissionDecidedByPolicy(ev.data || {})); + closeUserWait(state, `permission:${str(ev.data?.requestId)}`, eventTime(ev), permissionDecidedByYou(ev.data || {}), permissionDecidedByPolicy(ev.data || {}), + textField('answer', str(recordValue(ev.data?.result)?.kind))); return; case 'external_tool.requested': noteSessionToolCall(state, ev.data || {}, eventTime(ev)); @@ -941,6 +1042,7 @@ function handleCliEvent(ev: CLIEvent, state: CLIParseState, wsId: string): void if (state.turn && ev.data?.success === true && typeof ev.data.summary === 'string' && ev.data.summary.trim()) { state.turn.answerEvidence = 'final'; if (!state.turn.responseChunks.includes(ev.data.summary)) state.turn.responseChunks.push(ev.data.summary); + if (!state.turn.agentMessages.includes(ev.data.summary)) state.turn.agentMessages.push(ev.data.summary); state.turn.lastAssistantTs = ev.timestamp || state.turn.lastAssistantTs; } return; @@ -994,6 +1096,7 @@ function createInitialCliState(wsId: string, editLocIndex?: EditLocIndex): CLIPa closedWaits: new Map(), humanRequestIds: new Map(), humanResponses: new Map(), + humanAnswers: new Map(), earlyWaits: [], }; } @@ -1014,6 +1117,7 @@ function closeUnresolvedWaits(state: CLIParseState): void { attachUserWait(state, { start: open.start, end: attested ? answeredAt : open.nextTs ?? open.start, kind: open.kind, answered: state.humanResponses.has(key), ...(answeredAt != null ? { answeredAt } : {}), ...waitRequestId(state, key, open), + ...(open.text ? { text: { ...open.text, ...textField('answer', state.humanAnswers.get(key)) } } : {}), }, open.owner); } } diff --git a/src/core/parser-vscode-request.ts b/src/core/parser-vscode-request.ts index 94ccd95c..fffa67b5 100644 --- a/src/core/parser-vscode-request.ts +++ b/src/core/parser-vscode-request.ts @@ -70,6 +70,7 @@ interface ToolCallResult { } interface ResponsePart { + kind?: string; value?: string | { value?: string }; } @@ -95,12 +96,14 @@ function extractMessageText(msg: RawRequest['message']): string { return ''; } -function extractResponseText(resp: unknown[] | undefined): string { +/** The response's text parts; `reply` leaves out the model's thinking, keeping only what it said. */ +function extractResponseText(resp: unknown[] | undefined, reply = false): string { if (!Array.isArray(resp)) return ''; const parts: string[] = []; for (const part of resp) { const p = part as ResponsePart; if (p && typeof p === 'object' && p.value != null) { + if (reply && p.kind === 'thinking') continue; const v = p.value; if (typeof v === 'object' && v !== null && 'value' in (v as object)) { const inner = (v as Record).value; @@ -431,12 +434,14 @@ function extractRequestText(req: RawRequest): { msgText: string; resp: RawRequest['response']; respText: string; + replyText: string; } { const resp = req.response; return { msgText: extractMessageText(req.message), resp, respText: extractResponseText(resp), + replyText: extractResponseText(resp, true), }; } @@ -571,7 +576,7 @@ function extractCompaction(meta: ParsedResultMetadata['meta']): import('./types' } export function parseRawRequest(req: RawRequest): SessionRequest { - const { msgText, resp, respText } = extractRequestText(req); + const { msgText, resp, respText, replyText } = extractRequestText(req); const result = req.result || {}; const { firstProgress, totalElapsed, agentName, agentMode, slashCommand } = extractRequestMetadata(req, result); const { @@ -637,6 +642,7 @@ export function parseRawRequest(req: RawRequest): SessionRequest { messageText: msgText, nonHumanKind: vscodeNonHumanKind(req), responseText: respText, + replyText, isCanceled: req.isCanceled || false, agentName, agentMode, modelId: req.modelId || '', diff --git a/src/core/parser-vscode.test.ts b/src/core/parser-vscode.test.ts index 1ed979e8..7920d9ce 100644 --- a/src/core/parser-vscode.test.ts +++ b/src/core/parser-vscode.test.ts @@ -346,6 +346,21 @@ describe('parseSessionFile (VS Code chat) — endState', () => { expect(sess?.requests[0].endState).toBeUndefined(); }); }); + + it('keeps thinking out of the reply the Timeline shows', () => { + const reqs = [ + { + requestId: 'r1', timestamp: 1000, message: { text: 'hi' }, + response: [{ kind: 'thinking', value: 'Weighing two options.' }, { value: 'Here it is.' }, { kind: 'thinking', value: '' }], + result: { metadata: { promptTokens: 50, outputTokens: 5 } }, + }, + { requestId: 'r2', timestamp: 2000, message: { text: 'and?' }, response: [{ kind: 'thinking', value: 'Only thinking.' }], result: {} }, + ]; + withChatSession(reqs, (filePath) => { + const sess = parseSessionFile(filePath, 'ws', 'wp', 'Local Agent'); + expect(sess?.requests.map(r => r.replyText)).toEqual(['Here it is.', '']); + }); + }); }); describe('parseSessionFile token extraction', () => { diff --git a/src/core/redact-secrets.test.ts b/src/core/redact-secrets.test.ts index 83e5eae0..39ac37b4 100644 --- a/src/core/redact-secrets.test.ts +++ b/src/core/redact-secrets.test.ts @@ -7,6 +7,12 @@ import { describe, it, expect } from 'vitest'; import { redactSecrets } from './redact-secrets'; describe('redactSecrets', () => { + it('scans a long run of letters and dashes in linear time', () => { + const t = Date.now(); + redactSecrets('--a-'.repeat(25_000)); + expect(Date.now() - t).toBeLessThan(1000); + }); + it('masks GitHub tokens', () => { const out = redactSecrets('push failed: ghp_abcdefghijklmnopqrstuvwxyz0123456789'); expect(out).not.toContain('ghp_'); diff --git a/src/core/redact-secrets.ts b/src/core/redact-secrets.ts index 912307eb..624590b6 100644 --- a/src/core/redact-secrets.ts +++ b/src/core/redact-secrets.ts @@ -29,8 +29,9 @@ const CONTEXT7_KEY = /\bctx7sk-[A-Za-z0-9_-]{10,250}\b/g; const SK_API_KEY = /\bsk-[A-Za-z0-9_-]{20,250}\b/g; // Stripe / underscore-prefixed keys (sk_live_, sk_test_, rk_live_, pk_live_, …). const STRIPE_KEY = /\b[srp]k_(?:live|test)_[0-9A-Za-z]{10,255}\b/g; -// Credentials embedded in a connection-string URI (scheme://user:pass@host). -const CONNECTION_STRING_CREDS = /\b([a-z][a-z0-9+.-]*:\/\/)[^\s:@/]+:[^\s@/]+@/gi; +// Credentials embedded in a connection-string URI (scheme://user:pass@host). The scheme is bounded, so a long run of +// letters and dashes is scanned once, not from each of its letters. +const CONNECTION_STRING_CREDS = /\b([a-z][a-z0-9+.-]{0,30}:\/\/)[^\s:@/]+:[^\s@/]+@/gi; // The key name may follow `_` or `-` (client_secret, refresh_token) but not a letter or digit. // Quotes may be backslash-escaped, as in raw JSON files and JSON.stringify output. const SECRET_KEY_NAME = String.raw`(? QUOTED.replaceAll('QQ', String(group)); + +/** An `Authorization`, API key or cookie header: its whole value, scheme and all, to the closing quote or the line's end. */ +const AUTH_HEADER = new RegExp( + String.raw`\b((?:proxy-)?authorization|x-api-key|api-key|ocp-apim-subscription-key|private-token|x-auth-token|set-cookie|cookie)(\\?["']?[ \t]*[:=][ \t]*)(?:${quoted(3)}|([^\r\n"'\`]+))`, 'gi'); + +/** `Bearer …` and other schemes outside a header. */ +const AUTH_SCHEME = /\b(Bearer|Basic|Digest|SharedKey)\s+([A-Za-z0-9._~+/=:%-]{12,})/gi; + +/** A connection string's secret field, to the next `;`, spaces and all. */ +const CONNECTION_FIELD = /((?:^|[;\s"'])(?:password|pwd|account[ _]?key|shared[ _]?access[ _]?key|shared[ _]?access[ _]?signature|client[ _]?secret)[ \t]*=)([^;\r\n"']+)(?=;)/gim; + +/** Names whose value is a secret whatever it looks like. A name may end with one (`DB_PASSWORD`, `clientSecret`, `SMTP_PASS`). */ +const STRONG_KEYS = String.raw`api[_-]?key|apikey|secret|token|passwords?|passwd|passphrase|passcode|(? value !== MARK && value.length >= 8 && (/[\d+/=]/.test(value) || value.length >= 16); + +/** `the password is …`, `change the token to …`: a credential named in prose, and the word after it when that looks + * like one (with a digit or a sign, or long). `the token is expired` stays. */ +const PROSE_SECRET = /\b(password|passwd|passphrase|passcode|pin (?:code|number)|secret|token|api[ -]?key|access key)(\s+(?:is|was|to|=|:)\s+)(["'`]?)([^\s"'`]+)/gi; +const proseShaped = (value: string) => { + const word = value.replace(/[.,;:!?)\]]+$/, ''); + return word !== MARK && ((word.length >= 6 && /[^A-Za-z]/.test(word)) || word.length >= 12); +}; + +/** The mark in place of a value: inside its quotes when they were closed, after the opening one when not. */ +const quotedMark = (q: string | undefined, closed = true) => (q ? `${q}${MARK}${closed ? q : ''}` : MARK); + +/** Layer 2: the shapes credentials take. */ +function scrubShapes(text: string): string { + return text + .replaceAll(PRIVATE_KEY, MARK) + .replaceAll(TOKEN_FORMATS, MARK) + .replaceAll(ENTRA_SECRET, MARK) + .replaceAll(AUTH_HEADER, (_m, ...groups: (string | undefined)[]) => { + const [name, sep, q, closed] = groups; + return `${name ?? ''}${sep ?? ''}${quotedMark(q, closed !== undefined)}`; + }) + .replaceAll(AUTH_SCHEME, (m, scheme: string, value: string) => (/[\d+/=:%]/.test(value) ? `${scheme} ${MARK}` : m)) + .replaceAll(CONNECTION_FIELD, `$1${MARK}`) + .replaceAll(KEY_VALUE, (m, ...groups: (string | undefined)[]) => { + const [prefix, strong, q, closed, open, bare] = groups; + return strong || keyShaped(closed ?? open ?? bare ?? '') ? (prefix ?? '') + quotedMark(q, closed !== undefined) : m; + }) + .replaceAll(SECRET_FLAG, (_m, flag: string, q?: string, closed?: string) => flag + quotedMark(q, closed !== undefined)) + // curl -u user:password; docker login -u user -p password; mysql -u user -ppassword; sshpass -p password. + .replaceAll(/((?:^|\s)(?:-u|--user)[ \t]+[^\s:"'`]{1,200}:)[^\s"'`]+/g, `$1${MARK}`) + .replaceAll(/((?:^|\s)-u[ \t]*[^\s"'`]{1,200}[ \t]+-p)([ \t]*)(?!-)[^\s"'`]+/g, `$1$2${MARK}`) + .replaceAll(/(\bsshpass[ \t]+-p[ \t]*)[^\s"'`]+/g, `$1${MARK}`) + .replaceAll(/(? (m.length >= 32 && /[a-z]/.test(m) && /[A-Z]/.test(m) && /\d/.test(m) ? MARK : m)) + .replaceAll(/(? { + const [name, sep, q, value] = groups; + return proseShaped(value) ? `${name}${sep}${q}${MARK}` : m; + }); +} + +/** Whether a question or message asks for a credential: your answer to it is taken for one. */ +export function asksForSecret(text: string): boolean { + return /\b(?:password|passwd|passphrase|passcode|pin (?:code|number)|otp|one[- ]time (?:code|password)|2fa|mfa|token|api[ -]?key|secret|credentials?|private key|access key)\b/i.test(text); +} + +/** A line that names a credential. */ +const SECRET_WORD = /password|passwd|passphrase|secret|token|api[ _-]?key|credential|private[ _-]?key|authorization|access[ _-]?key|\bpat\b/i; + +/** Layer 3: on a line that names a credential, any run of 16 or more letters and digits (both) is taken for one. */ +function scrubNearSecretWords(text: string): string { + return text.split(/(\r?\n)/).map(line => (SECRET_WORD.test(line) + ? line.replaceAll(/(? (/[A-Za-z]/.test(w) && /\d/.test(w) ? MARK : w)) + : line)).join(''); +} + +/** `text` with every credential-shaped part replaced by `[secret]`. */ +export function scrubSecrets(text: string): string { + if (!text) return text; + const layer1 = redactSecrets(text).replaceAll(/\[REDACTED(?::[a-z0-9-]+)?\]/g, MARK); + return scrubNearSecretWords(scrubShapes(layer1)); +} diff --git a/src/core/session-image-loader.test.ts b/src/core/session-image-loader.test.ts index ad686aa8..3ee7d215 100644 --- a/src/core/session-image-loader.test.ts +++ b/src/core/session-image-loader.test.ts @@ -13,6 +13,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import { SessionImageLoader } from './session-image-loader'; import type { SessionSourceRequest } from './session-images'; import type { SessionSource } from './cache'; +import type { TimelineSessionText } from './types'; class FakeWorker extends EventEmitter { requests: SessionSourceRequest[] = []; @@ -110,6 +111,42 @@ describe('image worker lifecycle', () => { await rejected; }); + it('drops a lane-text read a newer one replaced before it ran, so the lane shown is read next', async () => { + const worker = new FakeWorker(); + const loader = new SessionImageLoader(() => worker); + loaders.push(loader); + const text = (from: number) => ({ type: 'timeline-text' as const, source, sessionId: 'session', scope: { from, to: from + 1, turns: [] }, labels: { names: [] } }); + const busy = loader.load(source, 'session', 'image'); + const older = loader.loadTimelineText(text(1)); + const newer = loader.loadTimelineText(text(2)); + await Promise.resolve(); + worker.emit('message', { type: 'session-images', images: [] }); + await busy; + expect(await older).toEqual({ superseded: true }); + await Promise.resolve(); + expect(worker.requests.map(r => r.type === 'timeline-text' ? r.scope.from : r.type)).toEqual(['session-images', 2]); + worker.emit('message', { type: 'timeline-text', text: null }); + expect(await newer).toBeNull(); + }); + + it('takes from the worker only the fields a lane shows', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const worker = new FakeWorker(); + const loader = new SessionImageLoader(() => worker); + loaders.push(loader); + const request = { type: 'timeline-text' as const, source, sessionId: 'session', scope: { from: 0, to: 10, turns: [] }, labels: { names: [] } }; + const text = loader.loadTimelineText(request); + await Promise.resolve(); + worker.emit('message', { type: 'timeline-text', text: { sessionId: 'session', turns: [{ t: 1, k: 'you', prompt: 'Go' }], waits: [] } }); + expect(await text).toEqual({ sessionId: 'session', turns: [{ t: 1, k: 'you', prompt: 'Go' }], waits: [] }); + // A reply carrying anything more of the session (here its raw response) is refused. + const more = loader.loadTimelineText(request); + const rejected = expect(more).rejects.toThrow(); + await Promise.resolve(); + worker.emit('message', { type: 'timeline-text', text: { sessionId: 'session', turns: [{ t: 1, k: 'you', responseText: 'raw' }], waits: [] } }); + await rejected; + }); + it('extracts images and session details through the real bundled parse-worker protocol', async () => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'coach-image-worker-')); try { @@ -145,4 +182,50 @@ describe('image worker lifecycle', () => { fs.rmSync(directory, { recursive: true, force: true }); } }); + + it('builds one lane’s text in the bundled parse worker: its scope only, scrubbed', async () => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'coach-text-worker-')); + try { + const workerPath = path.join(directory, 'parse-worker.cjs'); + await build({ + entryPoints: [path.resolve('src', 'core', 'parse-worker.ts')], + outfile: workerPath, bundle: true, platform: 'node', format: 'cjs', + }); + const at = (day: number, m: number) => new Date(2026, 4, day, 10, m).toISOString(); + const secret = 'ghp_' + 'Abc123'.repeat(6); + const events = path.join(directory, 'events.jsonl'); + fs.writeFileSync(events, [ + { type: 'session.start', data: { sessionId: 'session' } }, + { type: 'user.message', timestamp: at(1, 0), id: 'u1', data: { content: 'Yesterday’s prompt' } }, + { type: 'tool.execution_start', timestamp: at(1, 1), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Yesterday’s question?' } } }, + { type: 'tool.execution_complete', timestamp: at(1, 2), data: { toolCallId: 'q1', success: true, result: { content: 'User selected: no' } } }, + { type: 'user.message', timestamp: at(2, 0), id: 'u2', data: { content: `Deploy with ${secret}` } }, + { type: 'tool.execution_start', timestamp: at(2, 1), data: { toolName: 'ask_user', toolCallId: 'q2', arguments: { question: 'Today’s question?' } } }, + { type: 'tool.execution_complete', timestamp: at(2, 2), data: { toolCallId: 'q2', success: true, result: { content: 'User selected: yes' } } }, + { type: 'user.message', timestamp: at(2, 30), id: 'u3', data: { content: 'Not listed by the lane' } }, + ].map(event => JSON.stringify(event)).join('\n')); + const worker = new Worker(workerPath, { execArgv: [] }); + const loader = new SessionImageLoader(() => worker); + loaders.push(loader); + const day = new Date(2026, 4, 2).getTime(); + const text = await loader.loadTimelineText({ + type: 'timeline-text', source: { ...source, filePath: events }, sessionId: 'session', + scope: { from: day, to: day + 86_400_000, turns: [{ t: Date.parse(at(2, 0)), id: 'u2' }] }, labels: { names: [] }, + }) as TimelineSessionText | null; + expect(text?.turns.map(t => t.prompt)).toEqual(['Deploy with [secret]']); + expect(text?.waits.map(w => w.ask)).toEqual(['Today’s question?']); + expect(JSON.stringify(text)).not.toContain('Yesterday'); + // The session detail view gets none of the Timeline's text: no reply text, no question or answer, raw. + const detail = await loader.loadSession({ ...source, filePath: events }, 'session'); + expect(detail?.requests.length).toBe(3); + expect(detail?.requests.some(r => r.replyText !== undefined || (r.userWaits ?? []).some(w => w.text))).toBe(false); + // A malformed scope is refused, not read. + const invalid = new Promise(resolve => worker.once('message', resolve)); + worker.postMessage({ type: 'timeline-text', source: { ...source, filePath: events }, sessionId: 'session', scope: { from: 'x' }, labels: { names: [] } }); + expect(await invalid).toEqual({ type: 'error', message: 'Invalid session source request' }); + loader.dispose(); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); }); diff --git a/src/core/session-image-loader.ts b/src/core/session-image-loader.ts index 740310c0..9d9e80c8 100644 --- a/src/core/session-image-loader.ts +++ b/src/core/session-image-loader.ts @@ -6,12 +6,14 @@ import * as path from 'path'; import { Worker } from 'worker_threads'; import type { SessionSource } from './cache'; -import type { Session } from './types'; -import type { SessionSourceRequest } from './session-images'; -import { SessionSchema } from './schemas'; +import type { Session, TimelineSessionText, TimelineTextSuperseded } from './types'; +import type { SessionSourceRequest, TimelineTextRequest } from './session-images'; +import { SessionSchema, TimelineSessionTextSchema } from './schemas'; import { warnCore } from './log'; import type { ImageRequestMatch } from './image-data'; +const SUPERSEDED: TimelineTextSuperseded = { superseded: true }; + interface ImageWorker { on(event: 'message', listener: (value: unknown) => void): void; on(event: 'error', listener: (error: Error) => void): void; @@ -28,6 +30,7 @@ export class SessionImageLoader { private worker: ImageWorker | null = null; private queue: Promise = Promise.resolve(); private idleTimer: ReturnType | undefined; + private textTicket = 0; constructor(private readonly createWorker: () => ImageWorker = () => new Worker(path.join(__dirname, 'parse-worker.js'), { execArgv: [], @@ -51,8 +54,19 @@ export class SessionImageLoader { }); } - private enqueue(request: SessionSourceRequest, decode: (value: object) => T): Promise { - const result = this.queue.then(() => this.run(request, decode)); + /** One Timeline lane's text, built and scrubbed in the worker: the host gets only what the lane shows. Only the newest + * such read matters (one lane's details are shown at a time): one still queued behind it is dropped unread, as + * `{ superseded: true }`, so the lane shown isn't kept waiting. */ + loadTimelineText(request: TimelineTextRequest): Promise { + const ticket = ++this.textTicket; + return this.enqueue(request, value => { + if (!('text' in value)) throw new Error('Invalid timeline text worker response'); + return value.text === null ? null : TimelineSessionTextSchema.parse(value.text); + }, () => (ticket === this.textTicket ? undefined : SUPERSEDED)); + } + + private enqueue(request: SessionSourceRequest, decode: (value: object) => T, skip?: () => T | undefined): Promise { + const result = this.queue.then(() => skip?.() ?? this.run(request, decode)); // A failed request must not prevent subsequent image requests from running. this.queue = result.then(() => undefined, () => undefined); return result; @@ -142,3 +156,7 @@ export function loadSessionImages(source: SessionSource, sessionId: string, requ export function loadSessionDetails(source: SessionSource, sessionId: string): Promise { return imageLoader.loadSession(source, sessionId); } + +export function loadSessionTimelineText(request: TimelineTextRequest): Promise { + return imageLoader.loadTimelineText(request); +} diff --git a/src/core/session-images.ts b/src/core/session-images.ts index 2ece4078..a4b30be1 100644 --- a/src/core/session-images.ts +++ b/src/core/session-images.ts @@ -5,7 +5,9 @@ import * as path from 'path'; import type { SessionSource } from './cache'; -import type { Session } from './types'; +import type { Session, TimelineSessionText, TimelineTextScope } from './types'; +import type { ScrubContext } from './session-labels'; +import { timelineSessionText } from './timeline-text'; import { extractCLIImageReferences, parseCLIEventsFile } from './parser-vscode-cli'; import { earliestRequestTime, extractClaudeImageReferences, isClaudeSubagentFile, parseClaudeSessionFile } from './parser-claude'; import { extractCodexImageReferences, parseCodexSessionFile } from './parser-codex'; @@ -28,7 +30,38 @@ export interface SessionDetailRequest { sessionId: string; } -export type SessionSourceRequest = SessionImagesRequest | SessionDetailRequest; +/** The text behind one Timeline lane, built in the worker so the full session never crosses to the extension host. */ +export interface TimelineTextRequest { + type: 'timeline-text'; + source: SessionSource; + sessionId: string; + scope: TimelineTextScope; + /** The turns the analysis kept, by identity, when it dropped a fork's copied turns. */ + kept?: string[]; + labels: ScrubContext; +} + +export type SessionSourceRequest = SessionImagesRequest | SessionDetailRequest | TimelineTextRequest; + +/** Runs in the parse worker: the lane's scoped, scrubbed text, or null when its log can't be read again. */ +export function loadTimelineText(request: TimelineTextRequest): TimelineSessionText | null { + const session = loadSourceSession(request.source, request.sessionId); + return session ? timelineSessionText(session, request.labels, request.scope, request.kept ? new Set(request.kept) : undefined) : null; +} + +/** Runs in the parse worker: a session for its detail view, without the text only the Timeline shows (the agent's + * own messages apart from its code, and what each question and permission prompt asked and you answered). That + * reaches the extension only through `loadTimelineText`, scoped and scrubbed. */ +export function loadSourceSessionDetail(source: SessionSource, sessionId: string): Session | null { + const session = loadSourceSession(source, sessionId); + if (!session) return null; + for (const r of session.requests) { + delete r.replyText; + for (const w of r.userWaits ?? []) delete w.text; + } + for (const w of session.userWaits ?? []) delete w.text; + return session; +} export function loadSourceSession(source: SessionSource, sessionId: string): Session | null { switch (source.kind) { diff --git a/src/core/session-labels.test.ts b/src/core/session-labels.test.ts index 29ea82ca..c449bbdb 100644 --- a/src/core/session-labels.test.ts +++ b/src/core/session-labels.test.ts @@ -7,7 +7,7 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { afterEach, describe, expect, it } from 'vitest'; -import { harnessLabel, lastSegment, PERSONAL_REPOSITORY, scrubBranch, scrubLabel, scrubRepository } from './session-labels'; +import { harnessLabel, lastSegment, PERSONAL_REPOSITORY, scrubBranch, scrubLabel, scrubRepository, scrubText } from './session-labels'; import { isPromptText, readCliClient, readCliWorkspaceMeta, yamlScalar } from './session-workspace-meta'; const ctx = { home: 'C:\\Users\\Dev', names: ['Dev', 'octo-dev', 'me'], handles: ['octo-dev'] }; @@ -88,6 +88,54 @@ describe('session labels with several paths', () => { }); }); +describe('scrubText', () => { + const text = { home: 'C:\\Users\\jdoe', names: ['jdoe', 'vscode'], handles: ['octo-dev'] }; + + it('keeps the text readable: line breaks and ordinary paths stay, the home folder becomes ~ and names [name]', () => { + expect(scrubText('Edit C:\\Users\\jdoe\\repo\\a.ts\nthen D:\\work\\b.ts, asked by jdoe and octo-dev in vscode', text)) + .toBe('Edit ~\\repo\\a.ts\nthen D:\\work\\b.ts, asked by [name] and [name] in vscode'); + expect(scrubText('See https://x.io/a?token=1 or mail a@b.io', text)).toBe('See [link] or mail [email]'); + }); + + it('replaces secret-like tokens but keeps hashes and IDs', () => { + // Built at run time, so no token-shaped literal sits in the repository. + const letters = 'abcdefghijklmnopqrstuvwxyz'; + const secrets = [ + 'ghp_' + letters + '0123', 'github_pat_' + '11ABCDEFG0123456789_' + letters.slice(0, 10), 'AKIA' + letters.slice(0, 16).toUpperCase(), + 'sk-' + 'proj-' + letters.slice(0, 24), ['eyJhbGciOiJIUzI1NiJ9', 'eyJzdWIiOiIxMjM0In0', letters.slice(0, 16)].join('.'), 'Q2xpZW50U2VjcmV0VmFsdWUxMjM0NTY3OEFC', + ]; + for (const s of secrets) expect(scrubText(`key ${s} end`, text)).toBe('key [secret] end'); + // A header's whole value goes, its scheme too. + expect(scrubText('Authorization: Bearer abcdef0123456789xyz', text)).toBe('Authorization: [secret]'); + expect(scrubText('set password=hunter2hunter and api_key: "abc123def456"', text)).toBe('set password=[secret] and api_key: "[secret]"'); + expect(scrubText('-----BEGIN RSA PRIVATE KEY-----\nMIIB\n-----END RSA PRIVATE KEY-----', text)).toBe('[secret]'); + const ids = 'commit 3f2a9c4e1b7d8a6f5e4d3c2b1a0f9e8d7c6b5a49 session 7e470000-0000-4000-8000-000000000001'; + expect(scrubText(ids, text)).toBe(ids); + }); + + it('replaces the value of a prefixed secret variable and of a secret flag followed by a space', () => { + expect(scrubText('DB_PASSWORD=hunter2hunter SERVICE_API_KEY=0123456789abcdef0123456789abcdef npm start', text)) + .toBe('DB_PASSWORD=[secret] SERVICE_API_KEY=[secret] npm start'); + expect(scrubText('$env:STORAGE_ACCOUNT_KEY = "abc123def456"', text)).toBe('$env:STORAGE_ACCOUNT_KEY = "[secret]"'); + expect(scrubText('{ accessToken=abc123def456, refreshToken: "abc123def456", clientSecret: abc123def456 }', text)) + .toBe('{ accessToken=[secret], refreshToken: "[secret]", clientSecret: [secret] }'); + expect(scrubText('login --password hunter2hunter --client-secret abc123def456 --token=abc123def456', text)) + .toBe('login --password [secret] --client-secret [secret] --token=[secret]'); + // Words that only contain a key's name, and flags that name a file or a count, stay. + const plain = 'design=wide max_tokens=4096 --token-file cfg.json --max-tokens 4096 --password-stdin'; + expect(scrubText(plain, text)).toBe(plain); + }); + + it('replaces credentials given to a command line as user:password, -u … -p …, or a secret access key', () => { + expect(scrubText('curl -u admin:hunter2 x && curl --user ci:abc123 y', text)).toBe('curl -u admin:[secret] x && curl --user ci:[secret] y'); + expect(scrubText('docker login -u ci -p hunter2hunter registry', text)).toBe('docker login -u ci -p [secret] registry'); + expect(scrubText('AWS_SECRET_ACCESS_KEY=abcdefghijklmnop AWS_PRIVATE_KEY: abcdefghijklmnop', text)) + .toBe('AWS_SECRET_ACCESS_KEY=[secret] AWS_PRIVATE_KEY: [secret]'); + const plain = 'mkdir -p out && sort -u names.txt && npm run -s build'; + expect(scrubText(plain, text)).toBe(plain); + }); +}); + describe('Copilot workspace.yaml', () => { let dir = ''; afterEach(() => { if (dir) fs.rmSync(dir, { recursive: true, force: true }); }); diff --git a/src/core/session-labels.ts b/src/core/session-labels.ts index 19d5bf43..33678324 100644 --- a/src/core/session-labels.ts +++ b/src/core/session-labels.ts @@ -6,6 +6,8 @@ /* Session names and branches as a harness logged them, made safe to display: links, email addresses, drive and * home paths, and the user's own names (OS account, GitHub handles) are removed. Browser-safe: no Node imports. */ +import { scrubSecrets } from './secret-scrub'; + /** What to remove from a label: the user's home directory and the names that identify them. */ export interface ScrubContext { /** Home directory, replaced by `~` (after drive paths are replaced). */ @@ -130,6 +132,19 @@ export function scrubBranch(value: string, ctx: ScrubContext): string { return scrubLabel(out, ctx, MAX_BRANCH, '[name]'); } +/** Free text (a prompt, a question, your answer, an agent's message) made safe to show on this machine: links, email + * addresses and credentials (see `scrubSecrets`) are replaced, the home directory becomes `~` and the user's names + * become `[name]`. Line breaks and other paths stay, so the text reads as written. */ +export function scrubText(value: string, ctx: ScrubContext): string { + let out = scrubSecrets(value.replaceAll(/[a-z][a-z0-9+.-]{0,30}:\/\/\S+/gi, '[link]').replaceAll(/[\w.+-]{1,64}@[\w-]{1,63}(?:\.[\w-]{1,63}){1,10}/g, '[email]')); + if (ctx.home && ctx.home.length > 1) { + const home = ctx.home.replace(/[\\/]+$/, ''); + const variants = new Set([home, home.replaceAll('\\', '/'), home.replaceAll('/', '\\')]); + for (const variant of variants) out = out.replace(new RegExp(escapeRegExp(variant), 'gi'), '~'); + } + return removeNames(out, usableNames([...ctx.names, ...(ctx.handles ?? [])]), '[name]'); +} + /** Shown when a repository or folder name is nothing but the user's name, so scrubbing left nothing. */ export const PERSONAL_REPOSITORY = 'personal repository'; diff --git a/src/core/timeline-model.test.ts b/src/core/timeline-model.test.ts index fd8414b8..e79ee54e 100644 --- a/src/core/timeline-model.test.ts +++ b/src/core/timeline-model.test.ts @@ -5,9 +5,10 @@ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { - buildFamilies, buildLanes, buildViewFamilies, createNamer, familiesInsights, familyUnattendedMs, filterLanes, formatDuration, hourTicks, + buildFamilies, buildLanes, buildViewFamilies, createNamer, familiesInsights, familyUnattendedMs, filteredDayTotals, filterLanes, formatDuration, hourTicks, NO_LANE_FILTERS, peakParallel, prepareTimeline, sessionWaits, sessionWork, stepDate, timelineKpis, timelineWindow, turnTimes, - verdictText, VERDICTS, viewInsights, type PreparedTimeline, + textScope, verdictText, VERDICTS, viewInsights, type PreparedTimeline, + waitInWindow, } from './timeline-model'; import type { TimelineDataset, TimelineSessionRecord, TimelineTurn, TurnSender } from './types/timeline-types'; @@ -55,6 +56,13 @@ describe('timeline model', () => { expect(waitsOf([turn(at(9), 0, 'you', { noDuration: true }), turn(at(10), 5), turn(at(10, 30), 5)])).toEqual([[at(10, 5), at(10, 30)]]); }); + it('ties a wait for your next prompt to the turn whose end started it, not the latest-started one', () => { + const a = turn(at(10), 10, 'you', { id: 'a' }); + const b = turn(at(10, 2), 1, 'agent', { id: 'b' }); + const idle = sessionWaits([a, b, turn(at(10, 40), 1)]).waits.find(w => w.kind === 'idle'); + expect([idle?.start, idle?.after?.id]).toEqual([at(10, 10), 'a']); + }); + it('measures the longest unattended stretch in a family, up to your next input anywhere in it', () => { const p = prepareTimeline(fixture()); // From the 9:00 prompt the family kept working, but your prompt into child-a at 10:30 ends that stretch; the next one @@ -300,3 +308,96 @@ describe('conditional coaching sentences', () => { expect(p.days).toEqual(['2024-03-13']); }); }); + +describe('waitInWindow', () => { + it('takes a question asked, waited on or answered in the window, and not one that only ended at its start', () => { + const [from, to] = [100, 200]; + const w = (s: number, e: number, a = true, at?: number) => ({ s, e, k: 'question' as const, a, ...(at === undefined ? {} : { at }) }); + expect([ + waitInWindow(w(150, 150), from, to), waitInWindow(w(50, 150), from, to), waitInWindow(w(50, 90, true, 120), from, to), + waitInWindow(w(50, 100, true, 80), from, to), waitInWindow(w(200, 250), from, to), waitInWindow(w(50, 60, false), from, to), + ]).toEqual([true, true, true, false, false, false]); + }); +}); + +describe('textScope', () => { + it('lists each turn once: a wait’s preceding turn is often one the lane lists', () => { + const scope = textScope([at(9), at(18)], [{ t: at(10), id: 'a' }, { t: at(11) }, { t: at(10), id: 'a' }, { t: at(11) }, { t: at(11), id: 'b' }]); + expect(scope).toEqual({ from: at(9), to: at(18), turns: [{ t: at(10), id: 'a' }, { t: at(11) }, { t: at(11), id: 'b' }] }); + }); +}); + +describe('a dense session', () => { + it('builds its lane and family whatever its number of turns', () => { + // More values than a call can take as arguments: Math.min(...values) throws a RangeError on them. + // Measured agent turns between your prompts: a stretch the family ran unattended for each. + const prepared = (n: number) => { + const list = Array.from({ length: n }, (_, i) => turn(at(0) + i * 60_000, i % 2 ? 0.5 : 0, i % 2 ? 'agent' : 'you')); + return { list, p: prepareTimeline({ forkedSessions: 0, sessions: [session('busy', list), session('kid', [turn(at(22, 0, 14), 5, 'agent')], { parent: 0, via: 'create' })] }) }; + }; + const { list: turns, p } = prepared(300_000); + const win: [number, number] = [at(0), at(0, 0, 15 + 220)]; + // The same pattern in 10 turns (the child is before the window): the longest unattended stretch doesn't depend on how many there are. + const small = prepared(10).p; + const smallLanes = buildLanes(small, ...win); + const longest = buildViewFamilies(smallLanes, small)[0].unattendedMs; + expect(longest).toBeGreaterThan(0); + const lanes = buildLanes(p, ...win); + expect([lanes[0].first, lanes[0].turns.length]).toEqual([at(0), 300_000]); + expect(lanes[0].last).toBeGreaterThanOrEqual(turns[turns.length - 1].t); + expect(p.stretches.get(0)!.length).toBe(150_000); + const families = buildViewFamilies(lanes, p); + expect(families[0].unattendedMs).toBe(longest); + expect(timelineKpis(lanes, families).unattendedMs).toBe(longest); + expect(viewInsights(lanes, families, createNamer(p, false), 'range', p).length).toBeGreaterThan(0); + const overview = buildFamilies(p); + expect(overview.families[0].from).toBe('2024-03-14'); + expect(familiesInsights(overview.totals).length).toBeGreaterThan(0); + }); +}); + +describe('filteredDayTotals', () => { + // A types on the 15th only and works alone on the 16th; B, in Claude Code, types on the 16th. + const p = prepareTimeline({ + forkedSessions: 0, + sessions: [ + session('a', [turn(at(9), 30, 'you'), turn(at(10, 0, 16), 20, 'agent'), turn(at(11, 0, 16), 10, 'agent')]), + session('b', [turn(at(14, 0, 16), 5, 'you'), turn(at(14, 40, 16), 3, 'you')], { harness: 'Claude Code' }), + ], + }); + const dayKpis = (day: string, f = NO_LANE_FILTERS) => { + const lanes = filterLanes(buildLanes(p, ...timelineWindow('day', day)), f, p); + const k = timelineKpis(lanes, buildViewFamilies(lanes, p)); + return { typed: k.typed, automated: k.turns - k.typed, agentMs: k.agentMs, waitMs: k.waitMs }; + }; + const none = { typed: 0, automated: 0, agentMs: 0, waitMs: 0 }; + + it('counts each day what the Day view shows with the same filters', () => { + for (const f of [{ ...NO_LANE_FILTERS, harness: 'Claude Code' }, { ...NO_LANE_FILTERS, youTyped: true }, { ...NO_LANE_FILTERS, hideOneTurn: true }]) { + const totals = filteredDayTotals(p, f); + for (const day of p.days) expect([day, totals.get(day) ?? none]).toEqual([day, dayKpis(day, f)]); + } + // A session counts on a day when its lane that day passes: A typed nothing on the 16th. + expect(filteredDayTotals(p, { ...NO_LANE_FILTERS, youTyped: true }).get('2024-03-16')).toMatchObject({ typed: 2, automated: 0 }); + expect(filteredDayTotals(p, { ...NO_LANE_FILTERS, harness: 'Claude Code' }).has('2024-03-15')).toBe(false); + }); + + it('reads a long, busy session once, not once per day', () => { + // 300,000 turns over 209 days; preparing them is linear, and so must be filtering them. + const turns = Array.from({ length: 300_000 }, (_, i) => turn(at(0) + i * 60_000, i % 2 ? 0.5 : 0, i % 2 ? 'agent' : 'you')); + const data: TimelineDataset = { forkedSessions: 0, sessions: [session('busy', turns)] }; + let started = performance.now(); + const busy = prepareTimeline(data); + const prepareMs = performance.now() - started; + started = performance.now(); + const totals = filteredDayTotals(busy, { ...NO_LANE_FILTERS, youTyped: true }); + expect(performance.now() - started).toBeLessThan(prepareMs); + expect(totals.size).toBe(busy.days.length); + expect(totals.get(busy.days[1])).toEqual(busy.dayTotals.get(busy.days[1])); + }); + + it('is the unfiltered totals without filters', () => { + expect(filteredDayTotals(p, NO_LANE_FILTERS)).toBe(p.dayTotals); + for (const day of p.days) expect(p.dayTotals.get(day)).toEqual(dayKpis(day)); + }); +}); diff --git a/src/core/timeline-model.ts b/src/core/timeline-model.ts index 7e023fa4..4e13ca44 100644 --- a/src/core/timeline-model.ts +++ b/src/core/timeline-model.ts @@ -23,7 +23,7 @@ * Family a coordinator session and every session it started, directly or through its children. */ import { toDateStr } from './helpers'; -import type { TimelineDataset, TimelineSessionRecord, TimelineTurn, TimelineTurnWait } from './types/timeline-types'; +import type { TimelineDataset, TimelineSessionRecord, TimelineTextScope, TimelineTurn, TimelineTurnWait } from './types/timeline-types'; export const WAIT_MIN_MS = 2 * 60_000; export const WAIT_MAX_MS = 120 * 60_000; @@ -35,7 +35,10 @@ export const WIDE_FAN_OUT = 8; const UNATTENDED_CALLOUT_MS = 5 * 60_000; const MAX_DEPTH = 64; -export type TimelineView = 'day' | 'week' | 'families'; +export type TimelineView = 'day' | 'week' | 'range' | 'families'; + +/** The views that draw lanes over a period: a day, a Monday-to-Sunday week, or a custom range of days. */ +export type TimelinePeriod = Exclude; export type Interval = [number, number]; @@ -44,6 +47,9 @@ export interface TimelineWait { start: number; end: number; kind: 'idle' | TimelineTurnWait['k']; + /** For a wait for your next prompt: the turn whose end (or whose last question's) started it. With overlapping + * turns this is the one that ended last, not the one that started last. */ + after?: TimelineTurn; } /** Your answer to a question or a permission prompt, when you gave it. */ @@ -194,14 +200,17 @@ export function sessionWaits(turns: readonly TimelineTurn[], stops: readonly Tim for (const w of stops) if (waitedOnYou(w)) waits.push({ start: w.s, end: w.e, kind: w.k }); const away: Interval[] = []; let busyUntil = -1; + let busyTurn: TimelineTurn | undefined; for (const t of [...turns].sort((a, b) => a.t - b.t)) { if (t.k === 'you' && busyUntil > 0) { const gap = t.t - busyUntil; - if (gap >= WAIT_MIN_MS && gap <= WAIT_MAX_MS) waits.push({ start: busyUntil, end: t.t, kind: 'idle' }); + if (gap >= WAIT_MIN_MS && gap <= WAIT_MAX_MS) waits.push({ start: busyUntil, end: t.t, kind: 'idle', ...(busyTurn ? { after: busyTurn } : {}) }); else if (gap > WAIT_MAX_MS) away.push([busyUntil, t.t]); } for (const w of t.w ?? []) if (waitedOnYou(w)) waits.push({ start: w.s, end: w.e, kind: w.k }); - busyUntil = t.noDuration ? -1 : Math.max(busyUntil, t.t + t.d, ...(t.w ?? []).map(w => w.e)); + const end = Math.max(t.t + t.d, ...(t.w ?? []).map(w => w.e)); + if (t.noDuration) [busyUntil, busyTurn] = [-1, undefined]; + else if (end >= busyUntil) [busyUntil, busyTurn] = [end, t]; } return { waits: waits.sort((a, b) => a.start - b.start), away }; } @@ -266,6 +275,40 @@ function countRelayedAnswersOnce(sessions: readonly PreparedSession[]): void { .sort((x, y) => Math.abs(x.at - a.at) - Math.abs(y.at - a.at))[0]); } } +/** Finds each Timeline turn's text, read again from its log: by the turn's identity, else by its time when a single text + * turn has that time. Two turns can share a time (a sub-agent's), so time alone never picks between them; a turn whose + * prompt logged no ID is known by its latest reply, an identity a live turn changes as it gains messages. */ +export function textTurnFinder(turns: readonly T[]): (t: Pick) => T | undefined { + const byId = new Map(turns.filter(t => t.id).map(t => [t.id, t])); + const byTime = new Map(); + for (const t of turns) byTime.set(t.t, byTime.has(t.t) ? null : t); + return t => (t.id ? byId.get(t.id) : undefined) ?? byTime.get(t.t) ?? undefined; +} + +/** Most turns one lane's text read can list: a Range view of up to 92 days can hold far more than a day or a week. The + * host reads no scope longer than this, and the lane says so instead. */ +export const MAX_TEXT_SCOPE_TURNS = 50_000; + +/** A lane's text scope: its window and the turns it lists, each once (a wait's preceding turn is often a listed one). */ +export function textScope(win: Interval, turns: readonly Pick[]): TimelineTextScope { + const seen = new Set(); + const listed: TimelineTextScope['turns'] = []; + for (const t of turns) { + const key = `${t.t}|${t.id ?? ''}`; + if (seen.has(key)) continue; + seen.add(key); + listed.push({ t: t.t, ...(t.id ? { id: t.id } : {}) }); + } + return { from: win[0], to: win[1], turns: listed }; +} + +/** A question or permission prompt that belongs to the window [`from`, `to`): asked in it, its measured wait + * overlapping it (half-open), or answered in it. */ +export function waitInWindow(w: TimelineTurnWait, from: number, to: number): boolean { + const answered = w.at ?? w.e; + return (w.s >= from && w.s < to) || (w.e > w.s && w.e > from && w.s < to) || (w.a && answered >= from && answered < to); +} + /** Your answer to a question or permission prompt: when the harness recorded it, else when its result came. Asked at * the request, or at the answer when the answer was recorded first. */ function answerOf(w: TimelineTurnWait): TimelineAnswer { @@ -370,17 +413,22 @@ export function dayStart(date: string): number { return new Date(date + 'T00:00:00').getTime(); } -/** `days` calendar days later, at the same local clock time (not `days × 24 h`, which daylight saving breaks). */ +/** The start of the day `days` calendar days after the one holding `ts` (not `days × 24 h`, which daylight saving + * breaks): its midnight, or 1:00 where the clock springs forward at midnight. Read from the date, not carried from + * `ts`, so a day that started at 1:00 is followed by one that starts at midnight. */ export function addDays(ts: number, days: number): number { const d = new Date(ts); d.setDate(d.getDate() + days); + d.setHours(0, 0, 0, 0); return d.getTime(); } -/** Monday 00:00 of the week holding `date`. */ +/** The start of the Monday of the week holding `date` (its midnight, or 1:00 where the clock skips midnight), the same + * whichever of the week's days is given. */ export function weekStart(date: string): number { const d = new Date(date + 'T00:00:00'); d.setDate(d.getDate() - (d.getDay() + 6) % 7); + d.setHours(0, 0, 0, 0); return d.getTime(); } @@ -410,13 +458,18 @@ export function dayTicks(start: number, end: number): number[] { return ticks; } -/** Each local full hour from `start` up to `end`, in steps of `step` hours of the clock. */ +/** Each local full hour from `start` up to `end`, in steps of `step` hours of the clock. An hour the clock repeats gets + * its tick twice; after a half-hour change, ticks go back onto the clock's whole hours. */ export function hourTicks(start: number, end: number, step: number): number[] { const ticks: number[] = []; const d = new Date(start); d.setMinutes(0, 0, 0); if (d.getTime() < start) d.setHours(d.getHours() + 1); for (; d.getTime() < end && ticks.length < 400; d.setTime(d.getTime() + 3_600_000)) { + if (d.getMinutes() !== 0) { + d.setMinutes(60, 0, 0); + if (d.getTime() >= end) break; + } if (d.getHours() % step === 0) ticks.push(d.getTime()); } return ticks; @@ -464,39 +517,114 @@ export function buildLanes(p: PreparedTimeline, from: number, to: number): Timel const lanes: TimelineLane[] = []; if (start >= end) return lanes; for (const s of p.sessions) { - if (s.ctx) continue; - const turns = s.turns.filter(t => t.t >= start && t.t < end); - const segments = clipIntervals(s.work, win); - const waits = s.waits.filter(w => w.start < end && w.end > start); - // A relay that only delivered a child's answer is no activity of its own. - const answers = s.answers.filter(a => a.counted && a.at >= start && a.at < end); - if (turns.length === 0 && segments.length === 0 && waits.length === 0 && answers.length === 0) continue; - const typed = turns.filter(t => t.k === 'you').length; - const waiting = clipIntervals(s.waiting, win); - const edges = [...turns.map(t => t.t), ...segments.flat(), ...waiting.flat(), ...answers.map(a => a.at)]; - lanes.push({ - s, - turns, - segments, - typed, - automated: turns.length - typed, - answered: answers.filter(a => a.counted).length, - agentMs: intervalsMs(segments), - waitMs: intervalsMs(waiting), - credits: sum(turns, t => t.cr), - tokens: sum(turns, t => t.tok), - first: Math.min(...edges), - last: Math.max(...edges), - subagents: sum(turns, t => t.sub), - waits, - away: s.away.filter(([, b]) => b >= start && b < end).length, - visibleParent: -1, - win, - }); + const lane = sessionLane(s, win); + if (lane) lanes.push(lane); } return lanes; } +/** The session's lane in `win` (already within the dataset's bounds), or null without activity there. */ +function sessionLane(s: PreparedSession, win: Interval): TimelineLane | null { + if (s.ctx) return null; + const [start, end] = win; + const turns = s.turns.filter(t => t.t >= start && t.t < end); + const segments = clipIntervals(s.work, win); + const waits = s.waits.filter(w => w.start < end && w.end > start); + // A relay that only delivered a child's answer is no activity of its own. + const answers = s.answers.filter(a => a.counted && a.at >= start && a.at < end); + if (turns.length === 0 && segments.length === 0 && waits.length === 0 && answers.length === 0) return null; + const typed = turns.filter(t => t.k === 'you').length; + const waiting = clipIntervals(s.waiting, win); + const edges = [...turns.map(t => t.t), ...segments.flat(), ...waiting.flat(), ...answers.map(a => a.at)]; + return { + s, + turns, + segments, + typed, + automated: turns.length - typed, + answered: answers.filter(a => a.counted).length, + agentMs: intervalsMs(segments), + waitMs: intervalsMs(waiting), + credits: sum(turns, t => t.cr), + tokens: sum(turns, t => t.tok), + first: minOf(edges), + last: maxOf(edges), + subagents: sum(turns, t => t.sub), + waits, + away: s.away.filter(([, b]) => b >= start && b < end).length, + visibleParent: -1, + win, + }; +} + +/** Each day's totals over the sessions the filters keep, judged as the Day view judges them: a session counts on a + * day when its lane that day passes the filters, so a day's totals equal that day's KPIs. Without filters, the + * prepared totals. `repoLabel` as in `filterLanes`. Each session's activity is sorted into its days once, so a + * long, busy session costs its size, not its size times its days. */ +export function filteredDayTotals( + p: PreparedTimeline, f: LaneFilters, repoLabel: (s: PreparedSession) => string = s => s.repo, +): Map { + if (!hasLaneFilters(f)) return p.dayTotals; + const wins = p.days.map((d): Interval => { + const [a, b] = timelineWindow('day', d); + return [Math.max(a, p.bounds[0]), Math.min(b, p.bounds[1])]; + }); + const starts = wins.map(w => w[0]); + // The day holding `t`, or -1. + const dayOf = (t: number) => { + const i = upperBound(starts, t) - 1; + return i >= 0 && t < wins[i][1] ? i : -1; + }; + const totals = new Map(); + for (const s of p.sessions) { + if (s.ctx) continue; + const days = new Map>(); + const bucket = (i: number) => { + let b = days.get(i); + if (!b) days.set(i, b = { turns: [], work: [], waiting: [], waits: [], answers: [], away: [] }); + return b; + }; + const at = (t: number, add: (i: number) => void) => { + const i = dayOf(t); + if (i >= 0) add(i); + }; + // Every day an interval overlaps (half-open), as `clipIntervals` and the lane's wait test read it. + const over = (a: number, b: number, add: (i: number) => void) => { + for (let i = Math.max(0, upperBound(starts, a) - 1); i < wins.length && wins[i][0] < b; i++) if (wins[i][1] > a) add(i); + }; + for (const t of s.turns) at(t.t, i => bucket(i).turns.push(t)); + for (const w of s.work) over(w[0], w[1], i => bucket(i).work.push(w)); + for (const w of s.waiting) over(w[0], w[1], i => bucket(i).waiting.push(w)); + for (const w of s.waits) over(w.start, w.end, i => bucket(i).waits.push(w)); + for (const a of s.answers) at(a.at, i => bucket(i).answers.push(a)); + for (const w of s.away) at(w[1], i => bucket(i).away.push(w)); + for (const [i, part] of days) { + if (wins[i][0] >= wins[i][1]) continue; + const lane = sessionLane({ ...s, ...part }, wins[i]); + if (!lane || filterLanes([{ ...lane, s }], f, p, repoLabel).length === 0) continue; + const day = totals.get(p.days[i]) ?? { typed: 0, automated: 0, agentMs: 0, waitMs: 0 }; + day.typed += lane.typed; + day.automated += lane.automated; + day.agentMs += lane.agentMs; + day.waitMs += lane.waitMs; + totals.set(p.days[i], day); + } + } + return totals; +} + +/** The index of the first of the sorted `items` after `value`. */ +function upperBound(items: readonly number[], value: number): number { + let lo = 0; + let hi = items.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (items[mid] <= value) lo = mid + 1; + else hi = mid; + } + return lo; +} + export interface LaneFilters { /** Short harness label; empty for every harness. */ harness: string; @@ -557,7 +685,7 @@ export interface ViewFamily { /** The family's longest unattended stretch inside the window. */ export function familyUnattendedMs(p: PreparedTimeline, root: number, win: Interval): number { - return Math.max(0, ...(p.stretches.get(root) ?? []).map(([a, b]) => overlap(a, b, Math.max(win[0], p.bounds[0]), Math.min(win[1], p.bounds[1])))); + return Math.max(0, maxOf((p.stretches.get(root) ?? []).map(([a, b]) => overlap(a, b, Math.max(win[0], p.bounds[0]), Math.min(win[1], p.bounds[1]))))); } /** Most sessions doing agent work at once inside the lanes' window, and when that first happened. */ @@ -618,7 +746,7 @@ export function buildViewFamilies(lanes: TimelineLane[], p: PreparedTimeline): V root, lanes: members, ordered, - first: Math.min(...members.map(l => l.first)), + first: minOf(members.map(l => l.first)), size: p.familySize.get(root) ?? members.length, typed: sum(members, l => l.typed), automated: sum(members, l => l.automated), @@ -682,7 +810,7 @@ export function timelineKpis(lanes: readonly TimelineLane[], families: readonly answered: sum(lanes, l => l.answered), agentMs, agentMsPerPrompt: typed > 0 ? agentMs / typed : null, - unattendedMs: Math.max(0, ...families.map(f => f.unattendedMs)), + unattendedMs: Math.max(0, maxOf(families.map(f => f.unattendedMs))), waits: started.length, idleWaits: started.filter(w => w.kind === 'idle').length, waitMs: sum(lanes, l => l.waitMs), @@ -765,11 +893,11 @@ export function formatClock(ts: number): string { return `${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`; } -/** Clock time in a day view, weekday and clock time in a week view. */ -export function formatWhen(ts: number, view: 'day' | 'week'): string { - return view === 'week' - ? `${new Date(ts).toLocaleDateString(undefined, { weekday: 'short' })} ${formatClock(ts)}` - : formatClock(ts); +/** Clock time in a day view, weekday and clock time in a week view, and the date too in a custom range. */ +export function formatWhen(ts: number, view: TimelinePeriod): string { + if (view === 'day') return formatClock(ts); + const day = new Date(ts).toLocaleDateString(undefined, view === 'week' ? { weekday: 'short' } : { weekday: 'short', day: 'numeric', month: 'short' }); + return `${day} ${formatClock(ts)}`; } /** Whole AI credits, `1,234`. */ @@ -797,11 +925,11 @@ const them = (n: number) => (n === 1 ? 'it' : 'them'); /* ---- coaching callouts (H) ---- */ -/** The three findings of a day or week, as plain sentences: only what the logs show. */ +/** The three findings of a day, week or range, as plain sentences: only what the logs show. */ export function viewInsights( - lanes: readonly TimelineLane[], families: readonly ViewFamily[], namer: Namer, period: 'day' | 'week', p?: PreparedTimeline, + lanes: readonly TimelineLane[], families: readonly ViewFamily[], namer: Namer, period: TimelinePeriod, p?: PreparedTimeline, ): string[] { - const when = period === 'week' ? 'this week' : 'on this day'; + const when = period === 'week' ? 'this week' : period === 'range' ? 'in this range' : 'on this day'; return [unattendedInsight(families, namer, when, p), creditsInsight(lanes, namer, when), waitsInsight(lanes, when)]; } @@ -1008,8 +1136,8 @@ function familyNode(s: PreparedSession, depth: number, bounds: Interval): Family agentMs: intervalsMs(work), credits: sum(s.turns, t => t.cr), tokens: sum(s.turns, t => t.tok), - first: starts.length ? Math.min(...starts) : 0, - last: ends.length ? Math.max(...ends) : 0, + first: starts.length ? minOf(starts) : 0, + last: ends.length ? maxOf(ends) : 0, subagents: sum(s.turns, t => t.sub), }; } @@ -1068,8 +1196,8 @@ function summarizeFamily(root: PreparedSession, kidsOf: Map n.depth)), - fanOut: Math.max(0, ...nodes.map(activeKids)), + depth: Math.max(0, maxOf(counted.map(n => n.depth))), + fanOut: Math.max(0, maxOf(nodes.map(activeKids))), repos: new Set(counted.map(n => n.s.repo)).size, // The repository named first: the coordinator's when it has activity in range, else the first active member's. repoSession: (counted[0] ?? coordinator).s, @@ -1090,9 +1218,9 @@ function summarizeFamily(root: PreparedSession, kidsOf: Map 0 ? childCredits / kids.length : 0, verdict: steppedInto > 0 ? 'needed' : 'alone', wide: kids.length >= WIDE_FAN_OUT, - from: firsts.length > 0 ? toDateStr(Math.min(...firsts)) : '', - to: lasts.length > 0 ? toDateStr(Math.max(...lasts)) : '', - busiest: busiestDayOf(counted) || (firsts.length > 0 ? toDateStr(Math.min(...firsts)) : ''), + from: firsts.length > 0 ? toDateStr(minOf(firsts)) : '', + to: lasts.length > 0 ? toDateStr(maxOf(lasts)) : '', + busiest: busiestDayOf(counted) || (firsts.length > 0 ? toDateStr(minOf(firsts)) : ''), rank: 0, }; } @@ -1125,8 +1253,8 @@ function familiesTotals(p: PreparedTimeline, families: FamilySummary[]): Familie childTyped: sum(families, f => f.childTyped), childAnswered: sum(families, f => f.childAnswered), childrenNeedingYou: sum(families, f => f.steppedInto), - maxDepth: Math.max(0, ...families.map(f => f.depth)), - maxFanOut: Math.max(0, ...families.map(f => f.fanOut)), + maxDepth: Math.max(0, maxOf(families.map(f => f.depth))), + maxFanOut: Math.max(0, maxOf(families.map(f => f.fanOut))), top3Share: sum(families.slice(0, 3), f => f.creditShare), alone: group(families.filter(f => f.verdict === 'alone')), needed: group(families.filter(f => f.verdict === 'needed')), @@ -1189,6 +1317,20 @@ export function familiesInsights(t: FamiliesTotals): string[] { return tips; } +/** The smallest of `values`: a loop, since spreading a dense lane's values into `Math.min` overflows the call stack. */ +function minOf(values: readonly number[]): number { + let min = Infinity; + for (const v of values) if (v < min) min = v; + return min; +} + +/** The largest of `values` (see `minOf`). */ +function maxOf(values: readonly number[]): number { + let max = -Infinity; + for (const v of values) if (v > max) max = v; + return max; +} + function sum(items: readonly T[], value: (item: T) => number): number { let total = 0; for (const item of items) total += value(item); diff --git a/src/core/timeline-range.test.ts b/src/core/timeline-range.test.ts new file mode 100644 index 00000000..6d2b5383 --- /dev/null +++ b/src/core/timeline-range.test.ts @@ -0,0 +1,184 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See LICENSE in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* Custom ranges: the calendar math, and a range read end to end from synthetic Copilot logs, which must equal its days + * put together and the summary export of the same dates, also over a daylight-saving change. */ + +import { afterAll, describe, expect, it } from 'vitest'; +import { analyzer, end, prompt, removeTimelineSessions, reply, session, start } from '../test/timeline-cli'; +import { buildSummaryExportFromAnalyzer } from './summary-export'; +import { addDays, buildLanes, buildViewFamilies, dayStart, hourTicks, prepareTimeline, timelineKpis, timelineWindow, weekStart, type TimelineKpis } from './timeline-model'; +import { + clampRange, isDate, MAX_RANGE_DAYS, monthCells, quickRange, rangeDays, rangeTicks, rangeWindow, shiftDate, shiftDateByMonths, shiftMonth, + stepRange, type DateRange, +} from './timeline-range'; +import type { Analyzer } from './analyzer'; + +afterAll(removeTimelineSessions); + +/** Runs `body` with the machine in `zone`, whatever zone the test runs in. */ +function inZone(zone: string, body: () => void): void { + const saved = process.env.TZ; + process.env.TZ = zone; + try { + body(); + } finally { + if (saved === undefined) delete process.env.TZ; + else process.env.TZ = saved; + } +} + +describe('date ranges', () => { + it('reads only real dates', () => { + expect(['2026-11-17', '2026-02-29', '2028-02-29', '2026-13-01', '17/11/2026', 20261117].map(isDate)).toEqual([true, false, true, false, false, false]); + }); + + it('orders, keeps within the loaded days and cuts a range to its longest', () => { + expect(clampRange('2026-11-20', '2026-11-17', '2026-11-01', '2026-11-30')).toEqual({ range: { from: '2026-11-17', to: '2026-11-20' }, capped: false }); + expect(clampRange('2026-10-20', '2026-12-20', '2026-11-01', '2026-11-30')?.range).toEqual({ from: '2026-11-01', to: '2026-11-30' }); + expect(clampRange('2026-10-01', '2026-10-20', '2026-11-01', '2026-11-30')).toBeNull(); + const long = clampRange('2026-01-01', '2026-12-31', '2026-01-01', '2026-12-31'); + expect([long?.capped, long && rangeDays(long.range)]).toEqual([true, MAX_RANGE_DAYS]); + }); + + it('steps a range by its own length, stops at the loaded days keeping its length, then no further', () => { + const r: DateRange = { from: '2026-11-10', to: '2026-11-12' }; + expect(stepRange(r, 1, '2026-11-01', '2026-11-30')).toEqual({ from: '2026-11-13', to: '2026-11-15' }); + expect(stepRange(r, -1, '2026-11-01', '2026-11-30')).toEqual({ from: '2026-11-07', to: '2026-11-09' }); + expect(stepRange({ from: '2026-11-27', to: '2026-11-29' }, 1, '2026-11-01', '2026-11-30')).toEqual({ from: '2026-11-28', to: '2026-11-30' }); + expect(stepRange({ from: '2026-11-28', to: '2026-11-30' }, 1, '2026-11-01', '2026-11-30')).toBeNull(); + expect(stepRange({ from: '2026-11-01', to: '2026-11-03' }, -1, '2026-11-01', '2026-11-30')).toBeNull(); + }); + + it('makes the quick picks end on the given day', () => { + expect(quickRange('last7', '2026-11-17')).toEqual({ from: '2026-11-11', to: '2026-11-17' }); + expect(rangeDays(quickRange('last30', '2026-03-01'))).toBe(30); + expect(quickRange('month', '2026-11-17')).toEqual({ from: '2026-11-01', to: '2026-11-17' }); + }); + + it('lays a month out in six Monday-to-Sunday weeks', () => { + const cells = monthCells('2026-02'); + expect([cells.length, cells[0], cells[6], cells[41]]).toEqual([42, '2026-01-26', '2026-02-01', '2026-03-08']); + expect([shiftMonth('2026-12', 1), shiftMonth('2026-01', -1), shiftDateByMonths('2026-01-31', 1), shiftDateByMonths('2026-03-15', -1)]) + .toEqual(['2027-01', '2025-12', '2026-02-28', '2026-02-15']); + }); + + it('draws few enough ticks for any length: hours over 2–3 days, days, every other day, then Mondays', () => { + const ticks = (from: string, days: number) => rangeTicks(...rangeWindow({ from, to: shiftDate(from, days - 1) })); + expect(ticks('2026-11-16', 2).map(([, label]) => label).filter(l => l.endsWith(':00'))).toEqual(['6:00', '12:00', '18:00', '6:00', '12:00', '18:00']); + expect(ticks('2026-11-16', 10)).toHaveLength(10); + expect(ticks('2026-11-01', 30)).toHaveLength(15); + const quarter = ticks('2026-09-01', MAX_RANGE_DAYS); + expect([quarter.length <= 14, quarter.every(([t]) => new Date(t).getDay() === 1)]).toEqual([true, true]); + }); + +}); + +describe('date ranges over daylight-saving changes', () => { + // Each zone with its own transitions, whatever the machine's zone. + it('keeps ticks on the clock’s whole hours over a half-hour daylight-saving change (Lord Howe Island)', () => inZone('Australia/Lord_Howe', () => { + const offHour = (ticks: [number, string][]) => ticks.filter(([t, label]) => { + const d = new Date(t); + return d.getMinutes() !== 0 || (label.endsWith(':00') && label !== `${d.getHours()}:00`) || (!label.endsWith(':00') && d.getHours() !== 0); + }); + // 4 October: 2:00 becomes 2:30. 5 April: 2:00 becomes 1:30 again. + for (const from of ['2026-10-03', '2026-04-04']) { + const ticks = rangeTicks(...rangeWindow({ from, to: shiftDate(from, 2) })); + expect([from, ticks.length, offHour(ticks)]).toEqual([from, 12, []]); + } + const day = timelineWindow('day', '2026-10-04'); + expect(hourTicks(day[0], day[1], 1).map(t => new Date(t).getHours())).toEqual([0, 1, ...Array.from({ length: 21 }, (_, i) => i + 3)]); + })); + + // Where the clock springs forward at midnight, the day starts at 1:00: it keeps its date marker there. + for (const [zone, day] of [['America/Santiago', '2026-09-06'], ['America/Havana', '2026-03-08'], ['Asia/Beirut', '2026-03-29']] as const) { + it(`names every day on a short range's axis when ${zone} skips midnight`, () => inZone(zone, () => { + const r = { from: shiftDate(day, -1), to: shiftDate(day, 1) }; + const named = rangeTicks(...rangeWindow(r)).filter(([, label]) => !label.endsWith(':00')); + expect(named.map(([t]) => t)).toEqual([0, 1, 2].map(i => dayStart(shiftDate(r.from, i)))); + expect(new Date(named[1][0]).getHours()).toBe(1); + // That day ends at the next midnight, not at 1:00 the day after: its window, a range ending on it, its share of work. + const next = dayStart(shiftDate(day, 1)); + expect([timelineWindow('day', day)[1], rangeWindow({ from: day, to: day })[1]]).toEqual([next, next]); + const p = prepareTimeline({ forkedSessions: 0, sessions: [{ + id: 'late', name: 'late', branch: '', repo: 'r', harness: 'Copilot CLI', model: 'm', parent: -1, via: null, + turns: [{ t: next - 3_600_000, d: 3 * 3_600_000, k: 'you', sub: 0, comp: false, cr: 0, tok: 0 }], + }] }); + expect([p.dayTotals.get(day)?.agentMs, p.dayTotals.get(shiftDate(day, 1))?.agentMs]).toEqual([3_600_000, 2 * 3_600_000]); + // Its week is the same whichever of its days is picked: from that Monday's start to the next Monday's. + const weeks = [-3, -2, -1, 0, 1, 2, 3].map(i => timelineWindow('week', shiftDate(day, i))); + const monday = weekStart(shiftDate(day, -6)); + expect(new Set(weeks.filter(w => w[0] <= dayStart(day) && dayStart(day) < w[1]).map(w => w.join()))).toEqual(new Set([[monday, addDays(monday, 7)].join()])); + })); + } + + for (const [zone, spring, autumn] of [['Europe/Berlin', '2026-03-29', '2026-10-25'], ['America/New_York', '2026-03-08', '2026-11-01']] as const) { + it(`steps whole calendar days over daylight-saving changes in ${zone}`, () => inZone(zone, () => { + for (const [day, hours] of [[spring, 3 * 24 - 1], [autumn, 3 * 24 + 1]] as const) { + const r = { from: shiftDate(day, -1), to: shiftDate(day, 1) }; + const [a, b] = rangeWindow(r); + // Its days, put end to end, are exactly the range. + const days = [r.from, day, r.to].map(d => timelineWindow('day', d)); + expect([rangeDays(r), (b - a) / 3_600_000, days[0][0] === a && days[0][1] === days[1][0] && days[1][1] === days[2][0] && days[2][1] === b]) + .toEqual([3, hours, true]); + } + })); + } +}); + +const ADDITIVE = ['agentMs', 'waitMs', 'waits', 'idleWaits', 'longWaits', 'answered', 'typed', 'turns'] as const; + +function kpisOf(an: Analyzer, [from, to]: [number, number]): TimelineKpis { + const p = prepareTimeline(an.getTimelineData()); + const lanes = buildLanes(p, from, to); + return timelineKpis(lanes, buildViewFamilies(lanes, p)); +} + +/** The range's additive values next to the sum of its days, and the summary export of the same dates. */ +function compare(an: Analyzer, r: DateRange) { + const whole = kpisOf(an, rangeWindow(r)); + const days = Array.from({ length: rangeDays(r) }, (_, i) => kpisOf(an, timelineWindow('day', shiftDate(r.from, i)))); + const sum = Object.fromEntries(ADDITIVE.map(k => [k, days.reduce((n, d) => n + d[k], 0)])); + const out = buildSummaryExportFromAnalyzer(an, { fromDate: r.from, toDate: r.to }).autonomy; + return { + whole: Object.fromEntries(ADDITIVE.map(k => [k, whole[k]])), sum, + exported: [out?.typedTurns, out?.automatedTurns, out?.agentHours, out?.waitsOnYou, out?.questionsAndPermissionsAnswered, out?.waitHours], + expected: [whole.typed, whole.turns - whole.typed, Math.round(whole.agentMs / 360_000) / 10, whole.waits, whole.answered, Math.round(whole.waitMs / 360_000) / 10], + }; +} + +describe('a custom range of days', () => { + it('equals its days put together and the summary export of the same dates', () => { + const t = (day: number, h: number, m = 0) => new Date(2026, 10, day, h, m).getTime(); + const an = analyzer( + session(1, [prompt(t(16, 22)), reply(t(16, 23, 30)), prompt(t(17, 0, 20)), start(t(17, 0, 25)), end(t(17, 0, 40)), reply(t(17, 1))]), + session(2, [prompt(t(17, 23), 1), reply(t(18, 2))]), + session(3, [prompt(t(18, 10)), reply(t(18, 10, 30)), prompt(t(18, 11)), reply(t(18, 11, 5))]), + ); + const c = compare(an, { from: '2026-11-16', to: '2026-11-18' }); + expect(c.whole).toEqual(c.sum); + expect(c.whole.agentMs).toBeGreaterThan(0); + expect(c.exported).toEqual(c.expected); + // A range inside it: the same rules, cut at its own midnights. + const inner = compare(an, { from: '2026-11-17', to: '2026-11-18' }); + expect([inner.whole, inner.exported]).toEqual([inner.sum, inner.expected]); + }); + + for (const [zone, day] of [['Europe/Berlin', 29], ['America/New_York', 8]] as const) { + it(`equals its days put together over the spring change in ${zone}`, () => inZone(zone, () => { + const t = (d: number, h: number, m = 0) => new Date(2026, 2, d, h, m).getTime(); + const an = analyzer( + session(11, [prompt(t(day - 1, 23)), reply(t(day, 4))]), + session(12, [prompt(t(day, 1, 30)), reply(t(day, 3, 30)), prompt(t(day, 4)), reply(t(day, 4, 10))]), + ); + const date = `2026-03-${String(day).padStart(2, '0')}`; + const r = { from: shiftDate(date, -1), to: shiftDate(date, 1) }; + const c = compare(an, r); + expect([c.whole, c.exported]).toEqual([c.sum, c.expected]); + // 23:00 to 04:00 across the skipped hour is 4 h of work, and 1:30 to 3:30 is one. + expect(c.whole.agentMs).toBe((4 + 1 + 1 / 6) * 3_600_000); + })); + } +}); diff --git a/src/core/timeline-range.ts b/src/core/timeline-range.ts new file mode 100644 index 00000000..624efdfa --- /dev/null +++ b/src/core/timeline-range.ts @@ -0,0 +1,118 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See LICENSE in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* Custom date ranges for the Timeline's Range view and its date picker: calendar dates (`YYYY-MM-DD`, local), their + * [start, end) window, the month grid and the axis. Days are stepped on the calendar, never as 24 h, so a range over a + * daylight-saving change has 23 or 25 hours on that day and is still exactly its days put end to end. Browser-safe. */ + +import { toDateStr } from './helpers'; +import { addDays, dayStart, dayTicks, hourTicks, type Interval } from './timeline-model'; + +/** A range of whole local days, both included. */ +export interface DateRange { + from: string; + to: string; +} + +/** Longest range the lanes are drawn for: about a quarter. Longer picks are cut to it, and the page says so. */ +export const MAX_RANGE_DAYS = 92; + +/** A real calendar date written `YYYY-MM-DD` (not `2026-02-30`). */ +export function isDate(value: unknown): value is string { + return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) && toDateStr(dayStart(value)) === value; +} + +/** The date `days` calendar days from `date`. */ +export function shiftDate(date: string, days: number): string { + return toDateStr(addDays(dayStart(date), days)); +} + +/** The number of days in the range, both ends included. */ +export function rangeDays(r: DateRange): number { + // Whole days apart; a daylight-saving change moves the difference by an hour at most, which rounding absorbs. + return Math.round((dayStart(r.to) - dayStart(r.from)) / 86_400_000) + 1; +} + +/** The range's [start, end): from the first day's midnight to the midnight after its last day. */ +export function rangeWindow(r: DateRange): Interval { + return [dayStart(r.from), addDays(dayStart(r.to), 1)]; +} + +/** `a`–`b` in either order, kept within `lo`–`hi` and cut to `MAX_RANGE_DAYS` from its first day; null when none of + * it is within `lo`–`hi`. */ +export function clampRange(a: string, b: string, lo: string, hi: string): { range: DateRange; capped: boolean } | null { + const [first, last] = a <= b ? [a, b] : [b, a]; + const from = first < lo ? lo : first; + const to = last > hi ? hi : last; + if (from > to) return null; + const end = shiftDate(from, MAX_RANGE_DAYS - 1); + return end < to ? { range: { from, to: end }, capped: true } : { range: { from, to }, capped: false }; +} + +/** The range moved by its own length, earlier (-1) or later (1); at the edge of `lo`–`hi` it stops there, keeping its + * length where it fits. Null when it already ends at that edge. */ +export function stepRange(r: DateRange, dir: -1 | 1, lo: string, hi: string): DateRange | null { + if (dir > 0 ? r.to >= hi : r.from <= lo) return null; + const n = rangeDays(r); + let from = shiftDate(r.from, n * dir); + let to = shiftDate(r.to, n * dir); + if (to > hi) [from, to] = [shiftDate(hi, 1 - n), hi]; + if (from < lo) [from, to] = [lo, shiftDate(lo, n - 1)]; + return clampRange(from, to, lo, hi)?.range ?? null; +} + +export type QuickRange = 'last7' | 'last30' | 'month'; + +export const QUICK_RANGES: [QuickRange, string][] = [['last7', 'Last 7 days'], ['last30', 'Last 30 days'], ['month', 'This month']]; + +/** A quick pick ending `today`: the last 7 or 30 days, or this month so far. */ +export function quickRange(kind: QuickRange, today: string): DateRange { + if (kind === 'month') return { from: today.slice(0, 8) + '01', to: today }; + return { from: shiftDate(today, kind === 'last7' ? -6 : -29), to: today }; +} + +/** `YYYY-MM` of a date. */ +export function monthOf(date: string): string { + return date.slice(0, 7); +} + +/** The month `n` months from `month` (`YYYY-MM`). */ +export function shiftMonth(month: string, n: number): string { + const d = new Date(Number(month.slice(0, 4)), Number(month.slice(5, 7)) - 1 + n, 1); + return toDateStr(d.getTime()).slice(0, 7); +} + +/** The 42 days (six Monday-to-Sunday weeks) a month's calendar shows, from the Monday on or before its first day. */ +export function monthCells(month: string): string[] { + const first = new Date(month + '-01T00:00:00'); + const start = shiftDate(month + '-01', -((first.getDay() + 6) % 7)); + return Array.from({ length: 42 }, (_, i) => shiftDate(start, i)); +} + +/** The same calendar day `n` months later, kept within that month (31 Jan + 1 month is 28 or 29 Feb). */ +export function shiftDateByMonths(date: string, n: number): string { + const month = shiftMonth(monthOf(date), n); + const last = shiftDate(shiftMonth(month, 1) + '-01', -1); + const day = `${month}-${date.slice(8)}`; + return isDate(day) && day <= last ? day : last; +} + +/** Axis ticks for a range of two days or more: every 6 hours over up to 3 days (each day's start named by its day), each day + * up to 2 weeks, every other day up to a month, then each Monday. Few enough to draw in every lane. */ +export function rangeTicks(start: number, end: number): [number, string][] { + const days = dayTicks(start, end); + const dayName = (t: number) => new Date(t).toLocaleDateString(undefined, { weekday: 'short', day: 'numeric' }); + const dateName = (t: number) => new Date(t).toLocaleDateString(undefined, { day: 'numeric', month: 'short' }); + if (days.length <= 3) { + // Each day is named at its start: midnight, or 1:00 where the clock springs forward at midnight. + const starts = new Set(days); + const hours = hourTicks(start, end, 6).filter(t => !starts.has(t) && new Date(t).getHours() !== 0); + return [...days.map((t): [number, string] => [t, dayName(t)]), ...hours.map((t): [number, string] => [t, `${new Date(t).getHours()}:00`])] + .sort((a, b) => a[0] - b[0]); + } + if (days.length <= 14) return days.map((t): [number, string] => [t, dayName(t)]); + if (days.length <= 31) return days.filter((_, i) => i % 2 === 0).map((t): [number, string] => [t, dateName(t)]); + return days.filter(t => new Date(t).getDay() === 1).map((t): [number, string] => [t, dateName(t)]); +} diff --git a/src/core/timeline-secrets.test.ts b/src/core/timeline-secrets.test.ts new file mode 100644 index 00000000..9ea80c13 --- /dev/null +++ b/src/core/timeline-secrets.test.ts @@ -0,0 +1,203 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See LICENSE in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* A synthetic secret corpus: fake credentials in the shapes people paste into prompts, commands and config, built at + * run time so no token-shaped literal sits in the repository. No part of any of them may reach what the Timeline shows + * of a lane's text, nor its dataset, the chat tool or the summary export. */ +// cspell:ignore shpat numpy + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; +import { formatTimeline } from '../mcp/formatters'; +import { Analyzer } from './analyzer'; +import { parseCLIEventsFile } from './parser-vscode-cli'; +import { scrubText } from './session-labels'; +import { buildSummaryExportFromAnalyzer } from './summary-export'; +import { timelineSessionText } from './timeline-text'; + +let seed = 20261121; +function rand(alphabet: string, n: number): string { + let out = ''; + for (let i = 0; i < n; i++) { + seed = (seed * 1103515245 + 12345) % 2147483648; + out += alphabet[Math.floor(seed / 65536) % alphabet.length]; + } + return out; +} +const UPPER = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; +const LOWER = 'abcdefghijklmnopqrstuvwxyz'; +const DIGITS = '0123456789'; +const ALNUM = UPPER + LOWER + DIGITS; +/** Letters in both cases and digits, as generated keys are. */ +const mixed = (n: number) => rand(ALNUM, n - 3) + rand(UPPER, 1) + rand(LOWER, 1) + rand(DIGITS, 1); +const b64 = (n: number) => mixed(n - 2) + '+/'; +const urlSafe = (n: number) => mixed(n - 2) + '-_'; +const hex = (n: number) => rand('0123456789abcdef', n); +/** A pass phrase: words that appear nowhere else in the corpus. */ +const phrase = () => `${rand(LOWER, 7)} ${rand(LOWER, 6)} ${rand(LOWER, 8)}${rand(DIGITS, 2)}`; + +interface Case { name: string; text: string; secrets: string[] } + +function corpus(): Case[] { + const c = (name: string, text: (s: string[]) => string, ...secrets: string[]): Case => ({ name, text: text(secrets), secrets }); + const keyBody = () => [b64(64), b64(64), b64(20)].join('\n'); + return [ + c('bearer header', ([t]) => `curl -H "Authorization: Bearer ${t}" https://api.example.com`, mixed(40)), + c('other Authorization scheme', ([t]) => `Authorization: SharedKey demoacct:${t}=`, b64(43)), + c('Authorization in JSON', ([t]) => `{"headers": {"Authorization": "token ${t}"}}`, mixed(30)), + c('JWT', ([t]) => `the id token is ${t}`, `eyJ${urlSafe(20)}.${urlSafe(40)}.${urlSafe(43)}`), + c('GitHub tokens', ([a, b, d, e, f]) => `${a} ${b} ${d} ${e}\nGH=${f}`, 'ghp_' + mixed(36), 'gho_' + mixed(36), 'ghs_' + mixed(36), 'ghu_' + mixed(36), `github_pat_11${rand(UPPER + DIGITS, 20)}_${mixed(59)}`), + c('AWS', ([id, key]) => `aws configure set aws_access_key_id ${id}\naws_secret_access_key = ${key}`, 'AKIA' + rand(UPPER + DIGITS, 16), b64(40)), + c('GCP', ([k, o, p, i]) => `key=${k} and ${o}\n{"private_key_id": "${i}", "private_key": "-----BEGIN PRIVATE KEY-----\\n${p}\\n-----END PRIVATE KEY-----\\n"}`, + 'AIza' + urlSafe(35), 'ya29.' + urlSafe(60), b64(64), hex(40)), + c('Azure storage connection string', ([k]) => `DefaultEndpointsProtocol=https;AccountName=demo;AccountKey=${k}==;EndpointSuffix=core.windows.net`, b64(86)), + c('Azure SAS', ([s]) => `BlobEndpoint=https://demo.blob.core.windows.net/;SharedAccessSignature=sv=2022-11-02&ss=b&sig=${s}`, mixed(43)), + c('SQL connection string', ([p]) => `Server=tcp:db.example.net;Database=app;User ID=app;Password=${p};Encrypt=true`, phrase()), + c('Azure OpenAI key', ([k, s]) => `api-key: ${k}\nThen call it with ${s} as the key.`, hex(32), hex(32)), + c('Azure DevOps PAT', ([p]) => `PAT ${p}`, rand('abcdefghijklmnopqrstuvwxyz234567', 52)), + c('OpenAI and Anthropic keys', ([o, a]) => `OPENAI=${o}\nuse ${a}`, 'sk-proj-' + urlSafe(48), 'sk-ant-api03-' + urlSafe(80)), + c('Slack, npm, GitLab, Hugging Face, Stripe, SendGrid', ([s, n, g, h, st, sg]) => [s, n, g, h, st, sg].join(' '), + `xoxb-${rand(DIGITS, 12)}-${rand(DIGITS, 13)}-${mixed(24)}`, 'npm_' + mixed(36), 'glpat-' + urlSafe(20), 'hf_' + mixed(34), 'sk_live_' + mixed(24), `SG.${urlSafe(22)}.${urlSafe(43)}`), + c('private key blocks', ([a, b, d, e]) => [ + `-----BEGIN RSA PRIVATE KEY-----\n${a}\n-----END RSA PRIVATE KEY-----`, + `-----BEGIN OPENSSH PRIVATE KEY-----\n${b}\n-----END OPENSSH PRIVATE KEY-----`, + `-----BEGIN PGP PRIVATE KEY BLOCK-----\n${d}\n-----END PGP PRIVATE KEY BLOCK-----`, + `paste: -----BEGIN EC PRIVATE KEY-----\n${e}`, + ].join('\n'), keyBody(), keyBody(), keyBody(), keyBody()), + c('.npmrc', ([t, a]) => `//registry.npmjs.org/:_authToken=${t}\n_auth=${a}=`, mixed(24), b64(24)), + c('basic auth in a URL', ([p, q]) => `git clone https://deploy:${p}@git.example.com/repo.git; psql postgres://app:${q}@db:5432/app`, mixed(16), mixed(16)), + c('query-string secrets', ([t, s, k]) => `GET /callback?code=1&token=${t}&sig=${s} then /v1?key=${k}`, mixed(20), b64(30), mixed(24)), + c('env lines', ([a, b, d, e]) => `export GITHUB_TOKEN=${a}\nDB_PASSWORD=${b}\n$env:OPENAI_API_KEY = "${d}"\nset STRIPE_SECRET=${e}`, mixed(20), phrase().replaceAll(' ', '_'), mixed(24), mixed(20)), + c('JSON and YAML fields', ([a, b, d, e, f, g]) => + `{"clientSecret": "${a}", "apiKey":"${b}"}\n{\\"password\\":\\"${d}\\"}\nclient-secret: ${e}\nPassword: ${f}\nrefresh_token: '${g}'`, + phrase(), mixed(24), mixed(18), mixed(20), mixed(14), mixed(30)), + c('doubled-quote JSON in a command', ([a]) => `az rest --body "{""password"":""${a}""}"`, mixed(18)), + c('command-line flags', ([a, b, d, e, f, g, h, i, j]) => [ + `gh auth login --token ${a}`, `login --password "${b}"`, `az ad sp create --client-secret=${d}`, `curl -u ci:${e} x`, + `docker login -u ci -p ${f} registry`, `mysql -u root -p${g} app`, `sshpass -p ${h} ssh host`, `az storage blob upload --account-key ${i}`, + `openssl enc -pass pass:${j}`, + ].join('\n'), mixed(20), phrase(), mixed(20), mixed(12), mixed(14), mixed(12), mixed(12), b64(88), mixed(12)), + c('random-looking strings next to a secret word', ([a, b, d]) => `my password is ${a}\nthe api key ${b}\ntoken for CI: ${d}`, + rand(LOWER, 10) + rand(DIGITS, 6), mixed(32), rand(LOWER + DIGITS, 14) + '7q'), + c('oversized values', ([a, b, d, e, f, g]) => [ + `{"password": "${a}"}`, `login --password "${b}"`, `login --password "${d}`, `DB_PASSWORD=${e}`, `Authorization: Bearer ${f}`, `push ${g}`, + ].join('\n'), rand(LOWER, 2100), rand(LOWER, 2500), rand(LOWER, 3000), rand(LOWER, 2600), mixed(3000), 'ghp_' + mixed(400)), + c('long lower-case values of a key', ([a]) => `?key=${a}`, rand(LOWER, 20)), + ]; +} + +/** Credentials written as people talk and paste them: in prose, cookies, pretty-printed JSON, newer key formats. */ +function moreCorpus(): Case[] { + const c = (name: string, text: (s: string[]) => string, ...secrets: string[]): Case => ({ name, text: text(secrets), secrets }); + return [ + c('short passwords in prose and *_PASS names', ([a, b, d]) => `change the password to ${a}\nSMTP_PASS=${b}\nthe PIN code is ${d}`, + rand(UPPER, 1) + rand(LOWER, 6) + rand(DIGITS, 4) + '!', rand(LOWER, 5) + rand(DIGITS, 3), rand(DIGITS, 6)), + c('cookies and other auth headers', ([a, b]) => `curl -H "Cookie: session=${a}; theme=dark" -H 'Private-Token: ${b}' x`, mixed(24), urlSafe(20)), + c('pretty-printed JSON', ([a]) => `{\n "password":\n "${a}"\n}`, rand(LOWER, 6) + rand(DIGITS, 4)), + c('Azure AD client secret', ([a]) => `client secret ${a}`, rand(ALNUM, 3) + '8Q~' + rand(ALNUM + '_~.-', 34)), + c('hex keys with a prefix, and 64-hex secrets', ([a, b, d, e]) => `${a} ${b} ${d}\nwebhook ${e}`, + 'dapi' + hex(32), 'shpat_' + hex(32), 'SK' + hex(32), hex(64)), + ]; +} + +const CASES = [...corpus(), ...moreCorpus()]; + +/** Every part of a secret that would give it away: each word of a phrase, and every 8-character run of a token. */ +function leaks(out: string, secrets: readonly string[]): string[] { + const found: string[] = []; + for (const secret of secrets) { + for (const part of secret.split(/[\s\n]+/).filter(Boolean)) { + if (part.length < 8) { if (part.length >= 5 && out.includes(part)) found.push(part); continue; } + for (let i = 0; i + 8 <= part.length; i++) if (out.includes(part.slice(i, i + 8))) { found.push(part.slice(i, i + 8)); break; } + } + } + return found; +} + +const labels = { home: '/home/jdoe', names: ['jdoe'], handles: ['octo-dev'] }; + +describe('scrubText against the secret corpus', () => { + it.each(CASES.map(x => [x.name, x] as const))('leaks nothing of %s', (_name, x) => { + expect(leaks(scrubText(x.text, labels), x.secrets)).toEqual([]); + }); + + it('keeps ordinary text readable', () => { + const plain = [ + 'commit 3f2a9c4e1b7d8a6f5e4d3c2b1a0f9e8d7c6b5a49, session 7e470000-0000-4000-8000-000000000001', + 'claude-sonnet-4-5-20250929 used 1200 tokens; set max_tokens=4096', + 'design=wide, mkdir -p out && sort -u names.txt && npm run -s build -- --token-file cfg.json --max-tokens 4096', + 'Primary key: userId. Released 2.4.1 on 2026-05-02 at 15:02.', + 'The token is expired; the password is unchanged. Pull image@sha256:' + 'ab'.repeat(32) + ', set bypass=true and compass: north.', + 'Pin numpy to 1.26.4, then pin to 2.0.1.', + ].join('\n'); + expect(scrubText(plain, labels)).toBe(plain); + }); + + it('stays linear on long runs that look like the start of a secret', () => { + const t = Date.now(); + for (const s of ['a_'.repeat(50_000), '--a-'.repeat(25_000), 'token '.repeat(20_000), `password: "${'x'.repeat(100_000)}`, + `--password "${'x'.repeat(100_000)}`, `Authorization: "${'x '.repeat(50_000)}`, 'password: "a" '.repeat(10_000)]) scrubText(s, labels); + expect(Date.now() - t).toBeLessThan(2000); + }); +}); + +describe('the Timeline surfaces against the secret corpus', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'aec-timeline-secrets-')); + afterAll(() => fs.rmSync(root, { recursive: true, force: true, maxRetries: 3 })); + const ID = '7e470000-0000-4000-8000-00000000000a'; + const at = (m: number) => new Date(2026, 10, 17, 10, m).toISOString(); + + /** One Copilot session that carries the corpus in every field the Timeline can show. */ + function session() { + const text = (i: number) => CASES[i % CASES.length].text; + let m = 0; + const events: Record[] = [{ type: 'session.start', timestamp: at(0), data: { sessionId: ID } }]; + for (let i = 0; i < CASES.length; i++) { + const id = `c${i}`; + events.push( + { type: 'user.message', timestamp: at(m++), id: `u${i}`, data: { content: text(i) } }, + { type: 'assistant.message', timestamp: at(m++), id: `a${i}`, data: { content: text(i + 1) } }, + { type: 'tool.execution_start', timestamp: at(m++), data: { toolName: 'ask_user', toolCallId: `q${id}`, arguments: { question: text(i + 2), choices: [text(i + 3)] } } }, + { type: 'human_response.recorded', timestamp: at(m), data: { toolCallId: `q${id}`, response: { answer: text(i + 4) } } }, + { type: 'tool.execution_complete', timestamp: at(m++), data: { toolCallId: `q${id}`, success: true, result: { content: `User responded: ${text(i + 4)}` } } }, + { type: 'permission.requested', timestamp: at(m++), data: { requestId: `p${id}`, permissionRequest: { kind: text(i + 5), fullCommandText: text(i + 6), intention: text(i + 7) } } }, + { type: 'permission.completed', timestamp: at(m++), data: { requestId: `p${id}`, decisionSource: 'human_response', result: { kind: 'approved' } } }, + { type: 'tool.execution_start', timestamp: at(m++), data: { toolName: 'relay_session_input', toolCallId: `r${id}`, arguments: { context: text(i + 8) } } }, + { type: 'tool.execution_complete', timestamp: at(m++), data: { toolCallId: `r${id}`, success: true, result: { content: JSON.stringify({ question: text(i + 9), answer: text(i + 10) }) } } }, + { type: 'session.task_complete', timestamp: at(m++), data: { success: true, summary: text(i + 11) } }, + ); + } + const dir = path.join(root, ID); + fs.mkdirSync(dir, { recursive: true }); + const file = path.join(dir, 'events.jsonl'); + fs.writeFileSync(file, events.map(x => JSON.stringify(x)).join('\n')); + const s = parseCLIEventsFile(file, 'ws', 'fixture'); + if (!s) throw new Error('fixture did not parse'); + return s; + } + + const all = CASES.flatMap(x => x.secrets); + + it('the text of a lane, as the panel receives it, leaks none', () => { + const s = session(); + const out = timelineSessionText(s, labels); + // The fixture did carry the corpus into every field. + expect(out.turns.length).toBe(CASES.length); + expect(out.waits.filter(w => w.k === 'question' && w.ask && w.answer && w.choices && w.before)).toHaveLength(CASES.length); + expect(out.waits.filter(w => w.k === 'permission' && w.ask && w.intention && w.tool)).toHaveLength(CASES.length); + expect(out.waits.filter(w => w.k === 'relay' && w.ask && w.answer)).toHaveLength(CASES.length); + expect(leaks(JSON.stringify(out), all)).toEqual([]); + }); + + it('the dataset, the chat tool and the summary export carry none of it', () => { + const an = new Analyzer([session()], new Map()); + const day = { fromDate: '2026-11-17', toDate: '2026-11-17' }; + for (const out of [an.getTimelineData(day), formatTimeline(an, day, '2026-11-17'), buildSummaryExportFromAnalyzer(an, day)]) { + expect(leaks(JSON.stringify(out), all)).toEqual([]); + } + }); +}); diff --git a/src/core/timeline-text.test.ts b/src/core/timeline-text.test.ts new file mode 100644 index 00000000..0abd03f4 --- /dev/null +++ b/src/core/timeline-text.test.ts @@ -0,0 +1,244 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See LICENSE in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* The text behind a Timeline lane: built from a session re-read in full, scrubbed and cut, and never carried by the + * Timeline's dataset, the chat tool or the summary export. Synthetic Copilot logs. */ + +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { afterAll, describe, expect, it, vi } from 'vitest'; +import { formatTimeline } from '../mcp/formatters'; +import { Analyzer } from './analyzer'; +import { parseCLIEventsFile } from './parser-vscode-cli'; +import { buildSummaryExportFromAnalyzer } from './summary-export'; +import { MAX_TEXT, timelineSessionText } from './timeline-text'; +import { textTurnFinder } from './timeline-model'; +import { createRequest, createSession } from './parser-shared'; +import type { Session } from './types'; + +const root = fs.mkdtempSync(path.join(os.tmpdir(), 'aec-timeline-text-')); +afterAll(() => fs.rmSync(root, { recursive: true, force: true, maxRetries: 3 })); + +const ID = '7e470000-0000-4000-8000-000000000001'; +const at = (m: number) => new Date(2026, 10, 17, 10, m).toISOString(); +const labels = { home: '/home/jdoe', names: ['jdoe'], handles: ['octo-dev'] }; + +function parse(events: Record[]): Session { + const dir = path.join(root, ID); + fs.mkdirSync(dir, { recursive: true }); + const file = path.join(dir, 'events.jsonl'); + fs.writeFileSync(file, [{ type: 'session.start', timestamp: at(0), data: { sessionId: ID } }, ...events].map(x => JSON.stringify(x)).join('\n')); + const s = parseCLIEventsFile(file, 'ws', 'fixture'); + if (!s) throw new Error('fixture did not parse'); + return s; +} + +const fixture = () => parse([ + { type: 'user.message', timestamp: at(0), data: { content: `Benchmark the cache in /home/jdoe/lab, token ${'ghp_' + 'abcdefghijklmnopqrstuvwxyz0123'}` } }, + { type: 'assistant.message', timestamp: at(1), data: { content: 'Two cache sizes fit.' } }, + { type: 'tool.execution_start', timestamp: at(2), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Which size, jdoe?', choices: ['64 MB', '256 MB'] } } }, + { type: 'tool.execution_complete', timestamp: at(5), data: { toolCallId: 'q1', success: true, result: { content: 'User selected: 256 MB' } } }, + { type: 'permission.requested', timestamp: at(6), data: { requestId: 'p1', permissionRequest: { kind: 'url', url: 'https://example.com/x', intention: 'Read the docs' } } }, + { type: 'permission.completed', timestamp: at(7), data: { requestId: 'p1', decisionSource: 'human_response', result: { kind: 'approved' } } }, + { type: 'assistant.message', timestamp: at(8), data: { content: 'Done: 256 MB is 12% faster.' } }, + { type: 'user.message', timestamp: at(30), data: { content: 'x'.repeat(MAX_TEXT + 50) } }, + { type: 'assistant.message', timestamp: at(31), data: { content: 'ok' } }, +]); + +describe('timelineSessionText', () => { + it('lists each turn’s prompt and reply and each stop’s question and answer, scrubbed, in time order', () => { + const text = timelineSessionText(fixture(), labels); + expect(text.turns[0]).toMatchObject({ + k: 'you', prompt: 'Benchmark the cache in ~/lab, token [secret]', reply: 'Two cache sizes fit.\n\nDone: 256 MB is 12% faster.', + }); + expect(text.waits.map(w => [w.k, w.a, w.ask, w.choices, w.answer, w.before, w.tool, w.intention])).toEqual([ + ['question', true, 'Which size, [name]?', ['64 MB', '256 MB'], '256 MB', 'Two cache sizes fit.', undefined, undefined], + ['permission', true, '[link]', undefined, 'approved', undefined, 'url', 'Read the docs'], + ]); + // Long text is cut, and says so. + expect([text.turns[1].prompt?.length, text.turns[1].cut]).toEqual([MAX_TEXT + 2, true]); + }); + + it('times an answer to Copilot’s record of it, apart from the result, and carries no request ID', () => { + const text = timelineSessionText(parse([ + { type: 'user.message', timestamp: at(0), data: { content: 'Go' } }, + { type: 'tool.execution_start', timestamp: at(2), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Ship it?' } } }, + { type: 'human_response.recorded', timestamp: at(4), data: { toolCallId: 'q1', requestId: 'req-1', response: { answer: 'yes' } } }, + { type: 'tool.execution_complete', timestamp: at(9), data: { toolCallId: 'q1', success: true, result: { content: 'User responded: yes' } } }, + { type: 'assistant.message', timestamp: at(10), data: { content: 'Shipped.' } }, + ]), labels); + expect(text.waits.map(w => [w.s, w.e, w.at, w.answer, 'rid' in w])).toEqual([[Date.parse(at(2)), Date.parse(at(9)), Date.parse(at(4)), 'yes', false]]); + }); + + it('scrubs and cuts the kind of a permission request, as the log can hold any text there', () => { + const text = timelineSessionText(parse([ + { type: 'user.message', timestamp: at(0), data: { content: 'Go' } }, + { type: 'permission.requested', timestamp: at(1), data: { requestId: 'p1', permissionRequest: { kind: `custom jdoe ${'x'.repeat(100)}`, path: 'a.ts' } } }, + { type: 'permission.completed', timestamp: at(2), data: { requestId: 'p1', decisionSource: 'human_response', result: { kind: 'approved' } } }, + { type: 'assistant.message', timestamp: at(3), data: { content: 'ok' } }, + ]), labels); + expect(text.waits[0].tool).toMatch(/^custom \[name\] x+ …$/); + expect(text.waits[0].tool!.length).toBeLessThanOrEqual(42); + }); + +}); + +describe('timelineSessionText replies and turns', () => { + it('shows the agent’s own messages as its reply, never the code it wrote to a file', () => { + const text = timelineSessionText(parse([ + { type: 'user.message', timestamp: at(0), data: { content: 'Add the config' } }, + { type: 'assistant.message', timestamp: at(1), data: { content: 'Writing the config.' } }, + { type: 'tool.execution_start', timestamp: at(2), data: { toolName: 'create', toolCallId: 'c1', arguments: { path: 'cfg.json', file_text: '{ "port": 1 }' } } }, + { type: 'tool.execution_complete', timestamp: at(3), data: { toolCallId: 'c1', success: true, result: { content: 'Created' } } }, + { type: 'tool.execution_start', timestamp: at(4), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'Keep it?' } } }, + { type: 'tool.execution_complete', timestamp: at(5), data: { toolCallId: 'q1', success: true, result: { content: 'User selected: yes' } } }, + ]), labels); + expect([text.turns[0].reply, text.waits[0].before]).toEqual(['Writing the config.', 'Writing the config.']); + }); +}); + +describe('timelineSessionText replies of live and file-writing turns', () => { + it('shows no reply for a turn that only wrote files, never the file’s contents', () => { + const s = parse([ + { type: 'user.message', timestamp: at(0), data: { content: 'Add the config' } }, + { type: 'tool.execution_start', timestamp: at(2), data: { toolName: 'create', toolCallId: 'c1', arguments: { path: 'cfg.json', file_text: '{ "port": 1 }' } } }, + { type: 'tool.execution_complete', timestamp: at(3), data: { toolCallId: 'c1', success: true, result: { content: 'Created' } } }, + ]); + expect([s.requests[0].responseText.includes('"port"'), s.requests[0].replyText, timelineSessionText(s, labels).turns[0].reply]).toEqual([true, '', undefined]); + }); + + it('keeps a turn’s final task summary in its reply, after its progress messages, once', () => { + const text = timelineSessionText(parse([ + { type: 'user.message', timestamp: at(0), data: { content: 'Fix it' } }, + { type: 'assistant.message', timestamp: at(1), data: { content: 'Looking at the failing test.' } }, + { type: 'session.task_complete', timestamp: at(2), data: { success: true, summary: 'Fixed the off-by-one in the parser.' } }, + { type: 'session.task_complete', timestamp: at(3), data: { success: true, summary: 'Fixed the off-by-one in the parser.' } }, + ]), labels); + expect(text.turns[0].reply).toBe('Looking at the failing test.\n\nFixed the off-by-one in the parser.'); + }); + + it('joins a live turn’s text to the analyzed turn after the turn gained another message', () => { + const start = [ + { type: 'user.message', timestamp: at(0), id: 'u1', data: { content: 'First' } }, + { type: 'assistant.message', timestamp: at(1), id: 'a1', data: { content: 'One' } }, + ]; + const analyzed = new Analyzer([parse(start)], new Map()).getTimelineData().sessions[0].turns; + const text = timelineSessionText(parse([...start, { type: 'assistant.message', timestamp: at(2), id: 'a2', data: { content: 'And more' } }]), labels); + expect(analyzed.map(t => text.turns.find(x => x.id === t.id)?.prompt)).toEqual(['First']); + }); + + it('finds a live turn’s text when its prompt logged no ID and the turn gained another message', () => { + const start = [ + { type: 'user.message', timestamp: at(0), data: { content: 'First' } }, + { type: 'assistant.message', timestamp: at(1), id: 'a1', data: { content: 'One' } }, + { type: 'user.message', timestamp: at(5), data: { content: 'Second' } }, + { type: 'assistant.message', timestamp: at(6), id: 'b1', data: { content: 'Two' } }, + ]; + const analyzed = new Analyzer([parse(start)], new Map()).getTimelineData().sessions[0].turns; + const text = timelineSessionText(parse([...start, { type: 'assistant.message', timestamp: at(7), id: 'b2', data: { content: 'And more' } }]), labels); + const find = textTurnFinder(text.turns); + expect(analyzed.map(t => find(t)?.prompt)).toEqual(['First', 'Second']); + // Two turns at one time are told apart by identity alone. + const same = text.turns.map(t => ({ ...t, t: 0 })); + expect(['a1', 'b2', 'b1'].map(id => textTurnFinder(same)({ t: 0, id })?.prompt)).toEqual(['First', 'Second', undefined]); + }); +}); + +describe('timelineSessionText turns', () => { + it('joins each turn’s text by its request, not its time, so two turns at the same moment keep their own', () => { + const s = parse([ + { type: 'user.message', timestamp: at(0), data: { content: 'First' } }, + { type: 'assistant.message', timestamp: at(1), id: 'a1', data: { content: 'One' } }, + { type: 'user.message', timestamp: at(2), data: { content: 'Second' } }, + { type: 'assistant.message', timestamp: at(3), id: 'a2', data: { content: 'Two' } }, + ]); + s.requests[1].timestamp = s.requests[0].timestamp; + const text = timelineSessionText(s, labels); + const turns = new Analyzer([s], new Map()).getTimelineData().sessions[0].turns; + expect(turns.map(t => [t.t, text.turns.find(x => x.id === t.id)?.prompt])).toEqual([[turns[0].t, 'First'], [turns[0].t, 'Second']]); + }); + +}); + +describe('timelineSessionText scope and secrets asked for', () => { + it('builds only what a lane’s scope lists, and only the turns the analysis kept', () => { + const s = parse([ + { type: 'user.message', timestamp: at(0), id: 'u1', data: { content: 'Before the window' } }, + { type: 'assistant.message', timestamp: at(1), data: { content: 'Its reply' } }, + { type: 'user.message', timestamp: at(20), id: 'u2', data: { content: 'In the window' } }, + { type: 'tool.execution_start', timestamp: at(21), data: { toolName: 'ask_user', toolCallId: 'q2', arguments: { question: 'In-window question?' } } }, + { type: 'tool.execution_complete', timestamp: at(22), data: { toolCallId: 'q2', success: true, result: { content: 'User selected: yes' } } }, + { type: 'user.message', timestamp: at(30), id: 'u3', data: { content: 'Not listed' } }, + ]); + const window = { from: Date.parse(at(15)), to: Date.parse(at(40)) }; + // The lane lists its turn in the window, and the turn before its wait for your next prompt (outside the window). + const scoped = timelineSessionText(s, labels, { ...window, turns: [{ t: Date.parse(at(20)), id: 'u2' }, { t: Date.parse(at(0)), id: 'u1' }] }); + expect(scoped.turns.map(t => t.prompt)).toEqual(['Before the window', 'In the window']); + expect(scoped.waits.map(w => w.ask)).toEqual(['In-window question?']); + // A turn the analysis dropped (a fork's copy) is never read, nor its stops, even when listed. + const kept = timelineSessionText(s, labels, { ...window, turns: [{ t: Date.parse(at(20)), id: 'u2' }] }, new Set(['u1', 'u3'])); + expect([kept.turns, kept.waits]).toEqual([[], []]); + }); + + it('hides your answer to a question that asks for a secret, and a lone word you send after the agent asks for one', () => { + const answer = 'Plum' + '2024!'; + const s = parse([ + { type: 'user.message', timestamp: at(0), id: 'u1', data: { content: 'Connect the app' } }, + { type: 'assistant.message', timestamp: at(1), data: { content: 'I need the database password.' } }, + { type: 'tool.execution_start', timestamp: at(2), data: { toolName: 'ask_user', toolCallId: 'q1', arguments: { question: 'What is the database password?' } } }, + { type: 'tool.execution_complete', timestamp: at(3), data: { toolCallId: 'q1', success: true, result: { content: `User responded: ${answer}` } } }, + { type: 'assistant.message', timestamp: at(4), data: { content: 'It failed. Please paste the new API key.' } }, + { type: 'user.message', timestamp: at(10), id: 'u2', data: { content: 'Mango' + '7731' } }, + { type: 'assistant.message', timestamp: at(11), data: { content: 'Connected.' } }, + { type: 'user.message', timestamp: at(20), id: 'u3', data: { content: 'Thanks, go on' } }, + ]); + const text = timelineSessionText(s, labels); + expect(text.waits.map(w => [w.ask, w.answer])).toEqual([['What is the database password?', '[secret]']]); + expect(text.turns.map(t => t.prompt)).toEqual(['Connect the app', '[secret]', 'Thanks, go on']); + }); +}); + +describe('timelineSessionText kinds and boundaries', () => { + it('shows no text for compaction or system turns', () => { + const s = fixture(); + s.requests[0].nonHumanKind = 'compaction'; + // Nor the reply to a compaction, which is the summary itself (OpenCode logs it as the agent's message). + expect([timelineSessionText(s, labels).turns[0].prompt, timelineSessionText(s, labels).turns[0].reply]).toEqual([undefined, undefined]); + }); + + it('never reaches the Timeline dataset, the chat tool or the summary export', () => { + // An unstripped session, as a parse returns it, to make sure none of these copy the text. + const an = new Analyzer([fixture()], new Map()); + const day = { fromDate: '2026-11-17', toDate: '2026-11-17' }; + for (const out of [an.getTimelineData(day), formatTimeline(an, day, '2026-11-17'), buildSummaryExportFromAnalyzer(an, day)]) { + const json = JSON.stringify(out); + for (const secret of ['Which size', '256 MB', 'Read the docs', 'Two cache sizes', 'Benchmark the cache']) expect(json).not.toContain(secret); + } + }); +}); + +describe('timelineSessionText at the scope limit', () => { + it('finds each turn’s predecessor without searching, still hiding a word sent after a request for a key', () => { + const t0 = new Date(2026, 10, 17, 10).getTime(); + const n = 20_000; + const requests = Array.from({ length: n }, (_, i) => createRequest({ + requestId: `r${i}`, timestamp: t0 + i * 1_000, messageText: i === n - 1 ? 'hunter2' : 'continue', + responseText: i === n - 2 ? 'Please paste the new API key.' : 'Done', + })); + const session = createSession({ sessionId: 'long', workspaceId: 'ws', workspaceName: 'Project', harness: 'GitHub Copilot CLI', requests }); + const scope = { from: t0, to: t0 + n * 1_000, turns: requests.map(r => ({ t: r.timestamp! })) }; + // A search per one-word prompt is quadratic: at the 50,000-turn scope limit, 1.25 billion comparisons. + const searches = vi.spyOn(Array.prototype, 'indexOf'); + try { + const text = timelineSessionText(session, labels, scope); + expect(searches.mock.calls.length).toBeLessThan(n / 10); + expect(text.turns).toHaveLength(n); + expect(text.turns.map(t => t.prompt).slice(-3)).toEqual(['continue', 'continue', '[secret]']); + } finally { + searches.mockRestore(); + } + }); +}); diff --git a/src/core/timeline-text.ts b/src/core/timeline-text.ts new file mode 100644 index 00000000..32fb049e --- /dev/null +++ b/src/core/timeline-text.ts @@ -0,0 +1,115 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See LICENSE in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* The text behind one session's Timeline lane: the message that started each turn, the end of the agent's reply, and what + * each question, relayed question and permission prompt asked and what you answered. Built from a session re-read in + * full when its lane is opened (the analyzers hold no such text), scrubbed, and sent only to the local Timeline panel: + * never to the chat tool, the summary export or anywhere else. */ + +import type { Session, SessionRequest, TimelineSessionText, TimelineTextScope, TimelineTextTurn, TimelineTextWait, UserWait, UserWaitText } from './types'; +import { turnSender } from './analyzer-timeline'; +import { turnIdentity } from './fork-ownership'; +import { scrubText, type ScrubContext } from './session-labels'; +import { asksForSecret } from './secret-scrub'; +import { textTurnFinder, waitInWindow } from './timeline-model'; + +/** Longest prompt, question or answer shown; the rest is cut. */ +export const MAX_TEXT = 4000; +/** How much of the end of the agent's reply is shown. */ +const MAX_REPLY = 1500; + +function cutHead(value: string, max: number): [string, boolean] { + return value.length > max ? [value.slice(0, max).trimEnd() + ' …', true] : [value, false]; +} + +/** The end of a reply, from a paragraph start when there is one near the cut. */ +function cutTail(value: string, max: number): [string, boolean] { + if (value.length <= max) return [value, false]; + const tail = value.slice(-max); + const para = tail.indexOf('\n\n'); + return ['… ' + (para >= 0 && para < max / 3 ? tail.slice(para + 2) : tail).trimStart(), true]; +} + +function waitText(w: UserWait, labels: ScrubContext): TimelineTextWait { + const out: TimelineTextWait = { + s: w.start, e: w.end, k: w.kind, a: w.answered, ...(w.answered && w.answeredAt !== undefined && w.answeredAt !== w.end ? { at: w.answeredAt } : {}), + }; + const text: UserWaitText = w.text ?? {}; + // Your answer to a question that asks for a credential is one, whatever it looks like. + const secretAnswer = w.kind !== 'permission' && !!text.ask && asksForSecret(text.ask); + let cut = false; + for (const key of ['ask', 'answer', 'intention'] as const) { + const value = text[key]?.trim(); + if (!value) continue; + const [v, c] = key === 'answer' && secretAnswer ? ['[secret]', false] : cutHead(scrubText(value, labels), MAX_TEXT); + out[key] = v; + cut ||= c; + } + if (text.before?.trim()) { + const [v, c] = cutTail(scrubText(text.before.trim(), labels), MAX_REPLY); + out.before = v; + cut ||= c; + } + if (text.tool) out.tool = cutHead(scrubText(text.tool, labels), 40)[0]; + if (text.choices?.length) out.choices = text.choices.slice(0, 20).map(c => cutHead(scrubText(c, labels), 300)[0]); + if (cut) out.cut = true; + return out; +} + +/** The text of `session`'s turns and stops, scrubbed with `labels`. `session` is the full session, re-read from its + * log. With `scope`, only what that lane shows is built: the turns it lists (matched by identity, else by a time no + * other turn has) and the stops that belong to its window; nothing else is scrubbed or returned. With `kept`, only + * the turns the analysis kept are read (a fork's copied turns, and their stops, count in their source). Compaction + * and system turns carry no prompt text (a summary or a harness message, not an instruction). */ +export function timelineSessionText(session: Session, labels: ScrubContext, scope?: TimelineTextScope, kept?: ReadonlySet): TimelineSessionText { + const requests = kept ? session.requests.filter(r => kept.has(turnIdentity(r))) : session.requests; + const timed = requests.filter((r): r is SessionRequest & { timestamp: number } => !!r.timestamp) + .map(r => ({ r, t: r.timestamp, ...(turnIdentity(r) ? { id: turnIdentity(r) } : {}) })); + let shown = timed; + if (scope) { + const find = textTurnFinder(timed); + const wanted = new Set(scope.turns.map(find)); + shown = timed.filter(x => wanted.has(x)); + } + const allWaits = [...requests.flatMap(r => r.userWaits ?? []), ...session.userWaits ?? []]; + const waits = scope + ? allWaits.filter(w => waitInWindow({ s: w.start, e: w.end, k: w.kind, a: w.answered, ...(w.answeredAt != null ? { at: w.answeredAt } : {}) }, scope.from, scope.to)) + : allWaits; + // Each turn's predecessor among the turns read, found once: a search per turn is quadratic on a long range's lane. + const before = new Map(requests.map((r, i) => [r, requests[i - 1]])); + return { + sessionId: session.sessionId, + turns: shown.map(x => textTurn(x.r, x.t, labels, answersSecretRequest(x.r, before.get(x.r)))).sort((a, b) => a.t - b.t), + waits: waits.map(w => waitText(w, labels)).sort((a, b) => a.s - b.s), + }; +} + +/** A lone word you sent right after the agent asked for a credential (`Please paste the API key.`): taken for one. + * `before` is the turn read just before `r`. */ +function answersSecretRequest(r: SessionRequest, before: SessionRequest | undefined): boolean { + const prompt = r.messageText.trim(); + if (r.nonHumanKind || !prompt || prompt.length > 200 || /\s/.test(prompt)) return false; + return !!before && asksForSecret((before.replyText ?? before.responseText).slice(-400)); +} + +function textTurn(r: SessionRequest, t: number, labels: ScrubContext, secretPrompt = false): TimelineTextTurn { + const k = turnSender(r.nonHumanKind); + const turn: TimelineTextTurn = { t, k, ...(turnIdentity(r) ? { id: turnIdentity(r) } : {}) }; + let cut = false; + if (k !== 'compaction' && k !== 'other' && r.messageText.trim()) { + const [v, c] = secretPrompt ? ['[secret]', false] : cutHead(scrubText(r.messageText.trim(), labels), MAX_TEXT); + turn.prompt = v; + cut ||= c; + } + // The agent's own messages: the code it wrote to files is no reply. A compaction's reply is its summary. + const reply = k === 'compaction' ? '' : (r.replyText ?? r.responseText).trim(); + if (reply) { + const [v, c] = cutTail(scrubText(reply, labels), MAX_REPLY); + turn.reply = v; + cut ||= c; + } + if (cut) turn.cut = true; + return turn; +} diff --git a/src/core/types/rpc-types.ts b/src/core/types/rpc-types.ts index 56de6885..33abe797 100644 --- a/src/core/types/rpc-types.ts +++ b/src/core/types/rpc-types.ts @@ -53,7 +53,7 @@ import type { ContextManagementData, FlowStateData, SessionRangeMatch, Workspace import type { PromptCacheData, PromptCacheSessionsData } from './prompt-cache-types'; import type { SessionTimelineData } from './session-timeline-types'; import type { TokenTypesData } from './token-usage-types'; -import type { TimelineDataset } from './timeline-types'; +import type { TimelineDataset, TimelineSessionText, TimelineTextScope, TimelineTextSuperseded } from './timeline-types'; import type { GitHubAppIssueCreditsSnapshot, GitHubAppSnapshot } from './github-app-types'; import type { DateFilter, Session } from './session-types'; import type { CuriosityData, CuriosityFilter } from './curiosity-types'; @@ -74,6 +74,7 @@ export interface RpcMethodMap { getAiCreditBurndown: { params: { config: BurndownConfig; filter?: DateFilter }; result: AiCreditBurndownData }; getTokenCoverage: { params: DateFilter | undefined; result: TokenCoverageData }; getTimelineData: { params: { filter?: DateFilter } | undefined; result: TimelineDataset }; + getTimelineSessionText: { params: { sessionId: string; scope: TimelineTextScope }; result: TimelineSessionText | TimelineTextSuperseded | null }; getSessions: { params: { page: number; pageSize: number; filter?: DateFilter; search?: string }; result: SessionList }; getSessionDetail: { params: { sessionId: string }; result: Session | null }; getWorkLifeBalance: { params: DateFilter | undefined; result: WorkLifeBalanceResult | null }; diff --git a/src/core/types/session-types.ts b/src/core/types/session-types.ts index e8f45f8d..25a5264a 100644 --- a/src/core/types/session-types.ts +++ b/src/core/types/session-types.ts @@ -163,6 +163,10 @@ export interface SessionRequest { timestamp: number | null; messageText: string; responseText: string; + /** The agent's own messages in the turn, without the code it wrote to files (which `responseText` also holds for code + * analysis). Kept only when one session is re-read for its detail view; stripped like `responseText`. Empty when the + * agent wrote no message of its own; absent for harnesses that don't tell them apart. */ + replyText?: string; isCanceled: boolean; agentName: string; agentMode: string; @@ -293,6 +297,25 @@ export interface UserWait { /** The request it answered, as logged: a relay's `request_id`, or the `requestId` the record of your answer to a * question carried. The same request in two sessions is the same answer. */ requestId?: string; + /** What was asked and answered, as logged. Kept only when one session is re-read for its detail view; the sessions + * the analyzers hold have it stripped (`stripSingleSession`). */ + text?: UserWaitText; +} + +/** The text behind a question, relayed question or permission prompt. */ +export interface UserWaitText { + /** Questions and relays: the question. Permission prompts: what was requested (a command, a path, a URL…). */ + ask?: string; + /** The choices a question offered. */ + choices?: string[]; + /** Your answer (questions, relays) or the decision logged for a permission prompt (`approved`, `denied…`). */ + answer?: string; + /** Permission prompts: the kind of request the harness logged (`shell`, `write`, `read`, `url`, `mcp`…). */ + tool?: string; + /** Permission prompts: why the agent asked, in its words. */ + intention?: string; + /** The agent's last message before it stopped, when one was logged in the same turn. */ + before?: string; } /** Session-level disposition. Used to distinguish "missing token data diff --git a/src/core/types/timeline-types.ts b/src/core/types/timeline-types.ts index bc151f42..c5e7cb09 100644 --- a/src/core/types/timeline-types.ts +++ b/src/core/types/timeline-types.ts @@ -27,6 +27,8 @@ export interface TimelineTurn { cr: number; /** Tokens logged for the turn: Copilot usage records, else the turn's prompt and completion tokens. */ tok: number; + /** The request's ID, to join the text read on demand to the turn (two turns can share a time). No text itself. */ + id?: string; /** The harness logged no duration for the turn, so when its work ended is unknown (`d` is 0). */ noDuration?: boolean; /** When the turn was stopped on a question or a permission prompt (absolute ms, in order; they can overlap, and one @@ -102,3 +104,49 @@ export interface TimelineDataset { from?: number; to?: number; } + +/** What one lane's detail panel shows, so the text read returns that and no more: its window [`from`, `to`) and the + * turns it lists (by identity, else time), with the turn before each wait for your next prompt. */ +export interface TimelineTextScope { + from: number; + to: number; + turns: { t: number; id?: string }[]; +} + +/** A lane-text read dropped unread because a newer one was asked for before it ran (only one lane's details show). */ +export interface TimelineTextSuperseded { + superseded: true; +} + +/** The text behind one session's turns and stops, for the Timeline detail panel: loaded when a lane is opened, never + * part of the dataset, the chat tool or the export. Scrubbed of links, email addresses, the home directory, the user's + * names and credentials; long text is cut, with `cut` set. Read for one lane's scope: nothing it doesn't show. */ +export interface TimelineSessionText { + sessionId: string; + /** Turns by start time (`t`, as in `TimelineTurn`): the prompt that started each one, and the end of the agent's reply. */ + turns: TimelineTextTurn[]; + /** Questions, relayed questions and permission prompts by start time (`s`, as in `TimelineTurnWait`). */ + waits: TimelineTextWait[]; +} + +export interface TimelineTextTurn { + t: number; + k: TurnSender; + /** The request's ID: joins the text to its turn (`TimelineTurn.id`); turns can share a time. */ + id?: string; + /** The message that started the turn. Left out for compaction and system turns. */ + prompt?: string; + /** The end of the agent's reply in the turn. */ + reply?: string; + cut?: boolean; +} + +export interface TimelineTextWait extends TimelineTurnWait { + ask?: string; + choices?: string[]; + answer?: string; + tool?: string; + intention?: string; + before?: string; + cut?: boolean; +} diff --git a/src/webview/app.ts b/src/webview/app.ts index 9e2b173f..fb7e90b7 100644 --- a/src/webview/app.ts +++ b/src/webview/app.ts @@ -58,7 +58,16 @@ if (!FF_TOKEN_REPORTING_ENABLED) { } /* ---- Global state ---- */ -let currentPage = new URLSearchParams(window.location.search).get('page') === 'curiosity' ? 'curiosity' : 'dashboard'; +/** A Timeline link in the address (`#view=range&from=…&to=…`, or a day, week or the families). */ +const TIMELINE_LINK = /^#view=(day|week|range|families)(&|$)/; + +/** The page the dashboard opens on: the one its address names, else the Dashboard. */ +function startPage(): string { + if (new URLSearchParams(window.location.search).get('page') === 'curiosity') return 'curiosity'; + return TIMELINE_LINK.test(window.location.hash) ? 'timeline' : 'dashboard'; +} + +let currentPage = startPage(); const currentFilter: DateFilter = {}; let _dataIsReady = false; let matchedWorkspaceId: string | undefined; @@ -436,6 +445,14 @@ export function navigateTo(page: string): void { page = normalizePageForFeatureFlags(page); if (!llmAvailable() && (page === 'skills' || page === 'level-up')) page = 'dashboard'; currentPage = page; + // A Timeline link names the Timeline's view; on another page it would open the Timeline again on reload. + if (page !== 'timeline' && TIMELINE_LINK.test(window.location.hash)) { + try { + history.replaceState(history.state, '', window.location.pathname + window.location.search); + } catch { + // A host that doesn't allow it keeps the address as it is. + } + } document.body.classList.toggle('github-app-view', isGitHubAppPage(page)); for (const a of $$('.nav-links a')) a.classList.toggle('active', a.dataset.page === page); void renderPage(page); diff --git a/src/webview/page-timeline.ts b/src/webview/page-timeline.ts index 1b48a342..a9a08ebc 100644 --- a/src/webview/page-timeline.ts +++ b/src/webview/page-timeline.ts @@ -7,20 +7,26 @@ * and which sessions started which; and a Families view that judges each delegation as a whole. The analyzer sends * the range once (`getTimelineData`); every view, filter and the name mask are computed here with the shared model. */ -import type { DateFilter, TimelineDataset, TimelineTurn, TurnSender } from '../core/types'; +import type { + DateFilter, TimelineDataset, TimelineSessionText, TimelineTextSuperseded, TimelineTextTurn, TimelineTextWait, TimelineTurn, TurnSender, +} from '../core/types'; import { - addDays, buildFamilies, buildLanes, buildViewFamilies, createNamer, dayStart, dayTicks, familiesInsights, filterLanes, - formatCount, formatCredits, formatDuration, formatHours, formatWhen, hasLaneFilters, hourTicks, neededYou, NO_LANE_FILTERS, - clipIntervals, clippedMs, intervalsMs, prepareTimeline, roleOf, stepDate, timelineKpis, timelineWindow, turnTimes, verdictText, VERDICTS, + addDays, buildFamilies, buildLanes, buildViewFamilies, createNamer, waitInWindow, dayStart, dayTicks, familiesInsights, filteredDayTotals, filterLanes, + formatCount, formatCredits, formatDuration, formatHours, formatWhen, hasLaneFilters, hourTicks, MAX_TEXT_SCOPE_TURNS, neededYou, NO_LANE_FILTERS, + clipIntervals, clippedMs, intervalsMs, prepareTimeline, roleOf, stepDate, textScope, textTurnFinder, timelineKpis, timelineWindow, turnTimes, verdictText, VERDICTS, viewInsights, weekStart, WIDE_FAN_OUT, type Interval, - type FamiliesOverview, type FamilySummary, type LaneFilters, type Namer, type PreparedSession, type PreparedTimeline, - type TimelineLane, type TimelineView, type TimelineWait, type ViewFamily, + type DayTotals, type FamiliesOverview, type FamilySummary, type LaneFilters, type Namer, type PreparedSession, type PreparedTimeline, + type TimelineLane, type TimelinePeriod, type TimelineView, type TimelineWait, type ViewFamily, } from '../core/timeline-model'; +import { + clampRange, isDate, MAX_RANGE_DAYS, rangeDays, rangeTicks, rangeWindow, shiftDate, stepRange, type DateRange, +} from '../core/timeline-range'; import { FF_TOKEN_REPORTING_ENABLED } from '../core/constants'; import { toDateStr } from '../core/helpers'; -import { rpc } from './shared'; +import { rpc, vscode } from './shared'; import { html, render, type VNode } from './render'; import { consumeNavHint } from './nav-hint'; +import { closePicker, datePicker, pickerOpen, type PickerActions, type PickerInput } from './timeline-date-picker'; type Group = 'tree' | 'flat'; type Color = 'family' | 'harness'; @@ -31,6 +37,10 @@ type FamilySort = 'credits' | 'children' | 'agentMs' | 'childTyped' | 'perChild' interface TimelineState { view: TimelineView; date: string; + /** The days the Range view shows, both included: kept by dates, so it survives a reload of another date range. */ + range: DateRange | null; + /** The range picked was longer than the longest drawn, and was cut. */ + rangeCapped: boolean; group: Group; color: Color; strip: StripMode; @@ -49,12 +59,18 @@ interface TimelineState { familySort: FamilySort; familyMin: number; verdict: VerdictFilter; + /** Show prompts and questions in the detail panel (kept in the webview state; null until read). */ + showText: boolean | null; + /** The prompt, question or wait highlighted in the detail panel (`t: