#!/usr/bin/env bash
# Issue #17363: an async pi-subagents run (`subagent({ agent, task, async: true })`) never shows in
# T3 Code's subagent UI, because the launch returns `details = { mode: "single", asyncId, results: [] }`.
# Claim: already fixed by #36599 (75c544a978). The Pi adapter now tracks any launch that returns an
# asyncId and no results, and projects its members from pi-subagents' `subagent-async` widget.
# Shows: before #36599 the issue's launch frame plus widget snapshots produce no subagent;
# at #36599 and on main the same frames produce one running "echo" subagent that settles completed.
# Needs deps installed (`vp i`). Run from the root of a clean t3code checkout.
set -euo pipefail

ok=1
pass() { echo "PASS  $*"; }
fail() { echo "FAIL  $*"; ok=0; }

if [ -n "$(git status --porcelain)" ]; then
  echo "refusing to run on a dirty tree"
  exit 2
fi
ORIG=$(git symbolic-ref -q --short HEAD || git rev-parse HEAD)
TEST=packages/provider-pi/src/server/adapter.test.ts
LOG=$(mktemp)
cleanup() {
  git checkout -q -- "$TEST" 2>/dev/null || true
  rm -f "$LOG"
  git checkout -q -f "$ORIG"
}
trap 'rc=$?; cleanup; [ "${PROOF_DONE:-0}" = 1 ] && exit 0; [ "$rc" -ne 0 ] && exit "$rc"; exit 1' EXIT

git fetch -q origin main
MAIN=$(git rev-parse FETCH_HEAD)
FIX=75c544a9788651e885ff82f5c0c50bf4180b7fdb
BEFORE=$(git rev-parse "$FIX^")
echo "main=$MAIN fix=$FIX before=$BEFORE"

subject=$(git log -1 --format=%s "$FIX")
if git merge-base --is-ancestor "$FIX" "$MAIN" \
  && [ "$subject" = "fix(pi): async pi-subagents workflow, chain and parallel members show as subagents (#36599)" ]; then
  pass "#36599 ($(git rev-parse --short "$FIX")) is on main: $subject"
else
  fail "#36599 is not on main, or $FIX is a different commit ($subject)"
fi

# Same harness as the file's own "shows the members of an async pi-subagents workflow" case,
# fed the launch frame from the issue (mode "single", results []).
append_test() {
  cat >> "$TEST" <<'EOF'

describe("prove-issue-17363", () => {
  it.effect("prove-issue-17363", () =>
    Effect.gen(function* () {
      const fake = yield* makeFakePi;
      const { runtime, takeEvent } = yield* openRuntime(fake);
      const providerThread = yield* runtime.ensureThread({
        threadId: THREAD_ID,
        modelSelection: modelSelection("default"),
        runtimePolicy,
      });
      yield* startTurn(runtime, providerThread);
      yield* fake.takeRequest("prompt");
      yield* fake.emit({ type: "agent_start" });
      const asyncId = "00000000-0000-4000-8000-000000000005";
      const snapshot = (state: string) =>
        fake.emit({
          type: "extension_ui_request",
          id: `widget-${state}`,
          method: "setWidget",
          widgetKey: "subagent-async",
          widgetLines: [
            `PI_SUBAGENT_ASYNC_JSON:${JSON.stringify({
              kind: "pi-subagents.async-status-snapshot",
              version: 1,
              generatedAt: 2_000,
              runs: [
                {
                  id: asyncId,
                  kind: "single",
                  label: "echo",
                  state,
                  startedAt: 1_000,
                  updatedAt: 2_000,
                  children: [
                    {
                      id: "step:0",
                      kind: "step",
                      label: "echo",
                      state,
                      startedAt: 1_000,
                      updatedAt: 2_000,
                      agent: "echo",
                      model: "openai-codex/gpt-6.1-sol",
                    },
                  ],
                },
              ],
            })}`,
          ],
        });
      const collect = (marker: string) =>
        Effect.gen(function* () {
          yield* fake.emit({
            type: "tool_execution_end",
            toolCallId: marker,
            toolName: marker,
            result: { content: [{ type: "text", text: "after" }] },
          });
          const subagents: Array<string> = [];
          const pending: Array<boolean> = [];
          while (true) {
            const event = yield* takeEvent(
              (event) =>
                event.type === "subagent.updated" ||
                event.type === "background_work.updated" ||
                (event.type === "turn_item.updated" &&
                  event.turnItem.type === "dynamic_tool" &&
                  event.turnItem.toolName === marker),
            );
            if (event.type === "background_work.updated") pending.push(event.pending);
            else if (event.type === "subagent.updated")
              subagents.push(`${event.subagent.title}:${event.subagent.status}`);
            else break;
          }
          return { subagents, pending };
        });
      // The issue's launch frame: an async single run returns no results.
      yield* fake.emit({
        type: "tool_execution_end",
        toolCallId: "call_async",
        toolName: "subagent",
        isError: false,
        result: {
          content: [{ type: "text", text: `Async: echo [${asyncId}]` }],
          details: {
            mode: "single",
            runId: asyncId,
            results: [],
            asyncId,
            asyncDir: `/tmp/async-subagent-runs/${asyncId}`,
          },
        },
      });
      yield* snapshot("running");
      const running = yield* collect("marker-1");
      yield* snapshot("complete");
      const settled = yield* collect("marker-2");
      if (process.env.PROOF_EXPECT === "bug") {
        assert.deepEqual(running, { subagents: [], pending: [] });
        assert.deepEqual(settled, { subagents: [], pending: [] });
      } else {
        assert.deepEqual(running, { subagents: ["echo:running"], pending: [true] });
        assert.deepEqual(settled, { subagents: ["echo:completed"], pending: [false] });
      }
    }).pipe(Effect.scoped, Effect.provide(layerTest)),
  );
});
EOF
}

run_at() {
  git checkout -q --detach "$1"
  append_test
  local rc=0
  PROOF_EXPECT="$2" vp test run "$TEST" -t "prove-issue-17363" > "$LOG" 2>&1 || rc=$?
  git checkout -q -- "$TEST"
  if [ "$rc" -eq 0 ] && ! grep -Eq 'Tests +1 passed' "$LOG"; then rc=3; fi
  if [ "$rc" -ne 0 ]; then sed 's#'"$HOME"'#~#g' "$LOG" | tail -25; fi
  return "$rc"
}

if run_at "$BEFORE" bug; then
  pass "before #36599 ($(git rev-parse --short "$BEFORE")): the async launch and both widget snapshots (running, complete) produce no subagent and no background work"
else
  fail "before #36599: the async launch was not invisible"
fi
if run_at "$FIX" fixed; then
  pass "#36599 ($(git rev-parse --short "$FIX")): the same frames produce subagent \"echo\" running, then completed, and hold background work until it settles"
else
  fail "#36599: the async launch did not show as a running subagent that settles"
fi
if run_at "$MAIN" fixed; then
  pass "main ($(git rev-parse --short "$MAIN")): the same frames produce subagent \"echo\" running, then completed, and hold background work until it settles"
else
  fail "main: the async launch did not show as a running subagent that settles"
fi

if [ "$ok" = 1 ]; then
  echo "VERDICT: #17363 is fixed on main by #36599"
  PROOF_DONE=1; exit 0
fi
echo "VERDICT: not shown"
exit 1
