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:
1 parent
f37ba60ed4
commit
63cc5f270d
11 files changed
+12
-118
No files matched your search
@@ -20,9 +20,7 @@ from nanobot.bus.events import (
|
|||||||
InboundMessage,
|
InboundMessage,
|
||||||
)
|
)
|
||||||
from nanobot.runtime_context import (
|
from nanobot.runtime_context import (
|
||||||
RUNTIME_CONTEXT_END,
|
|
||||||
RUNTIME_CONTEXT_MESSAGE_META,
|
RUNTIME_CONTEXT_MESSAGE_META,
|
||||||
RUNTIME_CONTEXT_TAG,
|
|
||||||
RuntimeContextBlock,
|
RuntimeContextBlock,
|
||||||
append_runtime_context,
|
append_runtime_context,
|
||||||
)
|
)
|
||||||
@@ -93,8 +91,6 @@ class ContextBuilder:
|
|||||||
|
|
||||||
BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md"]
|
BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md"]
|
||||||
_SKIPPABLE_DEFAULTS = {"AGENTS.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):
|
def __init__(self, workspace: Path, timezone: str | None = None, disabled_skills: list[str] | None = None):
|
||||||
self.workspace = workspace
|
self.workspace = workspace
|
||||||
|
|||||||
@@ -503,7 +503,6 @@ class TelegramChannel(BaseChannel):
|
|||||||
super().__init__(config, bus)
|
super().__init__(config, bus)
|
||||||
self.config: TelegramConfig = config
|
self.config: TelegramConfig = config
|
||||||
self._app: TelegramApplication | None = None
|
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._typing_tasks: dict[str, asyncio.Task[None]] = {} # chat_id -> typing loop task
|
||||||
self._media_group_buffers: dict[str, dict[str, Any]] = {}
|
self._media_group_buffers: dict[str, dict[str, Any]] = {}
|
||||||
self._media_group_tasks: dict[str, asyncio.Task[None]] = {}
|
self._media_group_tasks: dict[str, asyncio.Task[None]] = {}
|
||||||
@@ -1723,9 +1722,6 @@ class TelegramChannel(BaseChannel):
|
|||||||
return
|
return
|
||||||
self._remember_thread_context(message)
|
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):
|
if not await self._is_group_message_for_bot(message):
|
||||||
return
|
return
|
||||||
|
|
||||||
|
|||||||
@@ -539,9 +539,6 @@ class WebSocketChannel(BaseChannel):
|
|||||||
def default_config(cls) -> dict[str, Any]:
|
def default_config(cls) -> dict[str, Any]:
|
||||||
return WebSocketConfig().model_dump(by_alias=True)
|
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:
|
def _build_ssl_context(self) -> ssl.SSLContext | None:
|
||||||
cert = self.config.ssl_certfile.strip()
|
cert = self.config.ssl_certfile.strip()
|
||||||
key = self.config.ssl_keyfile.strip()
|
key = self.config.ssl_keyfile.strip()
|
||||||
@@ -579,9 +576,6 @@ class WebSocketChannel(BaseChannel):
|
|||||||
headers,
|
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 ---------------------------
|
# -- Server lifecycle and connection ingress ---------------------------
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ from nanobot.providers.factory import ProviderSnapshot
|
|||||||
from nanobot.runtime_context import (
|
from nanobot.runtime_context import (
|
||||||
RUNTIME_CONTEXT_HISTORY_META,
|
RUNTIME_CONTEXT_HISTORY_META,
|
||||||
RUNTIME_CONTEXT_MESSAGE_META,
|
RUNTIME_CONTEXT_MESSAGE_META,
|
||||||
|
RUNTIME_CONTEXT_TAG,
|
||||||
RuntimeContextBlock,
|
RuntimeContextBlock,
|
||||||
append_runtime_context,
|
append_runtime_context,
|
||||||
public_history_message,
|
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 = tmp_path / "user-tag.png"
|
||||||
image.write_bytes(_PNG_1X1)
|
image.write_bytes(_PNG_1X1)
|
||||||
user_text = (
|
user_text = (
|
||||||
f"{ContextBuilder._RUNTIME_CONTEXT_TAG}\n"
|
f"{RUNTIME_CONTEXT_TAG}\n"
|
||||||
"This entire block is user-authored and must remain in history."
|
"This entire block is user-authored and must remain in history."
|
||||||
)
|
)
|
||||||
messages = ContextBuilder(tmp_path).build_messages(
|
messages = ContextBuilder(tmp_path).build_messages(
|
||||||
|
|||||||
+7
-19
@@ -24,7 +24,7 @@ import type {
|
|||||||
} from "./protocol"
|
} from "./protocol"
|
||||||
import type { TuiHost } from "./host"
|
import type { TuiHost } from "./host"
|
||||||
import type { ClipboardImageReader } from "./clipboard-image"
|
import type { ClipboardImageReader } from "./clipboard-image"
|
||||||
import { userMessageText, type Transcript } from "./transcript"
|
import type { Transcript } from "./transcript"
|
||||||
|
|
||||||
const options: AppOptions = {
|
const options: AppOptions = {
|
||||||
wsUrl: "ws://localhost.invalid/ws",
|
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 {
|
function contrastRatio(foreground: string, background: string): number {
|
||||||
const luminance = (color: string) => {
|
const luminance = (color: string) => {
|
||||||
const channel = (offset: number) => {
|
const channel = (offset: number) => {
|
||||||
@@ -3111,6 +3097,8 @@ describe("NanobotTui layout", () => {
|
|||||||
const app = mount(setup, sent)
|
const app = mount(setup, sent)
|
||||||
const composer = (app as unknown as { composer: TextareaRenderable }).composer
|
const composer = (app as unknown as { composer: TextareaRenderable }).composer
|
||||||
const connection = app as unknown as {
|
const connection = app as unknown as {
|
||||||
|
ready: boolean
|
||||||
|
submitPending: boolean
|
||||||
handleStatus(
|
handleStatus(
|
||||||
status: "reconnecting" | "connected",
|
status: "reconnecting" | "connected",
|
||||||
detail?: string,
|
detail?: string,
|
||||||
@@ -3119,7 +3107,7 @@ describe("NanobotTui layout", () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
app.accept({ event: "attached", chat_id: "chat" })
|
app.accept({ event: "attached", chat_id: "chat" })
|
||||||
await Bun.sleep(1)
|
await waitUntil(() => connection.ready)
|
||||||
connection.handleStatus("reconnecting", "connection closed", {
|
connection.handleStatus("reconnecting", "connection closed", {
|
||||||
endpoint: "127.0.0.1:8769",
|
endpoint: "127.0.0.1:8769",
|
||||||
attempt: 1,
|
attempt: 1,
|
||||||
@@ -3128,16 +3116,16 @@ describe("NanobotTui layout", () => {
|
|||||||
connection.handleStatus("connected")
|
connection.handleStatus("connected")
|
||||||
composer.setText("draft before attach")
|
composer.setText("draft before attach")
|
||||||
composer.submit()
|
composer.submit()
|
||||||
await Bun.sleep(5)
|
await waitUntil(() => !connection.submitPending)
|
||||||
composer.submit()
|
composer.submit()
|
||||||
await Bun.sleep(5)
|
await waitUntil(() => !connection.submitPending)
|
||||||
|
|
||||||
expect(sent).toEqual([])
|
expect(sent).toEqual([])
|
||||||
expect(composer.plainText).toBe("draft before attach")
|
expect(composer.plainText).toBe("draft before attach")
|
||||||
|
|
||||||
app.accept({ event: "attached", chat_id: "chat" })
|
app.accept({ event: "attached", chat_id: "chat" })
|
||||||
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([])
|
expect(sent).toEqual([])
|
||||||
composer.submit()
|
composer.submit()
|
||||||
await waitUntil(() => sent.length === 1)
|
await waitUntil(() => sent.length === 1)
|
||||||
|
|||||||
@@ -104,18 +104,6 @@ function projectUserMessage(media: readonly UserMessageMedia[]): UserMessageProj
|
|||||||
return { imageLabels, attachmentNames }
|
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. */
|
/** Projects gateway events into retained, reflowable conversation cells. */
|
||||||
export class Transcript {
|
export class Transcript {
|
||||||
readonly root: ScrollBoxRenderable
|
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. */
|
/** Public URL normalized for timeline display, with credentials and request-specific noise removed. */
|
||||||
export function parseSafeActivityHttpUrl(value: string): URL | null {
|
export function parseSafeActivityHttpUrl(value: string): URL | null {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -27,7 +27,6 @@ import type {
|
|||||||
SessionHandle,
|
SessionHandle,
|
||||||
SessionAutomationsPayload,
|
SessionAutomationsPayload,
|
||||||
SettingsPayload,
|
SettingsPayload,
|
||||||
SettingsUpdate,
|
|
||||||
SidebarStatePayload,
|
SidebarStatePayload,
|
||||||
SkillDetail,
|
SkillDetail,
|
||||||
SkillActionPayload,
|
SkillActionPayload,
|
||||||
@@ -882,26 +881,6 @@ export async function updateSidebarState(
|
|||||||
return mutation<SidebarStatePayload>(transport, "sidebar.update", { state });
|
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(
|
function modelGenerationSettingsPayload(
|
||||||
configuration: Pick<
|
configuration: Pick<
|
||||||
ModelConfigurationCreate,
|
ModelConfigurationCreate,
|
||||||
|
|||||||
@@ -1204,15 +1204,6 @@ export interface ChannelConfigurePayload {
|
|||||||
nanobot_features?: NanobotFeaturesPayload;
|
nanobot_features?: NanobotFeaturesPayload;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SettingsUpdate {
|
|
||||||
model?: string;
|
|
||||||
provider?: string;
|
|
||||||
modelPreset?: string | null;
|
|
||||||
contextWindowTokens?: number;
|
|
||||||
timezone?: string;
|
|
||||||
toolHintMaxLength?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ModelConfigurationCreate {
|
export interface ModelConfigurationCreate {
|
||||||
name: string;
|
name: string;
|
||||||
provider: string;
|
provider: string;
|
||||||
|
|||||||
@@ -57,7 +57,6 @@ import {
|
|||||||
updateMcpServerTools,
|
updateMcpServerTools,
|
||||||
updateNetworkSafetySettings,
|
updateNetworkSafetySettings,
|
||||||
updateProviderSettings,
|
updateProviderSettings,
|
||||||
updateSettings,
|
|
||||||
updateSkillEnabled,
|
updateSkillEnabled,
|
||||||
updateWebSearchSettings,
|
updateWebSearchSettings,
|
||||||
validateChannel,
|
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 () => {
|
it("fetches token usage through the lightweight settings endpoint", async () => {
|
||||||
await fetchSettingsUsage("tok");
|
await fetchSettingsUsage("tok");
|
||||||
|
|
||||||
|
|||||||
@@ -2,13 +2,12 @@ import { describe, expect, it } from "vitest";
|
|||||||
|
|
||||||
import {
|
import {
|
||||||
formatCompactWebUrl,
|
formatCompactWebUrl,
|
||||||
parsePublicHttpUrl,
|
|
||||||
parseSafeActivityHttpUrl,
|
parseSafeActivityHttpUrl,
|
||||||
} from "@/components/thread/activity/web-url";
|
} from "@/components/thread/activity/web-url";
|
||||||
|
|
||||||
describe("activity web URLs", () => {
|
describe("activity web URLs", () => {
|
||||||
it("keeps public HTTP URLs and removes query noise from their label", () => {
|
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(url).not.toBeNull();
|
||||||
expect(formatCompactWebUrl(url!)).toBe("example.com/docs");
|
expect(formatCompactWebUrl(url!)).toBe("example.com/docs");
|
||||||
});
|
});
|
||||||
@@ -24,9 +23,8 @@ describe("activity web URLs", () => {
|
|||||||
"http://192.168.1.1",
|
"http://192.168.1.1",
|
||||||
"http://[::1]",
|
"http://[::1]",
|
||||||
"http://[::ffff:127.0.0.1]",
|
"http://[::ffff:127.0.0.1]",
|
||||||
"https://user:password@example.com",
|
])("rejects private target %s", (value) => {
|
||||||
])("rejects private or credential-bearing target %s", (value) => {
|
expect(parseSafeActivityHttpUrl(value)).toBeNull();
|
||||||
expect(parsePublicHttpUrl(value)).toBeNull();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it("normalizes credential-bearing public URLs for safe activity display", () => {
|
it("normalizes credential-bearing public URLs for safe activity display", () => {
|
||||||
|
|||||||
Reference in new issue
Block a user