codee-agent 0.9.2__py3-none-any.whl → 0.9.4__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
codee/admin.py CHANGED
@@ -11,7 +11,7 @@ from pydantic import BaseModel
11
11
  from codee.admin_api import api_app
12
12
  from codee.admin_service import (
13
13
  AGENTS_FILE, TASKS_CHECKS, WORKFLOW_HIGHLIGHT_GROUPS, AdminService,
14
- SKILL_TYPES, WorkflowGeneration, normalize_work_items)
14
+ SKILL_TYPES, WorkflowGeneration, context_tier_label, normalize_work_items)
15
15
  from codee.workflow_graph import workflow_graph
16
16
  from codee_main_context.context import (
17
17
  DEFAULT_ISSUE_TYPES, TasksProvider, credential_field)
@@ -50,7 +50,8 @@ def _skill_summary(skill: dict[str, str]) -> SkillSummary:
50
50
  """One listing row, with its agent named the way the editor's picker does."""
51
51
  return SkillSummary(**{
52
52
  **skill,
53
- "agent": AGENT_NAMES.get(skill["agent"], DEFAULT_AGENT_OPTION)})
53
+ "agent": AGENT_NAMES.get(skill["agent"], DEFAULT_AGENT_OPTION),
54
+ "context_tier": context_tier_label(skill["context_tier"])})
54
55
 
55
56
 
