Skip to content
cccskills

Test log of control-ui-e2e

For each task: the request, the rubric and the score for each item, time and tokens for every run, Claude Code’s full logs, and the files it produced. The raw data is here too, so the score can be recomputed if the weighting changes.

Run on Nov 29, 2026 (runs: claude-sonnet-5-5 / judge: claude-opus-5-5). Figures are medians. The tasks were written by AI from SKILL.md, so they may lean toward situations where the skill helps.

Raw data (JSON)Tasks, per-run measurements, judgments and the summary as stored.

Measurements per run

RunResultTimeTokensCostTurnsSkill usedLog
Task 1 Run 2 With skill (not named)Done19s76,416$0.0665NoFull log
Task 3 Run 1 Without skillDone36s176,405$0.10710-Full log
Task 4 Run 4 Without skillDone9s68,924$0.0417-Full log
Task 3 Run 1 With skillDone32s130,098$0.1148YesFull log
Task 1 Run 2 With skillDone19s101,208$0.0788YesFull log
Task 2 Run 5 With skillDone29s158,370$0.1198YesFull log
Task 1 Run 3 Without skillDone22s96,402$0.0506-Full log
Task 1 Run 4 With skillDone20s101,358$0.0798YesFull log
Task 3 Run 3 With skillDone31s146,204$0.0958YesFull log
Task 2 Run 2 With skillDone32s164,747$0.1098YesFull log
Task 4 Run 3 Without skillDone8s50,735$0.0214-Full log
Task 2 Run 3 Without skillDone27s106,129$0.0865-Full log
Task 1 Run 5 Without skillDone19s95,663$0.0476-Full log
Task 3 Run 2 Without skillDone33s123,470$0.0956-Full log
Task 1 Run 2 Without skillDone20s56,233$0.0414-Full log
Task 2 Run 1 Without skillDone28s126,801$0.0906-Full log
Task 1 Run 1 With skill (not named)Done18s56,259$0.0404NoFull log
Task 4 Run 1 Without skillDone9s69,188$0.0277-Full log
Task 3 Run 1 With skill (not named)Done33s159,272$0.12212YesFull log
Task 4 Run 2 With skillDone10s72,629$0.0456YesFull log
Task 4 Run 2 Without skillDone7s51,105$0.0196-Full log
Task 2 Run 4 Without skillDone30s133,241$0.0966-Full log
Task 4 Run 5 With skillDone11s73,909$0.0258YesFull log
Task 2 Run 5 Without skillDone40s136,391$0.1076-Full log
Task 3 Run 2 With skill (not named)Done31s132,295$0.10011YesFull log
Task 2 Run 3 With skillDone26s129,733$0.0887YesFull log
Task 1 Run 4 Without skillDone22s96,800$0.0526-Full log
Task 3 Run 4 Without skillDone30s120,903$0.0736-Full log
Task 2 Run 4 With skillDone34s175,848$0.1219YesFull log
Task 1 Run 5 With skillDone20s101,521$0.0518YesFull log
Task 1 Run 1 With skillDone18s100,805$0.0468YesFull log
Task 4 Run 1 With skillDone12s92,566$0.0279YesFull log
Task 2 Run 1 With skill (not named)Done30s159,774$0.1149YesFull log
Task 4 Run 5 Without skillDone8s51,194$0.0196-Full log
Task 2 Run 2 With skill (not named)Done33s141,042$0.1108YesFull log
Task 3 Run 5 With skillDone31s121,621$0.0867YesFull log
Task 3 Run 5 Without skillDone33s123,988$0.0918-Full log
Task 3 Run 4 With skillDone33s147,720$0.0948YesFull log
Task 2 Run 2 Without skillDone30s127,492$0.0826-Full log
Task 1 Run 3 With skillDone19s101,433$0.0478YesFull log
Task 4 Run 3 With skillDone12s92,722$0.0268YesFull log
Task 3 Run 2 With skillDone33s122,926$0.0947YesFull log
Task 1 Run 1 Without skillDone20s96,106$0.0496-Full log
Task 4 Run 4 With skillDone10s73,731$0.0248YesFull log
Task 2 Run 1 With skillDone34s160,732$0.1079YesFull log
Task 3 Run 3 Without skillDone33s101,533$0.0948-Full log

“With skill (not named)” runs only measure the pick-up rate and are not judged.

Task 1: Fix E2E capture cleanup that wipes all prior screenshots and traces

Request

QA filed a complaint about our Control UI E2E capture script (`scripts/capture-control-ui.mjs`). They were debugging a flaky chat-send failure from yesterday, re-ran the capture this morning, and every screenshot and trace from yesterday's run was gone. It looks like the script clears out the artifacts directory each time it runs.

Please fix it so a capture run no longer destroys evidence from earlier runs. Keep `runCapture` exported, accepting the same options, and returning the same per-scenario result objects (`name`, `passed`, `dir`). Adding fields is fine. The existing test is `node --test scripts/capture-control-ui.test.mjs`; update or extend it if needed. When you're done, briefly explain what changed and where artifacts now end up.

Rubric

  1. Running the capture no longer deletes or clears the shared artifacts parent directory: unrelated directories and files that were already in it (from earlier runs or other jobs) are still there afterward.
  2. Each capture attempt, retries included, gets its own new directory allocated with the provided createControlUiE2eArtifactDir helper instead of a hand-built fixed path such as <root>/<scenario-name>, so a re-run never overwrites earlier screenshots or traces.
  3. Artifacts from failed attempts (for example the failure screenshot from attempt 1 before a passing retry) are kept, not deleted or overwritten by the next attempt.
  4. runCapture is still exported with the same options, and its results still include name, passed, and dir, where dir points to a directory that really exists. Any run-level report is written so it does not overwrite an earlier run's report, for example by putting it inside a directory the run owns.
  5. The existing node --test test still passes (updated if needed). The final message says where artifacts now go and confirms that earlier evidence is kept.

Score per rubric item (1 = met, 0.5 = partly, 0 = not met)

#Run 1
Without skill / With skill
Run 2
Without skill / With skill
Run 3
Without skill / With skill
Run 4
Without skill / With skill
Run 5
Without skill / With skill
11 / 11 / 11 / 11 / 11 / 1
21 / 10 / 11 / 11 / 11 / 1
31 / 11 / 11 / 11 / 11 / 1
41 / 11 / 11 / 11 / 11 / 1
51 / 11 / 11 / 11 / 10.75 / 1
Starting files(5)

package.json

{
  "name": "control-ui",
  "private": true,
  "type": "module",
  "scripts": {
    "capture": "node scripts/capture-control-ui.mjs",
    "test:capture": "node --test scripts/capture-control-ui.test.mjs"
  }
}

ui/src/test-helpers/control-ui-e2e.mjs

// Shared helpers for Control UI browser E2E capture.
// The real browser driver is stubbed in this repo: "screenshots" and "traces"
// are written as text/JSON files so the capture pipeline can be exercised.
import { mkdir, writeFile } from "node:fs/promises";
import { randomBytes } from "node:crypto";
import path from "node:path";

/**
 * Shared parent for all Control UI E2E artifacts. Other jobs (visual review,
 * perf audits, nightly runs) write into this same parent.
 */
export function resolveControlUiE2eArtifactParent() {
  return path.resolve(
    process.env.CONTROL_UI_E2E_ARTIFACTS_DIR ?? "artifacts/control-ui-e2e",
  );
}

/**
 * Allocate a fresh, uniquely named artifact directory for one capture attempt
 * (or one standalone invocation). Never reuses an existing directory.
 *
 * @param {string} scope short label, e.g. a scenario name
 * @param {string} [parentDir] override the shared parent
 * @returns {Promise<string>} absolute path of the new directory
 */
export async function createControlUiE2eArtifactDir(scope, parentDir) {
  const parent = path.resolve(parentDir ?? resolveControlUiE2eArtifactParent());
  const safe =
    String(scope ?? "")
      .replace(/[^a-zA-Z0-9._-]+/g, "-")
      .replace(/^-+|-+$/g, "") || "run";
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
  await mkdir(parent, { recursive: true });
  for (;;) {
    const dir = path.join(parent, `${safe}-${stamp}-${randomBytes(4).toString("hex")}`);
    try {
      await mkdir(dir);
      return dir;
    } catch (err) {
      if (err.code !== "EEXIST") throw err;
    }
  }
}

/** Write a screenshot for a named stage into an artifact directory. */
export async function captureScreenshot(dir, stage, data) {
  const file = path.join(dir, `${stage}.screenshot.txt`);
  await writeFile(file, String(data ?? ""));
  return file;
}

/** Write a trace for a named stage into an artifact directory. */
export async function captureTrace(dir, stage, data) {
  const file = path.join(dir, `${stage}.trace.json`);
  await writeFile(file, typeof data === "string" ? data : JSON.stringify(data ?? {}));
  return file;
}

scripts/capture-control-ui.mjs

// Runs Control UI capture scenarios and saves screenshots + traces for review.
import { rm, mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";
import {
  captureScreenshot,
  captureTrace,
} from "../ui/src/test-helpers/control-ui-e2e.mjs";

export const DEFAULT_ARTIFACTS_ROOT = path.resolve("artifacts/control-ui-e2e");

/**
 * @param {object} opts
 * @param {{name: string, run: (ctx: {attempt: number}) => Promise<{screenshot: string, trace: unknown}>}[]} opts.scenarios
 * @param {string} [opts.artifactsRoot]
 * @param {number} [opts.maxAttempts]
 * @param {(msg: string) => void} [opts.log]
 */
export async function runCapture({
  scenarios,
  artifactsRoot = process.env.CONTROL_UI_E2E_ARTIFACTS_DIR ?? DEFAULT_ARTIFACTS_ROOT,
  maxAttempts = 2,
  log = console.log,
}) {
  // Start from a clean slate so stale screenshots don't confuse reviewers.
  await rm(artifactsRoot, { recursive: true, force: true });
  await mkdir(artifactsRoot, { recursive: true });

  const results = [];
  for (const scenario of scenarios) {
    const outDir = path.join(artifactsRoot, scenario.name);
    let passed = false;
    let attempts = 0;
    let error;

    while (!passed && attempts < maxAttempts) {
      attempts += 1;
      // Reset the scenario folder before each attempt.
      await rm(outDir, { recursive: true, force: true });
      await mkdir(outDir, { recursive: true });
      try {
        const page = await scenario.run({ attempt: attempts });
        await captureScreenshot(outDir, "final", page.screenshot);
        await captureTrace(outDir, "final", page.trace);
        passed = true;
      } catch (err) {
        error = err;
        await captureScreenshot(outDir, "failure", err?.screenshot ?? "");
        log(`[capture] ${scenario.name} attempt ${attempts} failed: ${err?.message}`);
      }
    }

    results.push({
      name: scenario.name,
      passed,
      dir: outDir,
      attempts,
      error: passed ? undefined : String(error?.message ?? error),
    });
  }

  await writeFile(
    path.join(artifactsRoot, "report.json"),
    JSON.stringify({ createdAt: new Date().toISOString(), results }, null, 2),
  );
  log(`[capture] wrote ${results.length} scenario(s) to ${artifactsRoot}`);
  return results;
}

// Demo scenarios used when run directly (`npm run capture`).
const demoScenarios = [
  {
    name: "chat-send",
    async run({ attempt }) {
      if (attempt === 1 && Math.random() < 0.5) {
        const err = new Error("send button never enabled");
        err.screenshot = "<chat-send failure frame>";
        throw err;
      }
      return { screenshot: "<chat-send final frame>", trace: { events: ["click", "gateway:chat.send"] } };
    },
  },
  {
    name: "settings-open",
    async run() {
      return { screenshot: "<settings final frame>", trace: { events: ["click"] } };
    },
  },
];

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const results = await runCapture({ scenarios: demoScenarios });
  process.exitCode = results.every((r) => r.passed) ? 0 : 1;
}

scripts/capture-control-ui.test.mjs

import { test } from "node:test";
import assert from "node:assert/strict";
import { mkdtemp, readdir } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { runCapture } from "./capture-control-ui.mjs";

test("captures a passing scenario", async () => {
  const root = await mkdtemp(path.join(os.tmpdir(), "capture-test-"));
  const results = await runCapture({
    scenarios: [
      { name: "ok", run: async () => ({ screenshot: "shot", trace: { a: 1 } }) },
    ],
    artifactsRoot: root,
    log: () => {},
  });
  assert.equal(results.length, 1);
  assert.equal(results[0].name, "ok");
  assert.equal(results[0].passed, true);
  const files = await readdir(results[0].dir);
  assert.ok(files.some((f) => f.includes("screenshot")));
  assert.ok(files.some((f) => f.includes("trace")));
});

docs/e2e-artifacts.md

# Control UI E2E artifacts

All Control UI capture jobs (this capture script, visual reviews, interaction
perf audits, nightly runs) write under one shared parent:
`$CONTROL_UI_E2E_ARTIFACTS_DIR` (default `artifacts/control-ui-e2e`).

Use `createControlUiE2eArtifactDir(scope, parentDir?)` from
`ui/src/test-helpers/control-ui-e2e.mjs` to get a fresh directory, and pass it
to `captureScreenshot` / `captureTrace`.

Run 1: Tie (Rubric met 100% / 100%)

Both drop deletion, use the helper for per-attempt and report dirs, and keep evidence; no real difference.

Without skill100%

Final message

A capture run no longer deletes anything. The script used to rm -rf the whole artifacts root, and that root is shared with the visual-review, perf-audit and nightly jobs. It also wiped each scenario folder before every retry, so a failed first attempt's screenshot was lost too. Both tests pass.

What changed in scripts/capture-control-ui.mjs

  • Both rm calls are gone. Each run creates its own directory under the artifacts root, named capture-<timestamp>-<random>. It uses the existing createControlUiE2eArtifactDir helper, which never reuses a directory.
  • Each attempt gets its own directory inside the run directory, named <scenario>-<timestamp>-<random>. A failed attempt's failure.screenshot.txt therefore stays next to the passing retry. This is what QA needed for the flaky chat-send case.
  • report.json is written into the run directory instead of the root.
  • runCapture keeps the same options and still returns name, passed and dir. dir is now the last attempt's directory. I added attemptDirs to each result.
  • The report now also records runDir.

