Skip to content

t3

Class info

Re-exported classes

Class Module Description
ShellChange acptui.t3.state Summary of what changed after applying a :class:ShellStreamItem.
T3Backend acptui.t3.state Transport seam for the T3 TUI (implemented by live native RPC and demo mode).
ThreadTimelineState acptui.t3.state Live projection of a single open T3 thread.
TimelineChange acptui.t3.state One incremental change to a thread's timeline.
WorkspaceState acptui.t3.state Live workspace projection for the Telegram-style thread sidebar.

🛈 DocStrings

Telegram-like Textual TUI client for T3 Code environments.

ShellChange dataclass

Summary of what changed after applying a :class:ShellStreamItem.

Source code in src/acptui/t3/state.py
@dataclass(frozen=True)
class ShellChange:
    """Summary of what changed after applying a :class:`ShellStreamItem`."""

    changed: bool = True
    needs_resubscribe: bool = False
    attention_thread_id: str | None = None
    attention_reason: AttentionReason | None = None

T3Backend

Bases: Protocol

Transport seam for the T3 TUI (implemented by live native RPC and demo mode).

Source code in src/acptui/t3/state.py
class T3Backend(Protocol):
    """Transport seam for the T3 TUI (implemented by live native RPC and demo mode)."""

    def subscribe_shell(
        self, *, after_sequence: int | None = None
    ) -> AsyncIterator[ShellStreamItem]:
        """Stream workspace projects and threads."""
        ...

    def subscribe_thread(
        self, thread_id: str, *, after_sequence: int | None = None
    ) -> AsyncIterator[ThreadStreamItem]:
        """Stream a single thread's snapshot and live events."""
        ...

    async def send_message(
        self,
        thread_id: str,
        text: str,
        *,
        model_selection: Mapping[str, JsonValue] | None = None,
    ) -> int:
        """Send a user message to `thread_id`."""
        ...

    async def stop_thread(self, thread_id: str) -> int:
        """Stop the active run on `thread_id`."""
        ...

    async def visit_thread(self, thread_id: str) -> int:
        """Mark `thread_id` as visited."""
        ...

    async def respond_to_request(
        self,
        thread_id: str,
        request_id: str,
        *,
        decision: ApprovalDecision | None = None,
        answers: Mapping[str, JsonValue] | None = None,
    ) -> int:
        """Respond to a pending approval or user-input request."""
        ...

    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`."""
        ...

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/state.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`."""
    ...

respond_to_request async

respond_to_request(
    thread_id: str,
    request_id: str,
    *,
    decision: ApprovalDecision | None = None,
    answers: Mapping[str, JsonValue] | None = None,
) -> int

Respond to a pending approval or user-input request.

Source code in src/acptui/t3/state.py
async def respond_to_request(
    self,
    thread_id: str,
    request_id: str,
    *,
    decision: ApprovalDecision | None = None,
    answers: Mapping[str, JsonValue] | None = None,
) -> int:
    """Respond to a pending approval or user-input request."""
    ...

send_message async

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

Send a user message to thread_id.

Source code in src/acptui/t3/state.py
async def send_message(
    self,
    thread_id: str,
    text: str,
    *,
    model_selection: Mapping[str, JsonValue] | None = None,
) -> int:
    """Send a user message to `thread_id`."""
    ...

stop_thread async

stop_thread(thread_id: str) -> int

Stop the active run on thread_id.

Source code in src/acptui/t3/state.py
async def stop_thread(self, thread_id: str) -> int:
    """Stop the active run on `thread_id`."""
    ...

subscribe_shell

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

Stream workspace projects and threads.

Source code in src/acptui/t3/state.py
def subscribe_shell(
    self, *, after_sequence: int | None = None
) -> AsyncIterator[ShellStreamItem]:
    """Stream workspace projects and threads."""
    ...

subscribe_thread

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

Stream a single thread's snapshot and live events.

Source code in src/acptui/t3/state.py
def subscribe_thread(
    self, thread_id: str, *, after_sequence: int | None = None
) -> AsyncIterator[ThreadStreamItem]:
    """Stream a single thread's snapshot and live events."""
    ...

visit_thread async

visit_thread(thread_id: str) -> int

Mark thread_id as visited.

Source code in src/acptui/t3/state.py
async def visit_thread(self, thread_id: str) -> int:
    """Mark `thread_id` as visited."""
    ...

ThreadTimelineState dataclass

Live projection of a single open T3 thread.

Source code in src/acptui/t3/state.py
@dataclass
class ThreadTimelineState:
    """Live projection of a single open T3 thread."""

    thread_id: str
    items: dict[str, TurnItem] = field(default_factory=dict)
    order: list[str] = field(default_factory=list)
    runs: dict[str, Run] = field(default_factory=dict)
    requests: dict[str, RuntimeRequest] = field(default_factory=dict)
    sequence: int = 0
    synchronized: bool = False

    @property
    def is_running(self) -> bool:
        """Whether any run in this thread is currently active."""
        return any(
            r.status in {"preparing", "queued", "starting", "running"} for r in self.runs.values()
        )

    @property
    def ordered_items(self) -> list[TurnItem]:
        """Timeline items in display order."""
        return [self.items[item_id] for item_id in self.order if item_id in self.items]

    def apply(self, stream_item: ThreadStreamItem) -> list[TimelineChange]:
        """Apply one `subscribeThread` stream item."""
        if isinstance(stream_item, ThreadSnapshot):
            return self._apply_snapshot(stream_item)
        if isinstance(stream_item, ThreadEvent):
            return self._apply_event(stream_item)
        if isinstance(stream_item, ThreadSynchronized):
            self.synchronized = True
            return []
        return []

    def _apply_snapshot(self, snapshot: ThreadSnapshot) -> list[TimelineChange]:
        self.sequence = snapshot.snapshot_sequence
        self.items.clear()
        self.order.clear()
        self.runs.clear()
        self.requests.clear()

        proj = snapshot.projection
        raw_items = proj.get("turnItems") or proj.get("items") or []
        if isinstance(raw_items, list):
            for raw in raw_items:
                if isinstance(raw, dict):
                    item = TurnItem.model_validate(raw)
                    self._upsert_item(item)

        raw_runs = proj.get("runs") or []
        if isinstance(raw_runs, list):
            for raw in raw_runs:
                if isinstance(raw, dict):
                    run = Run.model_validate(raw)
                    self.runs[run.id] = run

        raw_requests = proj.get("runtimeRequests") or proj.get("pendingRuntimeRequests") or []
        if isinstance(raw_requests, list):
            for raw in raw_requests:
                if isinstance(raw, dict):
                    req = RuntimeRequest.model_validate(raw)
                    self.requests[req.id] = req

        return [TimelineChange(kind="reset")]

    def _apply_event(self, event_item: ThreadEvent) -> list[TimelineChange]:
        self.sequence = max(self.sequence, event_item.sequence)
        ev = event_item.event
        changes: list[TimelineChange] = []

        if (turn_item := ev.turn_item()) is not None:
            existed = turn_item.id in self.items
            self._upsert_item(turn_item)
            changes.append(
                TimelineChange(
                    kind="item_updated" if existed else "item_added", item_id=turn_item.id
                )
            )
        elif (run := ev.run()) is not None:
            self.runs[run.id] = run
            changes.append(TimelineChange(kind="status_changed"))
        elif (req := ev.runtime_request()) is not None:
            self.requests[req.id] = req
            changes.append(TimelineChange(kind="request_updated", request_id=req.id))

        return changes

    def _upsert_item(self, item: TurnItem) -> None:
        if item.id not in self.items:
            self.order.append(item.id)
        self.items[item.id] = item

is_running property

is_running: bool

Whether any run in this thread is currently active.

ordered_items property

ordered_items: list[TurnItem]

Timeline items in display order.

apply

apply(stream_item: ThreadStreamItem) -> list[TimelineChange]

Apply one subscribeThread stream item.

Source code in src/acptui/t3/state.py
def apply(self, stream_item: ThreadStreamItem) -> list[TimelineChange]:
    """Apply one `subscribeThread` stream item."""
    if isinstance(stream_item, ThreadSnapshot):
        return self._apply_snapshot(stream_item)
    if isinstance(stream_item, ThreadEvent):
        return self._apply_event(stream_item)
    if isinstance(stream_item, ThreadSynchronized):
        self.synchronized = True
        return []
    return []

TimelineChange dataclass

One incremental change to a thread's timeline.

Source code in src/acptui/t3/state.py
@dataclass(frozen=True)
class TimelineChange:
    """One incremental change to a thread's timeline."""

    kind: Literal["reset", "item_added", "item_updated", "status_changed", "request_updated"]
    item_id: str | None = None
    request_id: str | None = None

WorkspaceState dataclass

Live workspace projection for the Telegram-style thread sidebar.

Source code in src/acptui/t3/state.py
@dataclass
class WorkspaceState:
    """Live workspace projection for the Telegram-style thread sidebar."""

    projects: dict[str, ProjectShell] = field(default_factory=dict)
    threads: dict[str, ThreadShell] = field(default_factory=dict)
    archived_threads: dict[str, ThreadShell] = field(default_factory=dict)
    active_thread_id: str | None = None
    unread_ids: set[str] = field(default_factory=set)
    sequence: int = 0
    synchronized: bool = False

    def select_thread(self, thread_id: str | None) -> None:
        """Set the currently open thread and clear its unread badge."""
        self.active_thread_id = thread_id
        if thread_id is not None:
            self.unread_ids.discard(thread_id)

    def project_title(self, project_id: str) -> str:
        """Human-readable project name for `project_id`."""
        project = self.projects.get(project_id)
        return project.title if project is not None else project_id

    def apply_shell(self, item: ShellStreamItem) -> ShellChange:
        """Apply one `subscribeShell` stream item to workspace state."""
        result = ShellChange(changed=False)
        match item:
            case ShellSnapshot():
                snap = item.snapshot
                self.sequence = snap.snapshot_sequence
                self.projects = {p.id: p for p in snap.projects if p.archived_at is None}
                self.threads = {t.id: t for t in snap.threads if t.deleted_at is None}
                self.archived_threads = {
                    t.id: t for t in snap.archived_threads if t.deleted_at is None
                }
                result = ShellChange(changed=True)
            case ShellProjectUpdated():
                self.sequence = max(self.sequence, item.sequence)
                if item.project.archived_at is None:
                    self.projects[item.project.id] = item.project
                else:
                    self.projects.pop(item.project.id, None)
                result = ShellChange(changed=True)
            case ShellProjectRemoved():
                self.sequence = max(self.sequence, item.sequence)
                self.projects.pop(item.project_id, None)
                result = ShellChange(changed=True)
            case ShellThreadUpdated():
                result = self._apply_thread_updated(item)
            case ShellThreadRemoved():
                self.sequence = max(self.sequence, item.sequence)
                target = self.threads if item.location == "active" else self.archived_threads
                target.pop(item.thread_id, None)
                self.unread_ids.discard(item.thread_id)
                result = ShellChange(changed=True)
            case ShellSynchronized():
                self.synchronized = True
            case ShellSnapshotRequired():
                result = ShellChange(changed=False, needs_resubscribe=True)
            case _:
                pass
        return result

    def _apply_thread_updated(self, item: ShellThreadUpdated) -> ShellChange:
        self.sequence = max(self.sequence, item.sequence)
        thread = item.thread
        if item.location == "archive":
            self.threads.pop(thread.id, None)
            self.archived_threads[thread.id] = thread
            self.unread_ids.discard(thread.id)
            return ShellChange(changed=True)

        previous = self.threads.get(thread.id)
        self.archived_threads.pop(thread.id, None)
        if thread.deleted_at is not None:
            self.threads.pop(thread.id, None)
            self.unread_ids.discard(thread.id)
            return ShellChange(changed=True)

        self.threads[thread.id] = thread
        reason = _detect_attention(previous, thread)
        if reason is not None and thread.id != self.active_thread_id:
            self.unread_ids.add(thread.id)
            return ShellChange(changed=True, attention_thread_id=thread.id, attention_reason=reason)
        return ShellChange(changed=True)

    def sorted_threads(
        self, filter_text: str = "", *, project_id: str | None = None
    ) -> list[ThreadShell]:
        """Return active threads in Telegram-like priority order.

        Waiting threads and pinned threads bubble to the top, followed by running
        threads, then most recently updated threads.
        """
        query = filter_text.strip().lower()
        rows: list[ThreadShell] = []
        for thread in self.threads.values():
            if project_id is not None and thread.project_id != project_id:
                continue
            if query:
                proj = self.project_title(thread.project_id).lower()
                preview = (
                    thread.latest_visible_message.text.lower()
                    if thread.latest_visible_message and thread.latest_visible_message.text
                    else ""
                )
                if query not in thread.title.lower() and query not in proj and query not in preview:
                    continue
            rows.append(thread)

        def sort_key(t: ThreadShell) -> tuple[int, int, int, str]:
            waiting = 0 if thread_needs_attention(t) else 1
            pinned = 0 if t.pinned_at else 1
            running = 0 if thread_is_running(t) else 1
            # Reverse lexicographical ISO timestamp via negative ordinal isn't needed if we
            # sort in two passes; instead we sort descending by timestamp first.
            return (waiting, pinned, running, t.id)

        rows.sort(key=lambda t: t.updated_at or t.created_at or "", reverse=True)
        rows.sort(key=sort_key)
        return rows

