Refactor collection handling for mobile remote connect
- Replace chained array transforms with explicit loops across mobile and server paths - Tighten provider, git, and orchestration parsing while preserving behavior - Improve remote-connect UI data shaping and thread activity filtering
This commit is contained in:
1 parent
7793bd6de7
commit
90fea7bb2f
54 files changed
+766
-544
No files matched your search
@@ -1,5 +1,6 @@
|
||||
import { Link, Stack } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { useMemo } from "react";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -21,26 +22,29 @@ export default function NewTaskRoute() {
|
||||
() => groupProjectsByRepository({ projects, threads }),
|
||||
[projects, threads],
|
||||
);
|
||||
const items = useMemo(
|
||||
() =>
|
||||
repositoryGroups
|
||||
.map((group) => {
|
||||
const project = group.projects[0]?.project;
|
||||
if (!project) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
environmentId: project.environmentId,
|
||||
id: project.id,
|
||||
key: group.key,
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
};
|
||||
})
|
||||
.filter((entry) => entry !== null),
|
||||
[repositoryGroups],
|
||||
);
|
||||
const items = useMemo(() => {
|
||||
const nextItems: Array<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly id: ProjectId;
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
}> = [];
|
||||
for (const group of repositoryGroups) {
|
||||
const project = group.projects[0]?.project;
|
||||
if (!project) {
|
||||
continue;
|
||||
}
|
||||
nextItems.push({
|
||||
environmentId: project.environmentId,
|
||||
id: project.id,
|
||||
key: group.key,
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
});
|
||||
}
|
||||
return nextItems;
|
||||
}, [repositoryGroups]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
|
||||
@@ -1001,12 +1001,15 @@ export async function highlightReviewSelectedLines(input: {
|
||||
const language =
|
||||
loadedLanguage ?? (await resolveLanguageFromPath(input.filePath, input.languageHint ?? null));
|
||||
const shikiTheme = SHIKI_THEME_NAME_BY_SCHEME[input.theme];
|
||||
const additionLikeLines = input.lines
|
||||
.filter((line) => line.change !== "delete")
|
||||
.map((line) => `${line.content}\n`);
|
||||
const deletionLines = input.lines
|
||||
.filter((line) => line.change === "delete")
|
||||
.map((line) => `${line.content}\n`);
|
||||
const additionLikeLines: string[] = [];
|
||||
const deletionLines: string[] = [];
|
||||
for (const line of input.lines) {
|
||||
if (line.change === "delete") {
|
||||
deletionLines.push(`${line.content}\n`);
|
||||
} else {
|
||||
additionLikeLines.push(`${line.content}\n`);
|
||||
}
|
||||
}
|
||||
const [additionTokens, deletionTokens] = await Promise.all([
|
||||
highlightLines(joinPatchLines(additionLikeLines), language, shikiTheme),
|
||||
highlightLines(joinPatchLines(deletionLines), language, shikiTheme),
|
||||
|
||||
@@ -268,15 +268,17 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
];
|
||||
const builtIn = allBuiltIn.filter((item) => item.command.includes(q));
|
||||
|
||||
const providerCommands: ComposerCommandItem[] = (selectedProviderStatus?.slashCommands ?? [])
|
||||
.filter((cmd) => cmd.name.toLowerCase().includes(q))
|
||||
.map((cmd) => ({
|
||||
const providerCommands: ComposerCommandItem[] = [];
|
||||
for (const cmd of selectedProviderStatus?.slashCommands ?? []) {
|
||||
if (!cmd.name.toLowerCase().includes(q)) continue;
|
||||
providerCommands.push({
|
||||
id: `pcmd:${cmd.name}`,
|
||||
type: "provider-slash-command" as const,
|
||||
command: cmd,
|
||||
label: `/${cmd.name}`,
|
||||
description: cmd.description ?? "",
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
return [...builtIn, ...providerCommands];
|
||||
}
|
||||
|
||||
@@ -44,13 +44,13 @@ export function GitBranchesSheet() {
|
||||
);
|
||||
const [worktreeBranchName, setWorktreeBranchName] = useState("");
|
||||
|
||||
const disabledExistingBranches = new Set(
|
||||
availableBranches
|
||||
.filter(
|
||||
(branch) => branch.worktreePath !== null && branch.worktreePath !== currentWorktreePath,
|
||||
)
|
||||
.map((branch) => branch.name),
|
||||
);
|
||||
const disabledExistingBranchNames: Array<string> = [];
|
||||
for (const branch of availableBranches) {
|
||||
if (branch.worktreePath !== null && branch.worktreePath !== currentWorktreePath) {
|
||||
disabledExistingBranchNames.push(branch.name);
|
||||
}
|
||||
}
|
||||
const disabledExistingBranches = new Set(disabledExistingBranchNames);
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
|
||||
@@ -205,14 +205,16 @@ function deriveWorkLogEntries(
|
||||
latestTurnId: TurnId | undefined,
|
||||
): WorkLogEntry[] {
|
||||
const ordered = Arr.sort(activities, activityOrder);
|
||||
const entries = ordered
|
||||
.filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
|
||||
.filter((activity) => activity.kind !== "tool.started")
|
||||
.filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
|
||||
.filter((activity) => activity.kind !== "context-window.updated")
|
||||
.filter((activity) => activity.summary !== "Checkpoint captured")
|
||||
.filter((activity) => !isPlanBoundaryToolActivity(activity))
|
||||
.map(toDerivedWorkLogEntry);
|
||||
const entries: DerivedWorkLogEntry[] = [];
|
||||
for (const activity of ordered) {
|
||||
if (latestTurnId && activity.turnId !== latestTurnId) continue;
|
||||
if (activity.kind === "tool.started") continue;
|
||||
if (activity.kind === "task.started" || activity.kind === "task.completed") continue;
|
||||
if (activity.kind === "context-window.updated") continue;
|
||||
if (activity.summary === "Checkpoint captured") continue;
|
||||
if (isPlanBoundaryToolActivity(activity)) continue;
|
||||
entries.push(toDerivedWorkLogEntry(activity));
|
||||
}
|
||||
return collapseDerivedWorkLogEntries(entries).map(
|
||||
({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
|
||||
);
|
||||
@@ -525,9 +527,13 @@ function formatCommandValue(value: unknown): string | null {
|
||||
if (!Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => asTrimmedString(entry))
|
||||
.filter((entry): entry is string => entry !== null);
|
||||
const parts: Array<string> = [];
|
||||
for (const entry of value) {
|
||||
const part = asTrimmedString(entry);
|
||||
if (part !== null) {
|
||||
parts.push(part);
|
||||
}
|
||||
}
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -64,11 +64,16 @@ export const makeAuthControlPlane = Effect.gen(function* () {
|
||||
|
||||
const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) =>
|
||||
bootstrapCredentials.listActive().pipe(
|
||||
Effect.map((pairingLinks) =>
|
||||
pairingLinks
|
||||
.filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true))
|
||||
.filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject))
|
||||
.map((pairingLink) =>
|
||||
Effect.map((pairingLinks) => {
|
||||
const activeLinks: Array<AuthPairingLink> = [];
|
||||
for (const pairingLink of pairingLinks) {
|
||||
if (input?.role && pairingLink.role !== input.role) {
|
||||
continue;
|
||||
}
|
||||
if (input?.excludeSubjects?.includes(pairingLink.subject)) {
|
||||
continue;
|
||||
}
|
||||
activeLinks.push(
|
||||
pairingLink.label
|
||||
? ({
|
||||
id: pairingLink.id,
|
||||
@@ -87,11 +92,12 @@ export const makeAuthControlPlane = Effect.gen(function* () {
|
||||
createdAt: pairingLink.createdAt,
|
||||
expiresAt: pairingLink.expiresAt,
|
||||
} satisfies AuthPairingLink),
|
||||
)
|
||||
.toSorted(
|
||||
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return activeLinks.toSorted(
|
||||
(left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds,
|
||||
);
|
||||
}),
|
||||
Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")),
|
||||
);
|
||||
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
|
||||
return stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0);
|
||||
const remoteNames: Array<string> = [];
|
||||
for (const line of stdout.split("\n")) {
|
||||
const remoteName = line.trim();
|
||||
if (remoteName.length > 0) {
|
||||
remoteNames.push(remoteName);
|
||||
}
|
||||
}
|
||||
return remoteNames;
|
||||
}
|
||||
|
||||
export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
|
||||
|
||||
@@ -35,10 +35,13 @@ export function parseBase64DataUrl(
|
||||
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
|
||||
if (!match) return null;
|
||||
|
||||
const headerParts = (match[1] ?? "")
|
||||
.split(";")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
const headerParts: Array<string> = [];
|
||||
for (const part of (match[1] ?? "").split(";")) {
|
||||
const trimmed = part.trim();
|
||||
if (trimmed.length > 0) {
|
||||
headerParts.push(trimmed);
|
||||
}
|
||||
}
|
||||
if (headerParts.length < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Predicate from "effect/Predicate";
|
||||
import * as PubSub from "effect/PubSub";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SchemaIssue from "effect/SchemaIssue";
|
||||
import * as SchemaTransformation from "effect/SchemaTransformation";
|
||||
@@ -538,9 +539,11 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
const matchingDefaults = DEFAULT_KEYBINDINGS.filter((defaultRule) =>
|
||||
customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule)),
|
||||
).map((rule) => rule.command);
|
||||
const matchingDefaults = Array.filterMap(DEFAULT_KEYBINDINGS, (defaultRule) =>
|
||||
customConfig.some((entry) => isSameKeybindingRule(entry, defaultRule))
|
||||
? Result.succeed(defaultRule.command)
|
||||
: Result.failVoid,
|
||||
);
|
||||
if (matchingDefaults.length > 0) {
|
||||
yield* Effect.logWarning("default keybinding rule already defined in user config", {
|
||||
path: keybindingsConfigPath,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
CommandId,
|
||||
type CheckpointRef,
|
||||
EventId,
|
||||
MessageId,
|
||||
type ProjectId,
|
||||
@@ -683,9 +684,12 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const staleCheckpointRefs = thread.checkpoints
|
||||
.filter((checkpoint) => checkpoint.checkpointTurnCount > event.payload.turnCount)
|
||||
.map((checkpoint) => checkpoint.checkpointRef);
|
||||
const staleCheckpointRefs: Array<CheckpointRef> = [];
|
||||
for (const checkpoint of thread.checkpoints) {
|
||||
if (checkpoint.checkpointTurnCount > event.payload.turnCount) {
|
||||
staleCheckpointRefs.push(checkpoint.checkpointRef);
|
||||
}
|
||||
}
|
||||
|
||||
if (staleCheckpointRefs.length > 0) {
|
||||
yield* checkpointStore.deleteCheckpointRefs({
|
||||
|
||||
@@ -536,12 +536,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
projectionPendingApprovalRepository.listByThreadId({ threadId }),
|
||||
]);
|
||||
|
||||
const latestUserMessageAt =
|
||||
messages
|
||||
.filter((message) => message.role === "user")
|
||||
.map((message) => message.createdAt)
|
||||
.toSorted()
|
||||
.at(-1) ?? null;
|
||||
let latestUserMessageAt: string | null = null;
|
||||
for (const message of messages) {
|
||||
if (
|
||||
message.role === "user" &&
|
||||
(latestUserMessageAt === null || message.createdAt > latestUserMessageAt)
|
||||
) {
|
||||
latestUserMessageAt = message.createdAt;
|
||||
}
|
||||
}
|
||||
|
||||
const pendingApprovalCount = pendingApprovals.filter(
|
||||
(approval) => approval.status === "pending",
|
||||
|
||||
@@ -24,9 +24,11 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Struct from "effect/Struct";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -1488,34 +1490,36 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects: projectRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map((row) =>
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
),
|
||||
threads: threadRows
|
||||
.filter((row) => row.deletedAt === null)
|
||||
.map(
|
||||
(row): OrchestrationThreadShell => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: row.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
|
||||
}),
|
||||
),
|
||||
projects: Arr.filterMap(projectRows, (row) =>
|
||||
row.deletedAt === null
|
||||
? Result.succeed(
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
)
|
||||
: Result.failVoid,
|
||||
),
|
||||
threads: Arr.filterMap(threadRows, (row) =>
|
||||
row.deletedAt === null
|
||||
? Result.succeed({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
archivedAt: row.archivedAt,
|
||||
session: sessionByThread.get(row.threadId) ?? null,
|
||||
latestUserMessageAt: row.latestUserMessageAt,
|
||||
hasPendingApprovals: row.pendingApprovalCount > 0,
|
||||
hasPendingUserInput: row.pendingUserInputCount > 0,
|
||||
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
|
||||
} satisfies OrchestrationThreadShell)
|
||||
: Result.failVoid,
|
||||
),
|
||||
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
@@ -1621,11 +1625,13 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
projects: projectRows
|
||||
.filter((row) => row.deletedAt === null && activeProjectIds.has(row.projectId))
|
||||
.map((row) =>
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
),
|
||||
projects: Arr.filterMap(projectRows, (row) =>
|
||||
row.deletedAt === null && activeProjectIds.has(row.projectId)
|
||||
? Result.succeed(
|
||||
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
|
||||
)
|
||||
: Result.failVoid,
|
||||
),
|
||||
threads: threadRows.map(
|
||||
(row): OrchestrationThreadShell => ({
|
||||
id: row.threadId,
|
||||
|
||||
@@ -244,9 +244,13 @@ function toProcessError(
|
||||
function normalizeClaudeStreamMessages(
|
||||
cause: Cause.Cause<{ readonly message: string }>,
|
||||
): ReadonlyArray<string> {
|
||||
const errors = Cause.prettyErrors(cause)
|
||||
.map((error) => error.message.trim())
|
||||
.filter((message) => message.length > 0);
|
||||
const errors: Array<string> = [];
|
||||
for (const error of Cause.prettyErrors(cause)) {
|
||||
const message = error.message.trim();
|
||||
if (message.length > 0) {
|
||||
errors.push(message);
|
||||
}
|
||||
}
|
||||
if (errors.length > 0) {
|
||||
return errors;
|
||||
}
|
||||
|
||||
@@ -248,11 +248,13 @@ export function resolveClaudeApiModelId(modelSelection: ModelSelection): string
|
||||
}
|
||||
|
||||
function toTitleCaseWords(value: string): string {
|
||||
return value
|
||||
.split(/[\s_-]+/g)
|
||||
.filter(Boolean)
|
||||
.map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
const parts: Array<string> = [];
|
||||
for (const part of value.split(/[\s_-]+/g)) {
|
||||
if (part.length > 0) {
|
||||
parts.push(part[0]!.toUpperCase() + part.slice(1).toLowerCase());
|
||||
}
|
||||
}
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
|
||||
|
||||
@@ -319,16 +319,21 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
|
||||
} satisfies CodexAppServerProviderSnapshot;
|
||||
});
|
||||
|
||||
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
|
||||
codexSettings.customModels
|
||||
.map((model) => model.trim())
|
||||
.filter((model, index, models) => model.length > 0 && models.indexOf(model) === index)
|
||||
.map((model) => ({
|
||||
slug: model,
|
||||
name: model,
|
||||
isCustom: true,
|
||||
capabilities: null,
|
||||
}));
|
||||
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] => {
|
||||
const models = new Set<string>();
|
||||
for (const model of codexSettings.customModels) {
|
||||
const trimmed = model.trim();
|
||||
if (trimmed.length > 0) {
|
||||
models.add(trimmed);
|
||||
}
|
||||
}
|
||||
return Array.from(models, (model) => ({
|
||||
slug: model,
|
||||
name: model,
|
||||
isCustom: true,
|
||||
capabilities: null,
|
||||
}));
|
||||
};
|
||||
|
||||
const makePendingCodexProvider = (
|
||||
codexSettings: CodexSettings,
|
||||
|
||||
@@ -596,11 +596,12 @@ export const discoverCursorModelCapabilitiesViaAcp = (
|
||||
);
|
||||
}
|
||||
|
||||
const targetModelSlugs = new Set(
|
||||
existingModels
|
||||
.filter((model) => !model.isCustom && !hasCursorModelCapabilities(model))
|
||||
.map((model) => model.slug),
|
||||
);
|
||||
const targetModelSlugs = new Set<string>();
|
||||
for (const model of existingModels) {
|
||||
if (!model.isCustom && !hasCursorModelCapabilities(model)) {
|
||||
targetModelSlugs.add(model.slug);
|
||||
}
|
||||
}
|
||||
if (targetModelSlugs.size === 0) {
|
||||
return buildCursorDiscoveredModels(
|
||||
modelChoices.map((modelChoice) => ({
|
||||
@@ -721,9 +722,13 @@ export interface CursorAboutResult {
|
||||
}
|
||||
|
||||
function joinProviderMessages(...messages: ReadonlyArray<string | undefined>): string | undefined {
|
||||
const parts = messages
|
||||
.map((message) => message?.trim())
|
||||
.filter((message): message is string => Boolean(message));
|
||||
const parts: Array<string> = [];
|
||||
for (const message of messages) {
|
||||
const trimmed = message?.trim();
|
||||
if (trimmed) {
|
||||
parts.push(trimmed);
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
@@ -790,11 +795,13 @@ export function parseCursorCliConfigChannel(raw: string): string | undefined {
|
||||
}
|
||||
|
||||
function toTitleCaseWords(value: string): string {
|
||||
return value
|
||||
.split(/[\s_-]+/g)
|
||||
.filter((part) => part.length > 0)
|
||||
.map((part) => part.charAt(0).toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
const parts: Array<string> = [];
|
||||
for (const part of value.split(/[\s_-]+/g)) {
|
||||
if (part.length > 0) {
|
||||
parts.push(part.charAt(0).toUpperCase() + part.slice(1).toLowerCase());
|
||||
}
|
||||
}
|
||||
return parts.join(" ");
|
||||
}
|
||||
|
||||
function cursorSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
|
||||
|
||||
@@ -1357,12 +1357,15 @@ export function makeOpenCodeAdapter(
|
||||
}),
|
||||
).pipe(Effect.mapError(toRequestError));
|
||||
|
||||
const turns = (messages.data ?? [])
|
||||
.filter((entry) => entry.info.role === "assistant")
|
||||
.map((entry) => ({
|
||||
id: TurnId.make(entry.info.id),
|
||||
items: [entry.info, ...entry.parts],
|
||||
}));
|
||||
const turns: Array<OpenCodeTurnSnapshot> = [];
|
||||
for (const entry of messages.data ?? []) {
|
||||
if (entry.info.role === "assistant") {
|
||||
turns.push({
|
||||
id: TurnId.make(entry.info.id),
|
||||
items: [entry.info, ...entry.parts],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
threadId,
|
||||
|
||||
@@ -137,11 +137,13 @@ function formatOpenCodeProbeError(input: {
|
||||
}
|
||||
|
||||
function titleCaseSlug(value: string): string {
|
||||
return value
|
||||
.split(/[-_/]+/)
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
||||
.join(" ");
|
||||
const segments: Array<string> = [];
|
||||
for (const segment of value.split(/[-_/]+/)) {
|
||||
if (segment.length > 0) {
|
||||
segments.push(segment.charAt(0).toUpperCase() + segment.slice(1));
|
||||
}
|
||||
}
|
||||
return segments.join(" ");
|
||||
}
|
||||
|
||||
function inferDefaultVariant(
|
||||
|
||||
@@ -126,19 +126,20 @@ export function parseSessionModeState(
|
||||
if (!currentModeId) {
|
||||
return undefined;
|
||||
}
|
||||
const availableModes = modes.availableModes
|
||||
.map((mode) => {
|
||||
const id = mode.id.trim();
|
||||
const name = mode.name.trim();
|
||||
if (!id || !name) {
|
||||
return undefined;
|
||||
}
|
||||
const description = mode.description?.trim() || undefined;
|
||||
return description !== undefined
|
||||
const availableModes: Array<AcpSessionMode> = [];
|
||||
for (const mode of modes.availableModes) {
|
||||
const id = mode.id.trim();
|
||||
const name = mode.name.trim();
|
||||
if (!id || !name) {
|
||||
continue;
|
||||
}
|
||||
const description = mode.description?.trim() || undefined;
|
||||
availableModes.push(
|
||||
description !== undefined
|
||||
? ({ id, name, description } satisfies AcpSessionMode)
|
||||
: ({ id, name } satisfies AcpSessionMode);
|
||||
})
|
||||
.filter((mode): mode is AcpSessionMode => mode !== undefined);
|
||||
: ({ id, name } satisfies AcpSessionMode),
|
||||
);
|
||||
}
|
||||
if (availableModes.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
@@ -186,9 +187,15 @@ function normalizeCommandValue(value: unknown): string | undefined {
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => (typeof entry === "string" && entry.trim().length > 0 ? entry.trim() : null))
|
||||
.filter((entry): entry is string => entry !== null);
|
||||
const parts: Array<string> = [];
|
||||
for (const entry of value) {
|
||||
if (typeof entry === "string") {
|
||||
const part = entry.trim();
|
||||
if (part.length > 0) {
|
||||
parts.push(part);
|
||||
}
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
@@ -222,18 +229,20 @@ function extractTextContentFromToolCallContent(
|
||||
content: ReadonlyArray<EffectAcpSchema.ToolCallContent> | null | undefined,
|
||||
): string | undefined {
|
||||
if (!content) return undefined;
|
||||
const chunks = content
|
||||
.map((entry) => {
|
||||
if (entry.type !== "content") {
|
||||
return undefined;
|
||||
}
|
||||
const nestedContent = entry.content;
|
||||
if (nestedContent.type !== "text") {
|
||||
return undefined;
|
||||
}
|
||||
return nestedContent.text.trim().length > 0 ? nestedContent.text.trim() : undefined;
|
||||
})
|
||||
.filter((entry): entry is string => entry !== undefined);
|
||||
const chunks: Array<string> = [];
|
||||
for (const entry of content) {
|
||||
if (entry.type !== "content") {
|
||||
continue;
|
||||
}
|
||||
const nestedContent = entry.content;
|
||||
if (nestedContent.type !== "text") {
|
||||
continue;
|
||||
}
|
||||
const text = nestedContent.text.trim();
|
||||
if (text.length > 0) {
|
||||
chunks.push(text);
|
||||
}
|
||||
}
|
||||
return chunks.length > 0 ? chunks.join("\n") : undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -214,13 +214,15 @@ export const make = Effect.fn("ProviderMaintenanceRunner.make")(function* () {
|
||||
instanceId: ProviderInstanceId,
|
||||
): Effect.Effect<VerifiedProviderRefresh> =>
|
||||
providerRegistry.getProviders.pipe(
|
||||
Effect.map((providers) =>
|
||||
providers
|
||||
.filter(
|
||||
(candidate) => candidate.driver === provider && candidate.instanceId === instanceId,
|
||||
)
|
||||
.map((candidate) => candidate.instanceId),
|
||||
),
|
||||
Effect.map((providers) => {
|
||||
const instanceIds: Array<ProviderInstanceId> = [];
|
||||
for (const candidate of providers) {
|
||||
if (candidate.driver === provider && candidate.instanceId === instanceId) {
|
||||
instanceIds.push(candidate.instanceId);
|
||||
}
|
||||
}
|
||||
return instanceIds;
|
||||
}),
|
||||
Effect.flatMap((instanceIds) =>
|
||||
instanceIds.length === 0
|
||||
? providerRegistry.refreshInstance(instanceId)
|
||||
|
||||
@@ -208,10 +208,13 @@ function parseRepositorySpecifier(repository: string): {
|
||||
readonly project: string | null;
|
||||
readonly name: string;
|
||||
} {
|
||||
const parts = repository
|
||||
.split("/")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
const parts: Array<string> = [];
|
||||
for (const part of repository.split("/")) {
|
||||
const trimmed = part.trim();
|
||||
if (trimmed.length > 0) {
|
||||
parts.push(trimmed);
|
||||
}
|
||||
}
|
||||
return {
|
||||
project: parts.length > 1 ? (parts.at(-2) ?? null) : null,
|
||||
name: parts.at(-1) ?? repository.trim(),
|
||||
|
||||
@@ -247,10 +247,13 @@ function parseRepositoryPath(repository: string): {
|
||||
readonly namespacePath: string | null;
|
||||
readonly projectPath: string;
|
||||
} {
|
||||
const parts = repository
|
||||
.split("/")
|
||||
.map((part) => part.trim())
|
||||
.filter((part) => part.length > 0);
|
||||
const parts: Array<string> = [];
|
||||
for (const part of repository.split("/")) {
|
||||
const trimmed = part.trim();
|
||||
if (trimmed.length > 0) {
|
||||
parts.push(trimmed);
|
||||
}
|
||||
}
|
||||
const projectPath = parts.at(-1) ?? repository.trim();
|
||||
const namespacePath = parts.length > 1 ? parts.slice(0, -1).join("/") : null;
|
||||
return { namespacePath, projectPath };
|
||||
|
||||
@@ -96,15 +96,24 @@ export function unknownAuth(detail?: string): SourceControlProviderAuth {
|
||||
}
|
||||
|
||||
export function combinedAuthOutput(input: SourceControlAuthProbeInput): string {
|
||||
return [input.stdout, input.stderr].filter((entry) => entry.trim().length > 0).join("\n");
|
||||
const parts: string[] = [];
|
||||
for (const entry of [input.stdout, input.stderr]) {
|
||||
if (entry.trim().length > 0) {
|
||||
parts.push(entry);
|
||||
}
|
||||
}
|
||||
return parts.join("\n");
|
||||
}
|
||||
|
||||
function sanitizedAuthLines(text: string): ReadonlyArray<string> {
|
||||
return text
|
||||
.split(/\r?\n/)
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.filter((entry) => !/^[-\s]*token(?:\s+scopes?)?:/iu.test(entry));
|
||||
const lines: string[] = [];
|
||||
for (const entry of text.split(/\r?\n/)) {
|
||||
const line = entry.trim();
|
||||
if (line.length === 0) continue;
|
||||
if (/^[-\s]*token(?:\s+scopes?)?:/iu.test(line)) continue;
|
||||
lines.push(line);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
export function firstSafeAuthLine(text: string): string | undefined {
|
||||
|
||||
@@ -92,18 +92,17 @@ function selectProviderContext(
|
||||
readonly url: string;
|
||||
}>,
|
||||
): SourceControlProvider.SourceControlProviderContext | null {
|
||||
const candidates = remotes
|
||||
.map((remote) => {
|
||||
const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
|
||||
return provider
|
||||
? {
|
||||
provider,
|
||||
remoteName: remote.name,
|
||||
remoteUrl: remote.url,
|
||||
}
|
||||
: null;
|
||||
})
|
||||
.filter((value): value is SourceControlProvider.SourceControlProviderContext => value !== null);
|
||||
const candidates: Array<SourceControlProvider.SourceControlProviderContext> = [];
|
||||
for (const remote of remotes) {
|
||||
const provider = detectSourceControlProviderFromRemoteUrl(remote.url);
|
||||
if (provider) {
|
||||
candidates.push({
|
||||
provider,
|
||||
remoteName: remote.name,
|
||||
remoteUrl: remote.url,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
candidates.find((candidate) => candidate.remoteName === "origin") ??
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Cache from "effect/Cache";
|
||||
import * as Data from "effect/Data";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
@@ -1693,10 +1694,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
);
|
||||
|
||||
return {
|
||||
diff: diffs
|
||||
.map((result) => result.stdout)
|
||||
.filter((diff) => diff.trim().length > 0)
|
||||
.join("\n"),
|
||||
diff: Arr.filterMap(diffs, (result) =>
|
||||
result.stdout.trim().length > 0 ? Result.succeed(result.stdout) : Result.failVoid,
|
||||
).join("\n"),
|
||||
truncated: untrackedResult.stdoutTruncated || diffs.some((result) => result.stdoutTruncated),
|
||||
};
|
||||
});
|
||||
@@ -1965,61 +1965,60 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
}
|
||||
}
|
||||
|
||||
const localBranches = localBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((refName): refName is { name: string; current: boolean } => refName !== null)
|
||||
.map((refName) => ({
|
||||
name: refName.name,
|
||||
current: refName.current,
|
||||
isRemote: false,
|
||||
isDefault: refName.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(refName.name) ?? null,
|
||||
}))
|
||||
.toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
const localBranches = Arr.filterMap(localBranchResult.stdout.split("\n"), (line) => {
|
||||
const refName = parseBranchLine(line);
|
||||
return refName === null
|
||||
? Result.failVoid
|
||||
: Result.succeed({
|
||||
name: refName.name,
|
||||
current: refName.current,
|
||||
isRemote: false,
|
||||
isDefault: refName.name === defaultBranch,
|
||||
worktreePath: worktreeMap.get(refName.name) ?? null,
|
||||
});
|
||||
}).toSorted((a, b) => {
|
||||
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
|
||||
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
|
||||
if (aPriority !== bPriority) return aPriority - bPriority;
|
||||
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
});
|
||||
|
||||
const remoteBranches =
|
||||
remoteBranchResult.exitCode === 0
|
||||
? remoteBranchResult.stdout
|
||||
.split("\n")
|
||||
.map(parseBranchLine)
|
||||
.filter((refName): refName is { name: string; current: boolean } => refName !== null)
|
||||
.map((refName) => {
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(refName.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return remoteBranch;
|
||||
})
|
||||
.toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
? Arr.filterMap(remoteBranchResult.stdout.split("\n"), (line) => {
|
||||
const refName = parseBranchLine(line);
|
||||
if (refName === null) {
|
||||
return Result.failVoid;
|
||||
}
|
||||
const parsedRemoteRef = parseRemoteRefWithRemoteNames(refName.name, remoteNames);
|
||||
const remoteBranch: {
|
||||
name: string;
|
||||
current: boolean;
|
||||
isRemote: boolean;
|
||||
remoteName?: string;
|
||||
isDefault: boolean;
|
||||
worktreePath: string | null;
|
||||
} = {
|
||||
name: refName.name,
|
||||
current: false,
|
||||
isRemote: true,
|
||||
isDefault: false,
|
||||
worktreePath: null,
|
||||
};
|
||||
if (parsedRemoteRef) {
|
||||
remoteBranch.remoteName = parsedRemoteRef.remoteName;
|
||||
}
|
||||
return Result.succeed(remoteBranch);
|
||||
}).toSorted((a, b) => {
|
||||
const aLastCommit = branchLastCommit.get(a.name) ?? 0;
|
||||
const bLastCommit = branchLastCommit.get(b.name) ?? 0;
|
||||
if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit;
|
||||
return a.name.localeCompare(b.name);
|
||||
})
|
||||
: [];
|
||||
|
||||
const refs = paginateBranches({
|
||||
@@ -2278,12 +2277,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
"--no-column",
|
||||
"--format=%(refname:short)",
|
||||
]).pipe(
|
||||
Effect.map((stdout) =>
|
||||
stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0),
|
||||
),
|
||||
Effect.map((stdout) => {
|
||||
const branchNames: Array<string> = [];
|
||||
for (const line of stdout.split("\n")) {
|
||||
const branchName = line.trim();
|
||||
if (branchName.length > 0) {
|
||||
branchNames.push(branchName);
|
||||
}
|
||||
}
|
||||
return branchNames;
|
||||
}),
|
||||
);
|
||||
|
||||
return GitVcsDriver.GitVcsDriver.of({
|
||||
|
||||
@@ -221,9 +221,13 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
return null;
|
||||
}
|
||||
|
||||
const listedPaths = [...listedFiles.paths]
|
||||
.map((entry) => toPosixPath(entry))
|
||||
.filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry));
|
||||
const listedPaths: Array<string> = [];
|
||||
for (const rawEntry of listedFiles.paths) {
|
||||
const entry = toPosixPath(rawEntry);
|
||||
if (entry.length > 0 && !isPathInIgnoredDirectory(entry)) {
|
||||
listedPaths.push(entry);
|
||||
}
|
||||
}
|
||||
const filePaths = yield* vcs.driver.filterIgnoredPaths(cwd, listedPaths).pipe(
|
||||
Effect.map((paths) => [...paths]),
|
||||
Effect.catch(() => filterVcsIgnoredPaths(cwd, listedPaths)),
|
||||
@@ -456,21 +460,23 @@ export const makeWorkspaceEntries = Effect.gen(function* () {
|
||||
|
||||
const showHidden = endsWithSeparator || prefix.startsWith(".");
|
||||
const lowerPrefix = prefix.toLowerCase();
|
||||
const entries: Array<{ readonly name: string; readonly fullPath: string }> = [];
|
||||
for (const dirent of dirents) {
|
||||
if (
|
||||
dirent.isDirectory() &&
|
||||
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
|
||||
(showHidden || !dirent.name.startsWith("."))
|
||||
) {
|
||||
entries.push({
|
||||
name: dirent.name,
|
||||
fullPath: path.join(parentPath, dirent.name),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
parentPath,
|
||||
entries: dirents
|
||||
.filter(
|
||||
(dirent) =>
|
||||
dirent.isDirectory() &&
|
||||
dirent.name.toLowerCase().startsWith(lowerPrefix) &&
|
||||
(showHidden || !dirent.name.startsWith(".")),
|
||||
)
|
||||
.map((dirent) => ({
|
||||
name: dirent.name,
|
||||
fullPath: path.join(parentPath, dirent.name),
|
||||
}))
|
||||
.toSorted((left, right) => left.name.localeCompare(right.name)),
|
||||
entries: entries.toSorted((left, right) => left.name.localeCompare(right.name)),
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
@@ -194,7 +194,6 @@ import {
|
||||
isVersionMismatchDismissed,
|
||||
resolveServerConfigVersionMismatch,
|
||||
} from "../versionSkew";
|
||||
import { equals } from "effect/Equal";
|
||||
|
||||
const IMAGE_ONLY_BOOTSTRAP_PROMPT =
|
||||
"[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { type KeybindingCommand, type FilesystemBrowseEntry } from "@t3tools/contracts";
|
||||
import type { SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Result from "effect/Result";
|
||||
import { type ReactNode } from "react";
|
||||
import { sortThreads } from "../lib/threadSort";
|
||||
import { formatRelativeTimeLabel } from "../timestampFormat";
|
||||
@@ -252,23 +254,18 @@ export function filterCommandPaletteGroups(input: {
|
||||
}
|
||||
|
||||
return searchableGroups.flatMap((group) => {
|
||||
const items = group.items
|
||||
.map((item, index) => {
|
||||
const haystack = normalizeSearchText(item.searchTerms.join(" "));
|
||||
if (!haystack.includes(normalizedQuery)) {
|
||||
return null;
|
||||
}
|
||||
const items = Arr.filterMap(group.items, (item, index) => {
|
||||
const haystack = normalizeSearchText(item.searchTerms.join(" "));
|
||||
if (!haystack.includes(normalizedQuery)) {
|
||||
return Result.failVoid;
|
||||
}
|
||||
|
||||
return {
|
||||
item,
|
||||
index,
|
||||
rank: rankCommandPaletteItemMatch(item, normalizedQuery),
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(entry): entry is { item: (typeof group.items)[number]; index: number; rank: number } =>
|
||||
entry !== null,
|
||||
)
|
||||
return Result.succeed({
|
||||
item,
|
||||
index,
|
||||
rank: rankCommandPaletteItemMatch(item, normalizedQuery),
|
||||
});
|
||||
})
|
||||
.toSorted((left, right) => right.rank - left.rank || left.index - right.index)
|
||||
.map((entry) => entry.item);
|
||||
|
||||
|
||||
@@ -194,12 +194,14 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
[selectedCheckpointTurnCount],
|
||||
);
|
||||
const conversationCheckpointTurnCount = useMemo(() => {
|
||||
const turnCounts = orderedTurnDiffSummaries
|
||||
.map(
|
||||
(summary) =>
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId],
|
||||
)
|
||||
.filter((value): value is number => typeof value === "number");
|
||||
const turnCounts: Array<number> = [];
|
||||
for (const summary of orderedTurnDiffSummaries) {
|
||||
const value =
|
||||
summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];
|
||||
if (typeof value === "number") {
|
||||
turnCounts.push(value);
|
||||
}
|
||||
}
|
||||
if (turnCounts.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1295,9 +1295,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
} catch {
|
||||
const currentImageIds = new Set(composerImages.map((image) => image.id));
|
||||
const fallbackPersistedAttachments = getPersistedAttachmentsForThread();
|
||||
const fallbackPersistedIds = fallbackPersistedAttachments
|
||||
.map((attachment) => attachment.id)
|
||||
.filter((id) => currentImageIds.has(id));
|
||||
const fallbackPersistedIds: Array<string> = [];
|
||||
for (const attachment of fallbackPersistedAttachments) {
|
||||
if (currentImageIds.has(attachment.id)) {
|
||||
fallbackPersistedIds.push(attachment.id);
|
||||
}
|
||||
}
|
||||
const fallbackPersistedIdSet = new Set(fallbackPersistedIds);
|
||||
const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) =>
|
||||
fallbackPersistedIdSet.has(attachment.id),
|
||||
|
||||
@@ -272,8 +272,13 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
// ignoring sidebar selection so account-scoped searches can find a
|
||||
// model before the user chooses a specific instance rail item.
|
||||
if (props.lockedProvider !== null) {
|
||||
return rankedMatches
|
||||
.filter((rankedModel) => matchesLockedProvider(rankedModel.model))
|
||||
const lockedProviderMatches: Array<(typeof rankedMatches)[number]> = [];
|
||||
for (const rankedModel of rankedMatches) {
|
||||
if (matchesLockedProvider(rankedModel.model)) {
|
||||
lockedProviderMatches.push(rankedModel);
|
||||
}
|
||||
}
|
||||
return lockedProviderMatches
|
||||
.toSorted((a, b) => {
|
||||
const scoreDelta = a.score - b.score;
|
||||
if (scoreDelta !== 0) {
|
||||
|
||||
@@ -376,22 +376,23 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
return null;
|
||||
}
|
||||
|
||||
const triggerLabel =
|
||||
descriptors
|
||||
.map((descriptor) => {
|
||||
if (ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id) {
|
||||
return "Ultrathink";
|
||||
}
|
||||
if (descriptor.type === "boolean") {
|
||||
if (descriptor.id === "fastMode") {
|
||||
return descriptor.currentValue === true ? "Fast" : "Normal";
|
||||
}
|
||||
return `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`;
|
||||
}
|
||||
return getProviderOptionCurrentLabel(descriptor);
|
||||
})
|
||||
.filter((label): label is string => typeof label === "string" && label.length > 0)
|
||||
.join(" · ") || "";
|
||||
const triggerLabels: Array<string> = [];
|
||||
for (const descriptor of descriptors) {
|
||||
const label =
|
||||
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
|
||||
? "Ultrathink"
|
||||
: descriptor.type === "boolean"
|
||||
? descriptor.id === "fastMode"
|
||||
? descriptor.currentValue === true
|
||||
? "Fast"
|
||||
: "Normal"
|
||||
: `${descriptor.label} ${descriptor.currentValue === true ? "On" : "Off"}`
|
||||
: getProviderOptionCurrentLabel(descriptor);
|
||||
if (typeof label === "string" && label.length > 0) {
|
||||
triggerLabels.push(label);
|
||||
}
|
||||
}
|
||||
const triggerLabel = triggerLabels.join(" · ");
|
||||
|
||||
const isCodexStyle = provider === "codex";
|
||||
|
||||
|
||||
@@ -68,9 +68,13 @@ export function scoreModelPickerSearch(
|
||||
let score = 0;
|
||||
|
||||
for (const token of tokens) {
|
||||
const tokenScores = fields
|
||||
.map((field, index) => scoreModelPickerSearchToken(field, token, index * 10))
|
||||
.filter((fieldScore): fieldScore is number => fieldScore !== null);
|
||||
const tokenScores: Array<number> = [];
|
||||
for (let index = 0; index < fields.length; index += 1) {
|
||||
const fieldScore = scoreModelPickerSearchToken(fields[index]!, token, index * 10);
|
||||
if (fieldScore !== null) {
|
||||
tokenScores.push(fieldScore);
|
||||
}
|
||||
}
|
||||
|
||||
if (tokenScores.length === 0) {
|
||||
return null;
|
||||
|
||||
@@ -7,11 +7,14 @@ export function buildInlineTerminalContextText(
|
||||
header: string;
|
||||
}>,
|
||||
): string {
|
||||
return contexts
|
||||
.map((context) => context.header.trim())
|
||||
.filter((header) => header.length > 0)
|
||||
.map(formatInlineTerminalContextLabel)
|
||||
.join(" ");
|
||||
const labels: Array<string> = [];
|
||||
for (const context of contexts) {
|
||||
const header = context.header.trim();
|
||||
if (header.length > 0) {
|
||||
labels.push(formatInlineTerminalContextLabel(header));
|
||||
}
|
||||
}
|
||||
return labels.join(" ");
|
||||
}
|
||||
|
||||
export function formatInlineTerminalContextLabel(header: string): string {
|
||||
|
||||
@@ -534,21 +534,27 @@ const PairingLinkListRow = memo(function PairingLinkListRow({
|
||||
const endpoint = selectPairingEndpoint(endpoints, defaultEndpointKey);
|
||||
return endpoint ? resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential) : null;
|
||||
}, [defaultEndpointKey, endpoints, pairingLink.credential]);
|
||||
const endpointCopyOptions = useMemo(
|
||||
() =>
|
||||
endpoints
|
||||
.filter((endpoint) => endpoint.status !== "unavailable")
|
||||
.map((endpoint) => {
|
||||
const url = resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential);
|
||||
return {
|
||||
key: endpointDefaultPreferenceKey(endpoint),
|
||||
label: endpoint.label,
|
||||
url,
|
||||
detail: isHostedAppPairingUrl(url) ? "Hosted app link" : "Backend pairing URL",
|
||||
};
|
||||
}),
|
||||
[endpoints, pairingLink.credential],
|
||||
);
|
||||
const endpointCopyOptions = useMemo(() => {
|
||||
const options: Array<{
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly url: string;
|
||||
readonly detail: string;
|
||||
}> = [];
|
||||
for (const endpoint of endpoints) {
|
||||
if (endpoint.status === "unavailable") {
|
||||
continue;
|
||||
}
|
||||
const url = resolveAdvertisedEndpointPairingUrl(endpoint, pairingLink.credential);
|
||||
options.push({
|
||||
key: endpointDefaultPreferenceKey(endpoint),
|
||||
label: endpoint.label,
|
||||
url,
|
||||
detail: isHostedAppPairingUrl(url) ? "Hosted app link" : "Backend pairing URL",
|
||||
});
|
||||
}
|
||||
return options;
|
||||
}, [endpoints, pairingLink.credential]);
|
||||
const shareablePairingUrl =
|
||||
endpointPairingUrl ??
|
||||
(endpointUrl != null && endpointUrl !== ""
|
||||
|
||||
@@ -140,14 +140,16 @@ export function keybindingConflictLabels(
|
||||
input: { readonly rowId: string; readonly key: string; readonly when: string },
|
||||
): ReadonlyArray<string> {
|
||||
if (input.key.trim().length === 0) return [];
|
||||
const conflicts = rows
|
||||
.filter(
|
||||
(candidate) =>
|
||||
candidate.id !== input.rowId &&
|
||||
candidate.key === input.key &&
|
||||
conflictsWithWhen(candidate.when, input.when),
|
||||
)
|
||||
.map((candidate) => commandLabel(candidate.command));
|
||||
const conflicts: Array<string> = [];
|
||||
for (const candidate of rows) {
|
||||
if (
|
||||
candidate.id !== input.rowId &&
|
||||
candidate.key === input.key &&
|
||||
conflictsWithWhen(candidate.when, input.when)
|
||||
) {
|
||||
conflicts.push(commandLabel(candidate.command));
|
||||
}
|
||||
}
|
||||
return [...new Set(conflicts)].toSorted();
|
||||
}
|
||||
|
||||
@@ -274,12 +276,13 @@ export function commandLabel(command: KeybindingCommand): string {
|
||||
}
|
||||
|
||||
function titleCaseCommandSegment(segment: string): string {
|
||||
return segment
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.split(/[-_\s]+/)
|
||||
.filter(Boolean)
|
||||
.map((part) => part.slice(0, 1).toUpperCase() + part.slice(1))
|
||||
.join(" ");
|
||||
const words: Array<string> = [];
|
||||
for (const part of segment.replace(/([a-z0-9])([A-Z])/g, "$1 $2").split(/[-_\s]+/)) {
|
||||
if (part.length > 0) {
|
||||
words.push(part.slice(0, 1).toUpperCase() + part.slice(1));
|
||||
}
|
||||
}
|
||||
return words.join(" ");
|
||||
}
|
||||
|
||||
export function normalizeShortcutKeyToken(key: string): string | null {
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
Trash2Icon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Result from "effect/Result";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import {
|
||||
isProviderDriverKind,
|
||||
@@ -118,9 +120,9 @@ export function deriveProviderModelsForDisplay(input: {
|
||||
readonly customModels: ReadonlyArray<string>;
|
||||
}): ReadonlyArray<ServerProviderModel> {
|
||||
const liveCustomModelsBySlug = new Map(
|
||||
(input.liveModels ?? [])
|
||||
.filter((model) => model.isCustom)
|
||||
.map((model) => [model.slug, model] as const),
|
||||
Arr.filterMap(input.liveModels ?? [], (model) =>
|
||||
model.isCustom ? Result.succeed([model.slug, model] as const) : Result.failVoid,
|
||||
),
|
||||
);
|
||||
const serverModels = input.liveModels?.filter((model) => !model.isCustom) ?? [];
|
||||
const customModels = input.customModels.map(
|
||||
|
||||
@@ -1376,21 +1376,30 @@ export function ArchivedThreadsPanel() {
|
||||
})),
|
||||
);
|
||||
|
||||
return [...projectsByEnvironmentAndId.values()]
|
||||
.map((project) => ({
|
||||
project,
|
||||
threads: threads
|
||||
.filter(
|
||||
(thread) =>
|
||||
thread.projectId === project.id && thread.environmentId === project.environmentId,
|
||||
)
|
||||
.toSorted((left, right) => {
|
||||
const archivedProjects = Array.from(projectsByEnvironmentAndId.values());
|
||||
const groups: Array<{
|
||||
readonly project: (typeof archivedProjects)[number];
|
||||
readonly threads: Array<(typeof threads)[number]>;
|
||||
}> = [];
|
||||
for (const project of archivedProjects) {
|
||||
const projectThreads: Array<(typeof threads)[number]> = [];
|
||||
for (const thread of threads) {
|
||||
if (thread.projectId === project.id && thread.environmentId === project.environmentId) {
|
||||
projectThreads.push(thread);
|
||||
}
|
||||
}
|
||||
if (projectThreads.length > 0) {
|
||||
groups.push({
|
||||
project,
|
||||
threads: projectThreads.toSorted((left, right) => {
|
||||
const leftKey = left.archivedAt ?? left.createdAt;
|
||||
const rightKey = right.archivedAt ?? right.createdAt;
|
||||
return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id);
|
||||
}),
|
||||
}))
|
||||
.filter((group) => group.threads.length > 0);
|
||||
});
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
}, [archivedSnapshots]);
|
||||
|
||||
const handleArchivedThreadContextMenu = useCallback(
|
||||
|
||||
@@ -450,11 +450,13 @@ function cloneModelSelection(selection: ModelSelection): DeepMutable<ModelSelect
|
||||
function compactModelSelectionByProvider(
|
||||
selections: Partial<Record<ProviderInstanceId, ModelSelection>>,
|
||||
): DeepMutable<Record<ProviderInstanceId, ModelSelection>> {
|
||||
return Object.fromEntries(
|
||||
Object.entries(selections)
|
||||
.filter((entry): entry is [string, ModelSelection] => entry[1] !== undefined)
|
||||
.map(([provider, selection]) => [provider, cloneModelSelection(selection)]),
|
||||
) as DeepMutable<Record<ProviderInstanceId, ModelSelection>>;
|
||||
const entries: Array<[string, DeepMutable<ModelSelection>]> = [];
|
||||
for (const [provider, selection] of Object.entries(selections)) {
|
||||
if (selection !== undefined) {
|
||||
entries.push([provider, cloneModelSelection(selection)]);
|
||||
}
|
||||
}
|
||||
return Object.fromEntries(entries) as DeepMutable<Record<ProviderInstanceId, ModelSelection>>;
|
||||
}
|
||||
|
||||
const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftStoreState>({
|
||||
@@ -1808,9 +1810,12 @@ function verifyPersistedAttachments(
|
||||
const persistedAttachments = attachments.filter(
|
||||
(attachment) => imageIdSet.has(attachment.id) && persistedIdSet.has(attachment.id),
|
||||
);
|
||||
const nonPersistedImageIds = current.images
|
||||
.map((image) => image.id)
|
||||
.filter((imageId) => !persistedIdSet.has(imageId));
|
||||
const nonPersistedImageIds: string[] = [];
|
||||
for (const image of current.images) {
|
||||
if (!persistedIdSet.has(image.id)) {
|
||||
nonPersistedImageIds.push(image.id);
|
||||
}
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...current,
|
||||
persistedAttachments,
|
||||
|
||||
@@ -1465,10 +1465,12 @@ async function syncSavedEnvironmentConnections(
|
||||
records: ReadonlyArray<SavedEnvironmentRecord>,
|
||||
): Promise<void> {
|
||||
const expectedEnvironmentIds = new Set(records.map((record) => record.environmentId));
|
||||
const staleEnvironmentIds = [...environmentConnections.values()]
|
||||
.filter((connection) => connection.kind === "saved")
|
||||
.map((connection) => connection.environmentId)
|
||||
.filter((environmentId) => !expectedEnvironmentIds.has(environmentId));
|
||||
const staleEnvironmentIds: EnvironmentId[] = [];
|
||||
for (const connection of environmentConnections.values()) {
|
||||
if (connection.kind !== "saved") continue;
|
||||
if (expectedEnvironmentIds.has(connection.environmentId)) continue;
|
||||
staleEnvironmentIds.push(connection.environmentId);
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
staleEnvironmentIds.map((environmentId) => disconnectSavedEnvironment(environmentId)),
|
||||
|
||||
@@ -127,19 +127,18 @@ export function buildTerminalContextPreviewTitle(
|
||||
if (contexts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const previews = contexts
|
||||
.map((context) => {
|
||||
const normalized = normalizeTerminalContextSelection(context);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
const preview = previewTerminalContextText(normalized.text);
|
||||
return preview.length > 0
|
||||
const previewParts: string[] = [];
|
||||
for (const context of contexts) {
|
||||
const normalized = normalizeTerminalContextSelection(context);
|
||||
if (!normalized) continue;
|
||||
const preview = previewTerminalContextText(normalized.text);
|
||||
previewParts.push(
|
||||
preview.length > 0
|
||||
? `${formatTerminalContextLabel(normalized)}\n${preview}`
|
||||
: formatTerminalContextLabel(normalized);
|
||||
})
|
||||
.filter((value): value is string => value !== null)
|
||||
.join("\n\n");
|
||||
: formatTerminalContextLabel(normalized),
|
||||
);
|
||||
}
|
||||
const previews = previewParts.join("\n\n");
|
||||
return previews.length > 0 ? previews : null;
|
||||
}
|
||||
|
||||
@@ -152,9 +151,13 @@ function buildTerminalContextBodyLines(selection: TerminalContextSelection): str
|
||||
export function buildTerminalContextBlock(
|
||||
contexts: ReadonlyArray<TerminalContextSelection>,
|
||||
): string {
|
||||
const normalizedContexts = contexts
|
||||
.map((context) => normalizeTerminalContextSelection(context))
|
||||
.filter((context): context is TerminalContextSelection => context !== null);
|
||||
const normalizedContexts: TerminalContextSelection[] = [];
|
||||
for (const context of contexts) {
|
||||
const normalized = normalizeTerminalContextSelection(context);
|
||||
if (normalized !== null) {
|
||||
normalizedContexts.push(normalized);
|
||||
}
|
||||
}
|
||||
if (normalizedContexts.length === 0) {
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -33,10 +33,14 @@ function normalizeSelectedOptionLabels(value: string[] | undefined): string[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
const normalized = value
|
||||
.filter((entry): entry is string => typeof entry === "string")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0);
|
||||
const normalized: string[] = [];
|
||||
for (const entry of value) {
|
||||
if (typeof entry !== "string") continue;
|
||||
const trimmed = entry.trim();
|
||||
if (trimmed.length > 0) {
|
||||
normalized.push(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
return Array.from(new Set(normalized));
|
||||
}
|
||||
|
||||
@@ -66,13 +66,15 @@ export interface ProviderInstanceEntry {
|
||||
* will take precedence over this fallback.
|
||||
*/
|
||||
function humanizeInstanceId(instanceId: ProviderInstanceId): string {
|
||||
return instanceId
|
||||
const words: string[] = [];
|
||||
for (const token of instanceId
|
||||
.replace(/[_-]+/g, " ")
|
||||
.replace(/([a-z])([A-Z])/g, "$1 $2")
|
||||
.split(" ")
|
||||
.filter((token) => token.length > 0)
|
||||
.map((token) => token.charAt(0).toUpperCase() + token.slice(1))
|
||||
.join(" ");
|
||||
.split(" ")) {
|
||||
if (token.length === 0) continue;
|
||||
words.push(token.charAt(0).toUpperCase() + token.slice(1));
|
||||
}
|
||||
return words.join(" ");
|
||||
}
|
||||
|
||||
function driverKindLabel(driverKind: ProviderDriverKind): string {
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import type { ServerProviderSkill } from "@t3tools/contracts";
|
||||
|
||||
function titleCaseWords(value: string): string {
|
||||
return value
|
||||
.split(/[\s:_-]+/)
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
|
||||
.join(" ");
|
||||
const words: string[] = [];
|
||||
for (const segment of value.split(/[\s:_-]+/)) {
|
||||
if (segment.length === 0) continue;
|
||||
words.push(segment.charAt(0).toUpperCase() + segment.slice(1));
|
||||
}
|
||||
return words.join(" ");
|
||||
}
|
||||
|
||||
function normalizePathSeparators(pathValue: string): string {
|
||||
|
||||
@@ -385,28 +385,25 @@ export function deriveActivePlanState(
|
||||
if (!Array.isArray(rawPlan)) {
|
||||
return null;
|
||||
}
|
||||
const steps = rawPlan
|
||||
.map((entry) => {
|
||||
if (!entry || typeof entry !== "object") return null;
|
||||
const record = entry as Record<string, unknown>;
|
||||
if (typeof record.step !== "string") {
|
||||
return null;
|
||||
}
|
||||
const status =
|
||||
record.status === "completed" || record.status === "inProgress" ? record.status : "pending";
|
||||
return {
|
||||
step: record.step,
|
||||
status,
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(
|
||||
step,
|
||||
): step is {
|
||||
step: string;
|
||||
status: "pending" | "inProgress" | "completed";
|
||||
} => step !== null,
|
||||
);
|
||||
const steps: Array<{
|
||||
step: string;
|
||||
status: "pending" | "inProgress" | "completed";
|
||||
}> = [];
|
||||
for (const entry of rawPlan) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
continue;
|
||||
}
|
||||
const record = entry as Record<string, unknown>;
|
||||
if (typeof record.step !== "string") {
|
||||
continue;
|
||||
}
|
||||
const status =
|
||||
record.status === "completed" || record.status === "inProgress" ? record.status : "pending";
|
||||
steps.push({
|
||||
step: record.step,
|
||||
status,
|
||||
});
|
||||
}
|
||||
if (steps.length === 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -485,14 +482,16 @@ export function deriveWorkLogEntries(
|
||||
latestTurnId: TurnId | undefined,
|
||||
): WorkLogEntry[] {
|
||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
||||
const entries = ordered
|
||||
.filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
|
||||
.filter((activity) => activity.kind !== "tool.started")
|
||||
.filter((activity) => activity.kind !== "task.started")
|
||||
.filter((activity) => activity.kind !== "context-window.updated")
|
||||
.filter((activity) => activity.summary !== "Checkpoint captured")
|
||||
.filter((activity) => !isPlanBoundaryToolActivity(activity))
|
||||
.map(toDerivedWorkLogEntry);
|
||||
const entries: DerivedWorkLogEntry[] = [];
|
||||
for (const activity of ordered) {
|
||||
if (latestTurnId && activity.turnId !== latestTurnId) continue;
|
||||
if (activity.kind === "tool.started") continue;
|
||||
if (activity.kind === "task.started") continue;
|
||||
if (activity.kind === "context-window.updated") continue;
|
||||
if (activity.summary === "Checkpoint captured") continue;
|
||||
if (isPlanBoundaryToolActivity(activity)) continue;
|
||||
entries.push(toDerivedWorkLogEntry(activity));
|
||||
}
|
||||
return collapseDerivedWorkLogEntries(entries).map(
|
||||
({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
|
||||
);
|
||||
@@ -834,9 +833,13 @@ function formatCommandValue(value: unknown): string | null {
|
||||
if (!Array.isArray(value)) {
|
||||
return null;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => asTrimmedString(entry))
|
||||
.filter((entry): entry is string => entry !== null);
|
||||
const parts: Array<string> = [];
|
||||
for (const entry of value) {
|
||||
const part = asTrimmedString(entry);
|
||||
if (part !== null) {
|
||||
parts.push(part);
|
||||
}
|
||||
}
|
||||
if (parts.length === 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -920,10 +923,13 @@ function normalizePreviewForComparison(value: string | null | undefined): string
|
||||
}
|
||||
|
||||
function summarizeToolTextOutput(value: string): string | null {
|
||||
const lines = value
|
||||
.split(/\r?\n/u)
|
||||
.map((line) => normalizeInlinePreview(line))
|
||||
.filter((line) => line.length > 0);
|
||||
const lines: Array<string> = [];
|
||||
for (const rawLine of value.split(/\r?\n/u)) {
|
||||
const line = normalizeInlinePreview(rawLine);
|
||||
if (line.length > 0) {
|
||||
lines.push(line);
|
||||
}
|
||||
}
|
||||
const firstLine = lines.find((line) => line !== "```");
|
||||
if (firstLine) {
|
||||
return truncateInlinePreview(firstLine);
|
||||
|
||||
@@ -409,12 +409,13 @@ function closeThreadTerminal(
|
||||
"")
|
||||
: normalized.activeTerminalId;
|
||||
|
||||
const terminalGroups = normalized.terminalGroups
|
||||
.map((group) => ({
|
||||
...group,
|
||||
terminalIds: group.terminalIds.filter((id) => id !== terminalId),
|
||||
}))
|
||||
.filter((group) => group.terminalIds.length > 0);
|
||||
const terminalGroups: ThreadTerminalGroup[] = [];
|
||||
for (const group of normalized.terminalGroups) {
|
||||
const terminalIds = group.terminalIds.filter((id) => id !== terminalId);
|
||||
if (terminalIds.length > 0) {
|
||||
terminalGroups.push({ ...group, terminalIds });
|
||||
}
|
||||
}
|
||||
|
||||
const nextActiveTerminalGroupId =
|
||||
terminalGroups.find((group) => group.terminalIds.includes(nextActiveTerminalId))?.id ??
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { EnvironmentId, type OrchestrationShellSnapshot } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as Order from "effect/Order";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import { AsyncResult, Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
export type ArchivedSnapshotEntry = {
|
||||
@@ -22,20 +26,24 @@ export interface ArchivedThreadsSnapshotState {
|
||||
const ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR = "\u001f";
|
||||
const DEFAULT_ARCHIVED_THREADS_STALE_TIME_MS = 5_000;
|
||||
const DEFAULT_ARCHIVED_THREADS_IDLE_TTL_MS = 5 * 60_000;
|
||||
const environmentIdOrder = Order.String as Order.Order<EnvironmentId>;
|
||||
|
||||
export function makeArchivedThreadsEnvironmentKey(
|
||||
environmentIds: ReadonlyArray<EnvironmentId>,
|
||||
): string {
|
||||
return environmentIds.toSorted().join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR);
|
||||
return pipe(environmentIds, Arr.sort(environmentIdOrder), (sortedEnvironmentIds) =>
|
||||
sortedEnvironmentIds.join(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR),
|
||||
);
|
||||
}
|
||||
|
||||
export function parseArchivedThreadsEnvironmentKey(key: string): ReadonlyArray<EnvironmentId> {
|
||||
if (key.length === 0) {
|
||||
return [];
|
||||
}
|
||||
return key
|
||||
.split(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR)
|
||||
.map((environmentId) => EnvironmentId.make(environmentId));
|
||||
return pipe(
|
||||
key.split(ARCHIVED_THREADS_ENVIRONMENT_KEY_SEPARATOR),
|
||||
Arr.map((environmentId) => EnvironmentId.make(environmentId)),
|
||||
);
|
||||
}
|
||||
|
||||
export function readArchivedThreadsSnapshotState(
|
||||
@@ -70,18 +78,26 @@ export function createArchivedThreadsManager(config: {
|
||||
return Atom.make(
|
||||
Effect.promise(async (): Promise<ReadonlyArray<ArchivedSnapshotEntry>> => {
|
||||
const snapshots = await Promise.all(
|
||||
parseArchivedThreadsEnvironmentKey(environmentKey).map(async (environmentId) => {
|
||||
const client = config.getClient(environmentId);
|
||||
if (!client) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
environmentId,
|
||||
snapshot: await client.getArchivedShellSnapshot(),
|
||||
};
|
||||
}),
|
||||
pipe(
|
||||
parseArchivedThreadsEnvironmentKey(environmentKey),
|
||||
Arr.map(async (environmentId) => {
|
||||
const client = config.getClient(environmentId);
|
||||
if (!client) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
environmentId,
|
||||
snapshot: await client.getArchivedShellSnapshot(),
|
||||
};
|
||||
}),
|
||||
),
|
||||
);
|
||||
return pipe(
|
||||
snapshots,
|
||||
Arr.filterMap((snapshot) =>
|
||||
snapshot !== null ? Result.succeed(snapshot) : Result.failVoid,
|
||||
),
|
||||
);
|
||||
return snapshots.filter((snapshot) => snapshot !== null);
|
||||
}),
|
||||
).pipe(
|
||||
Atom.swr({
|
||||
|
||||
@@ -6,6 +6,10 @@ import type {
|
||||
EnvironmentId,
|
||||
} from "@t3tools/contracts";
|
||||
import { ThreadId, type TerminalAttachInput } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as Order from "effect/Order";
|
||||
import * as Result from "effect/Result";
|
||||
import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
|
||||
|
||||
export interface TerminalSessionState {
|
||||
@@ -109,6 +113,13 @@ const knownTerminalMetadataEnvironmentIds = new Set<EnvironmentId>();
|
||||
const knownTerminalBufferTargets = new Map<string, KnownTerminalSessionTarget>();
|
||||
const textEncoder = new TextEncoder();
|
||||
const textDecoder = new TextDecoder();
|
||||
const terminalIdOrder = Order.make<string>(
|
||||
(left, right) => left.localeCompare(right, undefined, { numeric: true }) as -1 | 0 | 1,
|
||||
);
|
||||
const knownTerminalSessionOrder = Order.mapInput(
|
||||
terminalIdOrder,
|
||||
(session: KnownTerminalSession) => session.target.terminalId,
|
||||
);
|
||||
|
||||
export const terminalSessionMetadataAtom = Atom.family((environmentId: EnvironmentId) => {
|
||||
knownTerminalMetadataEnvironmentIds.add(environmentId);
|
||||
@@ -251,26 +262,25 @@ function listKnownSessionsFromMetadata(
|
||||
getBuffer: (target: KnownTerminalSessionTarget) => TerminalBufferState,
|
||||
filter?: Partial<KnownTerminalSessionTarget>,
|
||||
): ReadonlyArray<KnownTerminalSession> {
|
||||
return Object.values(metadata)
|
||||
.filter(({ target }) => {
|
||||
return pipe(
|
||||
Object.values(metadata),
|
||||
Arr.filterMap(({ target, summary }) => {
|
||||
if (filter?.environmentId && target.environmentId !== filter.environmentId) {
|
||||
return false;
|
||||
return Result.failVoid;
|
||||
}
|
||||
if (filter?.threadId && target.threadId !== filter.threadId) {
|
||||
return false;
|
||||
return Result.failVoid;
|
||||
}
|
||||
if (filter?.terminalId && target.terminalId !== filter.terminalId) {
|
||||
return false;
|
||||
return Result.failVoid;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.map(({ target, summary }) => ({
|
||||
target,
|
||||
state: combineSessionState(summary, getBuffer(target)),
|
||||
}))
|
||||
.sort((left, right) =>
|
||||
left.target.terminalId.localeCompare(right.target.terminalId, undefined, { numeric: true }),
|
||||
);
|
||||
return Result.succeed({
|
||||
target,
|
||||
state: combineSessionState(summary, getBuffer(target)),
|
||||
});
|
||||
}),
|
||||
Arr.sort(knownTerminalSessionOrder),
|
||||
);
|
||||
}
|
||||
|
||||
export const terminalSessionStateAtom = Atom.family((target: KnownTerminalSessionTarget) =>
|
||||
@@ -299,16 +309,18 @@ export const knownTerminalSessionsAtom = Atom.family((filter: KnownTerminalSessi
|
||||
|
||||
export const runningTerminalIdsAtom = Atom.family((filter: KnownTerminalSessionListFilter) =>
|
||||
Atom.make((get) => {
|
||||
return Object.values(get(terminalSessionMetadataAtom(filter.environmentId)))
|
||||
.filter(
|
||||
(entry) =>
|
||||
entry.target.environmentId === filter.environmentId &&
|
||||
(filter.threadId === null || entry.target.threadId === filter.threadId) &&
|
||||
(filter.terminalId === null || entry.target.terminalId === filter.terminalId) &&
|
||||
entry.summary.hasRunningSubprocess,
|
||||
)
|
||||
.map((entry) => entry.target.terminalId)
|
||||
.sort();
|
||||
return pipe(
|
||||
Object.values(get(terminalSessionMetadataAtom(filter.environmentId))),
|
||||
Arr.filterMap((entry) =>
|
||||
entry.target.environmentId === filter.environmentId &&
|
||||
(filter.threadId === null || entry.target.threadId === filter.threadId) &&
|
||||
(filter.terminalId === null || entry.target.terminalId === filter.terminalId) &&
|
||||
entry.summary.hasRunningSubprocess
|
||||
? Result.succeed(entry.target.terminalId)
|
||||
: Result.failVoid,
|
||||
),
|
||||
Arr.sort(Order.String),
|
||||
);
|
||||
}).pipe(
|
||||
Atom.keepAlive,
|
||||
Atom.withLabel(`terminal-session:running-terminal-ids:${JSON.stringify(filter)}`),
|
||||
@@ -540,8 +552,12 @@ export function createTerminalSessionManager(config: TerminalSessionManagerConfi
|
||||
return listKnownSessionsFromMetadata(getMetadata(filter.environmentId), getBuffer, filter);
|
||||
}
|
||||
|
||||
return [...knownTerminalMetadataEnvironmentIds].flatMap((environmentId) =>
|
||||
listKnownSessionsFromMetadata(getMetadata(environmentId), getBuffer, filter),
|
||||
return pipe(
|
||||
knownTerminalMetadataEnvironmentIds,
|
||||
Arr.fromIterable,
|
||||
Arr.flatMap((environmentId) =>
|
||||
listKnownSessionsFromMetadata(getMetadata(environmentId), getBuffer, filter),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -184,11 +184,13 @@ function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet(
|
||||
export function compactTraceAttributes(
|
||||
attributes: Readonly<Record<string, unknown>>,
|
||||
): TraceAttributes {
|
||||
return Object.fromEntries(
|
||||
Object.entries(attributes)
|
||||
.filter(([, value]) => value !== undefined)
|
||||
.map(([key, value]) => [key, normalizeJsonValue(value)]),
|
||||
);
|
||||
const entries: Array<[string, unknown]> = [];
|
||||
for (const [key, value] of Object.entries(attributes)) {
|
||||
if (value !== undefined) {
|
||||
entries.push([key, normalizeJsonValue(value)]);
|
||||
}
|
||||
}
|
||||
return Object.fromEntries(entries);
|
||||
}
|
||||
|
||||
function formatTraceExit(exit: Exit.Exit<unknown, unknown>): EffectTraceRecord["exit"] {
|
||||
|
||||
@@ -9,10 +9,13 @@ const SEMVER_NUMBER_SEGMENT = /^\d+$/;
|
||||
|
||||
export function normalizeSemverVersion(version: string): string {
|
||||
const [main, prerelease] = version.trim().split("-", 2);
|
||||
const segments = (main ?? "")
|
||||
.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0);
|
||||
const segments: string[] = [];
|
||||
for (const segment of (main ?? "").split(".")) {
|
||||
const trimmed = segment.trim();
|
||||
if (trimmed.length > 0) {
|
||||
segments.push(trimmed);
|
||||
}
|
||||
}
|
||||
|
||||
if (segments.length === 2) {
|
||||
segments.push("0");
|
||||
@@ -52,14 +55,24 @@ export function parseSemver(value: string): ParsedSemver | null {
|
||||
major,
|
||||
minor,
|
||||
patch,
|
||||
prerelease:
|
||||
prerelease
|
||||
?.split(".")
|
||||
.map((segment) => segment.trim())
|
||||
.filter((segment) => segment.length > 0) ?? [],
|
||||
prerelease: parsePrereleaseSegments(prerelease),
|
||||
};
|
||||
}
|
||||
|
||||
function parsePrereleaseSegments(prerelease: string | undefined): ReadonlyArray<string> {
|
||||
if (prerelease === undefined) {
|
||||
return [];
|
||||
}
|
||||
const segments: string[] = [];
|
||||
for (const segment of prerelease.split(".")) {
|
||||
const trimmed = segment.trim();
|
||||
if (trimmed.length > 0) {
|
||||
segments.push(trimmed);
|
||||
}
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
function comparePrereleaseIdentifier(left: string, right: string): number {
|
||||
const leftNumeric = SEMVER_NUMBER_SEGMENT.test(left);
|
||||
const rightNumeric = SEMVER_NUMBER_SEGMENT.test(right);
|
||||
|
||||
@@ -321,11 +321,12 @@ function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<str
|
||||
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
|
||||
if (!rawValue) return fallback;
|
||||
|
||||
const parsed = rawValue
|
||||
.split(";")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||
const parsed: string[] = [];
|
||||
for (const entry of rawValue.split(";")) {
|
||||
const trimmed = entry.trim();
|
||||
if (trimmed.length === 0) continue;
|
||||
parsed.push(trimmed.startsWith(".") ? trimmed.toUpperCase() : `.${trimmed.toUpperCase()}`);
|
||||
}
|
||||
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
|
||||
}
|
||||
|
||||
@@ -397,10 +398,13 @@ export function resolveCommandPath(
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(env);
|
||||
if (pathValue.length === 0) return null;
|
||||
const pathEntries = pathValue
|
||||
.split(pathDelimiterForPlatform(platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
const pathEntries: string[] = [];
|
||||
for (const entry of pathValue.split(pathDelimiterForPlatform(platform))) {
|
||||
const pathEntry = stripWrappingQuotes(entry.trim());
|
||||
if (pathEntry.length > 0) {
|
||||
pathEntries.push(pathEntry);
|
||||
}
|
||||
}
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of commandCandidates) {
|
||||
|
||||
@@ -22,9 +22,13 @@ function normalizeCommandValue(value: unknown): string | undefined {
|
||||
if (!Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
const parts = value
|
||||
.map((entry) => asTrimmedString(entry))
|
||||
.filter((entry): entry is string => entry !== undefined);
|
||||
const parts: string[] = [];
|
||||
for (const entry of value) {
|
||||
const part = asTrimmedString(entry);
|
||||
if (part !== undefined) {
|
||||
parts.push(part);
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join(" ") : undefined;
|
||||
}
|
||||
|
||||
|
||||
@@ -15,12 +15,17 @@ function stripInlineComment(line: string): string {
|
||||
}
|
||||
|
||||
function splitDirectiveArgs(value: string): ReadonlyArray<string> {
|
||||
return value
|
||||
const args: Array<string> = [];
|
||||
for (const rawEntry of value
|
||||
.replace(/=(?!=)/gu, " ")
|
||||
.trim()
|
||||
.split(/\s+/u)
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0);
|
||||
.split(/\s+/u)) {
|
||||
const entry = rawEntry.trim();
|
||||
if (entry.length > 0) {
|
||||
args.push(entry);
|
||||
}
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
function expandHomePath(input: string, homeDir: string): string {
|
||||
|
||||
@@ -112,11 +112,14 @@ export const parseTailscaleStatus = (
|
||||
Effect.mapError((cause) => new TailscaleStatusParseError({ cause })),
|
||||
Effect.map((parsed) => {
|
||||
const rawIps = parsed.Self?.TailscaleIPs;
|
||||
const tailnetIpv4Addresses = Array.isArray(rawIps)
|
||||
? rawIps
|
||||
.filter((address): address is string => typeof address === "string")
|
||||
.filter(isTailscaleIpv4Address)
|
||||
: [];
|
||||
const tailnetIpv4Addresses: Array<string> = [];
|
||||
if (Array.isArray(rawIps)) {
|
||||
for (const address of rawIps) {
|
||||
if (typeof address === "string" && isTailscaleIpv4Address(address)) {
|
||||
tailnetIpv4Addresses.push(address);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
magicDnsName: normalizeMagicDnsName(parsed),
|
||||
|
||||
Reference in new issue
Block a user