56
57
  def _model_option(models: list["ModelOption"],
@@ -114,6 +115,9 @@ class SkillSummary(BaseModel):
114
115
  agent: str = ""
115
116
  model: str = ""
116
117
  effort: str = ""
118
+ # The skill's `x-codee-context-tier:` as a person reads it, empty for the
119
+ # model's default window.
120
+ context_tier: str = ""
117
121
  issue_status: str = ""
118
122
  issue_type: str = ""
119
123
 
@@ -219,6 +223,25 @@ class PeepStep(BaseModel):
219
223
  timestamp: str = ""
220
224
 
221
225
 
226
+ def _context_summary(context: dict[str, int] | None) -> str:
227
+ """One line on how full a session's context window is, "" when unknown.
228
+
229
+ Reads "Context: 41,245 / 128,000 tokens (32%) · 1 compaction", dropping
230
+ the window and share when the agent didn't say how big it is.
231
+ """
232
+ if not context:
233
+ return ""
234
+ tokens, window = context["tokens"], context["window"]
235
+ compactions = context["compactions"]
236
+ parts = []
237
+ if tokens and window:
238
+ parts.append(f"{tokens:,} / {window:,} tokens ({tokens / window:.0%})")
239
+ elif tokens:
240
+ parts.append(f"{tokens:,} tokens")
241
+ parts.append(f"{compactions} compaction{'' if compactions == 1 else 's'}")
242
+ return "Context: " + " · ".join(parts)
243
+
244
+
222
245
  def _active_job(job: dict[str, Any]) -> ActiveJob:
223
246
  """One in-flight run as its dashboard row reads it.
224
247
 
@@ -425,11 +448,13 @@ class AdminState(rx.State):
425
448
  kill_job_label: str = ""
426
449
  # The session the Peep dialog shows, held for the same reason, with the
427
450
  # last steps read from its transcript. ``peep_note`` says why there are
428
- # none, or that the session has finished since.
451
+ # none, or that the session has finished since. ``peep_context`` is one
452
+ # line on how full its context window is, empty when the agent can't tell.
429
453
  peep_job_id: int = 0
430
454
  peep_job_label: str = ""
431
455
  peep_steps: list[PeepStep] = []
432
456
  peep_note: str = ""
457
+ peep_context: str = ""
433
458
  paused: bool = False
434
459
  total_runs: int = 0
435
460
  last_24h_runs: int = 0
@@ -445,6 +470,9 @@ class AdminState(rx.State):
445
470
  # slow loop of its own.
446
471
  claude_account_usage: list[ClaudeAccount] = []
447
472
  claude_usage_loading: bool = False
473
+ # The account a "Set current" click is switching to, or 0. One at a time:
474
+ # two switches racing would leave the CLI on whichever wrote last.
475
+ claude_switching_account: int = 0
448
476
 
449
477
  runs: list[RunRecord] = []
450
478
  runs_has_more: bool = False
@@ -1046,6 +1074,7 @@ class AdminState(rx.State):
1046
1074
  self.peep_job_id = job_id
1047
1075
  self.peep_job_label = label
1048
1076
  self.peep_steps = []
1077
+ self.peep_context = ""
1049
1078
  self._load_peep()
1050
1079
 
1051
1080
  def set_peep_dialog_open(self, is_open: bool) -> None:
@@ -1054,6 +1083,7 @@ class AdminState(rx.State):
1054
1083
  self.peep_job_label = ""
1055
1084
  self.peep_steps = []
1056
1085
  self.peep_note = ""
1086
+ self.peep_context = ""
1057
1087
 
1058
1088
  def refresh_peep(self) -> None:
1059
1089
  if self.peep_job_id:
@@ -1080,6 +1110,7 @@ class AdminState(rx.State):
1080
1110
  "sessions yet.")
1081
1111
  return
1082
1112
  self.peep_steps = [PeepStep(**entry) for entry in peep["entries"]]
1113
+ self.peep_context = _context_summary(peep.get("context"))
1083
1114
  self.peep_note = ("" if self.peep_steps else
1084
1115
  "Nothing to show yet. The agent may still be "
1085
1116
  "starting up.")
@@ -1147,6 +1178,36 @@ class AdminState(rx.State):
1147
1178
  for account in measured]
1148
1179
  await asyncio.sleep(USAGE_POLL_INTERVAL)
1149
1180
 
1181
+ @rx.event(background=True)
1182
+ async def use_claude_code_account(self, account_id: int) -> Any:
1183
+ """Make one account current and sign Claude Code in as it.
1184
+
1185
+ In the background because it can be two network round trips — renewing
1186
+ the token, then reading the profile — and the dashboard redraws every
1187
+ second meanwhile. The usage rows are redrawn as soon as it lands, so
1188
+ the "in use" badge moves without waiting out the slow usage loop.
1189
+ """
1190
+ async with self:
1191
+ if self.claude_switching_account:
1192
+ return
1193
+ self.claude_switching_account = account_id
1194
+
1195
+ try:
1196
+ switched, message = await asyncio.to_thread(
1197
+ SERVICE.use_claude_code_account, account_id)
1198
+ measured = await asyncio.to_thread(
1199
+ SERVICE.claude_code_account_usage)
1200
+ except Exception as error: # noqa: BLE001 - never leave the row spinning
1201
+ switched, message = False, f"{type(error).__name__}: {error}"
1202
+ measured = None
1203
+
1204
+ async with self:
1205
+ self.claude_switching_account = 0
1206
+ if measured is not None:
1207
+ self.claude_account_usage = [_usage_row(account)
1208
+ for account in measured]
1209
+ yield rx.toast.success(message) if switched else rx.toast.error(message)
1210
+
1150
1211
  def _fetch_runs_page(self, offset: int,
1151
1212
  limit: int = RUNS_PAGE_SIZE) -> list[RunRecord]:
1152
1213
  """One page of runs. Reads one row past the page to learn whether more exist."""
@@ -2008,13 +2069,34 @@ SUBTLE_ICON = "var(--codee-subtle-icon)"
2008
2069
  RUNNING_BACKGROUND = "var(--codee-running-background)"
2009
2070
  RUNNING_GLOW = "var(--codee-running-glow)"
2010
2071
  MONO = "IBM Plex Mono, monospace"
2011
- LOGO = "👨🏻‍💻"
2012
- # Inline SVG carrying the logo emoji, so the favicon needs no binary asset.
2072
+ # Corner brackets with an open palm and a spark; fills use currentColor so the
2073
+ # mark takes the colour of the badge it sits in.
2074
+ LOGO = (
2075
+ '<svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" style="display:block" aria-hidden="true" fill="none" viewBox="6 6 36 36"><path fill="currentColor" d="M7.5 14.9V7.5H14.9V10.5H10.5V14.9Z"></path><path fill="currentColor" d="M40.5 14.9V7.5H33.1V10.5H37.5V14.9Z"></path><path fill="currentColor" d="M7.5 33.1V40.5H14.9V37.5H10.5V33.1Z"></path><path fill="currentColor" d="M40.5 33.1V40.5H33.1V37.5H37.5V33.1Z"></path><g fill="currentColor"><rect x="19.9" y="16.4" width="2.85" height="10" rx="1.425"></rect><rect x="23.3" y="14.75" width="2.85" height="11" rx="1.425"></rect><rect x="26.7" y="15.6" width="2.85" height="10.5" rx="1.425"></rect><rect x="30.1" y="17.9" width="2.85" height="9" rx="1.425"></rect><path d="M32.95 24.6V28C32.95 31 30.6 33.25 27.6 33.25H25.6C23 33.25 18.71 28.21 17.29 26.52Q16.2 25.22 15.11 23.92A1.425 1.425 0 0 1 17.29 22.08Q18.6 23.64 19.9 25.19V24.6Z"></path></g><path fill="currentColor" d="M16 15.3Q16.69 16.91 18.3 17.6Q16.69 18.29 16 19.9Q15.31 18.29 13.7 17.6Q15.31 16.91 16 15.3Z"></path></svg>'
2076
+ )
2077
+ # The logo on the accent-blue badge, inline so the favicon needs no binary asset.
2013
2078
  FAVICON = (
2014
2079
  "data:image/svg+xml;base64,"
2015
- "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAxMD"
2016
- "AgMTAwIj48dGV4dCB5PSIuOWVtIiBmb250LXNpemU9IjkwIj7wn5Go8J+Pu+KAjfCfkrs8L3Rl"
2017
- "eHQ+PC9zdmc+"
2080
+ "PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAz"
2081
+ "MiAzMiI+PHJlY3Qgd2lkdGg9IjMyIiBoZWlnaHQ9IjMyIiByeD0iNiIgZmlsbD0iIzJmNmZk"
2082
+ "NiIvPjxzdmcgeD0iMyIgeT0iMyIgd2lkdGg9IjI2IiBoZWlnaHQ9IjI2IiB2aWV3Qm94PSI2"
2083
+ "IDYgMzYgMzYiPjxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik03LjUgMTQuOVY3LjVIMTQuOVYxMC41"
2084
+ "SDEwLjVWMTQuOVoiPjwvcGF0aD48cGF0aCBmaWxsPSIjZmZmIiBkPSJNNDAuNSAxNC45Vjcu"
2085
+ "NUgzMy4xVjEwLjVIMzcuNVYxNC45WiI+PC9wYXRoPjxwYXRoIGZpbGw9IiNmZmYiIGQ9Ik03"
2086
+ "LjUgMzMuMVY0MC41SDE0LjlWMzcuNUgxMC41VjMzLjFaIj48L3BhdGg+PHBhdGggZmlsbD0i"
2087
+ "I2ZmZiIgZD0iTTQwLjUgMzMuMVY0MC41SDMzLjFWMzcuNUgzNy41VjMzLjFaIj48L3BhdGg+"
2088
+ "PGcgZmlsbD0iI2ZmZiI+PHJlY3QgeD0iMTkuOSIgeT0iMTYuNCIgd2lkdGg9IjIuODUiIGhl"
2089
+ "aWdodD0iMTAiIHJ4PSIxLjQyNSI+PC9yZWN0PjxyZWN0IHg9IjIzLjMiIHk9IjE0Ljc1IiB3"
2090
+ "aWR0aD0iMi44NSIgaGVpZ2h0PSIxMSIgcng9IjEuNDI1Ij48L3JlY3Q+PHJlY3QgeD0iMjYu"
2091
+ "NyIgeT0iMTUuNiIgd2lkdGg9IjIuODUiIGhlaWdodD0iMTAuNSIgcng9IjEuNDI1Ij48L3Jl"
2092
+ "Y3Q+PHJlY3QgeD0iMzAuMSIgeT0iMTcuOSIgd2lkdGg9IjIuODUiIGhlaWdodD0iOSIgcng9"
2093
+ "IjEuNDI1Ij48L3JlY3Q+PHBhdGggZD0iTTMyLjk1IDI0LjZWMjhDMzIuOTUgMzEgMzAuNiAz"
2094
+ "My4yNSAyNy42IDMzLjI1SDI1LjZDMjMgMzMuMjUgMTguNzEgMjguMjEgMTcuMjkgMjYuNTJR"
2095
+ "MTYuMiAyNS4yMiAxNS4xMSAyMy45MkExLjQyNSAxLjQyNSAwIDAgMSAxNy4yOSAyMi4wOFEx"
2096
+ "OC42IDIzLjY0IDE5LjkgMjUuMTlWMjQuNloiPjwvcGF0aD48L2c+PHBhdGggZmlsbD0iI2Zm"
2097
+ "ZiIgZD0iTTE2IDE1LjNRMTYuNjkgMTYuOTEgMTguMyAxNy42UTE2LjY5IDE4LjI5IDE2IDE5"
2098
+ "LjlRMTUuMzEgMTguMjkgMTMuNyAxNy42UTE1LjMxIDE2LjkxIDE2IDE1LjNaIj48L3BhdGg+"
2099
+ "PC9zdmc+PC9zdmc+"
2018
2100
  )
2019
2101
 
2020
2102
 
@@ -2039,13 +2121,35 @@ def nav_link(label: str, icon: str, href: str) -> rx.Component:
2039
2121
  )
2040
2122
 
2041
2123
 
2124
+ def footer_link(label: str, href: str) -> rx.Component:
2125
+ return rx.link(label, href=href, is_external=True, color=MUTED,
2126
+ text_decoration="underline", text_underline_offset="2px",
2127
+ _hover={"color": ACCENT})
2128
+
2129
+
2130
+ def footer() -> rx.Component:
2131
+ return rx.flex(
2132
+ rx.text("Codee is developed by ",
2133
+ footer_link("FuseBase", "https://thefusebase.com")),
2134
+ rx.text("·", aria_hidden="true"),
2135
+ footer_link("Source code on GitHub", "https://github.com/fusebase-dev/codee"),
2136
+ gap="0.5rem",
2137
+ wrap="wrap",
2138
+ align="center",
2139
+ color=MUTED,
2140
+ font_size="0.8rem",
2141
+ padding_top="1rem",
2142
+ border_top=BORDER,
2143
+ )
2144
+
2145
+
2042
2146
  def shell(content: rx.Component) -> rx.Component:
2043
2147
  return rx.box(
2044
2148
  rx.grid(
2045
2149
  rx.box(
2046
2150
  rx.vstack(
2047
2151
  rx.hstack(
2048
- rx.box(LOGO, color="white", background=ACCENT, width="2rem",
2152
+ rx.box(rx.html(LOGO), color="white", background=ACCENT, width="2rem",
2049
2153
  height="2rem", display="grid", place_items="center",
2050
2154
  border_radius="6px", font_weight="700",
2051
2155
  font_size="1.1rem", line_height="1"),
@@ -2092,7 +2196,9 @@ def shell(content: rx.Component) -> rx.Component:
2092
2196
  background=NAV_BACKGROUND,
2093
2197
  min_height=rx.breakpoints(initial="auto", lg="100vh"),
2094
2198
  ),
2095
- rx.box(content, padding=rx.breakpoints(initial="1.25rem", md="2rem", xl="3rem"),
2199
+ rx.box(rx.box(content, flex="1", width="100%"), footer(),
2200
+ padding=rx.breakpoints(initial="1.25rem", md="2rem", xl="3rem"),
2201
+ display="flex", flex_direction="column", gap="3rem",
2096
2202
  min_width="0", max_width="1440px", width="100%"),
2097
2203
  columns=rx.breakpoints(initial="1fr", lg="230px minmax(0, 1fr)"),
2098
2204
  min_height="100vh",
@@ -2338,6 +2444,9 @@ def peep_dialog() -> rx.Component:
2338
2444
  font_size="0.85rem", overflow="hidden",
2339
2445
  text_overflow="ellipsis", white_space="nowrap"),
2340
2446
  color=MUTED),
2447
+ rx.cond(AdminState.peep_context != "",
2448
+ rx.text(AdminState.peep_context, color=MUTED,
2449
+ font_size="0.8rem", margin_top="0.35rem")),
2341
2450
  rx.vstack(
2342
2451
  rx.foreach(AdminState.peep_steps, peep_step),
2343
2452
  rx.cond(AdminState.peep_note != "",
@@ -2488,6 +2597,20 @@ def claude_account_usage_row(account: ClaudeAccount) -> rx.Component:
2488
2597
  variant="soft", flex_shrink="0"),
2489
2598
  rx.fragment()),
2490
2599
  rx.spacer(),
2600
+ # Not on the live one, and not on one that cannot be signed in
2601
+ # with: there is nothing to switch to in either case.
2602
+ rx.cond(
2603
+ account.in_use | account.needs_reconnect,
2604
+ rx.fragment(),
2605
+ rx.button(
2606
+ "Set current", type="button", size="1", variant="soft",
2607
+ flex_shrink="0",
2608
+ loading=AdminState.claude_switching_account == account.id,
2609
+ disabled=AdminState.claude_switching_account != 0,
2610
+ title="Make this the account Claude Code runs on, and "
2611
+ "write its credentials into Claude Code's config",
2612
+ on_click=lambda: AdminState.use_claude_code_account(
2613
+ account.id))),
2491
2614
  spacing="2", align="center", width="100%",
2492
2615
  margin_bottom="0.6rem"),
2493
2616
  rx.cond(
@@ -2588,6 +2711,9 @@ def skill_card(skill: SkillSummary) -> rx.Component:
2588
2711
  rx.cond(skill.effort != "",
2589
2712
  rx.code(skill.effort, font_size="0.72rem",
2590
2713
  color_scheme="gray")),
2714
+ rx.cond(skill.context_tier != "",
2715
+ rx.code(skill.context_tier, font_size="0.72rem",
2716
+ color_scheme="gray", title="Context window")),
2591
2717
  spacing="2", align="center", width="100%",
2592
2718
  class_name="skill-card-meta"),
2593
2719
  rx.cond(
codee/admin_service.py CHANGED
@@ -20,8 +20,10 @@ from dotenv import load_dotenv
20
20
  from codee_database import claude_code_accounts, oauth_tokens
21
21
  from codee_tasks_azure_devops import oauth as azure_oauth
22
22
  from codee_agent_abstract.provider import AbstractCodingAgent, AgentModel
23
+ from codee_agent_claude_code import credentials as claude_credentials
23
24
  from codee_agent_claude_code import oauth as claude_oauth
24
- from codee_agent_claude_code.account import AccountUnavailable, fetch_account
25
+ from codee_agent_claude_code.account import (
26
+ AccountUnavailable, fetch_account, fetch_profile)
25
27
  from codee_agent_claude_code.provider import ClaudeCodeAgent
26
28
  from codee_agent_claude_code.usage import (
27
29
  SESSION_WINDOW, WEEKLY_WINDOW, UsageRateLimited, UsageUnavailable,
@@ -640,11 +642,29 @@ def _skill_run_summary(
640
642
  if skill.effort:
641
643
  lines.append(f"Effort: {skill.effort}")
642
644
  if skill.context_tier:
643
- lines.append(f"Context: {skill.context_tier}")
645
+ lines.append(f"Context: {context_tier_label(skill.context_tier)}")
644
646
  lines.append(f"Skill: {skill.name}")
645
647
  return lines
646
648
 
647
649
 
650
+ def context_tier_label(tier: str) -> str:
651
+ """A skill's ``x-codee-context-tier:`` as a person reads it.
652
+
653
+ The window's own size ("1M") is only known from the agent's model catalog,
654
+ which takes a CLI run to read, so places that list skills say the tier.
655
+ """
656
+ return tier.replace("_", " ")
657
+
658
+
659
+ def _skill_model_line(skill: IssueTriggeredSkill) -> str:
660
+ """The model a skill runs on, with its effort and context tier when set."""
661
+ return " \u00b7 ".join(filter(None, [
662
+ skill.model or WORKFLOW_DEFAULT_MODEL_LABEL,
663
+ skill.effort,
664
+ context_tier_label(skill.context_tier),
665
+ ]))
666
+
667
+
648
668
  def _with_agent_tooltips(
649
669
  workflow: dict[str, Any],
650
670
  skills: list[IssueTriggeredSkill],
@@ -696,10 +716,10 @@ def _node_with_agent_tooltip(
696
716
  if lines:
697
717
  lines.append("")
698
718
  lines.extend(_skill_run_summary(skill, default_agent))
699
- # The models named under the status name on the node itself. Skills sharing
700
- # an entry status often ask for the same one, so it is said once.
701
- models = list(dict.fromkeys(
702
- skill.model or WORKFLOW_DEFAULT_MODEL_LABEL for skill in handled))
719
+ # The models named under the status name on the node itself, each with its
720
+ # effort and context tier. Skills sharing an entry status often ask for the
721
+ # same one, so it is said once.
722
+ models = list(dict.fromkeys(_skill_model_line(skill) for skill in handled))
703
723
  return {
704
724
  **node,
705
725
  "className": " ".join(
@@ -2094,8 +2114,10 @@ class AdminService:
2094
2114
  """The last ``limit`` steps of a running session. None once it finished.
2095
2115
 
2096
2116
  ``entries`` is None rather than a list when the session's agent keeps
2097
- no transcript Codee can read. A row that names no agent, from before
2098
- the dashboard recorded one, is read as the default agent's.
2117
+ no transcript Codee can read. ``context`` says how full the session's
2118
+ context window is, None when the agent can't tell. A row that names no
2119
+ agent, from before the dashboard recorded one, is read as the default
2120
+ agent's.
2099
2121
  """
2100
2122
  job = next((job for job in runs_db.active_jobs(main_context=self.context)
2101
2123
  if job["id"] == job_id), None)
@@ -2104,21 +2126,26 @@ class AdminService:
2104
2126
  agent = (resolve_agent_code(job.get("agent") or "")
2105
2127
  or self.context.settings.coding_agent)
2106
2128
  implementation = CODING_AGENTS.get(agent)
2107
- entries = None
2129
+ entries = context = None
2108
2130
  if implementation is not None:
2109
2131
  try:
2110
2132
  entries = implementation.peep(job["session_id"], self.root,
2111
2133
  limit)
2134
+ context = implementation.context_usage(job["session_id"],
2135
+ self.root)
2112
2136
  except Exception as error:
2113
2137
  print(f"[admin] Could not read job {job_id}'s transcript: "
2114
2138
  f"{error}")
2115
- entries = []
2139
+ entries = entries or []
2116
2140
  return {
2117
2141
  "agent": agent_label(agent),
2118
2142
  "entries": (None if entries is None else
2119
2143
  [{"kind": entry.kind, "text": entry.text,
2120
2144
  "timestamp": entry.timestamp}
2121
2145
  for entry in entries]),
2146
+ "context": (None if context is None else
2147
+ {"tokens": context.tokens, "window": context.window,
2148
+ "compactions": context.compactions}),
2122
2149
  }
2123
2150
 
2124
2151
  def set_paused(self, paused: bool) -> bool:
@@ -2455,6 +2482,57 @@ class AdminService:
2455
2482
  claude_code_accounts.remove_account(account_id, self.context)
2456
2483
  self._reconcile_claude_code_account()
2457
2484
 
2485
+ def use_claude_code_account(self, account_id: int) -> tuple[bool, str]:
2486
+ """Make one account the one in use, and sign the CLI in as it now.
2487
+
2488
+ Returns whether it worked and a sentence to show either way. Both
2489
+ halves are done here rather than left to the next rotation check: the
2490
+ pointer alone would only take effect up to five minutes later, and only
2491
+ in a running executor.
2492
+
2493
+ The token is renewed first, because an account waiting its turn holds
2494
+ one that may have expired hours ago. Its profile goes into
2495
+ ``.claude.json`` too, so the CLI names the account it is now running
2496
+ as instead of the previous one. That part is best-effort: the
2497
+ credentials are what makes the switch, and a profile that could not be
2498
+ read is fetched by the CLI itself on its next run.
2499
+ """
2500
+ try:
2501
+ stored = {account.id: account for account
2502
+ in claude_code_accounts.accounts(self.context)}
2503
+ except Exception as error: # noqa: BLE001 - the UI must never see a traceback
2504
+ return False, f"Could not read the connected accounts: {error}"
2505
+ account = stored.get(account_id)
2506
+ if account is None:
2507
+ return False, "That account is no longer connected"
2508
+ name = account.label or f"account {account.id}"
2509
+ now = int(datetime.now(timezone.utc).timestamp() * 1000)
2510
+ if account.needs_reconnect(now):
2511
+ return False, f"{name} has to be connected again first"
2512
+
2513
+ try:
2514
+ account = ensure_fresh(account, self.context)
2515
+ # A renewal the API refused retires the account rather than
2516
+ # raising, so the only way to hear about it is to look again.
2517
+ renewed = {row.id: row for row
2518
+ in claude_code_accounts.accounts(self.context)}
2519
+ if renewed[account.id].needs_reconnect(now):
2520
+ return False, f"{name} has to be connected again first"
2521
+ claude_credentials.write_credentials(
2522
+ account.access_token, account.refresh_token,
2523
+ account.expires_at, account.scopes, account.subscription_type)
2524
+ claude_code_accounts.set_current_account(account.id, self.context)
2525
+ except Exception as error: # noqa: BLE001
2526
+ return False, f"Could not switch to {name}: {error}"
2527
+
2528
+ try:
2529
+ claude_credentials.write_oauth_account(
2530
+ fetch_profile(account.access_token))
2531
+ except Exception as error: # noqa: BLE001 - the switch itself landed
2532
+ print(f"[admin] Switched Claude Code to {name} but could not "
2533
+ f"record its profile: {error}")
2534
+ return True, f"Claude Code is now running as {name}"
2535
+
2458
2536
  def _reconcile_claude_code_account(self) -> None:
2459
2537
  """Point the current account at a connected one.
2460
2538
 
codee/test_admin.py CHANGED
@@ -4,7 +4,8 @@ from types import SimpleNamespace
4
4
  from unittest.mock import Mock, patch
5
5
 
6
6
  from codee.admin import (EFFORT_DEFAULT, AdminState, ModelOption, PeepStep,
7
- _highlight_parts, _run_preview, running_panel)
7
+ _context_summary, _highlight_parts, _run_preview,
8
+ running_panel)
8
9
 