apply_shell

apply_shell(item: ShellStreamItem) -> ShellChange

Apply one subscribeShell stream item to workspace state.

Source code in src/acptui/t3/state.py
def apply_shell(self, item: ShellStreamItem) -> ShellChange:
    """Apply one `subscribeShell` stream item to workspace state."""
    result = ShellChange(changed=False)
    match item:
        case ShellSnapshot():
            snap = item.snapshot
            self.sequence = snap.snapshot_sequence
            self.projects = {p.id: p for p in snap.projects if p.archived_at is None}
            self.threads = {t.id: t for t in snap.threads if t.deleted_at is None}
            self.archived_threads = {
                t.id: t for t in snap.archived_threads if t.deleted_at is None
            }
            result = ShellChange(changed=True)
        case ShellProjectUpdated():
            self.sequence = max(self.sequence, item.sequence)
            if item.project.archived_at is None:
                self.projects[item.project.id] = item.project
            else:
                self.projects.pop(item.project.id, None)
            result = ShellChange(changed=True)
        case ShellProjectRemoved():
            self.sequence = max(self.sequence, item.sequence)
            self.projects.pop(item.project_id, None)
            result = ShellChange(changed=True)
        case ShellThreadUpdated():
            result = self._apply_thread_updated(item)
        case ShellThreadRemoved():
            self.sequence = max(self.sequence, item.sequence)
            target = self.threads if item.location == "active" else self.archived_threads
            target.pop(item.thread_id, None)
            self.unread_ids.discard(item.thread_id)
            result = ShellChange(changed=True)
        case ShellSynchronized():
            self.synchronized = True
        case ShellSnapshotRequired():
            result = ShellChange(changed=False, needs_resubscribe=True)
        case _:
            pass
    return result

project_title

project_title(project_id: str) -> str

Human-readable project name for project_id.

Source code in src/acptui/t3/state.py
def project_title(self, project_id: str) -> str:
    """Human-readable project name for `project_id`."""
    project = self.projects.get(project_id)
    return project.title if project is not None else project_id

select_thread

select_thread(thread_id: str | None) -> None

Set the currently open thread and clear its unread badge.

Source code in src/acptui/t3/state.py
def select_thread(self, thread_id: str | None) -> None:
    """Set the currently open thread and clear its unread badge."""
    self.active_thread_id = thread_id
    if thread_id is not None:
        self.unread_ids.discard(thread_id)

sorted_threads

sorted_threads(filter_text: str = '', *, project_id: str | None = None) -> list[ThreadShell]

Return active threads in Telegram-like priority order.

Waiting threads and pinned threads bubble to the top, followed by running threads, then most recently updated threads.

Source code in src/acptui/t3/state.py
def sorted_threads(
    self, filter_text: str = "", *, project_id: str | None = None
) -> list[ThreadShell]:
    """Return active threads in Telegram-like priority order.

    Waiting threads and pinned threads bubble to the top, followed by running
    threads, then most recently updated threads.
    """
    query = filter_text.strip().lower()
    rows: list[ThreadShell] = []
    for thread in self.threads.values():
        if project_id is not None and thread.project_id != project_id:
            continue
        if query:
            proj = self.project_title(thread.project_id).lower()
            preview = (
                thread.latest_visible_message.text.lower()
                if thread.latest_visible_message and thread.latest_visible_message.text
                else ""
            )
            if query not in thread.title.lower() and query not in proj and query not in preview:
                continue
        rows.append(thread)

    def sort_key(t: ThreadShell) -> tuple[int, int, int, str]:
        waiting = 0 if thread_needs_attention(t) else 1
        pinned = 0 if t.pinned_at else 1
        running = 0 if thread_is_running(t) else 1
        # Reverse lexicographical ISO timestamp via negative ordinal isn't needed if we
        # sort in two passes; instead we sort descending by timestamp first.
        return (waiting, pinned, running, t.id)

    rows.sort(key=lambda t: t.updated_at or t.created_at or "", reverse=True)
    rows.sort(key=sort_key)
    return rows