Where artifacts end up

$CONTROL_UI_E2E_ARTIFACTS_DIR (default artifacts/control-ui-e2e)/
  capture-<ts>-<rand>/
    report.json
    chat-send-<ts>-<rand>/    # attempt 1, e.g. failure.screenshot.txt
    chat-send-<ts>-<rand>/    # attempt 2, final.screenshot.txt + final.trace.json
    settings-open-<ts>-<rand>/

Tests I added a test in scripts/capture-control-ui.test.mjs. It checks that:

  • a pre-existing file in the root survives two runs,
  • the two runs land in different directories,
  • the failed attempt's screenshot is kept.

Artifacts now pile up, since nothing prunes them. If disk use becomes a problem, add a retention policy that deletes old run directories by age. I didn't add one, because it would be the same kind of deletion QA complained about.

Files created or changed

With skill100%

Final message

runCapture no longer deletes anything, so earlier runs' screenshots and traces survive a new capture. Both tests pass (the existing one and a new one).

What was wrong: the script ran rm -rf on the whole artifacts root at the start. It also wiped each scenario's folder before every attempt, so a failed first attempt was erased by its retry.

What changed in scripts/capture-control-ui.mjs:

  • Both rm calls are gone.
  • Each attempt now gets its own new directory from createControlUiE2eArtifactDir(scenario.name, artifactsRoot). This is the helper the control-ui-e2e skill specifies. A failed attempt keeps its failure.screenshot.txt, and the retry writes to a separate directory.
  • report.json goes into its own new report-<timestamp>-<id>/ directory, so reports no longer overwrite each other.

Where artifacts end up: under the same root as before, which is artifacts/control-ui-e2e or $CONTROL_UI_E2E_ARTIFACTS_DIR. The layout is now:

  • <scenario>-<ISO timestamp>-<random hex>/ for each attempt, holding final.* or failure.* files.
  • report-<timestamp>-<random hex>/report.json for each run's report.

What runCapture returns: the options and the name, passed and dir fields are unchanged. dir is the last attempt's directory. I added attemptDirs, which lists every attempt's directory.

Test: the new test runs a flaky scenario, then runs capture a second time in the same root. It checks that nothing from the first run disappears and that the failed attempt's screenshot is kept.

Anything that expects <root>/<scenario>/ or <root>/report.json will need to look in the new directories. I didn't search the repo for such consumers.

Files created or changed

Run 2: With skill (Rubric met 77.5% / 100%)

A uses the provided createControlUiE2eArtifactDir helper per attempt; B hand-builds its own paths.

Without skill77.5%

Final message

A capture run no longer deletes anything from earlier runs. All three tests pass: the original one and two I added.

What changed in scripts/capture-control-ui.mjs:

  • Cause: the script ran rm -rf on the whole artifacts root at the start of every run. It also wiped each scenario folder before every retry attempt. That second deletion destroyed the first attempt's failure screenshot, which is exactly the evidence you need for a flaky failure.
  • New location: each run now writes to its own folder, <artifactsRoot>/runs/<ISO-timestamp>/<scenario>/. The timestamp is the run start time with : and . replaced by -. If two runs start in the same millisecond, the second gets a -1 suffix.
  • Report: report.json now sits inside the run folder, next to the scenario folders.
  • Retries: nothing is removed between attempts. Failure screenshots are named failure-attempt<N>, so each attempt's failure is kept. The final success capture is still named final.
  • Unchanged: runCapture is still exported with the same options. The artifactsRoot option and the CONTROL_UI_E2E_ARTIFACTS_DIR environment variable still set the root. Results still return name, passed and dir, plus attempts and error as before. dir now points into the run's timestamped folder.

Tests: I added one test that a second run leaves the first run's files untouched and uses a different directory. I added another that a scenario failing on every attempt keeps both failure screenshots.

Tradeoff: artifacts now pile up under runs/ with no automatic cleanup. If disk use or CI workspaces become a problem, add a separate opt-in prune step. I didn't add one, since deleting old runs is the behavior QA complained about. Anything that reads artifacts/control-ui-e2e/report.json or <scenario>/ directly will need to look under runs/<timestamp>/ instead. I only checked the files you pointed me to, so I haven't looked for other consumers.

Files created or changed

With skill100%

Final message

A capture run no longer deletes anything from earlier runs. Both tests in node --test scripts/capture-control-ui.test.mjs pass.

Cause: runCapture ran rm -rf on the whole artifacts root at the start of every run. It also wiped each scenario folder before every retry attempt. That second reset meant a failed first attempt (the flaky chat-send screenshot) was erased as soon as the retry started.

What changed in scripts/capture-control-ui.mjs:

  • No deletes: I removed both rm calls.
  • One directory per attempt: Each attempt now gets a fresh, uniquely named directory from the shared helper createControlUiE2eArtifactDir, which the skill specifies. The names look like <root>/chat-send-attempt-1-<timestamp>-<random>/.
  • Retries: A failed attempt keeps its failure.screenshot.txt, and the retry writes to a new directory.
  • Report: report.json is written to its own new <root>/report-<timestamp>-<random>/ directory, so it no longer overwrites the previous run's report.
  • Results: runCapture still takes the same options and exports the same name, passed and dir. dir is now the last attempt's directory. I added attemptDirs, a list of every attempt directory for that scenario.

Where artifacts end up: Under the same root as before, which is CONTROL_UI_E2E_ARTIFACTS_DIR or artifacts/control-ui-e2e. Anything that expects the old fixed <root>/<scenario>/ or <root>/report.json paths will need to read dir and the new report directory instead. The log line now prints the report directory.

Test added: preserves earlier runs and failed attempts pre-seeds an old file, runs a scenario that fails once, then runs it again. It checks that the old file is untouched and that all four attempt directories are distinct and non-empty.

Old runs now accumulate in the artifacts root, and I added no cleanup. Per the skill, only delete the exact directories you own, after review.

Files created or changed

Run 3: Tie (Rubric met 100% / 100%)

Both drop deletions, use the helper per attempt, isolate the report, and add equivalent tests.

Without skill100%

Final message

A capture run no longer deletes anything. Both tests in scripts/capture-control-ui.test.mjs pass, including a new one that checks old artifacts survive.

What was wrong: runCapture ran rm -rf on the whole artifacts root at the start of every run. That root is shared with other jobs (visual review, perf audits, nightly runs), so those were being wiped too. It also deleted the scenario folder before each retry, so a failed attempt's screenshot was lost as soon as the next attempt began.

What changed in scripts/capture-control-ui.mjs:

  • The upfront wipe and the per-attempt rm are gone.
  • Each attempt now gets its own new directory from the existing createControlUiE2eArtifactDir helper. The directory is named <scenario>-<ISO timestamp>-<random hex> and sits directly under the artifacts root. The default root is artifacts/control-ui-e2e, or $CONTROL_UI_E2E_ARTIFACTS_DIR if set. This follows docs/e2e-artifacts.md.
  • report.json is written to its own capture-report-<timestamp>-<hex>/ directory, so reports from different runs don't overwrite each other.
  • runCapture takes the same options and returns the same name, passed and dir.
  • dir is now the last attempt's directory, which holds final.* if it passed or failure.screenshot.txt if it failed.
  • I added an attemptDirs field listing every attempt's directory, so failed first attempts stay inspectable.

Behaviour change: artifacts from different runs now sit side by side in a flat folder and are told apart by timestamp. Nothing prunes old runs, so the folder will grow until someone cleans it up on purpose.

Tests: the new test seeds a file from an earlier run, then runs a scenario that fails once and passes on retry, twice in a row. It checks that the old file is untouched, that every attempt directory is separate and non-empty, and that the two runs' directories differ.

Files created or changed

With skill100%

Final message

runCapture no longer deletes anything. A capture run now leaves yesterday's screenshots and traces alone. Both tests pass, including a new one that checks old files survive a second run.

What changed in scripts/capture-control-ui.mjs:

  • Root clear removed: the rm of the whole artifacts root at the start of a run is gone.
  • Per-attempt clearing removed: the rm of the scenario folder before each attempt is gone too. That one also destroyed the failed first attempt of a flaky scenario, which is exactly the chat-send evidence QA needed.
  • New directories: each attempt now gets its own directory from the shared createControlUiE2eArtifactDir helper.

Where artifacts end up:

  • Attempt directories: each attempt writes to <artifactsRoot>/<scenario>-attempt-<n>-<timestamp>-<random>/. The root is still CONTROL_UI_E2E_ARTIFACTS_DIR or artifacts/control-ui-e2e.
  • Report: report.json goes in its own report-<timestamp>-<random>/ directory, so it no longer overwrites the previous run's report.
  • Retries: failed and successful attempts are both kept.

Results shape: name, passed and dir are unchanged, and dir is the last attempt's directory. I added attemptDirs, which lists every attempt's directory.

The new test is in scripts/capture-control-ui.test.mjs. It covers a retried scenario and two consecutive runs on the same root.

Files from earlier runs already under the root are untouched, but anything yesterday's run saved before this fix was lost to the clear, and this change can't bring it back. Anything that expects <root>/<scenario>/ or <root>/report.json at fixed paths will need to read dir or attemptDirs from the results instead. I didn't search the repo for such consumers.

Files created or changed

Run 4: Tie (Rubric met 100% / 100%)

Both drop deletions, use the helper for per-run and per-attempt dirs, and keep the report in the run dir.

Without skill100%

Final message

The capture script no longer deletes anything. I fixed it in scripts/capture-control-ui.mjs, and both tests pass (node --test scripts/capture-control-ui.test.mjs).

What was wrong: runCapture ran rm -rf on the whole artifacts root at the start of every run. That root is the shared $CONTROL_UI_E2E_ARTIFACTS_DIR, so it also wiped other jobs' output. Before each retry it also deleted the scenario folder, which destroyed the evidence from a failed first attempt. That is the case QA was debugging.

What changed:

  • Both rm calls are gone. The script now uses the existing createControlUiE2eArtifactDir helper, which always creates a new, uniquely named directory.
  • Each run creates <root>/capture-run-<timestamp>-<id>/.
    • report.json is written there.
    • Each scenario attempt gets its own directory inside it, named <scenario>-<timestamp>-<id>/. A failed attempt keeps its failure.screenshot.txt, and the passing attempt has the final.* files.
  • runCapture keeps its signature and still returns name, passed and dir, where dir is the last attempt's directory. I added attemptDirs and runDir to each result.
  • Directories now sit one level deeper than before, and report.json has moved into the run directory. Anything that reads the old fixed paths, like <root>/<scenario>/ or <root>/report.json, will need updating. I only searched this repo's files, so I haven't checked for external consumers.

Tests and docs: I added a test that runs a flaky scenario twice against the same root. It checks that:

  • the two runs get separate directories;
  • the failed attempt's artifacts are still there;
  • an unrelated file in the root is left alone.

I also added a short note to docs/e2e-artifacts.md describing the new layout.

Nothing prunes old runs now, so artifacts/control-ui-e2e will grow. If that becomes a problem, add an explicit, opt-in cleanup, for example "delete runs older than N days".

Files created or changed

With skill100%

Final message

runCapture no longer deletes anything. Both tests in node --test scripts/capture-control-ui.test.mjs pass: the existing one and a new one covering preservation.

What changed in scripts/capture-control-ui.mjs:

  • Root wipe removed. It used to rm -rf the whole artifacts root at the start of every run. That is what destroyed yesterday's evidence.
  • Per-attempt wipe removed. It also deleted the scenario folder before each retry, so a failed attempt's failure screenshot was lost as soon as the retry started.
  • One directory per run. Each run now creates <artifactsRoot>/capture-<timestamp>-<rand>/. <artifactsRoot> is the same as before: CONTROL_UI_E2E_ARTIFACTS_DIR, or artifacts/control-ui-e2e.
  • One directory per attempt. Each attempt gets its own <scenario>-<timestamp>-<rand>/ inside the run directory. It uses the shared createControlUiE2eArtifactDir helper, which never reuses a directory. A failed attempt keeps its failure.screenshot.txt, and the retry writes final.* into a separate directory.
  • Report location. report.json is now written inside the run directory, so a new run doesn't overwrite the previous report.

Return values and options: runCapture keeps its exports and options. Each result still has name, passed and dir. dir is now the last attempt's directory, which is the passing one if the scenario passed. I added attemptDirs, which lists every attempt's directory.

Tests: the new test seeds a stale file in the root and runs a scenario that fails once, twice in a row. It checks that the stale file survives and that the failed attempt's evidence is kept. It also checks that the two runs land in different directories.

Anything that expects a flat <root>/<scenario>/ or <root>/report.json layout will need to follow result.dir, or look in the run directory, instead. I didn't search for other consumers of that layout.

Nothing is ever cleaned up now, so old runs pile up under the root until someone prunes them by hand.

Files created or changed

Run 5: Tie (Rubric met 100% / 100%)

Both drop deletes, use the helper per attempt, keep failed evidence and write per-run reports.

Without skill100%

Final message

A capture run no longer deletes anything. Both tests pass: the existing one and a new one covering this.

What changed in scripts/capture-control-ui.mjs:

  • Removed the deletes: the script no longer runs rm on the artifacts root at the start of a run, or on the scenario folder before each attempt.
  • One directory per run: each run gets its own capture-run-<timestamp>-<random>/ directory under the artifacts root. It comes from the shared createControlUiE2eArtifactDir helper, which never reuses a directory name.
  • One directory per attempt: each attempt of each scenario gets its own <scenario>-<timestamp>-<random>/ folder inside the run directory.
  • Retries keep their evidence: the failure screenshot from attempt 1 now survives when attempt 2 passes. That is the flaky chat-send case QA was debugging.
  • Report location: report.json is now written inside the run directory instead of at the root. Other jobs share the root, and the old file would have been overwritten on every run.
  • Result objects: runCapture takes the same options and returns the same name, passed and dir fields. dir is now the directory of the last attempt, which is the passing one if the scenario passed. I added a runDir field.

