Skip to content

DemoT3Backend

🛈 DocStrings

In-memory T3 backend that streams realistic events, approvals, and replies.

Source code in src/acptui/t3/demo.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
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

create_thread async

create_thread(
    project_id: str, title: str, *, model_selection: Mapping[str, JsonValue]
) -> tuple[str, int]

Create a new thread in project_id.

Source code in src/acptui/t3/demo.py
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

respond_to_request async

respond_to_request(
    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.

Source code in src/acptui/t3/demo.py
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

send_message async

send_message(
    thread_id: str, text: str, *, model_selection: Mapping[str, JsonValue] | None = None
) -> int

Record the user message and stream a simulated assistant reply.

Source code in src/acptui/t3/demo.py
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

stop_thread async

stop_thread(thread_id: str) -> int

Cancel the simulated reply if one is running.

Source code in src/acptui/t3/demo.py
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()

subscribe_shell async

subscribe_shell(*, after_sequence: int | None = None) -> AsyncIterator[ShellStreamItem]

Yield initial snapshot, synchronized marker, then live thread updates.

Source code in src/acptui/t3/demo.py
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)

subscribe_thread async

subscribe_thread(
    thread_id: str, *, after_sequence: int | None = None
) -> AsyncIterator[ThreadStreamItem]

Yield thread snapshot, synchronized marker, then live thread events.

Source code in src/acptui/t3/demo.py
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)

visit_thread async

visit_thread(thread_id: str) -> int

Record a visit timestamp.

Source code in src/acptui/t3/demo.py
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()

:fa-brands-github: Show source on GitHub