Compare commits

..
17 changed files with 430 additions and 321 deletions
-1
View File
@@ -29,7 +29,6 @@ The worker writes `$PASEO_HOME/terminal-worker/<pid>.json` (owner-only) with its
- Workers never query their own birth time or command line. Readers accept legacy identity fields but ignore them. Daemons through 0.15.1 report new records unreadable and cannot adopt them.
- Windows terminal programs have no recorded birth time and terminal lifecycle operations never launch PowerShell. Linux and macOS retain program birth-time checks through `ps` with `LC_ALL=C`; Linux also walks sessions to find surviving jobs.
- Unix socket paths have a byte budget (103 on macOS, 107 on Linux). Long dev homes use an owner-only fallback under `$TMPDIR/paseo-<uid>/` or `/tmp/paseo-<uid>/`. An existing directory must be a real `0700` directory owned by you; a shared root is never chmodded.
- A home on a filesystem that refuses Unix sockets (AFS, some network mounts) passes those checks and then fails the bind with `EPERM`, `EACCES`, `EOPNOTSUPP` or `ENOTSUP`. The worker moves on to the next directory on those codes only; any other listen error fails the start. The record carries the path the worker bound, so nothing else recomputes it.
- A kill cleanup that cannot confirm every process gone writes `closing-<recordId>.json` beside the worker record. The worker rewrites its own record whenever a terminal starts or exits, so the kill intent has to live in a file it never writes. A closing record is never adopted; the next stop or start retries it.
- An unreadable record of either kind makes `daemon status` and a kill restart fail with its path: a kill cleanup that met it could not check what it names, and leaves nothing else behind. A read that fails with `EPERM`, `EBUSY` or `EACCES` is retried for 250ms first: on Windows, opening a record while the worker renames its new copy over it fails that way for a moment.
@@ -15,5 +15,6 @@ android {
}
dependencies {
implementation 'com.facebook.react:react-android'
testImplementation "junit:junit:4.13.2"
}
@@ -1,26 +1,48 @@
package sh.paseo.trace
import android.os.Trace
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.bridge.ReactContext
import expo.modules.kotlin.modules.Module
import expo.modules.kotlin.modules.ModuleDefinition
class PaseoNativeTraceModule : Module() {
private var recorder: DiagnosticRecorder? = null
private var touches: TouchDiagnostics? = null
override fun definition() = ModuleDefinition {
Name("PaseoNativeTrace")
Function("startRecorder") { metadata: Map<String, String> ->
if (recorder == null) {
appContext.reactContext?.applicationContext?.let { recorder = DiagnosticRecorder(it, metadata) }
(appContext.reactContext as? ReactContext)?.let { context ->
val sink = DiagnosticRecorder(context.applicationContext, metadata)
recorder = sink
UiThreadUtil.runOnUiThread {
if (recorder === sink) {
touches = TouchDiagnostics(context, sink::record).also { it.start(appContext.currentActivity?.window) }
}
}
}
}
HeartbeatTiming.intervalMs
}
Function("record") { name: String, data: Map<String, String> -> recorder?.record(name, data) }
Function("heartbeat") { recorder?.heartbeat() }
OnActivityEntersForeground { recorder?.active(true) }
OnActivityEntersForeground {
recorder?.active(true)
UiThreadUtil.runOnUiThread { touches?.activity(appContext.currentActivity?.window) }
}
OnActivityEntersBackground { recorder?.active(false) }
OnDestroy { recorder?.close(); recorder = null }
OnDestroy {
val sink = recorder
recorder = null
UiThreadUtil.runOnUiThread {
touches?.close()
touches = null
sink?.close()
}
}
Function("beginSection") { name: String ->
Trace.beginSection(name.take(127))
@@ -0,0 +1,141 @@
package sh.paseo.trace
import android.graphics.Rect
import android.os.Build
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowInsets
import com.facebook.react.R
import com.facebook.react.bridge.ReactContext
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.interfaces.ExtraWindowEventListener
import com.facebook.react.uimanager.ReactPointerEventsView
import com.facebook.react.uimanager.TouchTargetHelper
import com.facebook.react.uimanager.RootView
/** Temporary touch evidence. Only attached while the diagnostic recorder is running. */
internal class TouchDiagnostics(
private val context: ReactContext,
private val write: (String, Map<String, String>) -> Unit,
) : ExtraWindowEventListener {
private val windows = mutableMapOf<Window, TouchCallback>()
private var nextWindow = 0
private var activityWindow: Window? = null
fun start(window: Window?) {
UiThreadUtil.assertOnUiThread()
context.addExtraWindowEventListener(this)
activity(window)
}
fun activity(window: Window?) {
if (activityWindow === window) return
activityWindow?.let { release(it) }
activityWindow = window
window?.let { observe(it) }
}
override fun onExtraWindowCreate(window: Window) = observe(window)
override fun onExtraWindowDestroy(window: Window) = release(window)
private fun observe(window: Window) {
if (windows.containsKey(window)) return
val callback = TouchCallback(window, window.callback, ++nextWindow, write)
windows[window] = callback
window.callback = callback
write("touch.window.open", mapOf("window" to "$nextWindow"))
}
private fun release(window: Window) {
val callback = windows.remove(window) ?: return
// Another observer may wrap ours. Disable it even when we cannot unwrap its owner.
callback.active = false
if (window.callback === callback) window.callback = callback.previous
write("touch.window.close", mapOf("window" to "${callback.id}"))
}
fun close() {
context.removeExtraWindowEventListener(this)
windows.keys.toList().forEach { release(it) }
activityWindow = null
}
}
private class TouchCallback(
private val window: Window,
val previous: Window.Callback,
val id: Int,
private val write: (String, Map<String, String>) -> Unit,
) : Window.Callback by previous {
var active = true
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
val boundary = event.actionMasked == MotionEvent.ACTION_DOWN ||
event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL
if (!active || !boundary) return previous.dispatchTouchEvent(event)
val fields = mutableMapOf(
"window" to "$id", "gesture" to "${event.downTime}",
"action" to "${event.actionMasked}", "eventMs" to "${event.eventTime}",
"x" to "${event.x}", "y" to "${event.y}",
"imeVisible" to if (Build.VERSION.SDK_INT >= 30) "${window.decorView.rootWindowInsets?.isVisible(WindowInsets.Type.ime())}" else "unsupported",
"imeBottom" to if (Build.VERSION.SDK_INT >= 30) "${window.decorView.rootWindowInsets?.getInsets(WindowInsets.Type.ime())?.bottom}" else "unsupported",
"focus" to describe(window.currentFocus),
)
// This is a hit-test prediction, not proof that the eventual responder accepted the press.
// Use RN's own pointer-events and transformed-coordinate rules, rather than approximating them.
val root = reactRootAt(window.decorView, event.x.toInt(), event.y.toInt())
if (root != null) {
try {
val origin = IntArray(2)
root.getLocationOnScreen(origin)
val path = TouchTargetHelper.findTargetPathAndCoordinatesForTouch(event.rawX - origin[0], event.rawY - origin[1], root, FloatArray(2))
path.take(10).forEachIndexed { index, target ->
fields["hit$index"] = "${target.getViewId()}:${describe(target.getView())}"
}
} catch (error: RuntimeException) {
fields["hitError"] = error.javaClass.simpleName
}
}
write("touch.window.before", fields)
val handled = previous.dispatchTouchEvent(event)
write("touch.window.after", mapOf(
"window" to "$id", "gesture" to "${event.downTime}",
"action" to "${event.actionMasked}", "handled" to "$handled",
"focus" to describe(window.currentFocus),
))
return handled
}
}
private fun describe(view: View?): String {
if (view == null) return "none"
// Deliberately omit text, accessibility labels, nativeID, and content descriptions.
val pointer = (view as? ReactPointerEventsView)?.pointerEvents
val testId = (view.getTag(R.id.react_test_id) as? String)?.takeIf { it in diagnosticTestIds } ?: ""
return "${view.javaClass.simpleName}#$testId/${view.id};p=$pointer;a=${view.alpha};enabled=${view.isEnabled};frame=${view.left},${view.top},${view.width},${view.height};translation=${view.translationX},${view.translationY}"
}
// Other test IDs include user-controlled entity IDs. Keep only fixed surface names.
private val diagnosticTestIds = setOf(
"message-input-root", "composer-fullscreen", "composer-viewport", "composer-viewport-content",
"composer-dock-content", "composer-track-scroll", "agent-list-backdrop", "file-explorer-backdrop",
"workspace-create-submit", "new-workspace-launch-submit", "compact-provider-list",
)
// Expo's developer menu adds a full-window Compose host above the React root. It passes ordinary
// touches through, but RN's helper cannot traverse that host. Start at the actual React surface;
// native modal windows expose a separate RootView and receive their own observation.
private fun reactRootAt(view: View, x: Int, y: Int): ViewGroup? {
if (view.visibility != View.VISIBLE || view.alpha == 0f) return null
// getGlobalVisibleRect is relative to the window root, including for offset/freeform windows.
val bounds = Rect()
if (!view.getGlobalVisibleRect(bounds) || !bounds.contains(x, y)) return null
if (view is RootView && view is ViewGroup) return view
if (view is ViewGroup) {
for (index in view.childCount - 1 downTo 0) {
reactRootAt(view.getChildAt(index), x, y)?.let { return it }
}
}
return null
}
@@ -1,3 +1,4 @@
import { recordComposerCommand } from "@/composer/touch-diagnostics";
import { forwardRef, useCallback, type ComponentProps } from "react";
import { Text, View, type PressableStateCallbackType } from "react-native";
import { StyleSheet } from "react-native-unistyles";
@@ -61,13 +62,18 @@ export const AgentControlTrigger = forwardRef<View, AgentControlTriggerProps>(
[disabled, isSheet, open, showToolbarLabel],
);
const activate = useCallback(() => {
recordComposerCommand("control");
onPress();
}, [onPress]);
return (
<ComboboxTrigger
{...triggerProps}
ref={ref}
collapsable={false}
disabled={disabled}
onPress={onPress}
onPress={activate}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
@@ -1,3 +1,4 @@
import { recordComposerCommand } from "@/composer/touch-diagnostics";
import { useCallback, useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
@@ -31,7 +32,6 @@ import {
toolbarSlot,
type ToolbarGlyphs,
} from "@/components/ui/control-geometry";
import { shortModelLabel } from "./utils";
const SNAP_POINTS = ["80%", "90%"];
const MODEL_LIST_TOP_INSET = 4;
@@ -67,6 +67,11 @@ interface CompactModelSheetProps {
children: ReactNode;
}
function shortModelLabel(label: string): string {
const separatorIndex = label.lastIndexOf("/");
return separatorIndex === -1 ? label : label.slice(separatorIndex + 1);
}
function resolveModelSheetProfileActions(
onCreateProfile: ((seed: AgentProfileSeed) => void) | undefined,
onEditProfile: ((profileId: string) => void) | undefined,
@@ -202,6 +207,7 @@ export function CompactModelSheet({
);
const open = useCallback(() => {
recordComposerCommand("model");
Keyboard.dismiss();
rootBrowser.showAll();
setIsOpen(true);
@@ -4,7 +4,6 @@ import {
getAgentControlHintKey,
normalizeModelId,
resolveAgentModelSelection,
shortModelLabel,
} from "./utils";
describe("getAgentControlHintKey", () => {
@@ -252,19 +251,3 @@ describe("resolveAgentModelSelection", () => {
expect(selection.displayThinking).toBe("Max");
});
});
describe("shortModelLabel", () => {
it("drops a provider namespace", () => {
expect(shortModelLabel("openrouter/gpt-5.5")).toBe("gpt-5.5");
expect(shortModelLabel("openrouter/google/gemini-2.5-flash")).toBe("gemini-2.5-flash");
});
it("keeps slashes inside a display name", () => {
expect(shortModelLabel("DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)")).toBe(
"DeepSeek V4.1 Flash (~6-7 tok/s, 56/56)",
);
expect(shortModelLabel("llama-swap/DeepSeek V4.1 Flash (56/56)")).toBe(
"DeepSeek V4.1 Flash (56/56)",
);
});
});
@@ -35,12 +35,6 @@ export function normalizeModelId(modelId: string | null | undefined): string | n
return normalized;
}
// Drops a provider namespace ("openrouter/gpt-5.5" -> "gpt-5.5") for the compact trigger.
// A namespace segment has no spaces, so slashes inside a display name ("52/56") survive.
export function shortModelLabel(label: string): string {
return label.replace(/^(?:[^\s/]+\/)+(?=\S)/, "");
}
export function getFeatureHighlightColor(featureId: string): FeatureHighlightColor {
switch (featureId) {
case FAST_MODE_FEATURE_ID:
+23 -13
View File
@@ -1,3 +1,4 @@
import { useComposerTouchDiagnostics, recordComposerCommand } from "@/composer/touch-diagnostics";
import { useKeyboardFocusSurface } from "@/keyboard";
import type { SendShortcut } from "@/hooks/use-settings";
import {
@@ -1761,6 +1762,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
}, [resetComposerHeight]);
const handleSendMessage = useCallback(() => {
recordComposerCommand("send");
const liveValue = textInputRef.current?.getText() ?? valueRef.current;
if (!preserveHeightOnSubmit) {
updateLiveTextPresence("");
@@ -1790,19 +1792,18 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
exitFullscreen,
]);
const handleQueueMessage = useCallback(
() =>
queueMessageImpl({
value: textInputRef.current?.getText() ?? valueRef.current,
attachments,
cwd,
onQueue,
replaceText,
onMinimizeHeight: minimizeInputHeight,
exitFullscreen,
}),
[attachments, cwd, onQueue, replaceText, minimizeInputHeight, exitFullscreen],
);
const handleQueueMessage = useCallback(() => {
recordComposerCommand("queue");
return queueMessageImpl({
value: textInputRef.current?.getText() ?? valueRef.current,
attachments,
cwd,
onQueue,
replaceText,
onMinimizeHeight: minimizeInputHeight,
exitFullscreen,
});
}, [attachments, cwd, onQueue, replaceText, minimizeInputHeight, exitFullscreen]);
const handleDefaultSendAction = useCallback(() => {
runDefaultSendAction({
@@ -2327,8 +2328,17 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
handleRealtimeVoiceStop,
],
);
const touchDiagnostics = useComposerTouchDiagnostics({
active: isPaneFocused,
disabled,
sendDisabled: isSendButtonDisabled,
focused: isInputFocused,
fullscreen: isFullscreen,
voiceOverlay: showOverlay,
});
return (
<View
{...touchDiagnostics}
ref={rootRef}
style={
isFullscreen
@@ -0,0 +1,63 @@
import { useEffect } from "react";
import type { ComposerTouchState } from "./index";
import { Keyboard, type GestureResponderEvent } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { watchdog } from "@/watchdog";
/** Temporary companion to Android TouchDiagnostics. No draft text or identifiers are recorded. */
export function recordComposerCommand(command: "send" | "queue" | "control" | "model"): void {
watchdog?.record("touch.composer.command", { command });
}
function useRecordedComposerTouches(state: ComposerTouchState) {
const insets = useSafeAreaInsets();
const { active, disabled, sendDisabled, focused, fullscreen, voiceOverlay } = state;
useEffect(() => {
if (!active) return;
watchdog?.record("touch.composer.state", {
disabled: String(disabled),
sendDisabled: String(sendDisabled),
focused: String(focused),
fullscreen: String(fullscreen),
voiceOverlay: String(voiceOverlay),
});
}, [active, disabled, sendDisabled, focused, fullscreen, voiceOverlay]);
const record = (phase: string, event: GestureResponderEvent) => {
if (!watchdog) return;
const touch = event.nativeEvent;
watchdog.record("touch.composer", {
phase,
target: String(touch.target),
timestamp: String(touch.timestamp),
x: String(touch.pageX),
y: String(touch.pageY),
disabled: String(state.disabled),
sendDisabled: String(state.sendDisabled),
focused: String(state.focused),
fullscreen: String(state.fullscreen),
voiceOverlay: String(state.voiceOverlay),
keyboardVisible: String(Keyboard.isVisible()),
keyboardHeight: String(Keyboard.metrics()?.height),
safeBottom: String(insets.bottom),
});
};
return watchdog
? {
onStartShouldSetResponderCapture(event: GestureResponderEvent) {
record("capture", event);
return false;
},
onTouchEnd: (event: GestureResponderEvent) => record("end", event),
onTouchCancel: (event: GestureResponderEvent) => record("cancel", event),
}
: {};
}
function useNoComposerTouches(_state: ComposerTouchState) {
return {};
}
// Build configuration is fixed for the module lifetime. Ordinary builds subscribe to nothing.
export const useComposerTouchDiagnostics = watchdog
? useRecordedComposerTouches
: useNoComposerTouches;
@@ -0,0 +1,14 @@
/** Temporary diagnostics are Android-only. Metro selects index.android.ts on Android. */
export interface ComposerTouchState {
active: boolean;
disabled: boolean;
sendDisabled: boolean;
focused: boolean;
fullscreen: boolean;
voiceOverlay: boolean;
}
export function recordComposerCommand(_command: "send" | "queue" | "control" | "model"): void {}
export function useComposerTouchDiagnostics(_state: ComposerTouchState) {
return {};
}
@@ -51,6 +51,7 @@ import {
} from "./copilot-acp-agent.js";
import { GenericACPAgentClient } from "./generic-acp-agent.js";
import { parseKiroExtensionCommands } from "./kiro-acp-agent.js";
import { transformPiModels } from "./pi/agent.js";
import type { AgentStreamEvent } from "../agent-sdk-types.js";
import type {
AgentCapabilityFlags,
@@ -2259,12 +2260,7 @@ describe("ACPAgentClient modelTransformer", () => {
provider: "pi",
logger: createTestLogger(),
defaultCommand: ["test-acp"],
modelTransformer: (models) =>
models.map((model) => ({
...model,
label: model.label.split("/").at(-1) ?? model.label,
description: model.id,
})),
modelTransformer: transformPiModels,
});
await expect(
@@ -2918,6 +2914,60 @@ describe("ACP providers advertise session listing", () => {
});
});
describe("transformPiModels", () => {
test("keeps slash-free labels unchanged", () => {
expect(
transformPiModels([
{
provider: "pi",
id: "gpt-4.1-mini",
label: "GPT 4.1 Mini",
description: "Fast",
},
]),
).toEqual([
{
provider: "pi",
id: "gpt-4.1-mini",
label: "GPT 4.1 Mini",
description: "Fast",
},
]);
});
test("uses the last path segment as label and preserves existing descriptions", () => {
expect(
transformPiModels([
{
provider: "pi",
id: "openrouter/openai/gpt-4.1-mini",
label: "openrouter/openai/gpt-4.1-mini",
description: undefined,
},
{
provider: "pi",
id: "anthropic/claude-sonnet-4",
label: "anthropic/claude-sonnet-4",
description: "Balanced",
},
]),
).toEqual([
{
provider: "pi",
id: "openrouter/openai/gpt-4.1-mini",
label: "gpt-4.1-mini",
description: "openrouter/openai/gpt-4.1-mini",
},
{
provider: "pi",
id: "anthropic/claude-sonnet-4",
label: "claude-sonnet-4",
description: "Balanced",
},
]);
});
});
describe("ACPAgentSession slash commands", () => {
test("returns immediately for ACP sessions that do not wait for async command discovery", async () => {
const session = new ACPAgentSession(
@@ -19,7 +19,12 @@ import { pathToFileURL } from "node:url";
import { describe, expect, onTestFinished, test } from "vitest";
import type { AgentSession, AgentSessionConfig, AgentStreamEvent } from "../../agent-sdk-types.js";
import { PiProviderOptionsSchema, PiRpcAgentClient, PiRpcAgentSession } from "./agent.js";
import {
PiProviderOptionsSchema,
PiRpcAgentClient,
PiRpcAgentSession,
transformPiModels,
} from "./agent.js";
import { PiCliRuntime } from "./cli-runtime.js";
import { FakePi } from "./test-utils/fake-pi.js";
import { createPiExtensionHost } from "./extensions/index.js";
@@ -3965,73 +3970,35 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => {
});
});
describe("Pi catalog model labels", () => {
test.each([
{
name: "keeps slashes and underscores inside a free-text model name",
model: {
provider: "llama-swap",
id: "s-q3fn(p-t)",
name: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
describe("transformPiModels", () => {
test("normalizes labels that include the upstream provider prefix", () => {
expect(
transformPiModels([
{
provider: "pi",
id: "openrouter/google/gemini-2.5-flash-lite",
label: "openrouter/google/gemini_2.5 flash lite",
},
{
provider: "pi",
id: "openrouter/openai/gpt-5.5",
label: "openrouter/OpenAI: GPT-5.5",
},
]),
).toEqual([
{
provider: "pi",
id: "openrouter/google/gemini-2.5-flash-lite",
label: "gemini 2.5 flash lite",
description: "openrouter/google/gemini_2.5 flash lite",
},
label: "Qwen3.8 Flash Next IQ3_S, prior + tail skip (fastest, ~60-70 tok/s on 0.2.10, 52/56)",
},
{
name: "keeps a free-text name that ends in a slash-separated word",
model: {
provider: "llama-swap",
id: "ds-strata-6",
name: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
{
provider: "pi",
id: "openrouter/openai/gpt-5.5",
label: "GPT-5.5",
description: "openrouter/OpenAI: GPT-5.5",
},
label: "DeepSeek V4.1 Flash 2.25bpw via Strata (full 6 experts, untested, ~5-6 tok/s)",
},
{
name: "keeps a colon inside a free-text model name",
model: {
provider: "llama-swap",
id: "qwen3-tail",
name: "Qwen3 IQ3_S (tail skip: on, 52/56)",
},
label: "Qwen3 IQ3_S (tail skip: on, 52/56)",
},
{
name: "drops the vendor prefix from an upstream model name",
model: { provider: "openrouter", id: "openai/gpt-5.5", name: "OpenAI: GPT-5.5" },
label: "GPT-5.5",
},
{
name: "shortens a path-like name to its last segment",
model: {
provider: "openrouter",
id: "google/gemini-2.5-flash-lite",
name: "google/gemini-2.5-flash-lite",
},
label: "gemini-2.5-flash-lite",
},
{
name: "falls back to the last segment of a path-like id",
model: { provider: "openrouter", id: "google/gemini_2.5-flash-lite" },
label: "gemini 2.5-flash-lite",
},
{
name: "falls back to an id with spaces when the name is blank",
model: { provider: "local", id: "DeepSeek-V4.1-Flash 2.25bpw (Strata)", name: " " },
label: "DeepSeek-V4.1-Flash 2.25bpw (Strata)",
},
])("$name", async ({ model, label }) => {
const pi = new FakePi();
pi.queueSessionSetup((session) => {
session.models = [model];
});
const catalog = await createClient(pi).fetchCatalog({
scope: "workspace",
cwd: "/workspace/project",
force: false,
});
expect(catalog.models.map((entry) => entry.label)).toEqual([label]);
expect(catalog.models[0]?.id).toBe(`${model.provider}/${model.id}`);
]);
});
});
@@ -313,25 +313,34 @@ interface PiSlashCommandInvocation {
type AutoCompactMode = boolean | "toggle" | "unknown";
// Drops an upstream "Vendor: " prefix ("OpenAI: GPT-5.5"). A colon inside parentheses or after a
// comma belongs to the model name ("DeepSeek V4 (ctx: 128k)"), so it is kept.
function stripVendorPrefix(label: string): string {
const vendorSeparatorIndex = label.indexOf(": ");
if (vendorSeparatorIndex === -1 || /[(),]/.test(label.slice(0, vendorSeparatorIndex))) {
return label;
function normalizePiModelLabel(label: string): string {
const normalizedLabel = label.trim().replace(/[_\s]+/g, " ");
const vendorSeparatorIndex = normalizedLabel.indexOf(": ");
if (vendorSeparatorIndex === -1) {
return normalizedLabel;
}
return label.slice(vendorSeparatorIndex + 2).trim();
return normalizedLabel.slice(vendorSeparatorIndex + 2).trim();
}
// A Pi model name is either a path ("google/gemini_2.5-flash", as OpenRouter reports it) or
// free text that can contain slashes and underscores ("IQ3_S ... 52/56"). Only shorten paths.
function piModelLabel(model: Pick<PiModel, "id" | "name">): string {
const text = model.name?.trim().replace(/\s+/g, " ") || model.id.trim();
if (/\s/.test(text)) {
return stripVendorPrefix(text);
}
const lastSegment = text.split("/").findLast((segment) => segment.length > 0) ?? text;
return stripVendorPrefix(lastSegment.replace(/_+/g, " "));
export function transformPiModels(models: AgentModelDefinition[]): AgentModelDefinition[] {
return models.map((model) => {
if (!model.label.includes("/")) {
return model;
}
const segments = model.label.split("/").filter((segment) => segment.length > 0);
const rawLabel = segments.at(-1);
if (!rawLabel) {
return model;
}
return {
...model,
label: normalizePiModelLabel(rawLabel),
description: model.description ?? model.label,
};
});
}
function isPiThinkingLevel(value: string | null | undefined): value is PiThinkingLevel {
@@ -1157,7 +1166,7 @@ function mapPiModel(model: PiModel, provider: AgentProvider): AgentModelDefiniti
return {
provider,
id: `${model.provider}/${model.id}`,
label: piModelLabel(model),
label: `${model.provider}/${model.name ?? model.id}`,
description: `${model.provider}/${model.id}`,
metadata: {
provider: model.provider,
@@ -2808,13 +2817,15 @@ export class PiRpcAgentClient implements AgentClient {
"get_state",
() => catalogSession.getState(),
);
const models = piModels.map((model) => {
const mapped = mapPiModel(model, PI_PROVIDER);
const isConfigured =
model.provider === configuredModel?.provider && model.id === configuredModel?.id;
if (isConfigured) mapped.isDefault = true;
return mapped;
});
const models = transformPiModels(
piModels.map((model) => {
const mapped = mapPiModel(model, PI_PROVIDER);
const isConfigured =
model.provider === configuredModel?.provider && model.id === configuredModel?.id;
if (isConfigured) mapped.isDefault = true;
return mapped;
}),
);
return { models, modes: [] };
} finally {
context?.signal.removeEventListener("abort", handleAbort);
@@ -19,7 +19,7 @@ import {
type TerminalWorkerRecord,
} from "./terminal-worker-record.js";
import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js";
import { listenOnTerminalWorkerSocket } from "./terminal-worker-socket-path.js";
import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js";
import {
TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV,
TERMINAL_WORKER_PROTOCOL_VERSION,
@@ -700,25 +700,23 @@ function runWorker(argv: string[]): void {
}
async function start(): Promise<void> {
const { socketPath, listener } = await listenOnTerminalWorkerSocket({
const socketPath = resolveTerminalWorkerSocketPath({
paseoHome: args.paseoHome,
workerPid: process.pid,
recordId: args.recordId,
listen: (candidatePath) => {
if (process.platform !== "win32") {
rmSync(candidatePath, { force: true });
}
const listening = createServer(handleConnection);
return new Promise<Server>((resolve, reject) => {
listening.once("error", reject);
listening.listen(candidatePath, () => {
listening.off("error", reject);
resolve(listening);
});
});
},
});
server = listener;
if (process.platform !== "win32") {
rmSync(socketPath, { force: true });
}
const listening = createServer(handleConnection);
await new Promise<void>((resolve, reject) => {
listening.once("error", reject);
listening.listen(socketPath, () => {
listening.off("error", reject);
resolve();
});
});
server = listening;
if (process.platform !== "win32") {
chmodSync(socketPath, PRIVATE_FILE_MODE);
}
@@ -1,11 +1,10 @@
import { afterEach, describe, expect, it } from "vitest";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
import { createServer, type Server } from "node:net";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { isPlatform } from "../test-utils/platform.js";
import {
listenOnTerminalWorkerSocket,
resolveTerminalWorkerSocketPath,
TerminalWorkerSocketPathError,
} from "./terminal-worker-socket-path.js";
@@ -26,36 +25,7 @@ function longHome(root: string): string {
return home;
}
const openServers: Server[] = [];
function listenFor(socketPath: string): Promise<Server> {
const server = createServer();
return new Promise((resolve, reject) => {
server.once("error", reject);
server.listen(socketPath, () => {
openServers.push(server);
resolve(server);
});
});
}
// Stands in for a filesystem that passes the directory checks but refuses AF_UNIX bind, as AFS
// does with EPERM.
function refuseBindUnder(directory: string, code: string) {
return (socketPath: string): Promise<Server> => {
if (socketPath.startsWith(directory + path.sep)) {
return Promise.reject(
Object.assign(new Error(`listen ${code}: ${socketPath}`), { code, syscall: "listen" }),
);
}
return listenFor(socketPath);
};
}
afterEach(async () => {
await Promise.all(
openServers.splice(0).map((server) => new Promise((resolve) => server.close(resolve))),
);
afterEach(() => {
for (const dir of temporaryDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
@@ -172,66 +142,6 @@ describe.skipIf(isPlatform("win32"))("terminal worker socket path", () => {
});
});
describe.skipIf(isPlatform("win32"))("terminal worker socket listen", () => {
it("falls back to the next directory when the home's filesystem refuses the bind", async () => {
const home = makeDir("tw-b-", "/tmp");
const tmpDir = makeDir("tw-t-", "/tmp");
const homeSocketDirectory = path.join(home, "terminal-worker", "sock");
const { socketPath, listener } = await listenOnTerminalWorkerSocket({
paseoHome: home,
recordId: "test",
workerPid: 11,
tmpDir,
listen: refuseBindUnder(homeSocketDirectory, "EPERM"),
});
expect(path.dirname(socketPath)).toBe(path.join(tmpDir, `paseo-${process.getuid!()}`));
expect(listener.address()).toBe(socketPath);
});
it("throws a listen error that does not mean the filesystem refuses sockets", async () => {
const home = makeDir("tw-u-", "/tmp");
const homeSocketDirectory = path.join(home, "terminal-worker", "sock");
await expect(
listenOnTerminalWorkerSocket({
paseoHome: home,
recordId: "test",
workerPid: 12,
tmpDir: makeDir("tw-t-", "/tmp"),
listen: refuseBindUnder(homeSocketDirectory, "EADDRINUSE"),
}),
).rejects.toMatchObject({ code: "EADDRINUSE" });
});
it("names every candidate's bind error when no directory accepts a socket", async () => {
const home = makeDir("tw-n-", "/tmp");
const tmpDir = makeDir("tw-t-", "/tmp");
let caught: unknown;
try {
await listenOnTerminalWorkerSocket({
paseoHome: home,
recordId: "test",
workerPid: 13,
tmpDir,
listen: refuseBindUnder("", "EPERM"),
});
} catch (error) {
caught = error;
}
expect(caught).toBeInstanceOf(TerminalWorkerSocketPathError);
const rejected = (caught as TerminalWorkerSocketPathError).rejected;
expect(rejected.slice(0, 2)).toEqual([
expect.objectContaining({
path: expect.stringContaining(path.join(home, "terminal-worker", "sock")),
reason: "cannot bind a socket here (EPERM)",
}),
expect.objectContaining({
path: expect.stringContaining(path.join(tmpDir, `paseo-${process.getuid!()}`)),
reason: "cannot bind a socket here (EPERM)",
}),
]);
});
});
it("uses a separate socket for each record even when its pid is reused", () => {
const paseoHome = makeDir("tw-id-");
const first = resolveTerminalWorkerSocketPath({ paseoHome, workerPid: 42, recordId: "old" });
@@ -14,9 +14,6 @@ const SOCKET_PATH_BYTE_BUDGET: Partial<Record<NodeJS.Platform, number>> = {
};
const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103;
const OWNER_ONLY_MODE = 0o700;
// Bind errors that mean the directory's filesystem cannot hold a Unix socket. AFS and some other
// network filesystems pass the directory checks and then refuse AF_UNIX bind with EPERM.
const SOCKET_UNSUPPORTED_BIND_CODES = new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]);
export interface TerminalWorkerSocketPathInput {
paseoHome: string;
@@ -27,16 +24,6 @@ export interface TerminalWorkerSocketPathInput {
uid?: number;
}
export interface TerminalWorkerSocketListenInput<T> extends TerminalWorkerSocketPathInput {
/** Binds a fresh listener at the path, removing any stale socket there first. */
listen: (socketPath: string) => Promise<T>;
}
export interface TerminalWorkerSocketListener<T> {
socketPath: string;
listener: T;
}
export interface RejectedSocketCandidate {
path: string;
byteLength: number;
@@ -49,7 +36,7 @@ export class TerminalWorkerSocketPathError extends Error {
constructor(rejected: RejectedSocketCandidate[], budget: number) {
super(
[
`No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`,
`No terminal worker socket path fits ${budget} bytes in an owner-only directory:`,
...rejected.map(
(candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`,
),
@@ -70,73 +57,18 @@ export function terminalWorkerSocketId(paseoHome: string, workerPid: number): st
* Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX
* tries $PASEO_HOME/terminal-worker/sock, then <tmpdir>/paseo-<uid>, then /tmp/paseo-<uid>.
* A shared root is never chmodded: an existing directory there is used only when it is a real
* directory owned by this user with mode 0700. It does not bind; the worker listens through
* `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket.
* directory owned by this user with mode 0700.
*/
export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string {
const platform = input.platform ?? process.platform;
const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
if (platform === "win32") {
return windowsPipePath(input);
return `\\\\.\\pipe\\paseo-tw-${id}`;
}
const budget = socketPathByteBudget(platform);
const rejected: RejectedSocketCandidate[] = [];
for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
return candidate.path;
}
throw new TerminalWorkerSocketPathError(rejected, budget);
}
/**
* Listens on the first candidate path that accepts a socket. A bind refused by the filesystem
* moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is.
*/
export async function listenOnTerminalWorkerSocket<T>(
input: TerminalWorkerSocketListenInput<T>,
): Promise<TerminalWorkerSocketListener<T>> {
const { listen } = input;
const platform = input.platform ?? process.platform;
if (platform === "win32") {
const socketPath = windowsPipePath(input);
return { socketPath, listener: await listen(socketPath) };
}
const budget = socketPathByteBudget(platform);
const rejected: RejectedSocketCandidate[] = [];
for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
try {
return { socketPath: candidate.path, listener: await listen(candidate.path) };
} catch (error) {
const code = (error as NodeJS.ErrnoException).code;
if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code)) throw error;
rejected.push({
path: candidate.path,
byteLength: candidate.byteLength,
reason: `cannot bind a socket here (${code})`,
});
}
}
throw new TerminalWorkerSocketPathError(rejected, budget);
}
function windowsPipePath(input: TerminalWorkerSocketPathInput): string {
return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`;
}
function socketFileId(input: TerminalWorkerSocketPathInput): string {
return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
}
function socketPathByteBudget(platform: NodeJS.Platform): number {
return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
}
/** Yields each candidate that fits the budget in an owner-only directory, in order. */
function* eligibleUnixSocketPaths(
input: TerminalWorkerSocketPathInput,
budget: number,
rejected: RejectedSocketCandidate[],
): Generator<{ path: string; byteLength: number }> {
const uid = input.uid ?? process.getuid?.() ?? 0;
const fileName = `tw-${socketFileId(input)}.sock`;
const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
const fileName = `tw-${id}.sock`;
const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock");
const candidates: Array<{ directory: string; prepare: () => string | null }> = [
{
@@ -155,6 +87,7 @@ function* eligibleUnixSocketPaths(
}),
];
const rejected: RejectedSocketCandidate[] = [];
const seen = new Set<string>();
for (const candidate of candidates) {
const socketPath = path.join(candidate.directory, fileName);
@@ -175,8 +108,9 @@ function* eligibleUnixSocketPaths(
rejected.push({ path: socketPath, byteLength, reason: problem });
continue;
}
yield { path: socketPath, byteLength };
return socketPath;
}
throw new TerminalWorkerSocketPathError(rejected, budget);
}
function prepareSharedRootDirectory(directory: string, uid: number): string | null {