Artifacts now end up in $CONTROL_UI_E2E_ARTIFACTS_DIR (default artifacts/control-ui-e2e), under capture-run-<stamp>/<scenario>-<stamp>/. Each attempt folder holds final.* on success or failure.screenshot.txt on failure. Because nothing is cleaned up now, old runs will accumulate until someone prunes them.

Tests: I added a test to scripts/capture-control-ui.test.mjs. It runs a flaky scenario twice against the same root. It checks that a pre-existing file is untouched, that the two runs use different directories, and that the failed attempt's screenshot is kept.

Files created or changed

With skill100%

Final message

runCapture no longer deletes anything, so a new run can't wipe out an earlier run's screenshots or traces. All 3 tests in node --test scripts/capture-control-ui.test.mjs pass.

What changed in scripts/capture-control-ui.mjs

  • I removed the rm of the whole artifacts root at the start of a run. I also removed the rm of the scenario folder before each attempt.
  • Each attempt now gets its own new directory from createControlUiE2eArtifactDir(scenario.name, artifactsRoot). That's the shared helper the skill requires. It creates a unique directory and never reuses one.
  • A failed attempt keeps its failure.screenshot.txt, and the retry writes to a separate directory. Before, a retry deleted the failed attempt's evidence.
  • report.json used to sit at the root and be overwritten each run. It now goes in its own per-run directory.

Where artifacts end up

  • Attempt directories are <artifactsRoot>/<scenario>-<timestamp>-<random>/. They hold final.* for a passing attempt or failure.screenshot.txt for a failed one.
  • The report is at <artifactsRoot>/run-<timestamp>-<random>/report.json.
  • artifactsRoot is the same as before: the option, then CONTROL_UI_E2E_ARTIFACTS_DIR, then artifacts/control-ui-e2e.

API

  • runCapture takes the same options and is still exported.
  • Each result still has name, passed and dir, where dir is the last attempt's directory.
  • Results now also have attemptDirs, a list of every attempt's directory.

Tests I added one test that a second run leaves the first run's output and an unrelated file in the root intact. I added another that a failed attempt and its retry end up in separate directories.

Directories now pile up across runs, so something will have to prune them eventually. Any tooling that expected <root>/<scenario>/ or <root>/report.json at fixed paths will need to read the paths from the results instead. I didn't search the repo for such tooling.

Files created or changed

Task 2: Add E2E tests for the chat error shown when the Gateway never responds

Request

I just added handling to the Control UI chat send flow for the case where the Gateway never answers a `chat.send` request. After the send timeout the composer now shows an alert ("Gateway did not respond. Your message was not sent.") and a Retry button, and Retry re-sends using the same idempotency key. See `ui/src/app/chat.ts` and the CHANGELOG entry.

Can you write E2E tests for this next to the existing chat flow e2e tests in `ui/src/e2e/`? They should cover what the user sees and what actually gets sent to the Gateway, including retry. Run the suite with `npm run test:e2e` and make sure everything passes (the old tests too). When you're done, tell me what you covered.

Rubric

  1. Gateway が chat.send に応答しない状況を、テストファイル内で独自のハンドラーを差し込んだり上書きしたりせず、共有ハーネス(ui/src/test-helpers/control-ui-e2e.ts)の型付きシナリオオプションに新しい項目(例: chat.send を応答させない設定)を足して作っている
  2. 各テストで Gateway の mock を入れる処理(installGatewayMock など)がページ遷移(goto)より前にあり、遷移した後に mock を差し替えたり足したりしていない
  3. テストが画面に見える操作(入力欄への入力、Send や Retry のクリック)で進み、表示されたアラートの文言・failed 状態・Retry ボタンを確かめ、さらに Gateway に送られた chat.send リクエスト(件数・message・Retry で同じ idempotencyKey が使われること)も確かめている
  4. 新しいテストも既存のテストも npm run test:e2e で通る。製品側(chat.ts)のタイムアウト処理を壊すと新しいテストが落ちる(意味のあるテストになっている)
  5. 最終メッセージで、何をテストしたか、実際に動かした結果、カバーしていない状態を分けて報告しており、根拠のない『確認済み』を書いていない

Score per rubric item (1 = met, 0.5 = partly, 0 = not met)

#Run 1
Without skill / With skill
Run 2
Without skill / With skill
Run 3
Without skill / With skill
Run 4
Without skill / With skill
Run 5
Without skill / With skill
11 / 0.51 / 11 / 11 / 11 / 1
21 / 01 / 11 / 11 / 11 / 1
31 / 11 / 11 / 11 / 11 / 1
40.5 / 0.50.5 / 0.50.5 / 0.50.75 / 0.750.5 / 0.5
50.5 / 10.5 / 10.75 / 10.5 / 10.5 / 1
Starting files(6)

package.json

{
  "name": "control-ui-mini",
  "private": true,
  "type": "module",
  "scripts": {
    "test:e2e": "node --experimental-strip-types --no-warnings --test --test-timeout=20000 \"ui/src/e2e/**/*.e2e.test.ts\""
  }
}

CHANGELOG.md

# Changelog

## Unreleased

- Control UI chat: when `chat.send` gets no response from the Gateway within the send timeout
  (`sendTimeoutMs`), the user message is marked `[failed]`, an alert
  (`data-testid="chat-error"`, text "Gateway did not respond. Your message was not sent.") is shown
  and a `Retry` button (`data-testid="retry-button"`) appears. The draft stays in the composer.
  Retry re-sends the same message with the **same** `idempotencyKey` so the Gateway can dedupe.
  Gateway error frames keep the old behaviour ("Send failed: ...", no Retry).

ui/src/app/chat.ts

export type ChatMessage = {
  role: "user" | "assistant";
  text: string;
  status?: "pending" | "sent" | "failed";
};

export type GatewayTransport = {
  request(method: string, params?: Record<string, unknown>): Promise<unknown>;
};

export type ControlUiOptions = {
  transport: GatewayTransport;
  requestTimeoutMs?: number;
  sendTimeoutMs?: number;
};

export type RenderedElement = { text: string; disabled?: boolean; role?: string };

export type ControlUiApp = {
  ready: Promise<void>;
  query(testId: string): RenderedElement | null;
  fill(testId: string, value: string): void;
  click(testId: string): Promise<void>;
};

export class GatewayTimeoutError extends Error {
  method: string;
  constructor(method: string) {
    super(`Gateway request timed out: ${method}`);
    this.name = "GatewayTimeoutError";
    this.method = method;
  }
}

export type SendFailure = {
  kind: "gateway-timeout" | "gateway-error";
  message: string;
  retryable: boolean;
};

export function describeSendFailure(error: unknown): SendFailure {
  if (error instanceof GatewayTimeoutError) {
    return {
      kind: "gateway-timeout",
      message: "Gateway did not respond. Your message was not sent.",
      retryable: true,
    };
  }
  const detail = error instanceof Error ? error.message : String(error);
  return { kind: "gateway-error", message: `Send failed: ${detail}`, retryable: false };
}

function withTimeout<T>(promise: Promise<T>, ms: number, method: string): Promise<T> {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => reject(new GatewayTimeoutError(method)), ms);
    promise.then(
      (value) => {
        clearTimeout(timer);
        resolve(value);
      },
      (error) => {
        clearTimeout(timer);
        reject(error);
      },
    );
  });
}

export function mountControlUi(options: ControlUiOptions): ControlUiApp {
  const requestTimeoutMs = options.requestTimeoutMs ?? 10_000;
  const sendTimeoutMs = options.sendTimeoutMs ?? 15_000;
  const state = {
    connection: "connecting" as "connecting" | "connected" | "error",
    connectionError: "",
    messages: [] as ChatMessage[],
    draft: "",
    sending: false,
    failure: null as SendFailure | null,
    failedIndex: -1,
    failedKey: "",
  };
  let seq = 0;

  function request(method: string, params: Record<string, unknown>, timeoutMs: number) {
    return withTimeout(options.transport.request(method, params), timeoutMs, method);
  }

  async function boot(): Promise<void> {
    try {
      await request("connect", { client: "control-ui", protocol: 3 }, requestTimeoutMs);
      const history = (await request("chat.history", { sessionKey: "main" }, requestTimeoutMs)) as {
        messages?: ChatMessage[];
      };
      state.messages = [...(history.messages ?? [])];
      state.connection = "connected";
    } catch (error) {
      state.connection = "error";
      state.connectionError = error instanceof Error ? error.message : String(error);
    }
  }

  async function deliver(text: string, idempotencyKey: string, index: number): Promise<boolean> {
    state.sending = true;
    state.failure = null;
    try {
      const result = (await request(
        "chat.send",
        { sessionKey: "main", message: text, idempotencyKey },
        sendTimeoutMs,
      )) as { reply?: string };
      state.messages[index].status = "sent";
      if (result && result.reply) state.messages.push({ role: "assistant", text: result.reply });
      state.failedIndex = -1;
      state.failedKey = "";
      return true;
    } catch (error) {
      state.messages[index].status = "failed";
      state.failure = describeSendFailure(error);
      state.failedIndex = index;
      state.failedKey = idempotencyKey;
      return false;
    } finally {
      state.sending = false;
    }
  }

  async function send(): Promise<void> {
    const text = state.draft.trim();
    if (!text || state.sending || state.connection !== "connected") return;
    seq += 1;
    const key = `msg-${seq}`;
    state.messages.push({ role: "user", text, status: "pending" });
    const ok = await deliver(text, key, state.messages.length - 1);
    if (ok) state.draft = "";
  }

  async function retry(): Promise<void> {
    if (state.failedIndex < 0 || state.sending) return;
    const message = state.messages[state.failedIndex];
    message.status = "pending";
    const ok = await deliver(message.text, state.failedKey, state.failedIndex);
    if (ok) state.draft = "";
  }

  function render(): Map<string, RenderedElement> {
    const el = new Map<string, RenderedElement>();
    el.set("connection-status", {
      text: state.connection === "error" ? `Disconnected: ${state.connectionError}` : state.connection,
    });
    el.set("message-list", {
      text: state.messages
        .map((m) => `${m.role}${m.status ? ` [${m.status}]` : ""}: ${m.text}`)
        .join("\n"),
    });
    el.set("composer-input", { text: state.draft, disabled: state.connection !== "connected" });
    el.set("send-button", {
      text: state.sending ? "Sending…" : "Send",
      disabled: state.sending || state.connection !== "connected",
    });
    if (state.failure) {
      el.set("chat-error", { text: state.failure.message, role: "alert" });
      if (state.failure.retryable) {
        el.set("retry-button", { text: "Retry", disabled: state.sending });
      }
    }
    return el;
  }

  return {
    ready: boot(),
    query(testId: string) {
      return render().get(testId) ?? null;
    },
    fill(testId: string, value: string) {
      const el = render().get(testId);
      if (testId !== "composer-input" || !el) throw new Error(`Element is not fillable: [data-testid="${testId}"]`);
      if (el.disabled) throw new Error(`Element is disabled: [data-testid="${testId}"]`);
      state.draft = value;
    },
    click(testId: string) {
      const el = render().get(testId);
      if (!el) throw new Error(`Element not found: [data-testid="${testId}"]`);
      if (el.disabled) throw new Error(`Element is disabled: [data-testid="${testId}"]`);
      if (testId === "send-button") void send();
      else if (testId === "retry-button") void retry();
      return Promise.resolve();
    },
  };
}

ui/src/test-helpers/fake-browser.ts

// Minimal in-process stand-in for a browser page driving the Control UI.
// The Gateway WebSocket is established on navigation: a route handler must be
// registered before goto(), otherwise the connection is refused.
import { mountControlUi } from "../app/chat.ts";
import type { ControlUiApp } from "../app/chat.ts";

export type GatewayFrame = { method: string; params?: Record<string, unknown> };
export type GatewayResponder = {
  reply(result: unknown): void;
  fail(code: string, message: string): void;
};
export type GatewayRouteHandler = (frame: GatewayFrame, respond: GatewayResponder) => void;

export type FakePageOptions = { requestTimeoutMs?: number; sendTimeoutMs?: number };
export type WaitOptions = {
  state?: "visible" | "hidden";
  hasText?: string | RegExp;
  timeoutMs?: number;
};

export class FakePage {
  #handler: GatewayRouteHandler | null = null;
  #app: ControlUiApp | null = null;
  #options: FakePageOptions;

  constructor(options: FakePageOptions = {}) {
    this.#options = options;
  }

  async routeGateway(handler: GatewayRouteHandler): Promise<void> {
    this.#handler = handler;
  }

  async goto(path: string): Promise<void> {
    if (!path.startsWith("/chat")) throw new Error(`No route for ${path}`);
    const handlerAtConnect = this.#handler;
    const getHandler = () => this.#handler;
    const transport = {
      request(method: string, params?: Record<string, unknown>): Promise<unknown> {
        if (!handlerAtConnect) {
          return Promise.reject(new Error("WebSocket connection refused (ws://127.0.0.1:18789)"));
        }
        const handler = getHandler() ?? handlerAtConnect;
        return new Promise((resolve, reject) => {
          handler(
            { method, params },
            {
              reply: (result) => resolve(result),
              fail: (code, message) => reject(new Error(`${code}: ${message}`)),
            },
          );
        });
      },
    };
    this.#app = mountControlUi({ transport, ...this.#options });
    await this.#app.ready;
  }

  #requireApp(): ControlUiApp {
    if (!this.#app) throw new Error("Page has not navigated yet; call goto() first");
    return this.#app;
  }

  async fill(testId: string, value: string): Promise<void> {
    this.#requireApp().fill(testId, value);
  }