9
10
 
10
11
  def test_pause_with_running_agents_explains_they_will_finish() -> None:
@@ -101,7 +102,7 @@ def test_killing_a_session_that_already_finished_says_so() -> None:
101
102
 
102
103
  def _peep_state(**fields) -> SimpleNamespace:
103
104
  state = SimpleNamespace(peep_job_id=0, peep_job_label="", peep_steps=[],
104
- peep_note="")
105
+ peep_note="", peep_context="")
105
106
  state.__dict__.update(fields)
106
107
  state._load_peep = lambda: AdminState._load_peep(state)
107
108
  return state
@@ -112,7 +113,9 @@ def test_peep_shows_the_sessions_last_steps() -> None:
112
113
  with patch("codee.admin.SERVICE.peep_job", return_value={
113
114
  "agent": "Claude Code",
114
115
  "entries": [{"kind": "tool", "text": "Bash: ls",
115
- "timestamp": "2026-10-01T10:00:00Z"}]}) as peep:
116
+ "timestamp": "2026-10-01T10:00:00Z"}],
117
+ "context": {"tokens": 41245, "window": 128000,
118
+ "compactions": 1}}) as peep:
116
119
  AdminState.open_peep.fn(state, 7, "/nightly")
117
120
 
118
121
  peep.assert_called_once_with(7, 10)
