class DemoT3Backend:
"""In-memory T3 backend that streams realistic events, approvals, and replies."""
def __init__(self, *, stream_delay: float = 0.08) -> None:
self._delay = stream_delay
self._seq = 100
self._shell_queues: list[asyncio.Queue[ShellStreamItem]] = []
self._thread_queues: dict[str, list[asyncio.Queue[ThreadStreamItem]]] = {}
self._active_tasks: dict[str, asyncio.Task[None]] = {}
self._projects: dict[str, ProjectShell] = {
"proj-acptui": ProjectShell(
id="proj-acptui",
title="acptui",
workspace_root="/home/dev/oss/acptui",
default_model_selection={
"instanceId": "claude-main",
"model": "claude-sonnet-4-5",
},
),
"proj-pyt3": ProjectShell(
id="proj-pyt3",
title="pyt3client",
workspace_root="/home/dev/oss/pyt3client",
default_model_selection={
"instanceId": "codex-main",
"model": "gpt-5.3-codex",
},
),
}
self._threads: dict[str, ThreadShell] = {
"thr-approval": ThreadShell(
id="thr-approval",
project_id="proj-acptui",
title="Clean up stale build artifacts",
status="waiting",
branch="feat/t3-tui",
model_selection={"instanceId": "claude-main", "model": "claude-sonnet-4-5"},
pending_runtime_request=PendingRuntimeRequestSummary(
request_id="req-clean-1",
kind="command",
prompt="rm -rf dist/ .cache/old-build",
),
latest_visible_message=LatestVisibleMessageSummary(
text="Waiting for approval: rm -rf dist/ .cache/old-build",
role="assistant",
),
updated_at="2026-11-24T05:30:00Z",
),
"thr-streaming": ThreadShell(
id="thr-streaming",
project_id="proj-pyt3",
title="Add subscribeShell native stream",
status="completed",
branch="main",
pinned_at="2026-11-24T05:00:00Z",
model_selection={"instanceId": "codex-main", "model": "gpt-5.3-codex"},
latest_visible_message=LatestVisibleMessageSummary(
text="Added `subscribe_shell()` and 210 tests pass.",
role="assistant",
),
updated_at="2026-11-24T05:25:00Z",
),
"thr-review": ThreadShell(
id="thr-review",
project_id="proj-acptui",
title="Investigate slow Markdown rendering",
status="idle",
branch="perf/markdown",
model_selection={"instanceId": "claude-main", "model": "claude-opus-4-5"},
latest_visible_message=LatestVisibleMessageSummary(
text="StreamingMarkdown.sync() batches updates cleanly.",
role="assistant",
),
updated_at="2026-11-24T04:50:00Z",
),
}
self._items: dict[str, list[TurnItem]] = {
"thr-approval": [
TurnItem(
id="item-a1",
thread_id="thr-approval",
type="user_message",
status="completed",
text="Remove the stale build directories so `uv build` starts fresh.",
),
TurnItem(
id="item-a2",
thread_id="thr-approval",
type="reasoning",
status="completed",
text="Checking `dist/` and `.cache/old-build` before running `rm -rf`.",
),
TurnItem(
id="item-a3",
thread_id="thr-approval",
type="approval_request",
status="waiting",
request_id="req-clean-1",
request_kind="command",
title="Run shell command",
prompt="rm -rf dist/ .cache/old-build",
reason="Deletes two build directories inside the workspace.",
options=[
ApprovalOption(decision="accept", label="Allow once"),
ApprovalOption(decision="acceptForSession", label="Allow for session"),
ApprovalOption(decision="decline", label="Decline"),
],
),
],
"thr-streaming": [
TurnItem(
id="item-s1",
thread_id="thr-streaming",
type="user_message",
status="completed",
text="Add `subscribe_shell()` and command helpers to `pyt3client.native`.",
),
TurnItem(
id="item-s2",
thread_id="thr-streaming",
type="command_execution",
status="completed",
title="uv run pytest -q",
text="210 passed, 6 skipped in 0.74s",
),
TurnItem(
id="item-s3",
thread_id="thr-streaming",
type="assistant_message",
status="completed",
streaming=False,
text=(
"Done! Added `subscribe_shell()`, `send_message()`, `stop_thread()`, "
"`visit_thread()`, and `create_thread()` to `T3NativeClient`.\n\n"
"- **Tests:** 210 passed\n"
"- **Typecheck:** `ty check` clean"
),
),
],
"thr-review": [
TurnItem(
id="item-r1",
thread_id="thr-review",
type="user_message",
status="completed",
text="Why did streaming Markdown lag on large diffs?",
),
TurnItem(
id="item-r2",
thread_id="thr-review",
type="assistant_message",
status="completed",
streaming=False,
text=(
"Appending tiny chunks forced a re-parse per token. Syncing to the "
"latest full text (`StreamingMarkdown.sync()`) keeps frame times low."
),
),
],
}
self._runs: dict[str, list[Run]] = {tid: [] for tid in self._threads}
def _next_seq(self) -> int:
self._seq += 1
return self._seq
def _emit_shell(self, item: ShellStreamItem) -> None:
for queue in list(self._shell_queues):
queue.put_nowait(item)
def _emit_thread(self, thread_id: str, item: ThreadStreamItem) -> None:
for queue in list(self._thread_queues.get(thread_id, [])):
queue.put_nowait(item)
def _upsert_item(self, thread_id: str, item: TurnItem) -> int:
items = self._items.setdefault(thread_id, [])
for idx, existing in enumerate(items):
if existing.id == item.id:
items[idx] = item
break
else:
items.append(item)
seq = self._next_seq()
self._emit_thread(
thread_id,
ThreadEvent(
kind="event",
sequence=seq,
event=DomainEvent(
type="turn-item.updated",
thread_id=thread_id,
payload=item.model_dump(by_alias=True, exclude_none=True),
),
),
)
return seq
def _update_thread_shell(self, thread: ThreadShell) -> int:
self._threads[thread.id] = thread
seq = self._next_seq()
self._emit_shell(
ShellThreadUpdated(
kind="thread.updated",
sequence=seq,
location="active",
thread=thread,
)
)
return seq
async def subscribe_shell(
self, *, after_sequence: int | None = None
) -> AsyncIterator[ShellStreamItem]:
"""Yield initial snapshot, synchronized marker, then live thread updates."""
_ = after_sequence
queue: asyncio.Queue[ShellStreamItem] = asyncio.Queue()
self._shell_queues.append(queue)
try:
yield ShellSnapshot(
kind="snapshot",
snapshot=ShellSnapshotData(
schema_version=2,
snapshot_sequence=self._seq,
projects=list(self._projects.values()),
threads=list(self._threads.values()),
archived_threads=[],
),
)
yield ShellSynchronized(kind="synchronized")
while True:
yield await queue.get()
finally:
if queue in self._shell_queues:
self._shell_queues.remove(queue)
async def subscribe_thread(
self, thread_id: str, *, after_sequence: int | None = None
) -> AsyncIterator[ThreadStreamItem]:
"""Yield thread snapshot, synchronized marker, then live thread events."""
_ = after_sequence
queue: asyncio.Queue[ThreadStreamItem] = asyncio.Queue()
self._thread_queues.setdefault(thread_id, []).append(queue)
try:
items = [
it.model_dump(by_alias=True, exclude_none=True)
for it in self._items.get(thread_id, [])
]
runs = [
r.model_dump(by_alias=True, exclude_none=True)
for r in self._runs.get(thread_id, [])
]
yield ThreadSnapshot(
kind="snapshot",
snapshot_sequence=self._seq,
projection={"turnItems": items, "runs": runs},
)
yield ThreadSynchronized(kind="synchronized")
while True:
yield await queue.get()
finally:
queues = self._thread_queues.get(thread_id, [])
if queue in queues:
queues.remove(queue)
async def send_message(
self,
thread_id: str,
text: str,
*,
model_selection: Mapping[str, JsonValue] | None = None,
) -> int:
"""Record the user message and stream a simulated assistant reply."""
_ = model_selection
seq = self._upsert_item(
thread_id,
TurnItem(
id=f"item-u-{uuid4().hex[:8]}",
thread_id=thread_id,
type="user_message",
status="completed",
text=text,
),
)
task = asyncio.create_task(self._simulate_reply(thread_id, text))
self._active_tasks[thread_id] = task
return seq
async def _simulate_reply(self, thread_id: str, prompt: str) -> None:
thread = self._threads.get(thread_id)
if thread is None:
return
run_id = f"run-{uuid4().hex[:8]}"
self._update_run(thread_id, Run(id=run_id, thread_id=thread_id, status="running"))
self._update_thread_shell(
thread.model_copy(
update={
"status": "running",
"active_run_id": run_id,
"updated_at": _iso_now(),
}
)
)
reply_id = f"item-m-{uuid4().hex[:8]}"
chunks = [
"Got it! ",
f"Looking at **{prompt.strip()[:60]}**.\n\n",
"- Checked workspace state\n",
"- Everything looks good on `t3tui`.",
]
acc = ""
try:
for chunk in chunks:
if self._delay > 0:
await asyncio.sleep(self._delay)
acc += chunk
self._upsert_item(
thread_id,
TurnItem(
id=reply_id,
thread_id=thread_id,
run_id=run_id,
type="assistant_message",
status="running",
streaming=True,
text=acc,
),
)
self._upsert_item(
thread_id,
TurnItem(
id=reply_id,
thread_id=thread_id,
run_id=run_id,
type="assistant_message",
status="completed",
streaming=False,
text=acc,
),
)
self._update_run(thread_id, Run(id=run_id, thread_id=thread_id, status="completed"))
latest = self._threads[thread_id]
self._update_thread_shell(
latest.model_copy(
update={
"status": "completed",
"active_run_id": None,
"latest_visible_message": LatestVisibleMessageSummary(
text=acc.splitlines()[0], role="assistant"
),
"updated_at": _iso_now(),
}
)
)
except asyncio.CancelledError:
self._update_run(thread_id, Run(id=run_id, thread_id=thread_id, status="interrupted"))
latest = self._threads[thread_id]
self._update_thread_shell(
latest.model_copy(
update={
"status": "interrupted",
"active_run_id": None,
"updated_at": _iso_now(),
}
)
)
raise
def _update_run(self, thread_id: str, run: Run) -> None:
runs = self._runs.setdefault(thread_id, [])
for idx, existing in enumerate(runs):
if existing.id == run.id:
runs[idx] = run
break
else:
runs.append(run)
self._emit_thread(
thread_id,
ThreadEvent(
kind="event",
sequence=self._next_seq(),
event=DomainEvent(
type="run.updated",
thread_id=thread_id,
run_id=run.id,
payload=run.model_dump(by_alias=True, exclude_none=True),
),
),
)
async def stop_thread(self, thread_id: str) -> int:
"""Cancel the simulated reply if one is running."""
task = self._active_tasks.pop(thread_id, None)
if task is not None and not task.done():
task.cancel()
return self._next_seq()
async def visit_thread(self, thread_id: str) -> int:
"""Record a visit timestamp."""
thread = self._threads.get(thread_id)
if thread is not None:
self._threads[thread_id] = thread.model_copy(update={"last_visited_at": _iso_now()})
return self._next_seq()
async def respond_to_request(
self,
thread_id: str,
request_id: str,
*,
decision: ApprovalDecision | None = None,
answers: Mapping[str, JsonValue] | None = None,
) -> int:
"""Resolve a pending approval request and emit a follow-up assistant note."""
_ = answers
for item in self._items.get(thread_id, []):
if item.request_id == request_id:
resolved = item.model_copy(update={"status": "completed"})
self._upsert_item(thread_id, resolved)
break
verb = (
"Approved" if decision in {"accept", "acceptForSession", "acceptAlways"} else "Declined"
)
reply = f"{verb} (`{decision}`). Cleanup finished."
seq = self._upsert_item(
thread_id,
TurnItem(
id=f"item-res-{uuid4().hex[:8]}",
thread_id=thread_id,
type="assistant_message",
status="completed",
streaming=False,
text=reply,
),
)
thread = self._threads.get(thread_id)
if thread is not None:
self._update_thread_shell(
thread.model_copy(
update={
"status": "completed",
"pending_runtime_request": None,
"latest_visible_message": LatestVisibleMessageSummary(
text=reply, role="assistant"
),
"updated_at": _iso_now(),
}
)
)
return seq
async def create_thread(
self,
project_id: str,
title: str,
*,
model_selection: Mapping[str, JsonValue],
) -> tuple[str, int]:
"""Create a new thread in `project_id`."""
tid = f"thr-{uuid4().hex[:8]}"
thread = ThreadShell(
id=tid,
project_id=project_id,
title=title,
status="idle",
model_selection=dict(model_selection),
created_at=_iso_now(),
updated_at=_iso_now(),
)
self._items[tid] = []
self._runs[tid] = []
seq = self._update_thread_shell(thread)
return tid, seq