Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
refactor: remove unused internal helpers and state (#5667)
chengyongru63cc5f270d00
diff --git a/nanobot/agent/context.py b/nanobot/agent/context.pyindex 6d280a431..e58a4ab65 100644--- a/nanobot/agent/context.py+++ b/nanobot/agent/context.py@@ -20,9 +20,7 @@ from nanobot.bus.events import (InboundMessage,)from nanobot.runtime_context import (- RUNTIME_CONTEXT_END,RUNTIME_CONTEXT_MESSAGE_META,- RUNTIME_CONTEXT_TAG,RuntimeContextBlock,append_runtime_context,)@@ -93,8 +91,6 @@ class ContextBuilder:BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md"]_SKIPPABLE_DEFAULTS = {"AGENTS.md", "USER.md"}- _RUNTIME_CONTEXT_TAG = RUNTIME_CONTEXT_TAG- _RUNTIME_CONTEXT_END = RUNTIME_CONTEXT_ENDdef __init__(self, workspace: Path, timezone: str | None = None, disabled_skills: list[str] | None = None):self.workspace = workspacediff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.pyindex 38429924a..5aafb5bf5 100644--- a/nanobot/channels/telegram/runtime.py+++ b/nanobot/channels/telegram/runtime.py@@ -503,7 +503,6 @@ class TelegramChannel(BaseChannel):super().__init__(config, bus)self.config: TelegramConfig = configself._app: TelegramApplication | None = None- self._chat_ids: dict[str, int] = {} # Map sender_id to chat_id for repliesself._typing_tasks: dict[str, asyncio.Task[None]] = {} # chat_id -> typing loop taskself._media_group_buffers: dict[str, dict[str, Any]] = {}self._media_group_tasks: dict[str, asyncio.Task[None]] = {}@@ -1723,9 +1722,6 @@ class TelegramChannel(BaseChannel):returnself._remember_thread_context(message)- # Store chat_id for replies- self._chat_ids[sender_id] = chat_id-if not await self._is_group_message_for_bot(message):returndiff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.pyindex 89e82a125..d84b7e9e3 100644--- a/nanobot/channels/websocket/runtime.py+++ b/nanobot/channels/websocket/runtime.py@@ -539,9 +539,6 @@ class WebSocketChannel(BaseChannel):def default_config(cls) -> dict[str, Any]:return WebSocketConfig().model_dump(by_alias=True)- def _expected_path(self) -> str:- return _normalize_config_path(self.config.path)-def _build_ssl_context(self) -> ssl.SSLContext | None:cert = self.config.ssl_certfile.strip()key = self.config.ssl_keyfile.strip()@@ -579,9 +576,6 @@ class WebSocketChannel(BaseChannel):headers,)- def _consume_issued_token(self, connection: ServerConnection, token: str) -> bool:- return self.gateway.endpoint.consume_issued_token(connection, token)-# -- Server lifecycle and connection ingress ---------------------------@staticmethoddiff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.pyindex 47ed4c68e..b3928874c 100644--- a/tests/agent/test_loop_save_turn.py+++ b/tests/agent/test_loop_save_turn.py@@ -26,6 +26,7 @@ from nanobot.providers.factory import ProviderSnapshotfrom nanobot.runtime_context import (RUNTIME_CONTEXT_HISTORY_META,RUNTIME_CONTEXT_MESSAGE_META,+ RUNTIME_CONTEXT_TAG,RuntimeContextBlock,append_runtime_context,public_history_message,@@ -680,7 +681,7 @@ def test_build_and_save_preserves_multimodal_user_block_starting_with_runtime_taimage = tmp_path / "user-tag.png"image.write_bytes(_PNG_1X1)user_text = (- f"{ContextBuilder._RUNTIME_CONTEXT_TAG}\n"+ f"{RUNTIME_CONTEXT_TAG}\n""This entire block is user-authored and must remain in history.")messages = ContextBuilder(tmp_path).build_messages(diff --git a/tui/src/app.test.ts b/tui/src/app.test.tsindex a9ebd0c01..d730daebf 100644--- a/tui/src/app.test.ts+++ b/tui/src/app.test.ts@@ -24,7 +24,7 @@ import type {} from "./protocol"import type { TuiHost } from "./host"import type { ClipboardImageReader } from "./clipboard-image"-import { userMessageText, type Transcript } from "./transcript"+import type { Transcript } from "./transcript"const options: AppOptions = {wsUrl: "ws://localhost.invalid/ws",@@ -60,20 +60,6 @@ test("formats a reusable session ID after exit", () => {)})-test("projects image media as stable placeholders without exposing filenames", () => {- expect(userMessageText("What is this?", [- { name: "clipboard-image-2.png" },- { kind: "image", name: "screenshot.png" },- { kind: "file", name: "report.pdf" },- ])).toBe([- "What is this? [Image #2] [Image #1]",- "Attachments: report.pdf",- ].join("\n"))- expect(userMessageText("What is this?", [- { name: "clipboard-image-1.png" },- ], "What is this? [Image #1]")).toBe("What is this? [Image #1]")-})-function contrastRatio(foreground: string, background: string): number {const luminance = (color: string) => {const channel = (offset: number) => {@@ -3111,6 +3097,8 @@ describe("NanobotTui layout", () => {const app = mount(setup, sent)const composer = (app as unknown as { composer: TextareaRenderable }).composerconst connection = app as unknown as {+ ready: boolean+ submitPending: booleanhandleStatus(status: "reconnecting" | "connected",detail?: string,@@ -3119,7 +3107,7 @@ describe("NanobotTui layout", () => {}app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)+ await waitUntil(() => connection.ready)connection.handleStatus("reconnecting", "connection closed", {endpoint: "127.0.0.1:8769",attempt: 1,@@ -3128,16 +3116,16 @@ describe("NanobotTui layout", () => {connection.handleStatus("connected")composer.setText("draft before attach")composer.submit()- await Bun.sleep(5)+ await waitUntil(() => !connection.submitPending)composer.submit()- await Bun.sleep(5)+ await waitUntil(() => !connection.submitPending)expect(sent).toEqual([])expect(composer.plainText).toBe("draft before attach")app.accept({ event: "attached", chat_id: "chat" })app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ await waitUntil(() => connection.ready)expect(sent).toEqual([])composer.submit()await waitUntil(() => sent.length === 1)diff --git a/tui/src/transcript.ts b/tui/src/transcript.tsindex 026f137eb..9fd8d5283 100644--- a/tui/src/transcript.ts+++ b/tui/src/transcript.ts@@ -104,18 +104,6 @@ function projectUserMessage(media: readonly UserMessageMedia[]): UserMessageProjreturn { imageLabels, attachmentNames }}-export function userMessageText(- content: string,- media: readonly UserMessageMedia[] = [],- displayContent?: string,-): string {- const { imageLabels, attachmentNames } = projectUserMessage(media)- return [- displayContent ?? [content, imageLabels.join(" ")].filter(Boolean).join(" "),- attachmentNames.length ? `Attachments: ${attachmentNames.join(", ")}` : "",- ].filter(Boolean).join("\n")-}-/** Projects gateway events into retained, reflowable conversation cells. */export class Transcript {readonly root: ScrollBoxRenderablediff --git a/webui/src/components/thread/activity/web-url.ts b/webui/src/components/thread/activity/web-url.tsindex 6ffa14139..7cab2bb7f 100644--- a/webui/src/components/thread/activity/web-url.ts+++ b/webui/src/components/thread/activity/web-url.ts@@ -1,15 +1,3 @@-export function parsePublicHttpUrl(value: string): URL | null {- try {- const url = new URL(value);- if (url.protocol !== "http:" && url.protocol !== "https:") return null;- if (url.username || url.password) return null;- if (isPrivateHostname(url.hostname)) return null;- return url;- } catch {- return null;- }-}-/** Public URL normalized for timeline display, with credentials and request-specific noise removed. */export function parseSafeActivityHttpUrl(value: string): URL | null {try {diff --git a/webui/src/lib/api.ts b/webui/src/lib/api.tsindex 7af6fe3dd..fbb36b4ba 100644--- a/webui/src/lib/api.ts+++ b/webui/src/lib/api.ts@@ -27,7 +27,6 @@ import type {SessionHandle,SessionAutomationsPayload,SettingsPayload,- SettingsUpdate,SidebarStatePayload,SkillDetail,SkillActionPayload,@@ -882,26 +881,6 @@ export async function updateSidebarState(return mutation<SidebarStatePayload>(transport, "sidebar.update", { state });}-export async function updateSettings(- transport: WebUIMutationTransport,- update: SettingsUpdate,-): Promise<SettingsPayload> {- const payload: Record<string, unknown> = {};- if (update.modelPreset !== undefined) {- payload.model_preset = update.modelPreset ?? "default";- }- if (update.model !== undefined) payload.model = update.model;- if (update.provider !== undefined) payload.provider = update.provider;- if (update.contextWindowTokens !== undefined) {- payload.context_window_tokens = update.contextWindowTokens;- }- if (update.timezone !== undefined) payload.timezone = update.timezone;- if (update.toolHintMaxLength !== undefined) {- payload.tool_hint_max_length = update.toolHintMaxLength;- }- return mutation<SettingsPayload>(transport, "settings.agent.update", payload);-}-function modelGenerationSettingsPayload(configuration: Pick<ModelConfigurationCreate,diff --git a/webui/src/lib/types.ts b/webui/src/lib/types.tsindex e9aee6c87..546b8d392 100644--- a/webui/src/lib/types.ts+++ b/webui/src/lib/types.ts@@ -1204,15 +1204,6 @@ export interface ChannelConfigurePayload {nanobot_features?: NanobotFeaturesPayload;}-export interface SettingsUpdate {- model?: string;- provider?: string;- modelPreset?: string | null;- contextWindowTokens?: number;- timezone?: string;- toolHintMaxLength?: number;-}-export interface ModelConfigurationCreate {name: string;provider: string;diff --git a/webui/src/tests/api.test.ts b/webui/src/tests/api.test.tsindex 0afeee0da..65d810786 100644--- a/webui/src/tests/api.test.ts+++ b/webui/src/tests/api.test.ts@@ -57,7 +57,6 @@ import {updateMcpServerTools,updateNetworkSafetySettings,updateProviderSettings,- updateSettings,updateSkillEnabled,updateWebSearchSettings,validateChannel,@@ -402,30 +401,6 @@ describe("webui API helpers", () => {);});- it("serializes settings updates as a narrow mutation payload", async () => {- await updateSettings(mutationTransport, {- modelPreset: "default",- model: "openrouter/test",- provider: "openrouter",- contextWindowTokens: 262144,- timezone: "Asia/Shanghai",- toolHintMaxLength: 120,- });-- expect(requestMutation).toHaveBeenCalledWith(- "settings.agent.update",- {- model_preset: "default",- model: "openrouter/test",- provider: "openrouter",- context_window_tokens: 262144,- timezone: "Asia/Shanghai",- tool_hint_max_length: 120,- },- 20_000,- );- });-it("fetches token usage through the lightweight settings endpoint", async () => {await fetchSettingsUsage("tok");diff --git a/webui/src/tests/web-url.test.ts b/webui/src/tests/web-url.test.tsindex 3e8a69161..ab8ee905b 100644--- a/webui/src/tests/web-url.test.ts+++ b/webui/src/tests/web-url.test.ts@@ -2,13 +2,12 @@ import { describe, expect, it } from "vitest";import {formatCompactWebUrl,- parsePublicHttpUrl,parseSafeActivityHttpUrl,} from "@/components/thread/activity/web-url";describe("activity web URLs", () => {it("keeps public HTTP URLs and removes query noise from their label", () => {- const url = parsePublicHttpUrl("https://www.example.com/docs/?token=private#section");+ const url = parseSafeActivityHttpUrl("https://www.example.com/docs/?token=private#section");expect(url).not.toBeNull();expect(formatCompactWebUrl(url!)).toBe("example.com/docs");});@@ -24,9 +23,8 @@ describe("activity web URLs", () => {"http://192.168.1.1","http://[::1]","http://[::ffff:127.0.0.1]",- "https://user:[email protected]",- ])("rejects private or credential-bearing target %s", (value) => {- expect(parsePublicHttpUrl(value)).toBeNull();+ ])("rejects private target %s", (value) => {+ expect(parseSafeActivityHttpUrl(value)).toBeNull();});it("normalizes credential-bearing public URLs for safe activity display", () => {