fix: resolve 46 unused local findings in batch 6 (#2458)

This commit is contained in:
JATMN
2026-10-27 10:47:34 -07:00
committed by GitHub
parent 1ce3c30dee
commit 20a50493c7
19 changed files with 27 additions and 164 deletions
+1 -20
View File
@@ -536,25 +536,6 @@ export function buildProfileSaveMessage(
return lines.join('\n')
}
function buildUsageText(): string {
const summary = buildCurrentProviderSummary()
const availableProviders = isBareMode()
? 'Choose Auto, Ollama, OpenAI-compatible, Google AI / Gemini, or Codex, then save a provider profile.'
: 'Choose Auto, Ollama, OpenAI-compatible, Google AI / Gemini, Codex, or Codex OAuth, then save a provider profile.'
return [
'Usage: /provider',
'',
'Guided setup for saved provider profiles.',
'',
`Current provider: ${summary.providerLabel}`,
`Current model: ${summary.modelLabel}`,
`Current endpoint: ${summary.endpointLabel}`,
`Saved profile: ${summary.savedProfileLabel}`,
'',
availableProviders,
].join('\n')
}
function finishProfileSave(
onDone: LocalJSXCommandOnDone,
profile: ProviderProfile,
@@ -685,7 +666,7 @@ function ProviderChooser({
const canUseCodexOAuth = !isBareMode()
const ollamaMetadata = getProviderPresetUiMetadata('ollama')
const openAIMetadata = getProviderPresetUiMetadata('openai')
const geminiMetadata = getProviderPresetUiMetadata('gemini')
getProviderPresetUiMetadata('gemini')
const mistralMetadata = getProviderPresetUiMetadata('mistral')
const helperText = canUseCodexOAuth
? 'Save a provider profile without editing environment variables first. Codex profiles backed by env, auth.json, or OpenClaude secure storage can switch this session immediately when validation succeeds.'
+1 -48
View File
@@ -11,7 +11,7 @@ import type { Color } from '../ink/styles.js';
import { Box, Text, useInput, useTerminalFocus, useTheme } from '../ink.js';
import { useKeybinding } from '../keybindings/useKeybinding.js';
import { logEvent } from '../services/analytics/index.js';
import type { LogOption, SerializedMessage } from '../types/logs.js';
import type { LogOption } from '../types/logs.js';
import { formatLogMetadata, truncateToWidth } from '../utils/format.js';
import { getWorktreePaths } from '../utils/getWorktreePaths.js';
import { getBranch } from '../utils/git.js';
@@ -89,11 +89,6 @@ function normalizeAndTruncateToWidth(text: string, maxWidth: number): string {
const PARENT_PREFIX_WIDTH = 2; // '▼ ' or '▶ '
const CHILD_PREFIX_WIDTH = 4; // ' ▸ '
// Deep search constants
const DEEP_SEARCH_MAX_MESSAGES = 2000;
const DEEP_SEARCH_CROP_SIZE = 1000;
const DEEP_SEARCH_MAX_TEXT_LENGTH = 50000; // Cap searchable text per session
const FUSE_THRESHOLD = 0.3;
const SNIPPET_CONTEXT_CHARS = 50; // Characters to show before/after match
type Snippet = {
@@ -258,7 +253,6 @@ export function LogSelector(t0: LogSelectorProps) {
t3 = $[0];
}
const isResumeWithRenameEnabled = t3;
const isDeepSearchEnabled = false;
const [themeName] = useTheme();
let t4;
if ($[1] !== themeName) {
@@ -409,7 +403,6 @@ export function LogSelector(t0: LogSelectorProps) {
t18 = $[18];
}
React.useEffect(t17, t18);
const searchableTextByLog = new Map<LogOption, string>(logs.map(_temp));
let t19;
t19 = null;
let t20;
@@ -1524,46 +1517,6 @@ function _temp2(log_1: LogOption): boolean {
}
return false;
}
function _temp(log: LogOption): [LogOption, string] {
return [log, buildSearchableText(log)];
}
function extractSearchableText(message: SerializedMessage): string {
// Only extract from user and assistant messages that have content
if (message.type !== 'user' && message.type !== 'assistant') {
return '';
}
const content = 'message' in message ? message.message?.content : undefined;
if (!content) return '';
// Handle string content (simple messages)
if (typeof content === 'string') {
return content;
}
// Handle array of content blocks
if (Array.isArray(content)) {
return content.map(block => {
if (typeof block === 'string') return block;
if ('text' in block && typeof block.text === 'string') return block.text;
return '';
// we don't return thinking blocks and tool names here;
// they're not useful for search, as they can add noise to the fuzzy matching
}).filter(Boolean).join(' ');
}
return '';
}
/**
* Builds searchable text for a log including messages, titles, summaries, and metadata.
* Crops long transcripts to first/last N messages for performance.
*/
function buildSearchableText(log: LogOption): string {
const searchableMessages = log.messages.length <= DEEP_SEARCH_MAX_MESSAGES ? log.messages : [...log.messages.slice(0, DEEP_SEARCH_CROP_SIZE), ...log.messages.slice(-DEEP_SEARCH_CROP_SIZE)];
const messageText = searchableMessages.map(extractSearchableText).filter(Boolean).join(' ');
const metadata = [getResumeLogDisplayTitle(log), log.customTitle, log.sessionBranch?.branchName, log.summary, log.firstPrompt, log.gitBranch, log.tag, log.prNumber ? `PR #${log.prNumber}` : undefined, log.prRepository].filter(Boolean).join(' ');
const fullText = `${metadata} ${messageText}`.trim();
return fullText.length > DEEP_SEARCH_MAX_TEXT_LENGTH ? fullText.slice(0, DEEP_SEARCH_MAX_TEXT_LENGTH) : fullText;
}
export function groupLogsByResumeBranch(filteredLogs: LogOption[]): ResumeLogGroup[] {
type MutableGroup = {
id: string;
+1 -2
View File
@@ -59,7 +59,6 @@ import type { MCPServerConnection } from '../../services/mcp/types.js'
import {
acquireEnvMutex,
releaseEnvMutex,
mapMessageToSDK,
type SDKMessage,
type SDKUserMessage,
type SDKPermissionTimeoutMessage,
@@ -827,7 +826,7 @@ class QueryImpl implements Query {
requestSdkRootAbort(this.abortController, source, 'sdk_query')
}
// Deny all pending permission prompts before clearing
for (const [toolUseId, pending] of this.pendingPermissionPrompts) {
for (const [, pending] of this.pendingPermissionPrompts) {
pending.resolve({
behavior: 'deny',
message: 'Query interrupted',
+4 -5
View File
@@ -89,7 +89,7 @@ const coordinatorModeModule = feature('COORDINATOR_MODE') ? require('./coordinat
/* eslint-disable @typescript-eslint/no-require-imports */
const assistantModule = feature('KAIROS') ? require('./assistant/index.js') as typeof import('./assistant/index.js') : null;
const kairosGate = feature('KAIROS') ? require('./assistant/gate.js') as typeof import('./assistant/gate.js') : null;
import { relative, resolve } from 'path';
import { resolve } from 'path';
import { isAnalyticsDisabled } from 'src/services/analytics/config.js';
import { getFeatureValue_CACHED_MAY_BE_STALE } from 'src/services/analytics/growthbook.js';
import { type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS, logEvent } from 'src/services/analytics/index.js';
@@ -121,7 +121,7 @@ import { hasNodeOption, isBareMode, isEnvTruthy, isInProtectedNamespace } from '
import { refreshExampleCommands } from './utils/exampleCommands.js';
import type { FpsMetrics } from './utils/fpsTracker.js';
import { getWorktreePaths } from './utils/getWorktreePaths.js';
import { findGitRoot, getBranch, getIsGit, getWorktreeCount } from './utils/git.js';
import { getBranch, getIsGit, getWorktreeCount } from './utils/git.js';
import { getGhAuthStatus } from './utils/github/ghAuthStatus.js';
import { safeParseJSON } from './utils/json.js';
import { logError } from './utils/log.js';
@@ -137,7 +137,7 @@ import { getGlobExclusionsForPluginCache } from './utils/plugins/orphanedPluginF
import { getPluginSeedDirs } from './utils/plugins/pluginDirectories.js';
import { countFilesRoundedRg } from './utils/ripgrep.js';
import { processSessionStartHooks, processSetupHooks } from './utils/sessionStart.js';
import { cacheSessionTitle, getSessionIdFromLog, loadTranscriptFromFile, saveAgentSetting, saveMode, searchSessionsByCustomTitle, sessionIdExists } from './utils/sessionStorage.js';
import { cacheSessionTitle, getSessionIdFromLog, saveAgentSetting, saveMode, searchSessionsByCustomTitle, sessionIdExists } from './utils/sessionStorage.js';
import { ensureMdmSettingsLoaded } from './utils/settings/mdm/settings.js';
import { eagerLoadSettingsFromArgs } from './utils/settings/flagSettings.js';
import { getInitialSettings, getManagedSettingsKeysForLogging, getSettingsForSource, getSettingsWithErrors } from './utils/settings/settings.js';
@@ -165,7 +165,7 @@ import { createEmptyAttributionState } from 'src/utils/commitAttribution.js';
import { countConcurrentSessions, registerSession, updateSessionName } from 'src/utils/concurrentSessions.js';
import { getCwd } from 'src/utils/cwd.js';
import { logForDebugging, setHasFormattedOutput } from 'src/utils/debug.js';
import { errorMessage, getErrnoCode, isENOENT, TeleportOperationError, toError } from 'src/utils/errors.js';
import { errorMessage, getErrnoCode, TeleportOperationError, toError } from 'src/utils/errors.js';
import { isInteractiveSession } from 'src/utils/interactivity.js';
import { gracefulShutdown, gracefulShutdownSync } from 'src/utils/gracefulShutdown.js';
import { setAllHookEventsEnabled } from 'src/utils/hooks/hookEvents.js';
@@ -2153,7 +2153,6 @@ async function run(): Promise<CommanderCommand> {
event: 'startup' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
durationMs: Math.round(process.uptime() * 1000)
});
const setupScreensStart = Date.now();
const onboardingShown = await showSetupScreens(root, permissionMode, allowDangerouslySkipPermissions, commands, enableClaudeInChrome, devChannels);
// Now that trust is established and GrowthBook has auth headers,
+3 -4
View File
@@ -92,9 +92,9 @@ import {
const skillPrefetch = feature('EXPERIMENTAL_SKILL_SEARCH')
? (require('./services/skillSearch/prefetch.js') as typeof import('./services/skillSearch/prefetch.js'))
: null
const jobClassifier = feature('TEMPLATES')
? (require('./jobs/classifier.js') as typeof import('./jobs/classifier.js'))
: null
if (feature('TEMPLATES')) {
require('./jobs/classifier.js')
}
/* eslint-enable @typescript-eslint/no-require-imports */
import {
remove as removeFromQueue,
@@ -138,7 +138,6 @@ import {
import { AGENT_STEP_LIMIT_TOOL_RESULT_PREFIX } from './query/agentStepLimit.js'
import { buildQueryConfig } from './query/config.js'
import {
MAX_MESSAGES_COMPACTION_THRESHOLDS,
getGlobalConfig,
isValidMaxMessagesCompactionThreshold,
normalizeMaxMessagesCompactionThreshold,
+1 -30
View File
@@ -3,7 +3,7 @@ import { getEventListeners } from 'node:events'
import { acquireSharedMutationLock, releaseSharedMutationLock } from '../../test/sharedMutationLock.js'
import { snapshotEnv } from '../../test/envSnapshot.js'
import { asMockFetch } from '../../test/typedMocks.js'
import { _clearRegistryForTesting, ensureIntegrationsLoaded, registerGateway } from '../../integrations/index.ts'
import { _clearRegistryForTesting, ensureIntegrationsLoaded } from '../../integrations/index.ts'
import { applyProviderFlag } from '../../utils/providerFlag.ts'
import { applyProviderProfileToProcessEnv } from '../../utils/providerProfiles.ts'
import { PROFILE_ORCAROUTER_KEY_SHA256 } from '../../utils/providerProfile.js'
@@ -11,10 +11,6 @@ import {
__resetInterruptionTraceForTests,
__waitForInterruptionTraceFlushForTests,
} from '../../utils/interruptionTrace.js'
import {
getAssistantMessageFromError,
OPENCODE_GO_FREE_LIMIT_ERROR_MESSAGE,
} from './errors.ts'
import { accumulateUsage, updateUsage } from './claude.js'
import { EMPTY_USAGE } from './emptyUsage.js'
import {
@@ -23,11 +19,9 @@ import {
} from './openaiErrorClassification.ts'
import {
createOpenAIShimClient,
hasMistralApiHost,
parseTextToolCalls,
parseXmlToolCalls,
} from './openaiShim.ts'
import * as realGithubModelsCredentials from '../../utils/githubModelsCredentials.js'
import { tokenCountWithEstimation } from '../../utils/tokens.js'
import type { AssistantMessage } from '../../types/message.js'
@@ -437,24 +431,6 @@ function makeGithubChatFallbackResponse(): Response {
)
}
function makeResponsesApiResponse(model: string): Response {
return new Response(
JSON.stringify({
id: 'resp-fallback-test',
model,
output: [
{
type: 'message',
role: 'assistant',
content: [{ type: 'output_text', text: 'ok' }],
},
],
usage: { input_tokens: 1, output_tokens: 1, total_tokens: 2 },
}),
{ headers: { 'Content-Type': 'application/json' } },
)
}
function pendingFetchUntilAbort(
init: RequestInit | undefined,
): Promise<Response> {
@@ -6320,11 +6296,6 @@ test('preserves valid tool pairs after history pruning while dropping orphaned t
// Extraction boundary: history pruning | executor Copilot refresh behavior.
// The contiguous Copilot authentication retry block below moves with execution.
// Keep this marker stable for independent adjacent test migrations.
function makeCodexSseResponse(responseData: Record<string, unknown>): Response {
const data = JSON.stringify(responseData)
return makeSseResponse([`event: response.completed\ndata: ${data}\n\n`])
}
test('GitHub Copilot responses fallback does not replay after a pre-header timeout', async () => {
process.env.CLAUDE_CODE_USE_GITHUB = '1'
@@ -178,11 +178,6 @@ async function captureChatCompletionRequest(
return { authorization, headers, url }
}
function makeCodexSseResponse(responseData: Record<string, unknown>): Response {
const data = JSON.stringify(responseData)
return makeSseResponse([`event: response.completed\ndata: ${data}\n\n`])
}
beforeEach(async () => {
await acquireSharedMutationLock('openaiShim.test.ts')
process.env.OPENAI_BASE_URL = 'http://example.test/v1'
+9 -11
View File
@@ -1208,9 +1208,7 @@ export async function checkPermissionsAndCallTool(
permissionDecision.behavior !== 'ask' &&
!toolUseContext.toolDecisions?.has(toolUseID)
) {
const decision =
permissionDecision.behavior === 'allow' ? 'accept' : 'reject'
const source = decisionReasonToOTelSource(
decisionReasonToOTelSource(
permissionDecision.decisionReason,
permissionDecision.behavior,
)
@@ -1234,7 +1232,7 @@ export async function checkPermissionsAndCallTool(
if (permissionDecision.behavior !== 'allow') {
logForDebugging(`${tool.name} tool permission denied`)
const decisionInfo = toolUseContext.toolDecisions?.get(toolUseID)
toolUseContext.toolDecisions?.get(toolUseID)
if (!shouldSkipSessionPersistence()) {
try {
@@ -1397,7 +1395,7 @@ export async function checkPermissionsAndCallTool(
// Prepare tool parameters for logging in tool_result event.
// Gated by OTEL_LOG_TOOL_DETAILS — tool parameters can contain sensitive
// content (bash commands, MCP server names, etc.) so they're opt-in only.
const telemetryToolInput = extractToolInputForTelemetry(processedInput)
extractToolInputForTelemetry(processedInput)
let toolParameters: Record<string, unknown> = {}
if (isToolDetailsLoggingEnabled()) {
if (tool.name === BASH_TOOL_NAME && 'command' in processedInput) {
@@ -1594,9 +1592,9 @@ export async function checkPermissionsAndCallTool(
}
// Log tool result event for OTLP with tool parameters and decision context
const mcpServerScope = isMcpTool(tool)
? getMcpServerScopeFromToolName(tool.name)
: null
if (isMcpTool(tool)) {
getMcpServerScopeFromToolName(tool.name)
}
// Run PostToolUse hooks
@@ -1896,9 +1894,9 @@ export async function checkPermissionsAndCallTool(
),
})
// Log tool result error event for OTLP with tool parameters and decision context
const mcpServerScope = isMcpTool(tool)
? getMcpServerScopeFromToolName(tool.name)
: null
if (isMcpTool(tool)) {
getMcpServerScopeFromToolName(tool.name)
}
}
const content = formatError(error)
+1 -9
View File
@@ -20,7 +20,7 @@ import {
import { FileTooLargeError, readFileInRange } from './readFileInRange.js'
import { expandPath } from './path.js'
import { countCharInString } from './stringUtils.js'
import { count, uniq } from './array.js'
import { uniq } from './array.js'
import { getFsImplementation } from './fsOperations.js'
import { readdir, stat } from 'fs/promises'
import type { IDESelection } from '../hooks/useIdeSelection.js'
@@ -39,9 +39,7 @@ import {
import { getPlanFilePath, getPlan } from './plans.js'
import { getConnectedIdeName } from './ide.js'
import {
filterInjectedMemoryFiles,
getManagedAndUserConditionalRules,
getMemoryFiles,
getMemoryFilesForNestedDirectory,
getConditionalRulesForCwdLevelDirectory,
type MemoryFileInfo,
@@ -77,12 +75,6 @@ import type {
} from '@anthropic-ai/sdk/resources/messages.mjs'
import { maybeResizeAndDownsampleImageBlock } from './imageResizer.js'
import type { PastedContent } from './config.js'
import { getGlobalConfig } from './config.js'
import {
getDefaultSonnetModel,
getDefaultHaikuModel,
getDefaultOpusModel,
} from './model/model.js'
import type { ReadResourceResult } from '@modelcontextprotocol/sdk/types.js'
import { getSkillToolCommands, getMcpSkillCommands } from '../commands.js'
import type { Command } from '../types/command.js'
+1 -1
View File
@@ -1,5 +1,5 @@
import type { Message } from '../types/message.js'
import { describe, expect, it, beforeEach } from 'bun:test'
import { describe, expect, it } from 'bun:test'
import {
partitionContext,
getZoneMessages,
+1 -1
View File
@@ -276,7 +276,7 @@ describe('conversationArc', () => {
describe('finalizeArcTurn', () => {
it('writes session summary file when goals completed', async () => {
const arc = initializeArc(memDir)
initializeArc(memDir)
const goal = addGoal('Implement feature')
updateGoalStatus(goal.id, 'completed')
addDecision('Use TypeScript', 'Type safety')
+1 -18
View File
@@ -85,7 +85,7 @@ import {
memoryHeader,
} from './attachments.js'
import { quote } from './bash/shellQuote.js'
import { formatNumber, formatTokens } from './format.js'
import { formatNumber } from './format.js'
import { jsonStringify } from './slowOperations.js'
// Hook attachments that have a hookName field (excludes HookPermissionDecisionAttachment)
@@ -115,13 +115,6 @@ import {
} from 'src/tools/FileReadTool/prompt.js'
import type { DeepImmutable } from 'src/types/utils.js'
import { getStrictToolResultPairing } from '../bootstrap/state.js'
import {
COMMAND_ARGS_TAG,
COMMAND_MESSAGE_TAG,
COMMAND_NAME_TAG,
LOCAL_COMMAND_CAVEAT_TAG,
LOCAL_COMMAND_STDOUT_TAG,
} from '../constants/xml.js'
import { DiagnosticTrackingService } from '../services/diagnosticTracking.js'
import {
findToolByName,
@@ -140,26 +133,16 @@ import { TASK_UPDATE_TOOL_NAME } from '../tools/TaskUpdateTool/constants.js'
import type { PermissionMode } from '../types/permissions.js'
import { normalizeToolInput, normalizeToolInputForAPI } from './api.js'
import { logAntError, logForDebugging } from './debug.js'
import { hasEmbeddedSearchTools } from './embeddedTools.js'
import { formatFileSize } from './format.js'
import { validateImagesForAPI } from './imageValidation.js'
import { safeParseJSON } from './json.js'
import { logError, logMCPDebug } from './log.js'
import { normalizeLegacyToolName } from './permissions/permissionRuleParser.js'
import { isDangerousPermissionMode } from './permissions/PermissionMode.js'
import {
getPlanModeV2AgentCount,
getPlanModeV2ExploreAgentCount,
isPlanModeInterviewPhaseEnabled,
} from './planModeV2.js'
import { isTodoV2Enabled } from './tasks.js'
import {
CANCEL_MESSAGE,
createUserMessage,
INTERRUPT_MESSAGE,
INTERRUPT_MESSAGE_FOR_TOOL_USE,
isSyntheticApiErrorMessage,
REJECT_MESSAGE,
} from './messages/factories.js'
import {
formatToolResultPairingIssue,
-3
View File
@@ -17,7 +17,6 @@ import {
} from './envUtils.js'
import { getProviderValidationError } from './providerValidation.js'
import {
applySavedProfileToCurrentSession,
applyStartupEnvFromProfile,
buildStartupEnvFromProfile,
buildAtomicChatProfileEnv,
@@ -30,13 +29,11 @@ import {
buildLaunchEnv,
buildOllamaProfileEnv,
buildOpenAIProfileEnv,
clearPersistedCodexOAuthProfile,
createProfileFile,
DEFAULT_STARTUP_PROVIDER_ENV_VAR,
deleteProfileFile,
getDefaultProfileFilePath,
isDefaultStartupProviderEnv,
isPersistedCodexOAuthProfile,
maskSecretForDisplay,
loadProfileFile,
PROFILE_FILE_NAME,
-2
View File
@@ -41,8 +41,6 @@ import {
resolveRouteIdFromBaseUrl,
} from '../integrations/routeMetadata.js'
import {
maskSecretForDisplay,
redactSecretValueForDisplay,
sanitizeApiKey,
sanitizeProviderConfigValue,
type SecretValueSource,
+1 -1
View File
@@ -1,5 +1,5 @@
import { queryInternals, sessionInternals } from './helpers/query-test-doubles.js'
import { describe, test, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'bun:test'
import { describe, test, expect, vi, beforeAll, afterAll } from 'bun:test'
import { unstable_v2_createSession } from '../../src/entrypoints/sdk/index.js'
import { query } from '../../src/entrypoints/sdk/index.js'
import type { MCPServerConnection } from '../../src/services/mcp/types.js'
+1 -1
View File
@@ -2,7 +2,7 @@ import type { AppState } from '../../src/state/AppStateStore.js'
import type { AssistantMessage, ProgressMessage } from '../../src/types/message.js'
import type { SDKMessage } from '../../src/entrypoints/sdk/shared.js'
import { describe, test, expect, afterEach, beforeAll, afterAll } from 'bun:test'
import { query, forkSession, getSessionMessages, unstable_v2_createSession } from '../../src/entrypoints/sdk/index.js'
import { query, unstable_v2_createSession } from '../../src/entrypoints/sdk/index.js'
import {
buildPermissionContext,
createDefaultCanUseTool,
-1
View File
@@ -27,7 +27,6 @@ import {
import { clearAgentDefinitionsCache } from '../../src/tools/AgentTool/loadAgentsDir.js'
type SessionId = ReturnType<typeof getSessionId>
import {
drainQuery,
withTempDir,
createSessionJsonl,
createMinimalConversation,
@@ -359,7 +359,6 @@ class ChatController {
// Show turn info: if the model stopped without using tools (num_turns=1),
// the user knows the model chose not to edit
if (msg.num_turns !== undefined) {
const reason = msg.stop_reason || 'done';
this._broadcast({
type: 'status',
content: msg.num_turns > 1
@@ -13,7 +13,7 @@ const fsp = require('fs/promises');
const path = require('path');
const os = require('os');
const readline = require('readline');
const crypto = require('crypto');
require('crypto');
// Keep in sync with src/utils/sessionStoragePortable.ts.
const MAX_SANITIZED_LENGTH = 200;