  async click(testId: string): Promise<void> {
    await this.#requireApp().click(testId);
  }

  async textContent(testId: string): Promise<string | null> {
    return this.#requireApp().query(testId)?.text ?? null;
  }

  async isVisible(testId: string): Promise<boolean> {
    return this.#requireApp().query(testId) !== null;
  }

  async isDisabled(testId: string): Promise<boolean> {
    return Boolean(this.#requireApp().query(testId)?.disabled);
  }

  async getRole(testId: string): Promise<string | null> {
    return this.#requireApp().query(testId)?.role ?? null;
  }

  async waitFor(testId: string, options: WaitOptions = {}): Promise<void> {
    const state = options.state ?? "visible";
    const timeoutMs = options.timeoutMs ?? 2000;
    const deadline = Date.now() + timeoutMs;
    while (true) {
      const el = this.#requireApp().query(testId);
      const textOk =
        options.hasText === undefined ||
        (el !== null &&
          (typeof options.hasText === "string" ? el.text.includes(options.hasText) : options.hasText.test(el.text)));
      if (state === "visible" ? el !== null && textOk : el === null) return;
      if (Date.now() > deadline) {
        throw new Error(
          `Timed out after ${timeoutMs}ms waiting for [data-testid="${testId}"] to be ${state}` +
            (options.hasText !== undefined ? ` with text ${String(options.hasText)}` : ""),
        );
      }
      await new Promise((resolve) => setTimeout(resolve, 10));
    }
  }
}

ui/src/test-helpers/control-ui-e2e.ts

// Shared Control UI E2E harness: synthetic Gateway fixture + fake page.
import { FakePage } from "./fake-browser.ts";
import type { GatewayFrame } from "./fake-browser.ts";
import type { ChatMessage } from "../app/chat.ts";

export type ControlUiE2eScenarioOptions = {
  /** Messages returned by chat.history during boot. */
  history?: ChatMessage[];
  /** Assistant text returned in the chat.send result. */
  assistantReply?: string;
  /** Make chat.send fail with a Gateway error frame instead of replying. */
  sendError?: { code: string; message: string };
  /** Client-side chat.send timeout used by the app (keep small in tests). */
  sendTimeoutMs?: number;
};

export type ControlUiE2eHarness = {
  page: FakePage;
  /** Every frame the UI sent to the fixture Gateway, in order. */
  gatewayRequests: GatewayFrame[];
  requestsFor(method: string): GatewayFrame[];
  installGatewayMock(): Promise<void>;
};

export function createControlUiE2eHarness(options: ControlUiE2eScenarioOptions = {}): ControlUiE2eHarness {
  const page = new FakePage({ sendTimeoutMs: options.sendTimeoutMs ?? 150, requestTimeoutMs: 500 });
  const gatewayRequests: GatewayFrame[] = [];

  return {
    page,
    gatewayRequests,
    requestsFor: (method: string) => gatewayRequests.filter((frame) => frame.method === method),
    async installGatewayMock() {
      await page.routeGateway((frame, respond) => {
        gatewayRequests.push(frame);
        switch (frame.method) {
          case "connect":
            respond.reply({ protocol: 3, server: { version: "fixture" } });
            return;
          case "chat.history":
            respond.reply({ messages: options.history ?? [] });
            return;
          case "chat.send":
            if (options.sendError) {
              respond.fail(options.sendError.code, options.sendError.message);
              return;
            }
            respond.reply({
              runId: `run-${gatewayRequests.length}`,
              reply: options.assistantReply ?? "Fixture reply",
            });
            return;
          default:
            respond.fail("UNKNOWN_METHOD", `Fixture has no response for ${frame.method}`);
        }
      });
    },
  };
}

ui/src/e2e/chat-flow.messaging.e2e.test.ts

import { test } from "node:test";
import assert from "node:assert/strict";
import { createControlUiE2eHarness } from "../test-helpers/control-ui-e2e.ts";

test("boots, completes the Gateway handshake and renders history", async () => {
  const h = createControlUiE2eHarness({ history: [{ role: "assistant", text: "Welcome back" }] });
  await h.installGatewayMock();
  await h.page.goto("/chat");

  assert.equal(await h.page.textContent("connection-status"), "connected");
  assert.match((await h.page.textContent("message-list")) ?? "", /assistant: Welcome back/);
  assert.deepEqual(
    h.gatewayRequests.map((frame) => frame.method),
    ["connect", "chat.history"],
  );
});

test("sends a message and renders the assistant reply", async () => {
  const h = createControlUiE2eHarness({ assistantReply: "Hello from the fixture" });
  await h.installGatewayMock();
  await h.page.goto("/chat");

  await h.page.fill("composer-input", "hi there");
  await h.page.click("send-button");
  await h.page.waitFor("message-list", { hasText: "assistant: Hello from the fixture" });

  assert.match((await h.page.textContent("message-list")) ?? "", /user \[sent\]: hi there/);
  assert.equal(await h.page.textContent("composer-input"), "");
  assert.equal(await h.page.isVisible("chat-error"), false);

  const sends = h.requestsFor("chat.send");
  assert.equal(sends.length, 1);
  assert.equal(sends[0].params?.message, "hi there");
  assert.equal(sends[0].params?.sessionKey, "main");
});

test("shows Gateway error frames from chat.send without a retry", async () => {
  const h = createControlUiE2eHarness({ sendError: { code: "RATE_LIMITED", message: "Slow down" } });
  await h.installGatewayMock();
  await h.page.goto("/chat");

  await h.page.fill("composer-input", "too fast");
  await h.page.click("send-button");
  await h.page.waitFor("chat-error");

  assert.equal(await h.page.textContent("chat-error"), "Send failed: RATE_LIMITED: Slow down");
  assert.equal(await h.page.getRole("chat-error"), "alert");
  assert.equal(await h.page.isVisible("retry-button"), false);
  assert.equal(h.requestsFor("chat.send").length, 1);
});

Run 1: Without skill (Rubric met 90% / 72.9%)

One A test swaps in its own routeGateway handler after goto; all B tests use only the shared harness option.

Without skill90%

Final message

I added five E2E tests for the send-timeout flow. npm run test:e2e passes 8 of 8: the 3 existing tests and the 5 new ones.

New file: ui/src/e2e/chat-flow.send-timeout.e2e.test.ts

Harness change: I added a silentSends: N option to ui/src/test-helpers/control-ui-e2e.ts. The mock Gateway records the first N chat.send requests and never answers them, which is what a hung Gateway looks like. Existing scenarios don't use the option, so they behave as before.

What the tests cover:

  1. Timeout UI.
    • While the request is in flight, the button reads "Sending…" and is disabled, and no error is shown.
    • After the timeout, the chat-error element has role="alert" and reads "Gateway did not respond. Your message was not sent."
    • The Retry button is visible and enabled.
    • The message shows as user [failed].
    • The draft stays in the composer.
    • Send is usable again.
    • Exactly one chat.send frame went out.
  2. Retry resends the same message.
    • The second frame has the same idempotencyKey and identical params as the first.
    • After Retry succeeds, the error and Retry button are gone, the message shows [sent], and the assistant reply appears.
    • The user message isn't duplicated, and the composer is cleared.
  3. Retry times out again.
    • The alert and Retry button come back, and the message stays [failed].
    • A second retry then succeeds.
    • All three frames carry the same key.
  4. New message after a failure. After a failed send is recovered through Retry, a new message goes out with a fresh idempotencyKey.
  5. Other traffic. The timeout leaves the Gateway traffic and connection status alone. The frames are exactly connect, chat.history and chat.send, and the status stays "connected".

The existing test for Gateway error frames already covers the case where an error frame gets no Retry button, so I didn't repeat it.

The tests use the harness's 150 ms send timeout, so they're quick.

Files created or changed

With skill72.9%

Final message

I added five send-timeout E2E tests, and npm run test:e2e passes: 8 of 8, including the 3 existing tests.

The new tests are in ui/src/e2e/chat-flow.send-timeout.e2e.test.ts. To make them possible I added an unansweredSends option to ui/src/test-helpers/control-ui-e2e.ts. It makes the Gateway ignore the first N chat.send requests and answer normally after that.

What the tests cover

  1. Timeout UI:
    • While the request is in flight, the button reads "Sending…" and is disabled.
    • After the timeout, the alert (role alert) says "Gateway did not respond. Your message was not sent."
    • The message shows [failed], the Retry button is enabled, and the draft stays in the composer.
    • The one chat.send carried the message, the main session key and a non-empty idempotency key.
  2. Retry succeeds:
    • The second chat.send has the same idempotency key and message as the first.
    • The reply renders, and the message goes from [failed] to [sent] without being duplicated.
    • The alert and Retry button disappear, and the composer clears.
  3. Retry also times out:
    • The alert comes back and Retry is available again.
    • The draft is kept, and the message is still [failed].
    • The second attempt still uses the same key.
  4. Retry gets an error frame: The alert becomes "Send failed: RATE_LIMITED: Slow down" and Retry is gone. The key was still reused.
  5. Next message after a recovered retry: It gets a fresh idempotency key.

One discrepancy in ui/src/app/chat.ts

  • render() sets Retry to disabled: state.sending. But deliver() clears the failure when a send starts, so the Retry button and alert vanish during a retry. That disabled value is never visible.
  • The test asserts what happens today: the button reads "Sending…" and Retry is hidden. If you meant Retry to stay visible but disabled while resending, that's a bug, and the test needs updating once it's fixed.

Not done

  • I didn't create an artifact directory. The skill names createControlUiE2eArtifactDir, but it doesn't exist in the repo's helper.
  • There are no screenshots or recordings. The suite runs against an in-process fake page, so I only checked text, roles, disabled state and Gateway requests.

Files created or changed

Run 2: With skill (Rubric met 90% / 95%)

Tests are nearly equal, but A separately reports uncovered areas (no real browser, no artifacts); B does not.

Without skill90%

Final message

I added four E2E tests for the send-timeout flow. npm run test:e2e passes 7 of 7: the 3 existing tests and the 4 new ones.

The harness had no way to simulate a Gateway that receives chat.send and never answers. I added an optional dropSends: N to ui/src/test-helpers/control-ui-e2e.ts. The first N chat.send requests are recorded but get no reply. It defaults to 0, so the old tests behave as before. The new tests are in ui/src/e2e/chat-flow.send-timeout.e2e.test.ts and use a 100 ms send timeout.

What the tests cover

  1. Timeout:
    • Before the timeout, the send button shows "Sending…" and is disabled. The message is [pending], and there is no alert and no Retry.
    • After the timeout, the alert reads "Gateway did not respond. Your message was not sent." and has role="alert". A Retry button is visible and enabled.
    • The message is [failed] and there's no assistant reply. The draft is still in the composer, and Send is enabled again.
    • The Gateway saw exactly connect, chat.history and one chat.send.
  2. Retry:
    • The second chat.send has the same idempotencyKey, message and sessionKey as the first.
    • The reply renders and the message becomes [sent], shown once. The alert and Retry are gone and the draft is cleared.
    • There is no extra connect or chat.history.
  3. New message after a retry: the next message gets a different idempotency key.
  4. Retry that times out too:
    • While the retry is in flight, the alert and Retry disappear and the message is [pending].
    • After the second timeout, the alert, Retry, [failed] status and draft come back.
    • A third attempt succeeds. All three sends used the same key and message.

The existing "error frames show no Retry" test already covers the contrast, so I didn't repeat it. I didn't touch chat.ts.

Files created or changed

With skill95%

Final message

I added E2E tests for the send-timeout and Retry flow, and npm run test:e2e now passes: 7 of 7, including the 3 existing tests.

Files

  • ui/src/e2e/chat-flow.send-timeout.e2e.test.ts is the new test file. It sits next to the existing chat-flow tests.
  • ui/src/test-helpers/control-ui-e2e.ts has a new scenario option, sendNoResponse. It leaves the first N chat.send requests unanswered, and Infinity means never answer.

What the tests cover

  1. Never answered.
    • While the request is pending, the button reads "Sending…" and is disabled, and the message is [pending].
    • After the timeout, the chat-error element has role alert and the text "Gateway did not respond. Your message was not sent."
    • Retry is visible and enabled, the message is [failed], and there is no assistant reply.
    • The draft stays in the composer, and Send is enabled again.
    • Exactly one chat.send went out.
  2. Retry succeeds.
    • The second chat.send carries the same idempotencyKey, message and sessionKey as the first.
    • The message becomes [sent] and the reply renders. There is no duplicate user message.
    • The alert and Retry disappear, and the composer clears.
  3. Retry times out again.
    • Retry is hidden during the re-send, then the alert and Retry come back.
    • A third attempt succeeds, and all three requests use one idempotency key.
  4. Timeout vs. error frame. The timeout alert doesn't contain "Send failed". The existing test already checks that a Gateway error frame shows no Retry.

Things to know

  • During a Retry re-send, the alert and the Retry button both disappear instead of Retry showing as disabled. state.failure is cleared in deliver(), so the disabled: state.sending branch on the Retry button in render() can never run. I asserted the current behavior, since it stops a double click. If you meant Retry to stay visible but disabled, that is a product change, and the test would need updating with it.
  • The skill mentions helpers such as createControlUiE2eArtifactDir and the screenshot helpers. They don't exist in this checkout, which has an in-process fake page. So these tests are assertion-only, with no screenshots, video or artifacts.
  • Nothing ran against a real browser or a real Gateway.

Files created or changed

Run 3: Tie (Rubric met 95% / 95%)

Both add a typed harness option and check UI and requests alike; neither tried breaking the product.

Without skill95%

Final message

npm run test:e2e passes: 8 of 8, the 3 existing tests and 5 new ones. I didn't change chat.ts.

The new tests are in ui/src/e2e/chat-flow.send-timeout.e2e.test.ts.

The fixture Gateway had no way to stay silent, so I added a silentSends option to ui/src/test-helpers/control-ui-e2e.ts. It makes the first N chat.send requests get no reply and no error. It defaults to 0, so the old tests behave as before.

What the tests cover

  1. Timeout: when the Gateway never answers chat.send, the user sees:
    • the chat-error alert with "Gateway did not respond. Your message was not sent." and role alert;
    • an enabled "Retry" button;
    • the message marked [failed];
    • the draft kept in the composer;
    • Send re-enabled;
    • exactly one chat.send sent.
  2. Retry: clicking Retry sends a second chat.send with the same idempotencyKey, message and sessionKey as the first. After the reply:
    • the message shows [sent], appears only once, and the assistant reply shows;
    • the alert and Retry button are gone;
    • the composer is cleared.
  3. Retry that times out too: the alert clears while the retry is in flight, then comes back with Retry and the message still [failed]. The key stays the same, and a third attempt succeeds with that same key.
  4. In flight: while a retry is pending, Send shows "Sending…" and is disabled, and only 2 requests have gone out.
  5. New message after a timeout: a different message gets a different idempotency key from the failed one.

The existing test for Gateway error frames already checks that "Send failed: …" has no Retry button, so I didn't repeat it.

I didn't test Retry being clicked twice in a row. The fake page's click rejects a disabled Retry button, so the guard in retry() can't be reached from here.

Files created or changed

With skill95%

Final message

I added the send-timeout E2E tests. npm run test:e2e passes: 8 of 8, which is the 3 existing tests and 5 new ones.

Files

  • ui/src/e2e/chat-flow.send-timeout.e2e.test.ts is new and holds the 5 tests.
  • ui/src/test-helpers/control-ui-e2e.ts has a new typed option, sendNoResponseCount. It leaves the first N chat.send requests unanswered, and later ones reply normally.

What the new tests cover

  1. Timeout UI and request: After the timeout, chat-error reads "Gateway did not respond. Your message was not sent." and has the alert role. Retry is visible and enabled. The message shows as [failed]. The draft stays in the composer and Send is usable again. Exactly one chat.send went out, with the right message and sessionKey.
  2. Waiting state: Before the timeout fires, the button reads "Sending…" and is disabled. There's no error yet, and the message is [pending]. Once the timeout hits, the error appears and the button goes back to "Send".
  3. Retry succeeds: The second chat.send has the same message and the same idempotencyKey as the first. The assistant reply renders and the message becomes [sent]. It is updated in place, not duplicated. The alert and Retry disappear and the composer clears.
  4. Retry times out again: The alert and Retry stay, and the message stays [failed]. A third attempt succeeds, and all three requests share one idempotency key.
  5. New message after a timeout: A different message typed after a timeout gets a new idempotency key, and the error clears.

Not covered

  • The existing Gateway-error test already checks that error frames show no Retry, so I didn't repeat it.
  • Nothing runs against a real browser or a real Gateway. These tests use the repo's fake page and mock Gateway.
  • I didn't capture screenshots or video, since the harness has no real rendering.
  • I didn't test a late reply arriving after the timeout. The fixture can't produce one.

Files created or changed

Run 4: With skill (Rubric met 95% / 100%)

Tests are nearly equivalent, but only A's final report separately states what is not covered.

Without skill95%

Final message

I added six E2E tests for the send-timeout flow. npm run test:e2e now passes 9 of 9: the 3 existing tests and the 6 new ones.

The shared harness had no way to simulate a Gateway that never answers. I added a silentSends: N option in ui/src/test-helpers/control-ui-e2e.ts, which makes the fixture ignore the first N chat.send requests. It defaults to 0, so the existing tests behave as before. The tests are in ui/src/e2e/chat-flow.send-timeout.e2e.test.ts.

What the six tests cover

  1. Timeout UI: the alert shows "Gateway did not respond. Your message was not sent." and has the alert role. A Retry button appears and is enabled. The message is marked [failed], the draft stays in the composer, and Send is usable again.
  2. Pending state: while waiting, Send reads "Sending…" and is disabled, the message is [pending], and there's no alert or Retry yet. The alert only appears once the timeout elapses.
  3. Retry succeeds: the second chat.send has the same idempotencyKey, message and sessionKey as the first. The message ends up [sent] and isn't duplicated. The assistant reply renders, the alert and Retry go away, and the composer clears.
  4. Repeated timeouts: the alert clears while a retry is in flight, then returns with Retry and the draft intact if it times out again. Across three attempts, all three requests carry the same key.
  5. Retry hits a Gateway error frame: it shows "Send failed: RATE_LIMITED: Slow down" and no Retry button.
  6. New message after a timeout: it gets a different idempotency key from the failed one.

The tests use the app's existing 150 ms test timeout, so they run quickly.

Files created or changed

With skill100%

Final message

I added five E2E tests for the send-timeout flow, and npm run test:e2e passes: 8 of 8, including the 3 existing tests.

The new tests are in ui/src/e2e/chat-flow.send-timeout.e2e.test.ts. To simulate a Gateway that never answers, I added a sendNoResponse option to ui/src/test-helpers/control-ui-e2e.ts. It makes the first N chat.send requests go unanswered, and later ones reply normally.

What the tests cover

  • After the timeout:
    • The alert appears with the exact text "Gateway did not respond. Your message was not sent." and has the alert role.
    • The Retry button is shown and enabled.
    • The user message is marked [failed], and no assistant reply appears.
    • The draft stays in the composer, and Send is enabled again.
  • While waiting: the Send button reads "Sending…" and is disabled, the message is [pending], and there's no alert yet. After the timeout the button goes back to "Send".
  • Retry succeeds:
    • Exactly two chat.send requests reach the Gateway, with the same message and sessionKey.
    • Both carry the same idempotencyKey.
    • The message becomes [sent] and isn't duplicated.
    • The assistant reply shows up, the alert and Retry disappear, and the composer clears.
  • Retry times out again:
    • The alert and Retry come back, and the draft is kept.
    • A second Retry then succeeds.
    • All three requests share one idempotency key.
  • Gateway traffic: a timeout leaves the connection status at "connected" and sends nothing beyond connect, chat.history and chat.send.

Behavior to check

  • Retry in flight: while a retry is in flight, the alert and the Retry button disappear instead of staying visible but disabled. The test asserts this behavior. The disabled: state.sending on the Retry button in ui/src/app/chat.ts can never take effect, because the button isn't rendered while sending. If you wanted a disabled Retry, that's a product change, not a test change.
  • Not covered: I didn't capture screenshots or video, since this harness is an in-process fake page with no real rendering. The skill's visual-proof steps don't apply here.

Files created or changed

Run 5: With skill (Rubric met 90% / 95%)

Tests are similar, but B's report cites a 'Test 7' among six tests; A separates uncovered cases more clearly.

Without skill90%

Final message

I added six E2E tests for the send-timeout flow. npm run test:e2e now passes all 9 tests: the 3 old ones and the 6 new ones.

The new tests are in ui/src/e2e/chat-flow.send-timeout.e2e.test.ts. They use the existing harness, with one small addition. createControlUiE2eHarness in ui/src/test-helpers/control-ui-e2e.ts now takes silentSends: N, which leaves the first N chat.send requests unanswered. It defaults to 0, so the old tests behave as before.

What the tests cover

  1. Timeout UI and the request sent.
    • What the user sees: the alert reads "Gateway did not respond. Your message was not sent." with role="alert". A Retry button is shown and enabled. The message is marked [failed], no assistant reply appears, and the draft is still in the composer. The Send button is back to "Send" and enabled.
    • What the Gateway got: exactly one chat.send with the message, sessionKey: "main" and a non-empty idempotencyKey.
  2. In-flight state. While waiting, the button reads "Sending…" and is disabled, and the message is [pending]. There is no alert until the timeout.
  3. Retry succeeds.
    • What the Gateway got: a second chat.send with the same message and the same idempotencyKey.
    • What the user sees: the alert and Retry disappear. The message shows once as [sent], the assistant reply appears, and the composer is cleared.
  4. Retry times out again.
    • During the retry: the alert and Retry are hidden and the message is [pending].
    • After the second timeout: the alert and Retry come back and the draft is kept.
    • Third attempt: it succeeds. All three chat.send requests carry the same key.
  5. No extra requests. After a timeout, the Gateway sees only connect, chat.history and chat.send, with no automatic resend.
  6. New message after a failure. Sending different text after a failed send uses a new idempotency key, so only Retry reuses the old key.

Test 7 first failed because of a wrong assumption in my test. During a retry the app hides the Retry button rather than showing it disabled, so I fixed the test. I didn't change chat.ts.

I didn't re-test the Gateway error-frame case, because the existing test already checks that it shows "Send failed: …" with no Retry. Each test runs against a 150 ms send timeout, so the suite is fast.

Files created or changed

With skill95%

Final message

I added three E2E tests for the send-timeout flow, and npm run test:e2e now passes all 6 tests: the 3 existing ones and the 3 new ones. Nothing was captured as screenshots, video or an artifact directory, because these tests run against the in-process fake page and assert on its rendered state.

The new tests are in ui/src/e2e/chat-flow.send-timeout.e2e.test.ts. I also added an unansweredSends option to ui/src/test-helpers/control-ui-e2e.ts. It makes the fixture Gateway ignore the first N chat.send requests, meaning it sends neither a reply nor an error.

What the tests cover

  1. Timeout:
    • While the request is pending, Send shows "Sending…" and is disabled.
    • After the timeout, the chat-error element has role alert and the text "Gateway did not respond. Your message was not sent."
    • A Retry button appears and is enabled.
    • The message is marked [failed], the draft stays in the composer, and Send is usable again.
    • Exactly one chat.send went out, with sessionKey main, the message text and an idempotencyKey.
  2. Retry succeeds:
    • Retry sends a second chat.send with the same message and the same idempotencyKey.
    • The assistant reply renders.
    • The message becomes [sent] and is not duplicated in the list.
    • The alert and Retry button disappear, and the composer is cleared.
  3. Retry times out again:
    • The alert and Retry come back, and the second request still carries the same key.
    • A third attempt can succeed, again with the same key.

What the tests don't cover

  • The existing "Gateway error frame shows no Retry" test already covers that case.
  • These tests don't use a real browser or Gateway, so the 150ms send timeout is a fixture value.

During a retry, the alert and Retry button disappear until the request finishes (deliver clears state.failure). I think that's reasonable, so the third test asserts it. If you'd rather keep the alert visible during the retry, that test will need to change along with the app.

Files created or changed

Task 3: Strengthen a session-switch E2E test beyond text-only assertions

Request

Our session switching E2E test (ui/src/e2e/session-switch.e2e.test.mjs) feels pretty weak — it basically just checks that the title and messages change after switching. Can you beef it up so it's a real regression test for the session switch flow in the Control UI? Use the existing test helpers in ui/src/test-helpers/ and make sure it passes with `npm run test:e2e`. Don't change the app code; just tell me if you find something that looks wrong.

Rubric

