Compare commits

..
Author SHA1 Message Date
d15190803a Show Pi model names with slashes and underscores in full (#9823)
* fix(pi): keep slashes and underscores in model display names

Pi model labels were built as `${provider}/${name}` and then cut at the
last `/`, so a free-text name such as "... ~60-70 tok/s, 52/56)" was shown
as "56)". Underscores were also rewritten to spaces ("IQ3_S" -> "IQ3 S").
The compact model trigger in the app repeated the last-`/` cut.

Build the Pi label from the model's own `name`/`id`: shorten only
path-like values with no whitespace (OpenRouter reports names like
"google/gemini-2.5-flash-lite"), and keep free-text names intact. The
compact trigger now strips only a leading provider namespace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(pi): cover model labels through the catalog and drop stale ACP copies

acp-agent.test.ts still imported transformPiModels, which the Pi label
fix removed, so its modelTransformer test and a stale copy of the old
Pi label tests failed. The modelTransformer test now supplies its own
transformer, and the Pi label cases run through fetchCatalog with the
reported model names instead of an exported helper.

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(pi): keep colons inside free-text model names

The vendor-prefix strip cut a free-text Pi name at its first ": ", so
"Qwen3 IQ3_S (tail skip: on, 52/56)" showed as "on, 52/56)". Strip only
when the text before ": " has no parenthesis or comma, which keeps
OpenRouter's "Vendor: Model" names shortened.

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Rahul Sharma <19687913+rms523@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-16 04:55:28 +00:00
Josh BendavidandClaude Opus 5.5 ade3817a45 fix(server): fall back to the next socket directory when the bind is refused (#9214)
A PASEO_HOME on AFS passes the socket directory checks, then refuses the
Unix socket bind with EPERM, and the terminal worker failed to start. The
worker now binds each eligible candidate in turn and moves on when the
filesystem refuses the socket (EPERM, EACCES, EOPNOTSUPP, ENOTSUP). Other
listen errors still fail the start.

Fixes #9213

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 03:56:04 +00:00
17 changed files with 321 additions and 430 deletions
+1
View File
@@ -29,6 +29,7 @@ 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,6 +15,5 @@ android {
}
dependencies {
implementation 'com.facebook.react:react-android'
testImplementation "junit:junit:4.13.2"
}
@@ -1,48 +1,26 @@
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 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) }
}
}
}
appContext.reactContext?.applicationContext?.let { recorder = DiagnosticRecorder(it, metadata) }
}
HeartbeatTiming.intervalMs
}
Function("record") { name: String, data: Map<String, String> -> recorder?.record(name, data) }
Function("heartbeat") { recorder?.heartbeat() }
OnActivityEntersForeground {
recorder?.active(true)
UiThreadUtil.runOnUiThread { touches?.activity(appContext.currentActivity?.window) }
}
OnActivityEntersForeground { recorder?.active(true) }
OnActivityEntersBackground { recorder?.active(false) }
OnDestroy {
val sink = recorder
recorder = null
UiThreadUtil.runOnUiThread {
touches?.close()
touches = null
sink?.close()
}
}
OnDestroy { recorder?.close(); recorder = null }
Function("beginSection") { name: String ->
Trace.beginSection(name.take(127))
@@ -1,141 +0,0 @@
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,4 +1,3 @@
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";
@@ -62,18 +61,13 @@ 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={activate}
onPress={onPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
@@ -1,4 +1,3 @@
import { recordComposerCommand } from "@/composer/touch-diagnostics";
import { useCallback, useMemo, useState, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
@@ -32,6 +31,7 @@ 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,11 +67,6 @@ 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,
@@ -207,7 +202,6 @@ export function CompactModelSheet({
);
const open = useCallback(() => {
recordComposerCommand("model");
Keyboard.dismiss();
rootBrowser.showAll();
setIsOpen(true);
@@ -4,6 +4,7 @@ import {
getAgentControlHintKey,
normalizeModelId,
resolveAgentModelSelection,
shortModelLabel,
} from "./utils";
describe("getAgentControlHintKey", () => {
@@ -251,3 +252,19 @@ 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,6 +35,12 @@ 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:
+13 -23
View File
@@ -1,4 +1,3 @@
import { useComposerTouchDiagnostics, recordComposerCommand } from "@/composer/touch-diagnostics";
import { useKeyboardFocusSurface } from "@/keyboard";
import type { SendShortcut } from "@/hooks/use-settings";
import {
@@ -1762,7 +1761,6 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
}, [resetComposerHeight]);
const handleSendMessage = useCallback(() => {
recordComposerCommand("send");
const liveValue = textInputRef.current?.getText() ?? valueRef.current;
if (!preserveHeightOnSubmit) {
updateLiveTextPresence("");
@@ -1792,18 +1790,19 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
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 handleQueueMessage = useCallback(
() =>
queueMessageImpl({
value: textInputRef.current?.getText() ?? valueRef.current,
attachments,
cwd,
onQueue,
replaceText,
onMinimizeHeight: minimizeInputHeight,
exitFullscreen,
}),
[attachments, cwd, onQueue, replaceText, minimizeInputHeight, exitFullscreen],
);
const handleDefaultSendAction = useCallback(() => {
runDefaultSendAction({
@@ -2328,17 +2327,8 @@ 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
@@ -1,63 +0,0 @@
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;
@@ -1,14 +0,0 @@
/** 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,7 +51,6 @@ 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,
@@ -2260,7 +2259,12 @@ describe("ACPAgentClient modelTransformer", () => {
provider: "pi",
logger: createTestLogger(),
defaultCommand: ["test-acp"],
modelTransformer: transformPiModels,
modelTransformer: (models) =>
models.map((model) => ({
...model,
label: model.label.split("/").at(-1) ?? model.label,
description: model.id,
})),
});
await expect(
@@ -2914,60 +2918,6 @@ 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,12 +19,7 @@ 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,
transformPiModels,
} from "./agent.js";
import { PiProviderOptionsSchema, PiRpcAgentClient, PiRpcAgentSession } from "./agent.js";
import { PiCliRuntime } from "./cli-runtime.js";
import { FakePi } from "./test-utils/fake-pi.js";
import { createPiExtensionHost } from "./extensions/index.js";
@@ -3970,35 +3965,73 @@ readline.createInterface({ input: process.stdin }).on("line", (line) => {
});
});
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",
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)",
},
{
provider: "pi",
id: "openrouter/openai/gpt-5.5",
label: "GPT-5.5",
description: "openrouter/OpenAI: GPT-5.5",
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)",
},
]);
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,34 +313,25 @@ interface PiSlashCommandInvocation {
type AutoCompactMode = boolean | "toggle" | "unknown";
function normalizePiModelLabel(label: string): string {
const normalizedLabel = label.trim().replace(/[_\s]+/g, " ");
const vendorSeparatorIndex = normalizedLabel.indexOf(": ");
if (vendorSeparatorIndex === -1) {
return normalizedLabel;
// 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;
}
return normalizedLabel.slice(vendorSeparatorIndex + 2).trim();
return label.slice(vendorSeparatorIndex + 2).trim();
}
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,
};
});
// 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, " "));
}
function isPiThinkingLevel(value: string | null | undefined): value is PiThinkingLevel {
@@ -1166,7 +1157,7 @@ function mapPiModel(model: PiModel, provider: AgentProvider): AgentModelDefiniti
return {
provider,
id: `${model.provider}/${model.id}`,
label: `${model.provider}/${model.name ?? model.id}`,
label: piModelLabel(model),
description: `${model.provider}/${model.id}`,
metadata: {
provider: model.provider,
@@ -2817,15 +2808,13 @@ export class PiRpcAgentClient implements AgentClient {
"get_state",
() => catalogSession.getState(),
);
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;
}),
);
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;
});
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 { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js";
import { listenOnTerminalWorkerSocket } from "./terminal-worker-socket-path.js";
import {
TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV,
TERMINAL_WORKER_PROTOCOL_VERSION,
@@ -700,23 +700,25 @@ function runWorker(argv: string[]): void {
}
async function start(): Promise<void> {
const socketPath = resolveTerminalWorkerSocketPath({
const { socketPath, listener } = await listenOnTerminalWorkerSocket({
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);
});
});
},
});
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;
server = listener;
if (process.platform !== "win32") {
chmodSync(socketPath, PRIVATE_FILE_MODE);
}
@@ -1,10 +1,11 @@
import { afterEach, describe, expect, it } from "vitest";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, symlinkSync } from "node:fs";
import { createServer } from "node:net";
import { createServer, type Server } 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";
@@ -25,7 +26,36 @@ function longHome(root: string): string {
return home;
}
afterEach(() => {
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))),
);
for (const dir of temporaryDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
@@ -142,6 +172,66 @@ 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,6 +14,9 @@ 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;
@@ -24,6 +27,16 @@ 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;
@@ -36,7 +49,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:`,
`No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`,
...rejected.map(
(candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`,
),
@@ -57,18 +70,73 @@ 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.
* 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.
*/
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 `\\\\.\\pipe\\paseo-tw-${id}`;
return windowsPipePath(input);
}
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 budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
const fileName = `tw-${id}.sock`;
const fileName = `tw-${socketFileId(input)}.sock`;
const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock");
const candidates: Array<{ directory: string; prepare: () => string | null }> = [
{
@@ -87,7 +155,6 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI
}),
];
const rejected: RejectedSocketCandidate[] = [];
const seen = new Set<string>();
for (const candidate of candidates) {
const socketPath = path.join(candidate.directory, fileName);
@@ -108,9 +175,8 @@ export function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathI
rejected.push({ path: socketPath, byteLength, reason: problem });
continue;
}
return socketPath;
yield { path: socketPath, byteLength };
}
throw new TerminalWorkerSocketPathError(rejected, budget);
}
function prepareSharedRootDirectory(directory: string, uid: number): string | null {