refactor: remove unused internal helpers and state (#5667)

* refactor: remove unused internal helpers and state

* test(tui): await deferred submissions before reconnect attach
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-05 22:09:12 +08:00
1 parent f37ba60ed4
commit 63cc5f270d
11 files changed
+12 -118

No files matched your search

-4
View File
@@ -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_END
def __init__(self, workspace: Path, timezone: str | None = None, disabled_skills: list[str] | None = None):
self.workspace = workspace
-4
View File
@@ -503,7 +503,6 @@ class TelegramChannel(BaseChannel):
super().__init__(config, bus)
self.config: TelegramConfig = config
self._app: TelegramApplication | None = None
self._chat_ids: dict[str, int] = {} # Map sender_id to chat_id for replies
self._typing_tasks: dict[str, asyncio.Task[None]] = {} # chat_id -> typing loop task
self._media_group_buffers: dict[str, dict[str, Any]] = {}
self._media_group_tasks: dict[str, asyncio.Task[None]] = {}
@@ -1723,9 +1722,6 @@ class TelegramChannel(BaseChannel):
return
self._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):
return
-6
View File
@@ -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 ---------------------------
@staticmethod
+2 -1
View File
@@ -26,6 +26,7 @@ from nanobot.providers.factory import ProviderSnapshot
from 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_ta
image = 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(
+7 -19
View File
@@ -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 }).composer
const connection = app as unknown as {
ready: boolean
submitPending: boolean
handleStatus(
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)
-12
View File
@@ -104,18 +104,6 @@ function projectUserMessage(media: readonly UserMessageMedia[]): UserMessageProj
return { 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: ScrollBoxRenderable
@@ -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 {
-21
View File
@@ -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,
-9
View File
@@ -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;
-25
View File
@@ -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");
+3 -5
View File
@@ -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:password@example.com",
])("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", () => {