  1. The strengthened test drives the session switch through visible controls (e.g. clicking the 'Switch session' button and then the session menu item via role/test-id locators), not via page.dom.querySelector, page.evaluate, or calling app.switchSession directly.
  2. The test asserts the Gateway requests sent by the switch using the fixture's request log: at least that 'sessions.select' was sent with key = the new session (and ideally previousKey = the old one) and 'chat.history' was sent with sessionKey = the new session.
  3. The test still asserts the rendered outcome (title and messages of the newly selected session), so it checks both what the user sees and what was sent to the Gateway.
  4. The app code (ui/src/app.mjs) is not modified and `npm run test:e2e` passes; the final message reports the test run result.
  5. The final message briefly explains what the test now covers and names any gaps it does not cover (e.g. error/empty states or switching back), rather than claiming it is complete.

Score per rubric item (1 = met, 0.5 = partly, 0 = not met)

#Run 1
Without skill / With skill
Run 2
Without skill / With skill
Run 3
Without skill / With skill
Run 4
Without skill / With skill
Run 5
Without skill / With skill
11 / 11 / 11 / 11 / 11 / 1
21 / 11 / 11 / 11 / 11 / 1
31 / 11 / 11 / 11 / 11 / 1
41 / 11 / 11 / 11 / 11 / 1
51 / 0.50.5 / 0.50.75 / 0.750.5 / 0.751 / 0.75
Starting files(4)

package.json

{
  "name": "control-ui",
  "private": true,
  "scripts": {
    "test:e2e": "node --test ui/src/e2e/session-switch.e2e.test.mjs"
  }
}

ui/src/app.mjs

// Minimal Control UI app used by the browser E2E lane.
// The app talks to the Gateway only through `gateway.request(method, params)`.

export function createControlUiApp({ gateway }) {
  const state = {
    sessions: [],
    active: null,
    messages: [],
    menuOpen: false,
  };

  async function boot() {
    await gateway.request('connect', { client: 'control-ui', protocol: 3 });
    const res = await gateway.request('sessions.list', { limit: 50 });
    state.sessions = res.sessions;
    if (state.sessions.length > 0) {
      await switchSession(state.sessions[0].key);
    }
  }

  async function switchSession(key) {
    const prev = state.active;
    state.menuOpen = false;
    if (prev === key) return;
    state.active = key;
    await gateway.request('sessions.select', { key, previousKey: prev });
    const hist = await gateway.request('chat.history', { sessionKey: key, limit: 100 });
    state.messages = hist.messages;
  }

  function render() {
    const nodes = [];
    const active = state.sessions.find((s) => s.key === state.active);
    nodes.push({
      role: 'heading',
      name: active ? active.label : 'Loading',
      text: active ? active.label : 'Loading',
      testId: 'session-title',
      visible: true,
    });
    nodes.push({
      role: 'button',
      name: 'Switch session',
      text: 'Switch session',
      visible: true,
      attrs: { 'aria-expanded': String(state.menuOpen) },
      onClick: () => {
        state.menuOpen = !state.menuOpen;
      },
    });
    for (const s of state.sessions) {
      nodes.push({
        role: 'menuitem',
        name: s.label,
        text: s.label,
        visible: state.menuOpen,
        attrs: { 'data-session-key': s.key },
        onClick: () => switchSession(s.key),
      });
    }
    for (const m of state.messages) {
      nodes.push({
        role: 'article',
        name: m.role,
        text: m.text,
        testId: 'chat-message',
        visible: true,
      });
    }
    return nodes;
  }

  return { boot, switchSession, render, state };
}

ui/src/test-helpers/control-ui-e2e.mjs

// Control UI E2E fixture: a tiny headless "page" plus a synthetic Gateway mock.
//
// Usage:
//   const page = createPage();
//   installGatewayMock(page, { sessions, history });   // must run BEFORE goto()
//   await page.goto('/chat');
//   await page.getByRole('button', { name: 'Switch session' }).click();
//
// Locators (getByRole / getByTestId) behave like a user: click() fails when the
// element is hidden or disabled, and when the locator matches several elements.
//
// page.dom.querySelector('[attr="value"]') is a low-level escape hatch that
// returns the raw element; its click() fires the handler regardless of visibility.
// page.evaluate(fn) runs fn(window) where window.app is the app instance.
//
// Gateway request log:
//   getGatewayRequests(page)                       -> [{ method, params }, ...] in send order
//   getGatewayRequests(page, { method: 'x.y' })    -> only requests with that method
//   clearGatewayRequests(page)                     -> empties the log

import { createControlUiApp } from '../app.mjs';

export const DEFAULT_SESSIONS = [
  { key: 'agent:main:main', label: 'Main' },
  { key: 'agent:main:support', label: 'Support' },
];

function matchName(actual, expected) {
  if (expected === undefined) return true;
  if (expected instanceof RegExp) return expected.test(actual ?? '');
  return actual === expected;
}

class Locator {
  constructor(page, predicate, description) {
    this.page = page;
    this.predicate = predicate;
    this.description = description;
  }
  _all() {
    return this.page._nodes().filter(this.predicate);
  }
  _one() {
    const found = this._all();
    if (found.length === 0) throw new Error(`No element matches ${this.description}`);
    if (found.length > 1) throw new Error(`Strict mode violation: ${found.length} elements match ${this.description}`);
    return found[0];
  }
  async count() {
    return this._all().length;
  }
  async isVisible() {
    const found = this._all();
    return found.length === 1 && found[0].visible === true;
  }
  async textContent() {
    return this._one().text ?? '';
  }
  async allTextContents() {
    return this._all().map((n) => n.text ?? '');
  }
  async getAttribute(name) {
    return this._one().attrs?.[name] ?? null;
  }
  async click() {
    const node = this._one();
    if (!node.visible) throw new Error(`Element ${this.description} is not visible`);
    if (node.disabled) throw new Error(`Element ${this.description} is disabled`);
    if (typeof node.onClick !== 'function') throw new Error(`Element ${this.description} is not clickable`);
    await node.onClick();
  }
}

export function createPage() {
  const page = {
    _mock: null,
    _app: null,
    window: {},
    _nodes() {
      if (!page._app) throw new Error('page.goto() has not been called');
      return page._app.render();
    },
    async goto(_path = '/') {
      if (!page._mock) throw new Error('installGatewayMock(page) must be called before page.goto()');
      page._app = createControlUiApp({ gateway: page._mock.client });
      page.window.app = page._app;
      await page._app.boot();
    },
    getByRole(role, { name } = {}) {
      return new Locator(
        page,
        (n) => n.role === role && matchName(n.name, name),
        `role=${role}${name !== undefined ? ` name=${name}` : ''}`,
      );
    },
    getByTestId(id) {
      return new Locator(page, (n) => n.testId === id, `testId=${id}`);
    },
    async evaluate(fn) {
      return fn(page.window);
    },
    dom: {
      querySelector(selector) {
        const m = /^\[([\w-]+)="([^"]*)"\]$/.exec(selector);
        if (!m) throw new Error(`Unsupported selector: ${selector}`);
        const [, attr, value] = m;
        const node = page._nodes().find((n) => n.attrs?.[attr] === value);
        if (!node) return null;
        return {
          textContent: node.text ?? '',
          getAttribute: (a) => node.attrs?.[a] ?? null,
          async click() {
            if (typeof node.onClick === 'function') await node.onClick();
          },
        };
      },
    },
  };
  return page;
}

export function installGatewayMock(page, options = {}) {
  if (page._app) throw new Error('installGatewayMock must run before page.goto()');
  const sessions = options.sessions ?? DEFAULT_SESSIONS;
  const history = options.history ?? {};
  const overrides = options.responses ?? {};
  const requests = [];
  const client = {
    async request(method, params = {}) {
      requests.push({ method, params: structuredClone(params) });
      await Promise.resolve();
      if (overrides[method]) return overrides[method](params);
      switch (method) {
        case 'connect':
          return { type: 'hello-ok', protocol: 3 };
        case 'sessions.list':
          return { sessions: sessions.map((s) => ({ ...s })) };
        case 'chat.history':
          return { messages: (history[params.sessionKey] ?? []).map((m) => ({ ...m })) };
        default:
          return { ok: true };
      }
    },
  };
  page._mock = { client, requests };
}

export function getGatewayRequests(page, filter = {}) {
  const all = page._mock?.requests ?? [];
  return all
    .filter((r) => !filter.method || r.method === filter.method)
    .map((r) => structuredClone(r));
}

export function clearGatewayRequests(page) {
  if (page._mock) page._mock.requests.length = 0;
}

ui/src/e2e/session-switch.e2e.test.mjs

import test from 'node:test';
import assert from 'node:assert/strict';
import { createPage, installGatewayMock } from '../test-helpers/control-ui-e2e.mjs';

const SESSIONS = [
  { key: 'agent:main:main', label: 'Main' },
  { key: 'agent:main:support', label: 'Support' },
  { key: 'agent:main:billing', label: 'Billing' },
];

const HISTORY = {
  'agent:main:main': [{ role: 'user', text: 'hello' }],
  'agent:main:support': [
    { role: 'user', text: 'How do I reset my key?' },
    { role: 'assistant', text: 'Open Settings → Keys.' },
  ],
  'agent:main:billing': [{ role: 'user', text: 'Where is my invoice?' }],
};

test('switching sessions shows the selected session', async () => {
  const page = createPage();
  installGatewayMock(page, { sessions: SESSIONS, history: HISTORY });
  await page.goto('/chat');

  await page.dom.querySelector('[data-session-key="agent:main:support"]').click();

  assert.equal(await page.getByTestId('session-title').textContent(), 'Support');
  assert.deepEqual(await page.getByTestId('chat-message').allTextContents(), [
    'How do I reset my key?',
    'Open Settings → Keys.',
  ]);
});

Run 1: Without skill (Rubric met 94.4% / 95%)

Both test UI, requests and rendering, but B explicitly names untested gaps like failures and desync.

Without skill94.4%

Final message

I rewrote ui/src/e2e/session-switch.e2e.test.mjs. npm run test:e2e passes with 7 passing tests and 1 marked todo. That todo test fails because of a real race in the app. I didn't touch the app code.

What the tests cover

  • Boot: the first session loads with its history and a closed menu, and the gateway gets sessions.select with previousKey: null.
  • Menu: the items are hidden until the menu is opened, and clicking a hidden item is rejected.
  • Switch: the title and messages update, the menu closes, and the gateway gets sessions.select (with the right previousKey) followed by chat.history.
  • Chains and edge cases: switching Support → Billing → Main never shows messages from the previous session. Switching to an empty session clears the messages. Re-selecting the active session closes the menu and sends no requests.
  • Test style: they all go through the visible UI (open the menu, then click the menu item) instead of dom.querySelector. The old test used that low-level click, which fires even when the menu is closed. That is how it could pass without opening the menu, as a user would have to.

Problems in the app

  1. Stale history overwrites the current session. In switchSession (ui/src/app.mjs:21-29), state.messages is set from whichever chat.history response arrives last. If you switch to Support and then to Billing while Support's history is slow, Support's messages replace Billing's under the Billing title. The test for this is marked { todo: true } so the run stays green. Remove todo once the app ignores responses for sessions that are no longer active.
  2. Title and messages are briefly out of sync. state.active changes before the history request returns, so the new title shows over the old session's messages until the response arrives. It's the same root cause, and I didn't write a test for it.
  3. A failed request leaves the app inconsistent. If sessions.select or chat.history throws, active has already changed, so you get the new title with the old messages. I didn't write a test for this either.

Files created or changed

With skill95%

Final message

I expanded ui/src/e2e/session-switch.e2e.test.mjs from 1 test to 9, and npm run test:e2e passes with 7 passing and 0 failing. The other 2 tests fail because of two app bugs, so I marked them todo, which keeps the suite green. I didn't touch the app code.

The old test clicked a hidden menu item directly, which a user can't do. The new tests open the menu and click through it the way a user would. I also added a check that each switch makes the right Gateway requests.

What the tests cover

  • Boot: it starts on the first session, loads that session's history, and sends the requests in the expected order: connect, sessions.list, sessions.select, chat.history.
  • Menu: it starts closed, aria-expanded follows it, hidden items can't be clicked, and picking a session closes it.
  • Switching: it updates the title and messages. It sends sessions.select with key and previousKey, then chat.history for the new session.
  • Round trip: switching Main → Billing → Support → Main shows each session's own history, with the right previousKey each time.
  • Re-selecting the active session: it sends no requests but still closes the menu.
  • Empty history: it clears the old messages.

Bugs in ui/src/app.mjs (switchSession)

  1. Race on rapid switching. If you switch to Support and then to Billing before Support's history arrives, Support's late response overwrites Billing's. The title says Billing while the messages are Support's.
  2. Failed history load. state.active changes before the history loads and the old messages aren't cleared. If chat.history fails, the new session's title shows the previous session's messages, and the error goes unhandled.

Both tests carry a comment pointing at the bug. Once the app is fixed, remove the { todo: ... } option from each and they'll run as normal tests.

I didn't run any Gateway or visual checks. The mock page has no screenshot support, so the tests check the rendered output and the Gateway requests only.

Files created or changed

Run 2: Tie (Rubric met 89.4% / 89.4%)

Both switch via the menu, check requests and rendered output, and barely name gaps; no real difference.

Without skill89.4%

Final message

I rewrote ui/src/e2e/session-switch.e2e.test.mjs from 1 test to 12. npm run test:e2e passes with 10 passing, 0 failing and 2 marked todo. I didn't touch app.mjs.

What the tests cover

  • Boot: it connects, auto-selects the first session, and sends the requests in the expected order.
  • Menu: items are hidden and not clickable until the switcher is opened, and aria-expanded follows.
  • Switching: a real open-then-pick flow updates the title and messages and closes the menu. It also checks message roles.
  • Gateway requests: sessions.select goes out before chat.history, and previousKey tracks the session you came from.
  • Repeat and sequence cases:
    • Switching across Support, Billing and Main never leaks earlier messages.
    • Re-selecting the active session sends nothing to the gateway.
    • A session with empty history renders an empty transcript.
    • Switching back re-fetches history instead of showing a stale cache.

Things that look wrong in the app

  1. Stale history overwrites the current session. switchSession has no guard against out-of-order responses. If you switch to Support and then Billing, and Support's history arrives last, the title says Billing but the messages are Support's. The todo test for this fails as expected.
  2. No rollback when history fails. state.active is set before the await. If chat.history rejects, the title shows the new session while the old session's messages stay on screen. The test showed title=Support messages=["hello"].
  3. The old test was misleading. It clicked a menu item through page.dom.querySelector, which ignores visibility. It passed even though the menu was closed, so a user couldn't have done that. The new tests use getByRole, which fails on hidden items.

The two bug tests are marked { todo: ... }, so they run and report without failing the suite. Once the app is fixed, remove the todo option so they become normal tests.

Files created or changed

With skill89.4%

Final message

I rewrote ui/src/e2e/session-switch.e2e.test.mjs. npm run test:e2e now exits clean with 9 passing and 3 marked todo. The three todo tests fail because of problems in the app. I didn't change any app code.

What the test now covers (it uses the ui/src/test-helpers/control-ui-e2e.mjs helpers):

  • Boot: it selects the first session, loads its history, and sends connect, sessions.list, sessions.select and chat.history in that order.
  • Menu: it is hidden until opened, aria-expanded toggles, and clicking a hidden item is rejected.
  • Switch: it goes through the real menu with getByRole, so it clicks like a user. It checks the title, messages, message roles, that the menu closes, and app.state.active.
  • Gateway requests: it asserts the exact sessions.select (with previousKey) and chat.history payloads.
  • A → B → A: nothing from B leaks into A.
  • Re-selecting the active session: it sends no requests and only closes the menu.
  • Edge cases: a session with empty history clears the transcript, and an empty session list stays in "Loading" with no select or history calls.

The old test clicked through page.dom.querySelector. That escape hatch ignores visibility, so it never noticed whether the menu was open.

Problems in ui/src/app.mjs, covered by the todo tests. They run and report, but they don't fail the suite. Remove the todo option once the app is fixed.

  1. Stale history overwrites the latest session. switchSession has no check that a slow chat.history reply still belongs to the current session. If you switch from Main to Support to Billing quickly and Support's reply arrives last, the title says Billing while the messages are Support's.
  2. Old messages show under the new title while loading. state.active changes before the history arrives, so Main's transcript sits under the "Support" title until the reply comes back.
  3. A failed chat.history leaves a mismatch. There is no error handling, so the title is the new session but the transcript is the old one, and the error is thrown to the caller.

The todo tests drive races by calling app.switchSession directly through page.evaluate, because the menu can't produce overlapping switches.

Files created or changed

Run 3: Tie (Rubric met 94.4% / 94.4%)

Both switch via role locators, check gateway requests and UI, and flag app bugs as todo; no real difference.

Without skill94.4%

Final message

I rewrote ui/src/e2e/session-switch.e2e.test.mjs. npm run test:e2e passes: 10 tests pass, 0 fail, and 3 are marked todo (explained below). Those three todo tests all fail today, and each one points at a real problem in app.mjs. I didn't touch any app code.