@@ -120,6 +123,17 @@ def test_peep_shows_the_sessions_last_steps() -> None:
120
123
  assert [(step.kind, step.text) for step in state.peep_steps] == [
121
124
  ("tool", "Bash: ls")]
122
125
  assert state.peep_note == ""
126
+ assert state.peep_context == (
127
+ "Context: 41,245 / 128,000 tokens (32%) · 1 compaction")
128
+
129
+
130
+ def test_the_context_line_says_only_what_the_agent_wrote_down() -> None:
131
+ assert _context_summary(None) == ""
132
+ assert _context_summary({"tokens": 41245, "window": 0,
133
+ "compactions": 0}) == (
134
+ "Context: 41,245 tokens · 0 compactions")
135
+ assert _context_summary({"tokens": 0, "window": 0,
136
+ "compactions": 3}) == "Context: 3 compactions"
123
137
 
124
138
 
125
139
  def test_peep_says_when_there_is_nothing_yet() -> None:
@@ -154,12 +168,12 @@ def test_refreshing_a_finished_session_keeps_what_was_on_screen() -> None:
154
168
  def test_closing_the_peep_dialog_forgets_the_session() -> None:
155
169
  state = _peep_state(peep_job_id=7, peep_job_label="/nightly",
156
170
  peep_steps=[PeepStep(kind="text", text="x")],
157
- peep_note="note")
171
+ peep_note="note", peep_context="Context: 1 compaction")
158
172
 
159
173
  AdminState.set_peep_dialog_open.fn(state, False)
160
174
 
161
175
  assert (state.peep_job_id, state.peep_job_label, state.peep_steps,
162
- state.peep_note) == (0, "", [], "")
176
+ state.peep_note, state.peep_context) == (0, "", [], "", "")
163
177
 
164
178
 
165
179
  def test_clearing_skill_search_resets_query() -> None: