Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ import {
import { isLocalOnlyUrl } from "@/lib/loopback-hostname";
import { PluginBrowserToolbarActions } from "@/components/plugin/PluginBrowserToolbarActions";
import { isImeComposing, isNonImeKey } from "@bb/shared-ui/lib/ime-keyboard";
import { sliceUtf16Head } from "@bb/text-utils";

interface BrowserTabContentProps {
tabId: string;
Expand Down Expand Up @@ -973,7 +974,10 @@ export function BrowserTabContent({

const handleFindQueryChange = useCallback(
(rawQuery: string) => {
const query = rawQuery.slice(0, BB_DESKTOP_BROWSER_MAX_FIND_TEXT_LENGTH);
const query = sliceUtf16Head(
rawQuery,
BB_DESKTOP_BROWSER_MAX_FIND_TEXT_LENGTH,
);
setFindQuery(query);
if (query.length === 0) {
clearFind();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {
GENERATED_MESSAGE_COLLAPSED_PREVIEW_CHAR_CAP,
} from "@bb/client-core";
import { isNonImeKey } from "@bb/shared-ui/lib/ime-keyboard";
import { sliceUtf16Head } from "@bb/text-utils";

interface AutomationLink {
automationId: string;
Expand Down Expand Up @@ -135,8 +136,8 @@ export function generatedConversationBodySlice({
export function generatedConversationCollapsedPreview(
text: string,
): GeneratedConversationCollapsedPreview {
const previewWindow = text.slice(
0,
const previewWindow = sliceUtf16Head(
text,
GENERATED_MESSAGE_COLLAPSED_PREVIEW_CHAR_CAP + 1,
);
const lineBreakMatch = /\r\n|\r|\n/u.exec(previewWindow);
Expand Down
2 changes: 2 additions & 0 deletions apps/app/src/lib/plugin-sdk-app-impl.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { applicationLinkApprovals } from "./application-url";
import { matchesAppShortcutKey } from "@bb/domain";
import { sliceUtf16Head } from "@bb/text-utils";
import {
LazyPluginMarkdown,
LazyPluginDiff,
Expand Down Expand Up @@ -187,6 +188,7 @@ export const pluginSdkAppImplementation = {
experimental_FailedVoiceRecordings: FailedVoiceRecordings,
experimental_ShortcutHint: AppCommandShortcutHint,
experimental_matchesShortcutKey: matchesAppShortcutKey,
experimental_sliceUtf16Head: sliceUtf16Head,
experimental_ImageLightbox: ImageLightbox,
experimental_PromptMentionIcon: ComposerMentionIcon,
experimental_describePromptMention: describePromptMention,
Expand Down
3 changes: 2 additions & 1 deletion apps/app/src/views/root-compose-initial-prompt.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { sliceUtf16Head } from "@bb/text-utils";
export const INITIAL_PROMPT_MAX_LENGTH = 8000;

export const INITIAL_PROMPT_SEARCH_PARAM = "initialPrompt";
Expand All @@ -13,7 +14,7 @@ export function readInitialPromptFromSearch(search: string): string | null {
if (raw === null) return null;
const trimmed = raw.trim();
if (trimmed.length === 0) return null;
return trimmed.slice(0, INITIAL_PROMPT_MAX_LENGTH);
return sliceUtf16Head(trimmed, INITIAL_PROMPT_MAX_LENGTH);
}

export function stripInitialPromptFromSearch(search: string): string {
Expand Down
3 changes: 2 additions & 1 deletion apps/cli/src/commands/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import { runPluginCliCommand } from "../plugin-cli-proxy.js";
import { resolveBbCliVersion } from "../version.js";

import { renderBorderlessTable } from "../table.js";
import { sliceUtf16Head } from "@bb/text-utils";

interface NewPluginTarget {
packageName: string;
Expand Down Expand Up @@ -506,7 +507,7 @@ async function callPlugins(
parsed = text ? JSON.parse(text) : {};
} catch {
throw new Error(
`Unexpected response from /api/v1/plugins${path} (${response.status}): ${text.slice(0, 200)}`,
`Unexpected response from /api/v1/plugins${path} (${response.status}): ${sliceUtf16Head(text, 200)}`,
);
}
if (!response.ok && ![400, 404, 422].includes(response.status)) {
Expand Down
1 change: 1 addition & 0 deletions apps/demo-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"dependencies": {
"@bb/domain": "workspace:*",
"@bb/server-contract": "workspace:*",
"@bb/text-utils": "workspace:*",
"zod": "^4.6.7"
},
"devDependencies": {
Expand Down
11 changes: 7 additions & 4 deletions apps/demo-server/src/demo-world.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import {
threadResponse,
type DemoThreadView,
} from "./fixtures/world.js";
import { sliceUtf16Head } from "@bb/text-utils";

const SYSTEM_CONFIG = systemConfigResponseSchema.parse({
...configFixture,
Expand Down Expand Up @@ -147,10 +148,12 @@ async function readJson(request: Request): Promise<unknown> {
}

function promptText(input: readonly PromptInput[]): string {
return input
.flatMap((part) => (part.type === "text" ? [part.text] : []))
.join("\n")
.slice(0, MAX_MESSAGE_CHARS);
return sliceUtf16Head(
input
.flatMap((part) => (part.type === "text" ? [part.text] : []))
.join("\n"),
MAX_MESSAGE_CHARS,
);
}

function uiPreferenceEntry<Key extends UiPreferenceKey>(key: Key) {
Expand Down
5 changes: 3 additions & 2 deletions apps/desktop/src/browser-import/discovery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
type BrowserImportPathContext,
type BrowserImportSourceDefinition,
} from "./sources.js";
import { sliceUtf16Head } from "@bb/text-utils";

const MAX_DIRECTORIES = 2_000;
const MAX_SOURCES = 100;
Expand Down Expand Up @@ -239,7 +240,7 @@ async function detectProfiles(
continue;
if (detectCookieStorage(path) !== format) continue;
claimed.add(actual);
found.push({ ...profile, name: profile.name.slice(0, 256) });
found.push({ ...profile, name: sliceUtf16Head(profile.name, 256) });
break;
}
if (found.length >= MAX_PROFILES) break;
Expand Down Expand Up @@ -308,7 +309,7 @@ export async function discoverBrowserImportSources(
const name = known?.name ?? directoryName;
sources.push({
id: `storage-${createHash("sha256").update(`${engine}\0${root}`).digest("hex")}`,
name: `${name.slice(0, 48)} (${engine === "chromium" ? "Chromium" : "Firefox"})`,
name: `${sliceUtf16Head(name, 48)} (${engine === "chromium" ? "Chromium" : "Firefox"})`,
engine,
platforms: [context.platform],
userDataDirectory: () => root,
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/desktop-browser-broker-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
desktopBrowserResultSchemas,
} from "@bb/host-daemon-contract";
import type { DesktopBrowserBroker } from "./desktop-browser-broker.js";
import { sliceUtf16Head } from "@bb/text-utils";

export function isTrustedBrokerDescriptorFile(args: {
isFile: boolean;
Expand Down Expand Up @@ -259,7 +260,7 @@ export function createDesktopBrowserBrokerClient(args: {
requestId: parsed.requestId,
message:
error instanceof Error
? error.message.slice(0, 8192)
? sliceUtf16Head(error.message, 8192)
: "Desktop browser operation failed",
}),
);
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/desktop-browser-view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import {
evaluatePopupRate,
isAllowedBrowserUrl,
} from "./desktop-browser-policy.js";
import { sliceUtf16Head } from "@bb/text-utils";

const HIDDEN_PAGE_LIMIT = 4;
const HIDDEN_PAGE_IDLE_MS = 5 * 60_000;
Expand All @@ -88,7 +89,7 @@ const RENDERER_RECOVERY_DELAY_MS = 250;
const RENDERER_RECOVERY_MAX_ATTEMPTS = 2;

function truncate(value: string, max: number): string {
return value.length > max ? value.slice(0, max) : value;
return sliceUtf16Head(value, max);
}

function clampPopupDimension(
Expand Down
10 changes: 5 additions & 5 deletions apps/desktop/src/server-target.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { z } from "zod";
import { sliceUtf16Head } from "@bb/text-utils";

export const SERVER_TARGET_FILE_NAME = "server-target.json";
export const MAX_SERVER_NAME_LENGTH = 64;
Expand Down Expand Up @@ -88,11 +89,10 @@ const persistedServerTargetSchema = z.looseObject({
type PersistedServerTarget = z.infer<typeof persistedServerTargetSchema>;

export function normalizeServerName(rawName: string): string | null {
const name = rawName
.trim()
.replace(/\s+/gu, " ")
.slice(0, MAX_SERVER_NAME_LENGTH)
.trimEnd();
const name = sliceUtf16Head(
rawName.trim().replace(/\s+/gu, " "),
MAX_SERVER_NAME_LENGTH,
).trimEnd();
return name.length === 0 ? null : name;
}

Expand Down
3 changes: 2 additions & 1 deletion apps/host-daemon/src/enroll.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { hostDaemonEnrollResponseSchema } from "@bb/host-daemon-contract";
import { sliceUtf16Head } from "@bb/text-utils";

interface EnrollHostArgs {
fetchFn?: typeof fetch;
Expand All @@ -23,7 +24,7 @@ function summarizeErrorDetail(detail: string): string {
if (compact.length <= 200) {
return compact;
}
return `${compact.slice(0, 197)}...`;
return `${sliceUtf16Head(compact, 197)}...`;
}

export async function enrollDaemonHost(
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@bb/mobile-bridge": "workspace:*",
"@bb/sdk": "workspace:*",
"@bb/server-contract": "workspace:*",
"@bb/text-utils": "workspace:*",
"@expo/ui": "58.0.27",
"@gorhom/bottom-sheet": "^5.2.14",
"@hugeicons/core-free-icons": "~4.3.4",
Expand Down
3 changes: 2 additions & 1 deletion apps/mobile/src/lib/device-label.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import Constants from "expo-constants";
import { Platform } from "react-native";
import { sliceUtf16Head } from "@bb/text-utils";

export function describeThisDevice(): string {
const name = Constants.deviceName?.trim();
if (name && name.length > 0) return name.slice(0, 128);
if (name && name.length > 0) return sliceUtf16Head(name, 128);
return Platform.OS === "android" ? "Android device" : "iPhone";
}
6 changes: 5 additions & 1 deletion apps/server/src/assets/install-machine-windows.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,11 @@ async function downloadPackage({ bootstrap, dataDir, npmPrefix }) {
const body = await response.json();
if (body !== null && typeof body.message === "string") {
details.push(
`Server: ${body.message.replace(/[\x00-\x1f\x7f-\x9f]/gu, " ").slice(0, 2000)}`,
`Server: ${Array.from(
body.message.replace(/[\x00-\x1f\x7f-\x9f]/gu, " "),
)
.slice(0, 2000)
.join("")}`,
);
}
} catch {}
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/services/desktop-browsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
callHostOnlineRpc,
callHostOnlineRpcForWork,
} from "./hosts/online-rpc.js";
import { sliceUtf16Head } from "@bb/text-utils";

interface LeaseEntry {
lease: ExperimentalDesktopBrowserLease;
Expand Down Expand Up @@ -116,7 +117,7 @@ function toStoredBrowserTab(
id: tab.tabId,
kind: "browser" as const,
environmentId: null,
title: tab.title.slice(0, 1024) || null,
title: sliceUtf16Head(tab.title, 1024) || null,
url: tab.url,
desktopTarget: {
hostId: scope.hostId,
Expand Down
5 changes: 3 additions & 2 deletions apps/server/src/services/environments/environment-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ import {
operationInProgress,
} from "../lib/operation-response.js";
import { defineItemSweep, type ItemSweep } from "../system/item-sweep.js";
import { sliceUtf16Head } from "@bb/text-utils";

type Deps = ThreadProvisioningDeps;

Expand Down Expand Up @@ -296,9 +297,9 @@ function provisioningReporter(
step: (text) =>
report(
(row) => {
row.statusMessage = text.slice(0, 200);
row.statusMessage = sliceUtf16Head(text, 200);
},
text.slice(0, 200),
sliceUtf16Head(text, 200),
),
log: (text) =>
report((row) => {
Expand Down
12 changes: 7 additions & 5 deletions apps/server/src/services/machines/provider-orchestration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ import { toHostWithStatus } from "../lib/entity-lookup.js";
import { perDbRegistry } from "../lib/per-db-registry.js";
import { defineItemSweep, type ItemSweep } from "../system/item-sweep.js";
import { emitPluginHostDeleted } from "../plugins/plugin-thread-events.js";
import { sliceUtf16Head, sliceUtf16Tail } from "@bb/text-utils";

type Deps = ThreadProvisioningDeps;
type MachineLifecycleDeps = Pick<Deps, "db" | "hub" | "logger">;
Expand Down Expand Up @@ -191,17 +192,18 @@ function createReporter(
const current = getHost(deps.db, owner.id);
if (!createOwns(current, owner) || current.phase !== "creating") return;
updateHost(deps.db, deps.hub, owner.id, {
statusMessage: text.slice(0, 500),
statusMessage: sliceUtf16Head(text, 500),
});
deps.hub.notifyHost(owner.id, ["host-connected"]);
},
log: (text) => {
const current = getHost(deps.db, owner.id);
if (!createOwns(current, owner) || current.phase !== "creating") return;
updateHost(deps.db, deps.hub, owner.id, {
pendingLog: (
current.pendingLog + (text.endsWith("\n") ? text : `${text}\n`)
).slice(-16_384),
pendingLog: sliceUtf16Tail(
current.pendingLog + (text.endsWith("\n") ? text : `${text}\n`),
16_384,
),
});
deps.hub.notifyHost(owner.id, ["host-connected"]);
},
Expand All @@ -226,7 +228,7 @@ function lifecycleReporter(
)
return;
updateHost(deps.db, deps.hub, hostId, {
statusMessage: text.slice(0, 500),
statusMessage: sliceUtf16Head(text, 500),
});
deps.hub.notifyHost(hostId, ["host-connected"]);
},
Expand Down
7 changes: 4 additions & 3 deletions apps/server/src/services/plugins/install-sources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {
installCancellationSignal,
PluginInstallCancelledError,
} from "./install-cancellation.js";
import { sliceUtf16Tail } from "@bb/text-utils";

type ParsedGitSelector =
| { kind: "ref"; ref: string }
Expand Down Expand Up @@ -642,15 +643,15 @@ export async function runInstallCommand(
stdoutBytes += chunk.byteLength;
const limit = options?.maxStdoutBytes;
if (limit === undefined) {
if (stdout.length > 8192) stdout = stdout.slice(-8192);
if (stdout.length > 8192) stdout = sliceUtf16Tail(stdout, 8192);
} else if (stdoutBytes > limit && !overflowed) {
overflowed = true;
killCommand();
}
});
child.stderr.on("data", (chunk: Buffer) => {
stderr += chunk.toString("utf8");
if (stderr.length > 8192) stderr = stderr.slice(-8192);
if (stderr.length > 8192) stderr = sliceUtf16Tail(stderr, 8192);
});
let cancelled = false;
const cancel = () => {
Expand Down Expand Up @@ -696,7 +697,7 @@ export async function runInstallCommand(
resolve();
return;
}
const tail = stderr.trim().slice(-1000);
const tail = sliceUtf16Tail(stderr.trim(), 1000);
reject(
new Error(
`${command} ${args[0]} failed (exit ${code ?? "signal"})${tail ? `: ${tail}` : ""}`,
Expand Down
5 changes: 4 additions & 1 deletion apps/server/src/services/plugins/plugin-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ import type {
import type { PluginMachineProviderBridge } from "./plugin-machine-provider-registry.js";
import { fillPluginPresentation } from "./plugin-presentation.js";
import { defineItemSweep, type ItemSweep } from "../system/item-sweep.js";
import { sliceUtf16Head } from "@bb/text-utils";
export type {
PluginAgentToolContribution,
PluginMentionResolveResult,
Expand Down Expand Up @@ -524,7 +525,9 @@ class PluginRpcBoundaryError extends Error {
)
.join("; ");
const summary =
issues && issues.length > 300 ? `${issues.slice(0, 299)}…` : issues;
issues && issues.length > 300
? `${sliceUtf16Head(issues, 299)}…`
: issues;
super(summary ? `${rpcError.message} (${summary})` : rpcError.message);
this.name = "PluginRpcBoundaryError";
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
requireBridgeLaunchForProviderId,
resolveBridgeLaunchForProviderId,
} from "../system/provider-bridge-launch.js";
import { sliceUtf16Head } from "@bb/text-utils";

export const PROVIDER_MODEL_CATALOG_PUSH_COALESCE_MS = 250;
export const PROVIDER_MODEL_CATALOG_MEMORY_ENTRY_LIMIT = 256;
Expand Down Expand Up @@ -180,7 +181,7 @@ export function toProviderModelCatalogFailureDetail(
return null;
}
return collapsed.length > FAILURE_DETAIL_MAX_LENGTH
? `${collapsed.slice(0, FAILURE_DETAIL_MAX_LENGTH - 1).trimEnd()}\u2026`
? `${sliceUtf16Head(collapsed, FAILURE_DETAIL_MAX_LENGTH - 1).trimEnd()}\u2026`
: collapsed;
}

Expand Down
Loading
Loading