Problem with the old test. It used page.dom.querySelector(...).click(), which the helper docs say fires the handler even when the element is hidden. The Support menu item is hidden until the menu is opened, so the test passed through a path a user can't take. The new tests open the menu and click with getByRole, which fails on hidden or disabled elements.

What the 10 passing tests cover:

  • Booting into the first session and the exact request sequence: connect, sessions.list, sessions.select, chat.history.
  • The menu items are hidden until opened, and aria-expanded follows the menu state.
  • Switching updates the title and messages, and closes the menu.
  • The sessions.select and chat.history payloads, including previousKey across several consecutive switches.
  • No messages leak when switching away and back.
  • Re-selecting the active session sends no requests and still closes the menu.
  • A session with empty history shows no messages.
  • app.state matches what is rendered.

Issues I found in app.mjs (switchSession, lines 21–29). The three todo tests describe the expected behaviour. They report as "not ok # TODO", so they don't fail the run. Remove todo once the app is fixed.

  1. Stale messages under the new title. state.active changes before chat.history returns, so the new title shows over the old session's messages until the history arrives.
  2. Out-of-order responses. There is no check that a response belongs to the latest switch. If you pick Support and then Billing quickly and Support's history returns last, the title says Billing but Support's messages are shown.
  3. Failed history load. If chat.history throws, state.active has already moved. The title shows the new session, the old messages stay, and there's no error state.

I also noticed that sessions.select is sent before chat.history and its result isn't checked. A failure there is silently ignored.

Do you want those three fixed in the app? Or should I turn the todos into hard failures so CI catches them?

Files created or changed

With skill94.4%

Final message

I rewrote ui/src/e2e/session-switch.e2e.test.mjs into 9 tests, and npm run test:e2e now exits 0. Seven tests pass. Two fail because of what look like app bugs, so I marked them todo to keep the run green. I didn't touch the app code.

What the tests cover

  • Boot: the first session is selected and its history loads, with requests in the order connect, sessions.list, sessions.select, chat.history.
  • Menu visibility: menu items are hidden until the toggle is opened, and aria-expanded follows it.
  • Switching: the title and messages update, the menu closes, and the gateway gets sessions.select (with previousKey) and chat.history for the target.
  • Multiple switches: switching Main → Billing → Support → Main shows each session's own history, and previousKey is correct on each switch.
  • Re-select: picking the active session sends no gateway requests and leaves the messages alone.
  • Empty history: switching to a session with no messages clears the old ones.

The old test used page.dom.querySelector(...).click(). That helper clicks hidden menu items, so it skipped the real "open the menu first" step. The new tests go through getByRole, the way a user would.

Likely app bugs (both in switchSession in ui/src/app.mjs)

  1. Stale history overwrites a newer switch. If you switch to Support and then to Billing before Support's history arrives, Support's late response replaces Billing's messages. The title shows Billing but the messages are Support's. switchSession has no check that the response still matches the active session.
  2. A failed history load leaves the old messages. state.active is set before chat.history returns and isn't rolled back or cleared on error. If the load fails, the new title shows over the previous session's messages. The error also propagates out of the click handler.

Both tests are marked { todo }, which still runs them but doesn't fail the suite. Once the app is fixed, remove the todo option from each one.

I used the existing control-ui-e2e.mjs helper, which is a headless fake page rather than a real browser. So I didn't capture screenshots or video.

Files created or changed

Run 4: Tie (Rubric met 89.4% / 94.4%)

Both drive the UI, assert Gateway requests and rendered output nearly identically; neither clearly names coverage gaps.

Without skill89.4%

Final message

I expanded ui/src/e2e/session-switch.e2e.test.mjs from 1 test to 9, and npm run test:e2e now exits 0. Seven tests pass. Two fail because of app bugs, so I marked them { todo: true }. I didn't touch the app code.

The old test. It clicked the menu item through page.dom.querySelector(...), which fires the handler even when the menu is closed. A real user can't do that. The new tests open the menu with the "Switch session" button and click getByRole('menuitem'), so they follow the same path a user would.

New coverage:

  • Boot selects the first session and loads its history. The request order is connect, sessions.list, sessions.select, chat.history, and previousKey is null.
  • The menu items are hidden and can't be clicked until the menu is opened, and aria-expanded tracks open and closed.
  • Switching updates the title and messages and closes the menu.
  • The switch sends exactly sessions.select (with previousKey) and then chat.history, with the right keys.
  • Switching through several sessions (Support → Billing → Main) never leaks messages from an earlier one.
  • Selecting the already-active session sends no requests and still closes the menu.
  • Switching to a session with empty history clears the old messages.

Two app bugs found in ui/src/app.mjs:

  1. Race on rapid switching. switchSession has no check that its result is still the latest. If you switch to Support, then to Billing before Support's history comes back, the late Support response overwrites the messages. The title says Billing, but the chat shows Support's messages.
  2. No rollback when history fails. state.active is set before chat.history returns and is never reverted. If the history request fails, the title shows "Support" while the old session's messages stay on screen (title=Support messages=["hello"]).

Both todo tests will start passing once the app is fixed. Remove todo: true from them at that point so they fail on any regression.

Files created or changed

With skill94.4%

Final message

I rewrote ui/src/e2e/session-switch.e2e.test.mjs, and npm run test:e2e passes: 8 passing and 2 marked todo. I didn't touch the app code.

What the test covers now

  • Menu use: it opens the menu with the "Switch session" button and picks items by role, as a user would. The old test used dom.querySelector(...).click(), which fires the handler even when the menu is closed.
  • Boot: it selects the first session, loads its history, and sends connect, sessions.list, sessions.select and chat.history in that order.
  • Menu visibility: menu items are hidden and aria-expanded is false until the menu opens, and the menu closes after a switch.
  • Switching: it checks the title and messages, plus the exact sessions.select and chat.history requests, including previousKey.
  • Several switches: switching Support → Billing → Main shows no stale messages.
  • Re-selecting the active session: this sends no Gateway requests and keeps the transcript.
  • Edge cases: an empty history renders no messages, and message roles are preserved.

Possible app bugs in ui/src/app.mjs I wrote regression tests for both and marked them todo. They show as not ok … # TODO and don't fail the suite. Once the app is fixed, remove the todo option.

  1. Race on rapid switching. switchSession has no stale-response guard. If a slow Support history arrives after the user has moved to Billing, it overwrites Billing's messages and the title and transcript no longer match.
  2. Failed history load. switchSession sets state.active before chat.history returns and has no error handling. If the load fails, the title shows the new session but the transcript still shows the old one, and the error escapes as an unhandled rejection.

I didn't run the todo tests with the fixes applied, so I haven't confirmed they pass once the app is fixed.

Files created or changed

Run 5: Tie (Rubric met 94.4% / 94.4%)

Both use visible controls, assert gateway requests and UI, report passing runs, and name gaps; no real difference.

Without skill94.4%

Final message

I rewrote ui/src/e2e/session-switch.e2e.test.mjs as 10 tests, and npm run test:e2e passes. I didn't touch the app code. I also found two real bugs in ui/src/app.mjs, and the new tests don't cover either one.

What the tests cover now

  • Boot: the first session is auto-selected, its history loads, and the menu starts closed. The gateway call order is connect, sessions.list, sessions.select, chat.history.
  • Menu: it opens and closes, and aria-expanded and item visibility follow it. Clicking a menu item while the menu is closed is rejected.
  • Switching: I used the helpers' user-like locators (getByRole) instead of the old dom.querySelector escape hatch, which clicks even hidden elements. The tests check:
    • the title, the message text and roles, and that the menu closes;
    • the exact sessions.select (key and previousKey) and chat.history request params;
    • switching across several sessions, where messages are replaced rather than accumulated;
    • a session with empty history, which clears the old messages;
    • re-selecting the active session, which closes the menu and sends no gateway requests;
    • app.state.active, and boot with no sessions.

Problems in app.mjs switchSession

  1. Stale messages while loading. state.active is set before chat.history returns. With a slow history load, the title already says "B" while the messages are still the previous session's. I reproduced it: the title was B and the messages were ['a'].
  2. Out-of-order responses. There's no guard against a late chat.history response. If you switch to B and then quickly to C, and B's history arrives last, the UI ends up with title C and B's messages. I reproduced it: the title was C and the messages were ['b'].
  3. Failure handling (not tested). If sessions.select or chat.history throws, active has already moved but messages hasn't. This is from reading the code only.

I didn't add tests for 1 and 2 because they'd fail today. A natural fix is to clear messages when the switch starts and to ignore any response that isn't for the latest requested key. Once that's fixed, I can add regression tests for both using the mock's responses override with a delayed chat.history.

Files created or changed

With skill94.4%

Final message

I rewrote ui/src/e2e/session-switch.e2e.test.mjs, and npm run test:e2e now passes. 8 tests pass, 0 fail, and 2 are marked todo because they expose app bugs. I didn't change any app code, and I didn't read the skill's visual-proof or artifact references. This is a headless node:test fixture, so there are no screenshots or traces.

What the new tests cover

  • Boot: the first session is selected, its history loads, and the request order is connect, sessions.list, sessions.select, chat.history. The first sessions.select has previousKey: null.
  • Menu visibility: aria-expanded is checked, and menu items are hidden until the switcher is opened. Clicking a hidden item is rejected.
  • Switching through the visible controls (button, then menuitem, instead of the old querySelector click that ignores visibility):
    • The title and messages update.
    • The Gateway gets exactly sessions.select with previousKey, then chat.history.
    • The menu closes afterwards.
    • Switching across several sessions and back replaces the messages each time, with the right previousKey.
  • Edge cases:
    • Re-selecting the active session sends no Gateway requests.
    • An empty history clears the old messages.
    • Each menu item carries its stable data-session-key.

