Skip to content

session

Class info

Classes

Name Children Inherits
ErrorPanel
acptui.ui.screens.session
A problem with the agent (it failed to start, crashed, is unsupported, ...).
    SessionScreen
    acptui.ui.screens.session
    A conversation with one agent.
      SubagentScreen
      acptui.ui.screens.session
      The conversation of a subagent session (read-only).

        🛈 DocStrings

        The session screen: conversation, prompt and status; drives the agent connection.

        It implements :class:~acptui.protocol.connection.AgentEvents: every message the agent sends arrives here and is routed to the session it belongs to (the main session, or one of its subagent sessions).

        ErrorPanel

        Bases: Static

        A problem with the agent (it failed to start, crashed, is unsupported, ...).

        Source code in src/acptui/ui/screens/session.py
        class ErrorPanel(Static):
            """A problem with the agent (it failed to start, crashed, is unsupported, ...)."""
        
            DEFAULT_CSS = """
            ErrorPanel {
                height: auto;
                border: round $error;
                border-title-color: $error;
                padding: 0 1;
                margin: 1 0;
            }
            """
        

        SessionScreen

        Bases: Screen[None]

        A conversation with one agent.

        Source code in src/acptui/ui/screens/session.py
        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
        515
        516
        517
        518
        519
        520
        521
        522
        523
        524
        525
        526
        527
        528
        529
        530
        531
        532
        533
        534
        535
        536
        537
        538
        539
        540
        541
        542
        543
        544
        545
        546
        547
        548
        549
        550
        551
        552
        553
        554
        555
        556
        557
        558
        559
        560
        561
        562
        563
        564
        565
        566
        567
        568
        569
        570
        571
        572
        573
        574
        575
        576
        577
        578
        579
        580
        581
        582
        583
        584
        585
        586
        587
        588
        589
        590
        591
        592
        593
        594
        595
        596
        597
        598
        599
        600
        601
        602
        603
        604
        605
        606
        607
        608
        609
        610
        611
        612
        613
        614
        615
        616
        617
        618
        619
        620
        621
        622
        623
        624
        625
        626
        627
        628
        629
        630
        631
        632
        633
        634
        635
        636
        637
        638
        639
        640
        641
        642
        643
        644
        645
        646
        647
        648
        649
        650
        651
        652
        653
        654
        655
        656
        657
        658
        659
        660
        661
        662
        663
        664
        665
        666
        667
        668
        669
        670
        671
        672
        673
        674
        675
        676
        677
        678
        679
        680
        681
        682
        683
        684
        685
        686
        687
        688
        689
        690
        691
        692
        693
        694
        695
        696
        697
        698
        699
        700
        701
        702
        703
        704
        705
        706
        707
        708
        709
        710
        711
        712
        713
        714
        715
        716
        717
        718
        719
        720
        721
        722
        723
        724
        725
        726
        727
        728
        729
        730
        731
        732
        733
        734
        735
        736
        737
        738
        739
        740
        741
        742
        743
        744
        745
        746
        747
        748
        749
        750
        751
        752
        753
        754
        755
        756
        757
        758
        759
        760
        761
        762
        763
        764
        765
        766
        767
        768
        769
        770
        771
        772
        773
        774
        775
        776
        777
        778
        779
        780
        781
        782
        783
        784
        785
        786
        787
        788
        789
        790
        791
        792
        793
        794
        795
        796
        797
        798
        799
        800
        801
        802
        803
        804
        805
        806
        807
        808
        809
        810
        811
        812
        813
        814
        815
        816
        817
        818
        819
        820
        821
        822
        823
        824
        825
        826
        827
        828
        829
        830
        831
        832
        833
        834
        835
        836
        837
        838
        839
        840
        841
        842
        843
        844
        845
        846
        847
        848
        849
        850
        851
        852
        853
        854
        855
        856
        857
        858
        859
        860
        861
        862
        863
        864
        865
        866
        867
        868
        869
        870
        871
        872
        873
        874
        875
        876
        877
        878
        879
        880
        881
        882
        883
        884
        885
        886
        887
        888
        889
        890
        891
        class SessionScreen(Screen[None]):
            """A conversation with one agent."""
        
            DEFAULT_CSS = """
            SessionScreen {
                layout: vertical;
                #prompt-area { height: auto; }
            }
            """
        
            BINDINGS: ClassVar = [
                Binding("escape", "cancel_turn", "Cancel"),
                Binding("ctrl+n", "new_session", "New"),
                Binding("ctrl+r", "resume_session", "Resume"),
                Binding("ctrl+o", "options", "Options"),
                Binding("shift+tab", "next_mode", "Mode", show=False),
                Binding("ctrl+d", "toggle_diff", "Diff view", show=False),
                Binding("ctrl+f", "fork_session", "Fork", show=False),
                Binding("ctrl+l", "show_log", "Log"),
                Binding("f1", "help", "Help"),
                Binding("f2", "rename_session", "Rename", show=False),
                Binding("f5", "restart", "Restart", show=False),
                Binding("pageup", "scroll_conversation(-1)", show=False, priority=True),
                Binding("pagedown", "scroll_conversation(1)", show=False, priority=True),
            ]
        
            def __init__(
                self,
                spec: AgentSpec,
                cwd: Path,
                agent_log: AgentLog,
                *,
                diff_mode: DiffViewMode = "auto",
                expand_thoughts: bool = False,
                resume_id: str | None = None,
                setup: SessionSetup | None = None,
            ) -> None:
                super().__init__()
                self.spec = spec
                self.cwd = cwd
                self.agent_log = agent_log
                self.diff_mode: DiffViewMode = diff_mode
                self.expand_thoughts = expand_thoughts
                self.resume_id = resume_id
                self.setup = setup or SessionSetup()
                self.connection: AgentConnection | None = None
                self.state: SessionState | None = None
                """The session shown in this screen."""
                self.sessions: dict[str, SessionState] = {}
                """Every session the agent told us about: the main one and subagent sessions."""
                self.connected = False
                self.closing = False
                self._dialogs: set[Widget] = set()
                """Open permission and elicitation dialogs (closed when the agent goes away)."""
                self._url_elicitations: dict[str, UrlElicitationScreen] = {}
                self._subagent_screens: dict[str, SubagentScreen] = {}
        
            # --- Layout ---------------------------------------------------------------------
        
            def compose(self) -> ComposeResult:
                yield ConversationView(
                    self.agent_log,
                    diff_mode=self.diff_mode,
                    expand_thoughts=self.expand_thoughts,
                    id="conversation",
                )
                completion_list = CompletionList()
                prompt = PromptInput(self.cwd)
                prompt.completion_list = completion_list
                with Vertical(id="prompt-area"):
                    yield completion_list
                    yield prompt
                    yield StatusBar()
                yield Footer(compact=True)
        
            @property
            def conversation(self) -> ConversationView:
                """The main conversation."""
                return self.query_one("#conversation", ConversationView)
        
            @property
            def prompt(self) -> PromptInput:
                """The prompt editor."""
                return self.query_one(PromptInput)
        
            @property
            def status(self) -> StatusBar:
                """The status line."""
                return self.query_one(StatusBar)
        
            def on_mount(self) -> None:
                self.status.agent = self.spec.name
                self.status.refresh_status()
                self.prompt.focus()
                self.start_agent()
        
            def call[*Ts](self, func: Callable[[*Ts], Awaitable[object]], *args: *Ts) -> None:
                """Call ``func(*args)`` in the background (see :meth:`spawn`)."""
                self.spawn(func(*args))
        
            def spawn(self, call: Awaitable[object], group: str = "rpc") -> None:
                """Run a call in the background; failures are shown, never raised into the UI."""
        
                async def run() -> None:
                    try:
                        await call
                    except (RequestError, ConnectionError, AgentError) as exc:
                        self.notify(str(exc), severity="error")
        
                self.run_worker(run(), group=group, exit_on_error=False)
        
            # --- Agent lifecycle ------------------------------------------------------------
        
            def start_agent(self) -> None:
                """(Re)start the connection to the agent."""
                self.run_worker(
                    self._run_agent(), name="agent", group="agent", exclusive=True, exit_on_error=False
                )
        
            async def _run_agent(self) -> None:
                connection = AgentConnection(self.spec, self, self.cwd)
                self.connection = connection
                self._set_connection_state("starting")
                self.agent_log.add("info", f"starting {self.spec.name}: {self.spec.target}")
                try:
                    async with connection.open():
                        self.agent_log.add(
                            "info", f"connected to {connection.agent_name} {connection.agent_version}"
                        )
                        self.status.agent = f"{connection.agent_name} {connection.agent_version}".strip()
                        self._set_connection_state("connected")
                        if connection.supports_auth_status:
                            self.spawn(self._refresh_auth_status())
                        await self._start_session(self.resume_id)
                        await connection.wait_closed()
                    if not self.closing:
                        code = connection.exit_code
                        suffix = f" (exit code {code})" if code is not None else ""
                        self._fatal(f"The agent disconnected{suffix}.", title="Agent exited")
                except UnsupportedProtocolError as exc:
                    self._fatal(str(exc), title="Unsupported agent", show_stderr=False)
                except AgentError as exc:
                    self._fatal(str(exc), title="Agent error")
                except (ConnectionError, RequestError) as exc:
                    if not self.closing:
                        self._fatal(f"Connection to the agent failed: {exc}", title="Agent error")
                finally:
                    self._close_dialogs()
                    if not self.closing:
                        self._set_connection_state("disconnected")
        
            async def _start_session(self, resume_id: str | None) -> None:
                connection = self._connection()
                try:
                    if resume_id is not None:
                        await self._resume(resume_id)
                        return
                    response = await connection.new_session(self.setup)
                except RequestError as exc:
                    self._session_error(exc)
                    return
                self._show_session(
                    response.session_id, response.config_options, response.available_commands
                )
        
            def _show_session(
                self,
                session_id: str,
                options: list[SessionConfigOption] | object,
                commands: list[AvailableCommand] | object,
                *,
                replaying: bool = False,
                state: SessionState | None = None,
            ) -> SessionState:
                """Make ``session_id`` the shown session (a new state, or ``state``)."""
                if state is None:
                    state = SessionState(session_id, str(self.cwd), replaying=replaying)
                self.sessions[session_id] = state
                self.state = state
                self.status.state = state
                self.conversation.show(state)
                if isinstance(options, list) and options:
                    self.conversation.push(state.set_config_options(options))
                if isinstance(commands, list):
                    self.conversation.push(state.set_commands(commands))
                    self.prompt.commands = list(state.commands)
                self.status.refresh_status()
                return state
        
            def _session_error(self, exc: RequestError) -> None:
                connection = self._connection()
                if exc.code == -32000:  # noqa: PLR2004 - authentication required
                    methods = "\n".join(
                        f"  • {m.name}"
                        + (
                            " (ctrl+p → Log in)"
                            if isinstance(m, AuthMethodAgent | AuthMethodTerminal)
                            else ""
                        )
                        for m in connection.auth_methods
                    )
                    methods = methods or "  (it offers no login methods)"
                    text = f"{connection.agent_name} needs you to log in.\n{methods}"
                    self._fatal(text, title="Authentication required", show_stderr=False, fatal=False)
                else:
                    self._fatal(
                        f"Could not create a session: {exc} ({exc.code})",
                        title="Session error",
                        fatal=False,
                    )
        
            async def _resume(self, session_id: str, title: str | None = None) -> None:
                """Resume a session with its history replayed.
        
                The resume response has no title. The replayed history (handled when the response
                arrives) may name older ones: the session list's (current) title wins; without
                it, the one the session had here before, if the replay names none.
                """
                connection = self._connection()
                known = self.sessions.get(session_id)
                earlier = known.title if known is not None else None
                state = self._show_session(session_id, None, None, replaying=True)
                try:
                    response = await connection.resume_session(session_id, setup=self.setup)
                except RequestError as exc:
                    self._fatal(f"Could not resume the session: {exc}", title="Session error", fatal=False)
                    return
                state.replaying = False
                if title is not None or state.title is None:
                    state.title = title or earlier
                    self.status.refresh_status()
                if is_set(response.config_options):
                    self.conversation.push(state.set_config_options(response.config_options))
                if is_set(response.available_commands):
                    self.conversation.push(state.set_commands(response.available_commands))
                if connection.supports_status:
                    self.spawn(self.refresh_session_status())
        
            def _connection(self) -> AgentConnection:
                if self.connection is None:
                    msg = "no agent connection"
                    raise AgentError(msg)
                return self.connection
        
            def _set_connection_state(self, value: str) -> None:
                self.connected = value == "connected"
                self.status.connection_state = value
                self.status.refresh_status()
                self.prompt.set_class(not self.connected, "-disabled")
        
            def _fatal(
                self, message: str, *, title: str, show_stderr: bool = True, fatal: bool = True
            ) -> None:
                text = Content(message)
                if show_stderr and (tail := self.agent_log.tail("stderr", STDERR_TAIL)):
                    text = Content.assemble(
                        text, ("\n\nLast stderr lines:\n", "bold"), ("\n".join(tail), "$text-muted")
                    )
                hint = "\n\nf5: restart · ctrl+l: log · ctrl+q: quit" if fatal else "\n\nctrl+l: log"
                panel = ErrorPanel(Content.assemble(text, (hint, "$text-muted italic")))
                panel.border_title = title
                self.agent_log.add("error", f"{title}: {message}")
                self.conversation.mount(panel)
        
            # --- AgentEvents ----------------------------------------------------------------
        
            def _state_for(self, session_id: str) -> SessionState:
                """The state of a session; sessions we did not create are subagent sessions."""
                state = self.sessions.get(session_id)
                if state is None:
                    parent = next((s for s in self.sessions.values() if session_id in s.subagents), None)
                    state = SessionState(
                        session_id, str(self.cwd), parent_id=parent.session_id if parent else None
                    )
                    self.sessions[session_id] = state
                return state
        
            def session_update(self, notification: UpdateSessionNotification) -> None:
                state = self._state_for(notification.session_id)
                changes = state.apply(notification.update)
                if state is self.state:
                    self.conversation.push(changes)
                elif (
                    screen := self._subagent_screens.get(state.session_id)
                ) is not None and screen.is_attached:
                    screen.conversation.push(changes)
        
            async def request_permission(
                self, request: RequestPermissionRequest
            ) -> RequestPermissionResponse:
                state = self._state_for(request.session_id)
                if is_set(request.subject) and isinstance(request.subject, ToolCallPermissionSubject):
                    changes = state.apply_tool_call(request.subject.tool_call)
                    if state is self.state:
                        self.conversation.push(changes)
                screen = PermissionScreen(request, state.cwd, self.diff_mode)
                self.app.bell()
                return await self._ask(screen, cancelled())
        
            async def _ask[T](self, screen: ModalScreen[T], default: T) -> T:
                """Show a dialog and wait for its answer.
        
                If the agent cancels the request (``$/cancel_request``) or the connection ends,
                the dialog is closed.
                """
                loop = asyncio.get_running_loop()
                future: asyncio.Future[T] = loop.create_future()
                self._dialogs.add(screen)
        
                def done(result: T | None) -> None:
                    if not future.done():
                        future.set_result(result if result is not None else default)
        
                self.app.push_screen(screen, callback=done)
                try:
                    return await future
                except asyncio.CancelledError:
                    if screen.is_attached:
                        screen.dismiss(default)
                    raise
                finally:
                    self._dialogs.discard(screen)
        
            async def create_elicitation(
                self, request: CreateElicitationRequest
            ) -> CreateElicitationResponse:
                from acptui.ui.screens.elicitation import cancelled_elicitation
        
                match request:
                    case FormElicitationRequest():
                        return await self._ask(FormElicitationScreen(request), cancelled_elicitation())
                    case UrlElicitationRequest():
                        screen = UrlElicitationScreen(request)
                        self._url_elicitations[request.elicitation_id] = screen
                        try:
                            return await self._ask(screen, cancelled_elicitation())
                        finally:
                            self._url_elicitations.pop(request.elicitation_id, None)
                    case _:
                        self.notify(f"Unsupported elicitation mode {request.mode!r}", severity="warning")
                        return DeclineElicitationResponse()
        
            def complete_elicitation(self, notification: CompleteElicitationNotification) -> None:
                if (screen := self._url_elicitations.get(notification.elicitation_id)) is not None:
                    screen.complete()
        
            def auth_status_update(self, notification: AuthStatusUpdateNotification) -> None:
                accounts = notification.accounts if is_set(notification.accounts) else []
                self._show_auth(notification.state, accounts)
        
            def ext_notification(self, method: str, params: JsonValue) -> None:
                text = json.dumps(params, ensure_ascii=False)
                self.agent_log.add("info", f"extension notification {method}: {text}")
        
            def stderr_line(self, line: str) -> None:
                self.agent_log.add("stderr", line)
        
            def traffic(self, direction: str, text: str) -> None:
                self.agent_log.add("incoming" if direction == "incoming" else "outgoing", text)
        
            def _close_dialogs(self) -> None:
                for screen in list(self._dialogs):
                    if isinstance(screen, PermissionScreen | FormElicitationScreen | UrlElicitationScreen):
                        screen.cancel()
                self._dialogs.clear()
        
            def _show_auth(self, state: str, accounts: list[AuthAccount] | object) -> None:
                label = "not logged in" if state == "unauthenticated" else ""
                if isinstance(accounts, list):
                    active = next(
                        (a for a in accounts if is_set(a.active) and a.active),
                        accounts[0] if accounts else None,
                    )
                    if active is not None:
                        label = active.label
                self.status.account = label
                self.status.refresh_status()
        
            async def _refresh_auth_status(self) -> None:
                response = await self._connection().auth_status()
                accounts = response.accounts if is_set(response.accounts) else []
                self._show_auth(response.state, list(accounts))
        
            async def refresh_session_status(self) -> None:
                state = self.state
                if state is None:
                    return
                response = await self._connection().session_status(state.session_id)
                snapshot = response.state if is_set(response.state) else None
                if snapshot is not None:
                    state.activity = ACTIVITIES.get(snapshot.state, "unknown")
                self.notify(f"Session is {response.status}", timeout=2)
                self.status.refresh_status()
        
            # --- Conversation events --------------------------------------------------------
        
            def on_conversation_view_session_field_changed(
                self, message: ConversationView.SessionFieldChanged
            ) -> None:
                state = self.state
                if state is None:
                    return
                if message.field == "commands":
                    self.prompt.commands = list(state.commands)
                if message.field == "suggestions":
                    self._show_suggestion()
                self.status.refresh_status()
        
            def _show_suggestion(self) -> None:
                state = self.state
                suggestion = state.suggestions[0] if state is not None and state.suggestions else None
                text = (
                    content_markdown(suggestion.prompt, self.cwd).strip() if suggestion is not None else ""
                )
                self.prompt.suggestion = text
        
            # --- Prompt ---------------------------------------------------------------------
        
            def on_prompt_input_submitted(self, message: PromptInput.Submitted) -> None:
                state = self.state
                connection = self.connection
                if state is None or connection is None or not self.connected:
                    self.notify("Not connected to an agent", severity="warning")
                    return
                skills = frozenset(c.name for c in state.commands if isinstance(c, Skill))
                options = PromptOptions(
                    embedded_context=connection.supports_embedded_context,
                    images=connection.supports_images,
                    audio=connection.supports_audio,
                    skills=skills if connection.supports_skills else frozenset(),
                )
                blocks = build_prompt(message.text, self.cwd, options)
                changes = state.add_local_user_message(blocks)
                entry = changes[0].entry if changes and isinstance(changes[0], EntryAdded) else None
                self.conversation.push(changes)
                self.prompt.load_text("")
                self.prompt.suggestion = ""
                self.conversation.anchor()
                if isinstance(entry, MessageEntry):
                    self.run_worker(self._send_prompt(state, entry), group="rpc", exit_on_error=False)
        
            async def _send_prompt(self, state: SessionState, entry: MessageEntry) -> None:
                connection = self._connection()
                try:
                    response = await connection.prompt(state.session_id, entry.blocks)
                except (RequestError, ConnectionError) as exc:
                    self.conversation.push(
                        state.add_notice("error", "The agent rejected the prompt", str(exc))
                    )
                    return
                state.acknowledge_user_message(entry, response.message_id)
        
            # --- Actions --------------------------------------------------------------------
        
            def action_cancel_turn(self) -> None:
                """Cancel the running turn."""
                state = self.state
                if state is None or self.connection is None or not self.connected:
                    return
                if not state.running:
                    self.notify("Nothing to cancel", timeout=2)
                    return
                self.spawn(self.connection.cancel(state.session_id))
                self.notify("Cancelling…", timeout=2)
        
            def action_new_session(self) -> None:
                """Start a new session."""
                if self.connection is None or not self.connected:
                    return
                self.run_worker(self._new_session(), group="session", exclusive=True, exit_on_error=False)
        
            async def _new_session(self) -> None:
                connection = self._connection()
                if self.state is not None:
                    await connection.close_session(self.state.session_id)
                await self._start_session(None)
                self.prompt.focus()
        
            def action_resume_session(self) -> None:
                """Pick a session to resume."""
                if self.connection is None or not self.connected:
                    return
        
                listing = SessionListScreen(self.connection)
        
                def chosen(session_id: str | None) -> None:
                    if session_id is not None:
                        info = listing.sessions.get(session_id)
                        title = info.title if info is not None and is_set(info.title) else None
                        self.run_worker(
                            self._resume(session_id, title),
                            group="session",
                            exclusive=True,
                            exit_on_error=False,
                        )
        
                self.app.push_screen(listing, callback=chosen)
        
            def action_fork_session(self) -> None:
                """Fork the session (whole, or at a cursor the agent offers)."""
                connection = self.connection
                state = self.state
                if connection is None or state is None:
                    return
                if not connection.supports_fork:
                    self.notify("The agent cannot fork sessions", timeout=2)
                    return
        
                def chosen(choice: tuple[str | None] | None) -> None:
                    if choice is not None:
                        self.run_worker(
                            self._fork(state, choice[0]),
                            group="session",
                            exclusive=True,
                            exit_on_error=False,
                        )
        
                self.app.push_screen(ForkScreen(state), callback=chosen)
        
            async def _fork(self, source: SessionState, cursor_id: str | None) -> None:
                connection = self._connection()
                try:
                    response = await connection.fork_session(source.session_id, cursor_id, self.setup)
                except (RequestError, ConnectionError) as exc:
                    self.notify(f"Could not fork: {exc}", severity="error")
                    return
                # The fork has the history up to the cursor (all of it without): show that part
                cursor = source.cursors.get(cursor_id) if cursor_id is not None else None
                forked = source.forked(response.session_id, cursor)
                self._show_session(
                    response.session_id,
                    response.config_options,
                    response.available_commands,
                    state=forked,
                )
                self.notify("Forked: now in the new session", timeout=3)
        
            def action_rename_session(self) -> None:
                """Rename the session."""
                state = self.state
                connection = self.connection
                if state is None or connection is None:
                    return
                if not connection.supports_title:
                    self.notify("The agent cannot rename sessions", timeout=2)
                    return
        
                def chosen(title: str | None) -> None:
                    if title:
                        self.spawn(self._rename(state, title))
        
                self.app.push_screen(TextInputScreen("Session title", state.title or ""), callback=chosen)
        
            async def _rename(self, state: SessionState, title: str) -> None:
                state.title = await self._connection().set_title(state.session_id, title)
                self.status.refresh_status()
        
            def action_options(self) -> None:
                """Show the session options."""
                if self.state is None:
                    return
                self.app.push_screen(
                    ConfigScreen(list(self.state.config_options)), callback=self._config_chosen
                )
        
            def _config_chosen(self, choice: ConfigChoice | None) -> None:
                if choice is not None:
                    config_id, value = choice
                    self.spawn(self.set_config(config_id, value))
        
            async def set_config(self, config_id: str, value: str | bool) -> None:
                """Set a config option of the session."""
                state = self.state
                connection = self.connection
                if state is None or connection is None:
                    return
                try:
                    response = await connection.set_config_option(state.session_id, config_id, value)
                except (RequestError, ConnectionError) as exc:
                    self.notify(f"Could not change the option: {exc}", severity="error")
                    return
                self.conversation.push(state.set_config_options(response.config_options))
        
            def action_next_mode(self) -> None:
                """Switch to the next value of the mode option."""
                state = self.state
                if state is None:
                    return
                option = next(
                    (
                        o
                        for o in state.config_options
                        if isinstance(o, SelectSessionConfigOption)
                        and is_set(o.category)
                        and o.category == "mode"
                    ),
                    None,
                )
                if option is None:
                    self.notify("The agent has no mode option", timeout=2)
                    return
                self.spawn(self.set_config(option.config_id, next_select_value(option)))
        
            def action_toggle_diff(self) -> None:
                """Cycle the diff view: unified, split, auto."""
                self.diff_mode = DIFF_MODES[(DIFF_MODES.index(self.diff_mode) + 1) % len(DIFF_MODES)]
                self.conversation.set_diff_mode(self.diff_mode)
                self.notify(f"Diff view: {self.diff_mode}", timeout=2)
        
            def action_show_log(self) -> None:
                """Show the agent log."""
                self.app.push_screen(LogScreen(self.agent_log))
        
            def action_help(self) -> None:
                """Show the help."""
                self.app.push_screen(HelpScreen())
        
            def action_providers(self) -> None:
                """Configure the agent's LLM providers."""
                if self.connection is not None and self.connection.supports_providers:
                    self.app.push_screen(ProvidersScreen(self.connection))
                else:
                    self.notify("The agent has no configurable providers", timeout=2)
        
            def action_restart(self) -> None:
                """Restart the agent (and start a new session)."""
                self.run_worker(self._restart(), group="session", exclusive=True, exit_on_error=False)
        
            async def _restart(self) -> None:
                self.closing = True
                self.workers.cancel_group(self, "agent")
                await asyncio.sleep(0)
                self.closing = False
                self.sessions.clear()
                self.state = None
                self.status.state = None
                self.conversation.show(None)
                self.start_agent()
        
            def action_scroll_conversation(self, direction: int) -> None:
                """Scroll the conversation by a page."""
                if direction < 0:
                    self.conversation.scroll_page_up()
                else:
                    self.conversation.scroll_page_down()
        
            def on_tool_call_view_cancel_requested(self, message: ToolCallView.CancelRequested) -> None:
                state = self.state
                if state is not None and self.connection is not None:
                    self.spawn(self.connection.cancel_tool_call(state.session_id, message.tool_call_id))
        
            def on_terminal_view_cancel_requested(self, message: TerminalView.CancelRequested) -> None:
                state = self.state
                if state is not None and self.connection is not None:
                    self.spawn(self.connection.cancel_terminal(state.session_id, message.terminal_id))
        
            def on_subagent_view_open(self, message: SubagentView.Open) -> None:
                state = self._state_for(message.session_id)
                parent = self.state
                child = parent.subagents.get(message.session_id) if parent is not None else None
                screen = SubagentScreen(
                    self, state, child.display_title if child is not None else message.session_id
                )
                self._subagent_screens[message.session_id] = screen
        
                def closed(_: None) -> None:
                    self._subagent_screens.pop(message.session_id, None)
        
                self.app.push_screen(screen, callback=closed)
        
            def on_subagent_view_cancel_requested(self, message: SubagentView.CancelRequested) -> None:
                self.cancel_subagent(message.session_id)
        
            def cancel_subagent(self, session_id: str) -> None:
                """Cancel a subagent's work, if its parent allows it."""
                parent = self.state
                child = parent.subagents.get(session_id) if parent is not None else None
                if child is None or not child.can_cancel or self.connection is None:
                    self.notify("This subagent cannot be cancelled", timeout=2)
                    return
                self.spawn(self.connection.cancel(session_id))
        
            # --- Authentication -------------------------------------------------------------
        
            async def login(self, method_id: str) -> None:
                """Log in with an auth method, then retry creating a session."""
                connection = self._connection()
                method = next((m for m in connection.auth_methods if m.method_id == method_id), None)
                if isinstance(method, AuthMethodTerminal):
                    await self._terminal_login(method)
                else:
                    try:
                        await connection.login(method_id)
                    except (RequestError, ConnectionError) as exc:
                        self.notify(f"Login failed: {exc}", severity="error")
                        return
                self.notify("Logged in", timeout=2)
                if connection.supports_auth_status:
                    await self._refresh_auth_status()
                if self.state is None:
                    await self._start_session(None)
        
            async def logout(self) -> None:
                """Log out of the agent."""
                connection = self._connection()
                try:
                    await connection.logout()
                except (RequestError, ConnectionError) as exc:
                    self.notify(f"Logout failed: {exc}", severity="error")
                    return
                self.notify("Logged out", timeout=2)
                if connection.supports_auth_status:
                    await self._refresh_auth_status()
        
            async def _terminal_login(self, method: AuthMethodTerminal) -> None:
                if not self.spec.command:
                    self.notify("Terminal login needs a local agent", severity="error")
                    return
                args = list(method.args) if is_set(method.args) else []
                env = {**os.environ, **self.spec.resolved_env()}
                if is_set(method.env):
                    env.update({variable.name: variable.value for variable in method.env})
                with self.app.suspend():
                    process = await asyncio.create_subprocess_exec(
                        *self.spec.command, *args, env=env, cwd=self.cwd
                    )
                    await process.wait()
        
            async def shutdown(self) -> None:
                """Stop the agent (on quit)."""
                self.closing = True
                self._close_dialogs()
                self.conversation.stop()
                self.workers.cancel_group(self, "agent")
        

        conversation property

        conversation: ConversationView
        

        The main conversation.

        prompt property

        prompt: PromptInput
        

        The prompt editor.

        sessions instance-attribute

        sessions: dict[str, SessionState] = {}
        

        Every session the agent told us about: the main one and subagent sessions.

        state instance-attribute

        state: SessionState | None = None
        

        The session shown in this screen.

        status property

        status: StatusBar
        

        The status line.

        action_cancel_turn

        action_cancel_turn() -> None
        

        Cancel the running turn.

        Source code in src/acptui/ui/screens/session.py
        def action_cancel_turn(self) -> None:
            """Cancel the running turn."""
            state = self.state
            if state is None or self.connection is None or not self.connected:
                return
            if not state.running:
                self.notify("Nothing to cancel", timeout=2)
                return
            self.spawn(self.connection.cancel(state.session_id))
            self.notify("Cancelling…", timeout=2)
        

        action_fork_session

        action_fork_session() -> None
        

        Fork the session (whole, or at a cursor the agent offers).

        Source code in src/acptui/ui/screens/session.py
        def action_fork_session(self) -> None:
            """Fork the session (whole, or at a cursor the agent offers)."""
            connection = self.connection
            state = self.state
            if connection is None or state is None:
                return
            if not connection.supports_fork:
                self.notify("The agent cannot fork sessions", timeout=2)
                return
        
            def chosen(choice: tuple[str | None] | None) -> None:
                if choice is not None:
                    self.run_worker(
                        self._fork(state, choice[0]),
                        group="session",
                        exclusive=True,
                        exit_on_error=False,
                    )
        
            self.app.push_screen(ForkScreen(state), callback=chosen)
        

        action_help

        action_help() -> None
        

        Show the help.

        Source code in src/acptui/ui/screens/session.py
        def action_help(self) -> None:
            """Show the help."""
            self.app.push_screen(HelpScreen())
        

        action_new_session

        action_new_session() -> None
        

        Start a new session.

        Source code in src/acptui/ui/screens/session.py
        def action_new_session(self) -> None:
            """Start a new session."""
            if self.connection is None or not self.connected:
                return
            self.run_worker(self._new_session(), group="session", exclusive=True, exit_on_error=False)
        

        action_next_mode

        action_next_mode() -> None
        

        Switch to the next value of the mode option.

        Source code in src/acptui/ui/screens/session.py
        def action_next_mode(self) -> None:
            """Switch to the next value of the mode option."""
            state = self.state
            if state is None:
                return
            option = next(
                (
                    o
                    for o in state.config_options
                    if isinstance(o, SelectSessionConfigOption)
                    and is_set(o.category)
                    and o.category == "mode"
                ),
                None,
            )
            if option is None:
                self.notify("The agent has no mode option", timeout=2)
                return
            self.spawn(self.set_config(option.config_id, next_select_value(option)))
        

        action_options

        action_options() -> None
        

        Show the session options.

        Source code in src/acptui/ui/screens/session.py
        def action_options(self) -> None:
            """Show the session options."""
            if self.state is None:
                return
            self.app.push_screen(
                ConfigScreen(list(self.state.config_options)), callback=self._config_chosen
            )
        

        action_providers

        action_providers() -> None
        

        Configure the agent's LLM providers.

        Source code in src/acptui/ui/screens/session.py
        def action_providers(self) -> None:
            """Configure the agent's LLM providers."""
            if self.connection is not None and self.connection.supports_providers:
                self.app.push_screen(ProvidersScreen(self.connection))
            else:
                self.notify("The agent has no configurable providers", timeout=2)
        

        action_rename_session

        action_rename_session() -> None
        

        Rename the session.

        Source code in src/acptui/ui/screens/session.py
        def action_rename_session(self) -> None:
            """Rename the session."""
            state = self.state
            connection = self.connection
            if state is None or connection is None:
                return
            if not connection.supports_title:
                self.notify("The agent cannot rename sessions", timeout=2)
                return
        
            def chosen(title: str | None) -> None:
                if title:
                    self.spawn(self._rename(state, title))
        
            self.app.push_screen(TextInputScreen("Session title", state.title or ""), callback=chosen)
        

        action_restart

        action_restart() -> None
        

        Restart the agent (and start a new session).

        Source code in src/acptui/ui/screens/session.py
        def action_restart(self) -> None:
            """Restart the agent (and start a new session)."""
            self.run_worker(self._restart(), group="session", exclusive=True, exit_on_error=False)
        

        action_resume_session

        action_resume_session() -> None
        

        Pick a session to resume.

        Source code in src/acptui/ui/screens/session.py
        def action_resume_session(self) -> None:
            """Pick a session to resume."""
            if self.connection is None or not self.connected:
                return
        
            listing = SessionListScreen(self.connection)
        
            def chosen(session_id: str | None) -> None:
                if session_id is not None:
                    info = listing.sessions.get(session_id)
                    title = info.title if info is not None and is_set(info.title) else None
                    self.run_worker(
                        self._resume(session_id, title),
                        group="session",
                        exclusive=True,
                        exit_on_error=False,
                    )
        
            self.app.push_screen(listing, callback=chosen)
        

        action_scroll_conversation

        action_scroll_conversation(direction: int) -> None
        

        Scroll the conversation by a page.

        Source code in src/acptui/ui/screens/session.py
        def action_scroll_conversation(self, direction: int) -> None:
            """Scroll the conversation by a page."""
            if direction < 0:
                self.conversation.scroll_page_up()
            else:
                self.conversation.scroll_page_down()
        

        action_show_log

        action_show_log() -> None
        

        Show the agent log.

        Source code in src/acptui/ui/screens/session.py
        def action_show_log(self) -> None:
            """Show the agent log."""
            self.app.push_screen(LogScreen(self.agent_log))
        

        action_toggle_diff

        action_toggle_diff() -> None
        

        Cycle the diff view: unified, split, auto.

        Source code in src/acptui/ui/screens/session.py
        def action_toggle_diff(self) -> None:
            """Cycle the diff view: unified, split, auto."""
            self.diff_mode = DIFF_MODES[(DIFF_MODES.index(self.diff_mode) + 1) % len(DIFF_MODES)]
            self.conversation.set_diff_mode(self.diff_mode)
            self.notify(f"Diff view: {self.diff_mode}", timeout=2)
        

        call

        call(func: Callable[[*Ts], Awaitable[object]], *args: *Ts) -> None
        

        Call func(*args) in the background (see :meth:spawn).

        Source code in src/acptui/ui/screens/session.py
        def call[*Ts](self, func: Callable[[*Ts], Awaitable[object]], *args: *Ts) -> None:
            """Call ``func(*args)`` in the background (see :meth:`spawn`)."""
            self.spawn(func(*args))
        

        cancel_subagent

        cancel_subagent(session_id: str) -> None
        

        Cancel a subagent's work, if its parent allows it.

        Source code in src/acptui/ui/screens/session.py
        def cancel_subagent(self, session_id: str) -> None:
            """Cancel a subagent's work, if its parent allows it."""
            parent = self.state
            child = parent.subagents.get(session_id) if parent is not None else None
            if child is None or not child.can_cancel or self.connection is None:
                self.notify("This subagent cannot be cancelled", timeout=2)
                return
            self.spawn(self.connection.cancel(session_id))
        

        login async

        login(method_id: str) -> None
        

        Log in with an auth method, then retry creating a session.

        Source code in src/acptui/ui/screens/session.py
        async def login(self, method_id: str) -> None:
            """Log in with an auth method, then retry creating a session."""
            connection = self._connection()
            method = next((m for m in connection.auth_methods if m.method_id == method_id), None)
            if isinstance(method, AuthMethodTerminal):
                await self._terminal_login(method)
            else:
                try:
                    await connection.login(method_id)
                except (RequestError, ConnectionError) as exc:
                    self.notify(f"Login failed: {exc}", severity="error")
                    return
            self.notify("Logged in", timeout=2)
            if connection.supports_auth_status:
                await self._refresh_auth_status()
            if self.state is None:
                await self._start_session(None)
        

        logout async

        logout() -> None
        

        Log out of the agent.

        Source code in src/acptui/ui/screens/session.py
        async def logout(self) -> None:
            """Log out of the agent."""
            connection = self._connection()
            try:
                await connection.logout()
            except (RequestError, ConnectionError) as exc:
                self.notify(f"Logout failed: {exc}", severity="error")
                return
            self.notify("Logged out", timeout=2)
            if connection.supports_auth_status:
                await self._refresh_auth_status()
        

        set_config async

        set_config(config_id: str, value: str | bool) -> None
        

        Set a config option of the session.

        Source code in src/acptui/ui/screens/session.py
        async def set_config(self, config_id: str, value: str | bool) -> None:
            """Set a config option of the session."""
            state = self.state
            connection = self.connection
            if state is None or connection is None:
                return
            try:
                response = await connection.set_config_option(state.session_id, config_id, value)
            except (RequestError, ConnectionError) as exc:
                self.notify(f"Could not change the option: {exc}", severity="error")
                return
            self.conversation.push(state.set_config_options(response.config_options))
        

        shutdown async

        shutdown() -> None
        

        Stop the agent (on quit).

        Source code in src/acptui/ui/screens/session.py
        async def shutdown(self) -> None:
            """Stop the agent (on quit)."""
            self.closing = True
            self._close_dialogs()
            self.conversation.stop()
            self.workers.cancel_group(self, "agent")
        

        spawn

        spawn(call: Awaitable[object], group: str = 'rpc') -> None
        

        Run a call in the background; failures are shown, never raised into the UI.

        Source code in src/acptui/ui/screens/session.py
        def spawn(self, call: Awaitable[object], group: str = "rpc") -> None:
            """Run a call in the background; failures are shown, never raised into the UI."""
        
            async def run() -> None:
                try:
                    await call
                except (RequestError, ConnectionError, AgentError) as exc:
                    self.notify(str(exc), severity="error")
        
            self.run_worker(run(), group=group, exit_on_error=False)
        

        start_agent

        start_agent() -> None
        

        (Re)start the connection to the agent.

        Source code in src/acptui/ui/screens/session.py
        def start_agent(self) -> None:
            """(Re)start the connection to the agent."""
            self.run_worker(
                self._run_agent(), name="agent", group="agent", exclusive=True, exit_on_error=False
            )
        

        SubagentScreen

        Bases: Screen[None]

        The conversation of a subagent session (read-only).

        Source code in src/acptui/ui/screens/session.py
        class SubagentScreen(Screen[None]):
            """The conversation of a subagent session (read-only)."""
        
            BINDINGS: ClassVar = [
                Binding("escape", "close", "Back"),
                Binding("x", "cancel_subagent", "Cancel subagent"),
            ]
        
            DEFAULT_CSS = """
            SubagentScreen { #subagent-title { height: 1; background: $panel; padding: 0 1; } }
            """
        
            def __init__(self, parent: SessionScreen, state: SessionState, title: str) -> None:
                super().__init__()
                self.parent_screen = parent
                self.state = state
                self.title_text = title
        
            def compose(self) -> ComposeResult:
                yield Static(
                    Content.assemble(("subagent: ", "$text-muted"), (self.title_text, "bold")),
                    id="subagent-title",
                )
                yield ConversationView(
                    self.parent_screen.agent_log,
                    diff_mode=self.parent_screen.diff_mode,
                    expand_thoughts=self.parent_screen.expand_thoughts,
                )
                yield Footer(compact=True)
        
            @property
            def conversation(self) -> ConversationView:
                """The child's conversation."""
                return self.query_one(ConversationView)
        
            def on_mount(self) -> None:
                self.conversation.show(self.state)
        
            def action_close(self) -> None:
                """Back to the parent session."""
                self.dismiss(None)
        
            def action_cancel_subagent(self) -> None:
                """Cancel the subagent's work (if the parent allows it)."""
                self.parent_screen.cancel_subagent(self.state.session_id)
        

        conversation property

        conversation: ConversationView
        

        The child's conversation.

        action_cancel_subagent

        action_cancel_subagent() -> None
        

        Cancel the subagent's work (if the parent allows it).

        Source code in src/acptui/ui/screens/session.py
        def action_cancel_subagent(self) -> None:
            """Cancel the subagent's work (if the parent allows it)."""
            self.parent_screen.cancel_subagent(self.state.session_id)
        

        action_close

        action_close() -> None
        

        Back to the parent session.

        Source code in src/acptui/ui/screens/session.py
        def action_close(self) -> None:
            """Back to the parent session."""
            self.dismiss(None)