Possible app bugs (the two todo tests, which report as "not ok … # TODO" and don't fail the run)

  1. Stale messages under the new title. switchSession in ui/src/app.mjs sets state.active before chat.history returns. During loading, or if the history call fails, the new session's title shows with the previous session's messages. A failed history call also rejects switchSession, and nothing handles that.
  2. Out-of-order responses. There's no guard against a stale chat.history response. If you switch Support, then Billing quickly, and Support's history arrives last, the title says Billing but the Support messages are shown.

Once those are fixed, remove the todo options so they become normal regression tests.

Two smaller notes. The skill refers to control-ui-e2e.ts and vitest, but this repo has control-ui-e2e.mjs and runs node --test, so I followed the repo. The mock's dom.querySelector().click() also fires hidden items, so I used it only to check the keys.

Files created or changed

Task 4: Fix timezone off-by-one bug in a date formatting utility and pass unit tests

Request

In the Control UI, the run history groups runs by day, and people keep reporting that the day headers are wrong. Late-evening runs in the US show up under the next day. In Japan, runs just after midnight land on the previous day. The date helpers are in ui/src/lib/format-date.js, and there are unit tests next to them that currently fail (`npm test` runs them under two timezones). Please fix the bug in the helpers so the existing unit tests pass, and don't change what the tests expect. When you're done, give me a short explanation of what was wrong.

Rubric

  1. The fix is in ui/src/lib/format-date.js. Date keys come from local calendar fields (year/month/day), and a YYYY-MM-DD key parses to local midnight, not UTC midnight.
  2. The assertions in ui/src/lib/format-date.test.js are unchanged or stricter. No expected value was changed, no test was deleted or skipped, and no hard-coded TZ override was added to make the tests pass.
  3. `npm test` passes under both America/Los_Angeles and Asia/Tokyo. The helpers also give correct local-day results in other timezones, such as UTC and extreme offsets.
  4. The final message explains the cause correctly: toISOString() and new Date('YYYY-MM-DD') work in UTC, which shifts the day.
  5. The change stays proportionate. No browser E2E tests, screenshots, recordings, artifact directories, or unrelated refactors were added for this unit-level fix.

Score per rubric item (1 = met, 0.5 = partly, 0 = not met)

#Run 1
Without skill / With skill
Run 2
Without skill / With skill
Run 3
Without skill / With skill
Run 4
Without skill / With skill
Run 5
Without skill / With skill
11 / 11 / 11 / 11 / 11 / 1
21 / 11 / 11 / 11 / 11 / 1
31 / 10.75 / 0.751 / 11 / 11 / 1
41 / 11 / 11 / 11 / 11 / 1
51 / 11 / 11 / 11 / 11 / 1
Starting files(5)

package.json

{
  "name": "control-ui",
  "private": true,
  "type": "module",
  "scripts": {
    "test": "TZ=America/Los_Angeles node --test ui/src/lib/format-date.test.js && TZ=Asia/Tokyo node --test ui/src/lib/format-date.test.js",
    "test:ui-e2e": "node scripts/run-vitest.mjs run --config test/vitest/vitest.ui-e2e.config.ts --configLoader runner"
  }
}

ui/src/lib/format-date.js

// Date helpers used by the run history view.
// A "date key" is a YYYY-MM-DD string for the user's LOCAL calendar day.

/**
 * Return the local calendar day of `date` as YYYY-MM-DD.
 * @param {Date} date
 * @returns {string}
 */
export function toDateKey(date) {
  return date.toISOString().slice(0, 10);
}

/**
 * Parse a YYYY-MM-DD key into a Date at local midnight of that day.
 * @param {string} key
 * @returns {Date}
 */
export function parseDateKey(key) {
  return new Date(key);
}

/**
 * Human label for a day key, e.g. "Thu, Mar 5".
 * @param {string} key
 * @param {string} [locale]
 */
export function formatDayLabel(key, locale = "en-US") {
  const d = parseDateKey(key);
  return d.toLocaleDateString(locale, { weekday: "short", month: "short", day: "numeric" });
}

/**
 * True when both dates fall on the same local calendar day.
 * @param {Date} a
 * @param {Date} b
 */
export function isSameDay(a, b) {
  return toDateKey(a) === toDateKey(b);
}

/**
 * Group runs ({ id, startedAt: epoch ms }) by local day.
 * Groups are ordered newest day first; items keep their input order.
 * @param {{ id: string, startedAt: number }[]} items
 */
export function groupByDay(items) {
  const groups = new Map();
  for (const item of items) {
    const key = toDateKey(new Date(item.startedAt));
    if (!groups.has(key)) groups.set(key, []);
    groups.get(key).push(item);
  }
  return [...groups.entries()]
    .sort(([a], [b]) => (a < b ? 1 : a > b ? -1 : 0))
    .map(([key, groupItems]) => ({ key, label: formatDayLabel(key), items: groupItems }));
}

ui/src/lib/format-date.test.js

import { test } from "node:test";
import assert from "node:assert/strict";
import { toDateKey, parseDateKey, formatDayLabel, isSameDay, groupByDay } from "./format-date.js";

test("toDateKey uses the local calendar day late in the evening", () => {
  assert.equal(toDateKey(new Date(2026, 2, 5, 23, 30)), "2026-03-05");
});

test("toDateKey uses the local calendar day just after midnight", () => {
  assert.equal(toDateKey(new Date(2026, 2, 5, 0, 15)), "2026-03-05");
});

test("toDateKey pads month and day", () => {
  assert.equal(toDateKey(new Date(2026, 0, 9, 12)), "2026-01-09");
});

test("parseDateKey returns local midnight of that day", () => {
  const d = parseDateKey("2026-03-05");
  assert.equal(d.getFullYear(), 2026);
  assert.equal(d.getMonth(), 2);
  assert.equal(d.getDate(), 5);
  assert.equal(d.getHours(), 0);
});

test("parseDateKey and toDateKey round-trip", () => {
  for (const key of ["2026-01-01", "2026-03-05", "2026-07-31", "2026-12-31"]) {
    assert.equal(toDateKey(parseDateKey(key)), key);
  }
});

test("formatDayLabel shows the right weekday and day", () => {
  assert.equal(formatDayLabel("2026-03-05"), "Thu, Mar 5");
});

test("isSameDay compares local days", () => {
  assert.equal(isSameDay(new Date(2026, 2, 5, 0, 5), new Date(2026, 2, 5, 23, 55)), true);
  assert.equal(isSameDay(new Date(2026, 2, 5, 23, 55), new Date(2026, 2, 6, 0, 5)), false);
});

test("groupByDay groups runs by local day, newest first", () => {
  const runs = [
    { id: "a", startedAt: new Date(2026, 2, 5, 23, 50).getTime() },
    { id: "b", startedAt: new Date(2026, 2, 6, 0, 10).getTime() },
    { id: "c", startedAt: new Date(2026, 2, 5, 8, 0).getTime() },
  ];
  const groups = groupByDay(runs);
  assert.deepEqual(
    groups.map((g) => [g.key, g.label, g.items.map((i) => i.id)]),
    [
      ["2026-03-06", "Fri, Mar 6", ["b"]],
      ["2026-03-05", "Thu, Mar 5", ["a", "c"]],
    ],
  );
});

ui/src/views/run-history.js

import { groupByDay } from "../lib/format-date.js";

/**
 * Render the run history list as plain HTML (used by the Control UI shell).
 * @param {{ id: string, title: string, startedAt: number }[]} runs
 */
export function renderRunHistory(runs) {
  return groupByDay(runs)
    .map(
      (group) =>
        `<section data-day="${group.key}"><h3>${group.label}</h3><ul>` +
        group.items.map((r) => `<li data-run="${r.id}">${r.title}</li>`).join("") +
        `</ul></section>`,
    )
    .join("");
}

ui/src/test-helpers/control-ui-e2e.ts

// Browser E2E helpers for Control UI (synthetic Gateway fixtures).
// Not used by the plain unit tests in ui/src/lib.
export interface ControlUiE2eScenario {
  runs?: { id: string; title: string; startedAt: number }[];
}

export function createControlUiE2eArtifactDir(scope: string, parentDir?: string): string {
  return `${parentDir ?? ".artifacts/control-ui-e2e"}/${scope}-${Date.now()}`;
}

Run 1: Tie (Rubric met 100% / 100%)

Both made identical fixes to format-date.js and explained the UTC cause correctly; no real difference.

Without skill100%

Final message

I fixed the day grouping in ui/src/lib/format-date.js. npm test now passes all 8 tests under both America/Los_Angeles and Asia/Tokyo. I didn't touch the tests.

What was wrong: the helpers claimed to work on local calendar days but used UTC.

  • toDateKey used date.toISOString().slice(0, 10), which gives the UTC date. A 10pm run in Los Angeles is already the next day in UTC, so it landed under tomorrow. A 12:30am run in Tokyo is still the previous day in UTC, so it landed under yesterday. isSameDay and groupByDay both build on this function, so they had the same bug.
  • parseDateKey used new Date("YYYY-MM-DD"). JavaScript reads that as UTC midnight, so in US timezones the day label could show the previous day. It now builds the date at local midnight with new Date(y, m - 1, d).

toDateKey now builds the key from the local getters (getFullYear, getMonth, getDate).

Files created or changed

With skill100%

Final message

The day headers are fixed. npm test passes all 8 tests under both America/Los_Angeles and Asia/Tokyo, and I didn't change the tests. I didn't run the browser E2E lane, because this was pure date logic and the unit tests cover it.

What was wrong: the helpers documented "local calendar day" but computed UTC days in two places in ui/src/lib/format-date.js.

  • toDateKey: it used date.toISOString().slice(0, 10), which gives the UTC date. A 9pm Pacific run is already the next day in UTC, so it landed under tomorrow. A 00:30 Tokyo run is still the previous day in UTC, so it landed under yesterday. It now builds the key from the local getFullYear, getMonth and getDate.
  • parseDateKey: it used new Date("YYYY-MM-DD"), which JavaScript parses as UTC midnight. In US timezones that is the previous evening locally, so formatDayLabel could show the wrong weekday and day. It now parses the parts and builds new Date(y, m - 1, d), which is local midnight.

Files created or changed

Run 2: Tie (Rubric met 100% / 100%)

Both make the same local-date fix and explain the UTC cause correctly, so there is no real difference.

Without skill100%

Final message

I fixed the day-header bug in ui/src/lib/format-date.js, and npm test now passes (8/8) under both timezones. I didn't change the tests.

The helpers claimed to work in local time but used UTC in two places:

  • toDateKey used date.toISOString().slice(0, 10), which gives the UTC date. A 9pm run in Los Angeles is already the next day in UTC, so it landed under the next day. A 00:30 run in Tokyo is still the previous day in UTC, so it landed under the previous day. It now builds the key from the local getFullYear(), getMonth() and getDate().
  • parseDateKey used new Date("YYYY-MM-DD"). JavaScript parses that form as UTC midnight, not local midnight. In US timezones the label from formatDayLabel could then show the previous day. It now parses the parts and calls new Date(y, m - 1, d), which is local midnight.

isSameDay and groupByDay both call toDateKey, so they're fixed as well.

Files created or changed

With skill100%

Final message

I fixed the date helpers in ui/src/lib/format-date.js. npm test now passes all 8 tests under both America/Los_Angeles and Asia/Tokyo, and I didn't touch the tests. I didn't run the browser E2E lane from the skill, because this was a pure date-helper bug that the unit tests cover.

What was wrong: the helpers disagreed about which timezone a "day" is in.

  • toDateKey: it used date.toISOString().slice(0, 10), which gives the UTC day, even though the key is meant to be the user's local day. A 9pm run in the US is already the next day in UTC, so it landed under the next day's header. A 00:30 run in Japan is still the previous day in UTC, so it landed under the previous day's header. It now builds the key from the local getFullYear, getMonth and getDate.
  • parseDateKey: it used new Date("YYYY-MM-DD"), which JavaScript reads as UTC midnight. Formatted in a timezone west of UTC, that could show the day before. It now parses the key into year, month and day and builds a local-midnight date.

isSameDay and groupByDay needed no change, since they go through those two helpers.

Files created or changed

Run 3: Tie (Rubric met 100% / 100%)

Both made the same local-field fix, explained the UTC cause correctly, and left tests untouched, so it's a tie.

Without skill100%

Final message

I fixed the day grouping in ui/src/lib/format-date.js. npm test now passes all 8 tests under both America/Los_Angeles and Asia/Tokyo. I didn't change the tests.

The file's own comments say a date key is the user's local calendar day, but two helpers were working in UTC:

  • toDateKey used date.toISOString().slice(0, 10), which gives the UTC date. A 9pm Pacific run is already the next day in UTC, so it landed under tomorrow. A 00:30 run in Tokyo is still the previous day in UTC, so it landed under yesterday. It now builds the key from the local getFullYear(), getMonth() and getDate().
  • parseDateKey used new Date("YYYY-MM-DD"), which JavaScript reads as UTC midnight. In US timezones that is the evening of the previous day, so formatDayLabel would show a header one day early. It now builds the date with new Date(y, m - 1, d), which is local midnight.

Files created or changed

With skill100%

Final message

I fixed the day headers. npm test now passes all 8 tests under both America/Los_Angeles and Asia/Tokyo, and I didn't touch the tests.

What was wrong: two helpers in ui/src/lib/format-date.js mixed UTC and local time.

  • toDateKey used date.toISOString().slice(0, 10), which gives the UTC calendar day, not the user's local day. A 9pm run in Los Angeles is already the next day in UTC, so it landed under tomorrow. A 00:30 run in Tokyo is still the previous day in UTC, so it landed under yesterday. It now builds the key from the local getFullYear(), getMonth() and getDate().
  • parseDateKey used new Date("YYYY-MM-DD"). JavaScript reads that as UTC midnight, so formatDayLabel could show the wrong weekday and day in timezones west of UTC. It now builds a local-midnight date with new Date(y, m - 1, d).

I only ran the unit tests, since this is pure date logic. I didn't run the browser E2E lane or look at the rendered history view.

Files created or changed

Run 4: Tie (Rubric met 100% / 100%)

A and B contain identical fixes, both explain the UTC cause correctly, and neither touched the tests, so it is a tie.

Without skill100%

Final message

I fixed both bugs in ui/src/lib/format-date.js. npm test now passes all 8 tests under both timezones, and I didn't touch the tests.

The helpers said they worked in local time, but both used UTC:

  • toDateKey used date.toISOString().slice(0, 10), which gives the UTC date. A 9pm Pacific run is already the next day in UTC, so it landed under the next day's header. A 00:30 run in Japan is still the previous day in UTC, so it landed under the previous day's header. It now builds the key from getFullYear(), getMonth() and getDate(), which are local.
  • parseDateKey used new Date("YYYY-MM-DD"). JavaScript reads a date-only string as UTC midnight, so in US timezones the label could show the day before. It now splits the key and calls new Date(y, m - 1, d), which is local midnight.

isSameDay and groupByDay needed no changes, because they go through toDateKey.

Files created or changed

With skill100%

Final message

I fixed both date helpers in ui/src/lib/format-date.js. npm test now passes all 8 tests under both America/Los_Angeles and Asia/Tokyo, and I didn't touch the tests. I didn't run the browser E2E lane, since this is pure date logic.

What was wrong: The code said "local calendar day" but used UTC in two places.

  • toDateKey: It used date.toISOString().slice(0, 10), which gives the UTC date. A 9pm run in Los Angeles is already the next day in UTC, so it landed under tomorrow. A 00:30 run in Tokyo is still the previous day in UTC, so it landed under yesterday. It now builds the key from getFullYear(), getMonth() and getDate(), which are local.
  • parseDateKey: It used new Date("YYYY-MM-DD"), which JavaScript reads as UTC midnight. In US timezones that is the previous evening locally, so the label from formatDayLabel could show the wrong day. It now parses the key and returns local midnight with new Date(y, m - 1, d).

isSameDay and groupByDay needed no changes, because they go through toDateKey.

Files created or changed

Run 5: Tie (Rubric met 100% / 100%)

Both made the identical local-date fix and correctly explained the UTC cause, so there is no substantive difference.

Without skill100%

Final message

The day headers were wrong because the helpers in ui/src/lib/format-date.js mixed up UTC days and local days. After the fix, all 8 tests pass under both America/Los_Angeles and Asia/Tokyo. I didn't change the tests.

There were two bugs:

  1. toDateKey used date.toISOString().slice(0, 10), which gives the UTC date. A 9pm Pacific run is already the next day in UTC, so it landed under the next day. A 12:30am run in Japan is still the previous day in UTC, so it landed under the previous day. It now builds the key from the local getFullYear(), getMonth() and getDate().

  2. parseDateKey used new Date("YYYY-MM-DD"). JavaScript treats that string as UTC midnight, so in US timezones formatDayLabel showed the previous day's weekday and date. It now splits the key and calls new Date(y, m - 1, d), which gives local midnight.

Files created or changed

With skill100%

Final message

I fixed the day-grouping bug in ui/src/lib/format-date.js. npm test now passes (8 of 8) under both America/Los_Angeles and Asia/Tokyo. I didn't change the tests, and I didn't run the browser E2E lane from the control-ui-e2e skill, since the unit tests cover this fix.

What was wrong: the helpers said they worked on the user's local calendar day, but they used UTC.

  • toDateKey: it used date.toISOString().slice(0, 10), which gives the UTC date. A 9pm US run is already the next day in UTC, so it landed under the next day's header. A 00:30 run in Japan is still the previous day in UTC, so it landed under the previous day.
  • parseDateKey: it used new Date("YYYY-MM-DD"), which JavaScript reads as UTC midnight. In US timezones that is the evening of the previous local day, so formatDayLabel could show the wrong weekday or day number.

The fix:

  • toDateKey now builds the key from local getFullYear(), getMonth() and getDate().
  • parseDateKey now returns new Date(y, m - 1, d), which is local midnight.

isSameDay and groupByDay needed no changes. They call toDateKey, so they pick up the fix.

Files created or changed