Files
claude-code/src/components/teams/TeamsDialog.tsx
Dosion c2ac9a74c1 fix: resolve dependency audit findings precisely (#361)
* fix: harden ACP communication boundaries

Harden ACP communication boundaries

Remote ACP sessions now cannot widen permission mode through untrusted
metadata or client payloads. WebSocket ACP ingress measures payloads by bytes
before binary decode, and prompt queue handoff keeps exactly one prompt active
while queued prompts are drained FIFO.

Constraint: ACP remote clients must not be able to open bypassPermissions without local launch intent
Constraint: WebSocket payload limits must be byte-based and checked before binary decode
Rejected: Keep promptToQueryContent wrapper | no production consumers remained after prompt conversion single-sourcing
Confidence: high
Scope-risk: moderate
Directive: Do not re-enable remote bypassPermissions from _meta unless a local launch gate is verified in both acp-link and agent
Tested: targeted ACP/RCS/acp-link prompt queue, bridge, permission, payload, and prompt conversion tests; bun run typecheck; bun run build
Not-tested: Manual live ACP/RCS session against an external client

* fix: restore repository verification gates

Keep the full repository test, typecheck, build, and Biome lint gates usable
after the ACP fix pass. This commit is intentionally separate from the ACP
behavior change: it fixes Windows-safe Langfuse home redaction, removes stale
lint suppressions, resolves Biome warning/info diagnostics, and keeps env
expansion tests explicit without template-placeholder lint noise.

Constraint: The project completion contract requires full typecheck, lint, test, and build evidence
Rejected: Leave warning/info diagnostics as historical noise | they obscure future gate regressions and weaken flow-impact claims
Confidence: high
Scope-risk: narrow
Directive: Keep repository gate cleanup separate from feature fixes when it is not part of the same runtime path
Tested: bunx biome lint src/; bunx tsc --noEmit; bun test src/services/mcp/__tests__/envExpansion.test.ts src/utils/__tests__/sliceAnsi.test.ts src/utils/__tests__/stringUtils.test.ts; bun test; bun run build
Not-tested: Manual Langfuse export against a real external Langfuse service

* fix: harden ACP failure boundaries after review

Deep review found several paths that made ACP communication failures look normal: prompt errors could finish as end_turn, permission pipeline exceptions could fall through to client approval, tool rawInput was deep-copied with JSON, and acp-link accepted unbounded or unvalidated WebSocket payloads. This keeps the behavior fail-closed, validates WS payloads before dispatch, caps payload size before JSON parse, and preserves cancellation intent with a generation counter.

Constraint: User explicitly rejected pseudo-fixes, fallback behavior, and unbounded payload handling

Rejected: Keep JSON stringify/parse rawInput copy | duplicates large payloads and silently drops non-JSON inputs

Rejected: Delegate permission pipeline errors to client approval | allows a broken local permission check to be bypassed

Confidence: high

Scope-risk: moderate

Directive: Do not convert ACP errors into normal end_turn responses without a protocol-level reason and regression tests

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test packages/acp-link/src/__tests__/server.test.ts

Tested: bunx tsc --noEmit

Tested: bunx biome lint src/ packages/acp-link/src/

Tested: bun run test:all

Tested: bun run build

Not-tested: Manual end-to-end ACP client session over a real editor WebSocket

* fix: prevent ACP coverage runs from seeing partial mocks

GitHub Actions failed under bun test --coverage because permissions.test.ts replaced ../bridge.js with a partial mock that omitted forwardSessionUpdates. Coverage worker ordering on Linux let sibling tests observe that incomplete module.

This isolates ACP test mocks by snapshotting real exports, overriding only requested symbols, and restoring mocks in LIFO order. The shared helper also keeps the same behavior in agent.test.ts without duplicating mock infrastructure.

Constraint: bun:test mock.module is process-global inside a worker.

Rejected: Add fallback exports or production guards | the bridge export exists; the failure was test mock pollution.

Rejected: Keep per-file helper copies | duplication would let restore semantics drift again.

Confidence: high

Scope-risk: narrow

Directive: Prefer safeMockModule for partial mocks of real modules in ACP tests; plain mock.module is only appropriate for fully synthetic modules or isolated tests.

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test --coverage --coverage-reporter=lcov

Tested: bunx tsc --noEmit

Tested: bun run lint

Tested: git diff --check

Not-tested: Linux runner directly before push

* fix: normalize ACP bypass requests without warning noise

The previous CI repair removed the failing partial bridge mock, but it also added a shared safeMockModule helper and left the acp-link bypass normalization warning in the real new_session path.

This tightens the fix: acp-link now treats an unauthorized client bypass request as normal permission-mode normalization without emitting a warning, and the ACP permission test explicitly preserves the real bridge and permission exports instead of using a shared helper. The agent test keeps its local mock preservation but names it by behavior and restores mocks in LIFO order.

Constraint: CI output should not contain expected warning noise for covered policy branches.

Rejected: Silence the test only | the normal new_session path would still warn for an expected normalization branch.

Rejected: Keep the shared safeMockModule helper | the failing module was specific and should be fixed by preserving real exports at the mocking site.

Confidence: high

Scope-risk: narrow

Directive: Treat client-requested bypassPermissions as data to normalize unless the local default explicitly enables bypass.

Tested: bun test packages/acp-link/src/__tests__/server.test.ts

Tested: bun test src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/bridge.test.ts src/services/acp/__tests__/permissions.test.ts

Tested: bun test --coverage --coverage-reporter=lcov with UPPER_WARN_COUNT=0

Tested: bun run test:all

Tested: bun run lint

Tested: bunx tsc --noEmit

Tested: git diff --check

* fix: harden ACP bypass and CI warning gates

ACP clients must not be able to enter bypassPermissions unless the local ACP gate and process environment both allow it. The same gate now controls session creation, explicit mode changes, and the ExitPlanMode option list, while session setup restores process.cwd so coverage and later work do not inherit ACP session state.

Constraint: CI must stay warning-clean without hiding real ACP permission failures

Rejected: Logging rejected bypass requests on the normal new_session path | it preserves audit text but reintroduces warning noise the runtime should not emit

Rejected: Broad CI=true postinstall skip | it hides explicit Chrome MCP setup checks outside the install path

Confidence: high

Scope-risk: moderate

Directive: Keep bypassPermissions gated through one ACP availability decision before exposing it to clients

Tested: bun test src/services/acp/__tests__/permissions.test.ts src/services/acp/__tests__/agent.test.ts packages/acp-link/src/__tests__/server.test.ts

Tested: bun run test:all

Tested: bun run lint

Tested: bun run build:vite with zero warning matches

Tested: bun test --coverage --coverage-reporter lcov --coverage-dir coverage produced non-empty lcov with SF records and zero filtered warning matches

Not-tested: GitHub Actions result after this push

* fix: remove remaining CI warning noise

The CI log still had three non-failing warnings after the ACP hardening commit: git init default-branch advice from checkout, a Node 20 action-runtime deprecation, and one additional known Vite dynamic-import diagnostic that only surfaced on Linux. The workflow now provides explicit git config and opts actions into Node 24, while Vite keeps a narrow allowlist for acknowledged optimizer diagnostics.

Constraint: Do not use shell log filtering to hide warnings after they happen

Rejected: Grep warning lines out of CI output | it would make future diagnostics harder to find

Confidence: high

Scope-risk: narrow

Directive: Add new Vite warning allowlist entries only after checking that they are existing optimizer diagnostics, not new application defects

Tested: bunx tsc --noEmit --pretty false

Tested: bunx biome lint .github/workflows/ci.yml vite.config.ts

Tested: bun run build:vite with zero warning matches

Not-tested: GitHub Actions result after this push

* fix: reject unauthorized ACP bypass and harden CI actions

ACP clients now fail closed when permissionMode is malformed, unknown, or requests bypass without a local bypass opt-in. acp-link validates new_session input before forwarding to the agent and returns client error frames for expected unauthorized requests without logging create-failed noise. The direct AcpAgent path independently rejects invalid _meta.permissionMode and unauthorized bypass instead of falling back to settings.

CI workflows and generated GitHub App templates now use Node 24-compatible actions pinned to immutable commit SHAs, and acp-link startup output no longer prints the auth token.

Constraint: Must not hide warnings with test isolation or log filtering

Rejected: Silent fallback to local permission mode | accepts invalid client intent and masks boundary behavior

Rejected: Broad dependency churn from bun update | audit remained failing while package and lockfile churn expanded scope

Confidence: high

Scope-risk: moderate

Directive: Client-provided permissionMode must stay fail-closed before reaching AcpAgent; only local settings.defaultMode may fall back to default on invalid local config

Tested: bun test packages/acp-link/src/__tests__/server.test.ts src/services/acp/__tests__/agent.test.ts src/services/acp/__tests__/permissions.test.ts src/services/skillLearning/__tests__/skillLifecycle.test.ts src/utils/settings/__tests__/config.test.ts

Tested: bunx tsc -p packages/acp-link/tsconfig.json --noEmit --pretty false

Tested: bunx tsc --noEmit --pretty false

Tested: bun run lint

Tested: bun run test:all

Tested: local CI equivalent install/typecheck/coverage/build with warning_scan=0

Not-tested: Pre-existing bun audit vulnerabilities require a separate dependency-hardening PR

* fix: resolve dependency audit findings precisely

Use dependency-native upgrades and lockfile resolution to close the audit findings without suppressions. Keep the chrome MCP setup aligned with the new dependency graph and add real integration coverage so the override behavior stays verified.

Constraint: no audit ignores or warning suppression
Rejected: broad google-auth/protobuf overrides | replaced with upstream-compatible resolution
Confidence: high
Scope-risk: moderate
Directive: keep dependency fixes upstream-compatible; do not reintroduce blanket overrides unless the audit surface changes materially
Tested: bun audit; bun audit --json; bun install --frozen-lockfile with CLAUDE_CODE_SKIP_CHROME_MCP_SETUP=1; bunx tsc --noEmit --pretty false; bun run lint; targeted tests; bun run test:all; bun test --coverage --coverage-reporter lcov --coverage-dir coverage; bun run build:vite
Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks

* fix: keep ACP auth tokens out of URLs

Replace the ad hoc URL-token flow with crypto UUID-backed transport identifiers so the bearer token stays in structured request data instead of query strings. Keep the server, web client, and transport helpers aligned so the ACP/RCS handshake remains compatible after the API shape change.

Constraint: token must not be embedded in the URL
Rejected: token-as-uuid query fallback | leaked bearer tokens in URLs
Confidence: high
Scope-risk: moderate
Directive: preserve the structured auth path; do not reintroduce query-token fallback when adjusting ACP transport code
Tested: targeted ACP/RCS transport tests
Not-tested: unrelated pre-existing ACP/CORS/token fallback residual risks

* fix: normalize WebFetch request headers

Normalize WebFetch headers before dispatch so canonicalization preserves auth semantics and duplicate forms do not slip through. Keep the behavior locked with a focused header test instead of broadening the request pipeline.

Constraint: preserve header semantics without widening the fetch surface
Rejected: ad hoc caller-side normalization | too easy to bypass in future call sites
Confidence: high
Scope-risk: narrow
Directive: keep header normalization close to the WebFetch utility so future callers inherit the same behavior automatically
Tested: targeted WebFetch header tests
Not-tested: unrelated fetch backend behavior beyond header normalization

* fix: harden ACP remote auth surfaces

Tighten the remaining Claude security artifact items by requiring API keys on ACP global reads and relay upgrades, moving WebSocket tokens out of URLs, and replacing open web CORS with an explicit allowlist.

Constraint: Browser WebSocket clients cannot set arbitrary Authorization headers, so the token is carried in a selected subprotocol instead of a query string.
Rejected: Keep UUID auth for ACP channel groups | any caller can mint a UUID and read global ACP data.
Rejected: Preserve ?token= compatibility | secrets leak into logs, history, referrers, and intermediaries.
Confidence: high
Scope-risk: moderate
Directive: Do not reintroduce query-string bearer tokens; use Authorization or rcs.auth.<base64url-token>.
Tested: bunx tsc --noEmit --pretty false
Tested: bun run typecheck in packages/remote-control-server
Tested: bun run build in packages/acp-link
Tested: bun run lint
Tested: bun audit
Tested: focused RCS/acp-link/web tests, 160 pass
Tested: Edge headless browser WebSocket subprotocol handshake
Tested: bun run test:all, 3669 pass
Tested: bun run build:vite
Tested: bun run build
Not-tested: Manual end-to-end relay with a live external ACP agent

* fix: resolve CI dependency override lookup

The CI runner does not expose @grpc/proto-loader as a root-resolvable package, and the test was relying on local hoisting rather than the real dependency owner. Resolve proto-loader through @opentelemetry/exporter-trace-otlp-grpc and @grpc/grpc-js so the smoke test follows the package graph it is validating.

Constraint: Do not add a new root dependency for a transitive smoke test.

Rejected: Skip or weaken the test | the test protects the protobuf 7 override path and should keep exercising loadSync.

Rejected: Add @grpc/proto-loader directly to root package.json | that hides the owning-package resolution issue and broadens dependency surface.

Confidence: high

Scope-risk: narrow

Directive: Dependency override smoke tests should resolve from the package that actually owns the dependency, not from incidental root hoisting.

Tested: bun test tests/integration/dependency-overrides.test.ts; bunx tsc --noEmit --pretty false; bun run lint; bun audit; bun run test:all; git diff --check

---------

Co-authored-by: unraid <local@unraid.local>
2026-04-26 19:49:54 +08:00

656 lines
24 KiB
TypeScript

import { randomUUID } from 'crypto';
import figures from 'figures';
import * as React from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useInterval } from 'usehooks-ts';
import { useRegisterOverlay } from '../../context/overlayContext.js';
// eslint-disable-next-line custom-rules/prefer-use-keybindings -- raw j/k/arrow dialog navigation
import { Box, Text, useInput, stringWidth } from '@anthropic/ink';
import { useKeybindings } from '../../keybindings/useKeybinding.js';
import { useShortcutDisplay } from '../../keybindings/useShortcutDisplay.js';
import { type AppState, useAppState, useSetAppState } from '../../state/AppState.js';
import { getEmptyToolPermissionContext } from '../../Tool.js';
import { AGENT_COLOR_TO_THEME_COLOR } from '@claude-code-best/builtin-tools/tools/AgentTool/agentColorManager.js';
import { logForDebugging } from '../../utils/debug.js';
import { execFileNoThrow } from '../../utils/execFileNoThrow.js';
import { truncateToWidth } from '../../utils/format.js';
import { getNextPermissionMode } from '../../utils/permissions/getNextPermissionMode.js';
import {
getModeColor,
type PermissionMode,
permissionModeFromString,
permissionModeSymbol,
} from '../../utils/permissions/PermissionMode.js';
import { jsonStringify } from '../../utils/slowOperations.js';
import { IT2_COMMAND, isInsideTmuxSync } from '../../utils/swarm/backends/detection.js';
import { ensureBackendsRegistered, getBackendByType, getCachedBackend } from '../../utils/swarm/backends/registry.js';
import { isPaneBackend, type PaneBackendType } from '../../utils/swarm/backends/types.js';
import { getSwarmSocketName, TMUX_COMMAND } from '../../utils/swarm/constants.js';
import {
addHiddenPaneId,
removeHiddenPaneId,
removeMemberFromTeam,
setMemberMode,
setMultipleMemberModes,
} from '../../utils/swarm/teamHelpers.js';
import { listTasks, type Task, unassignTeammateTasks } from '../../utils/tasks.js';
import { getTeammateStatuses, type TeammateStatus, type TeamSummary } from '../../utils/teamDiscovery.js';
import {
createModeSetRequestMessage,
sendShutdownRequestToMailbox,
writeToMailbox,
} from '../../utils/teammateMailbox.js';
import { Dialog } from '@anthropic/ink';
import ThemedText from '../design-system/ThemedText.js';
type Props = {
initialTeams?: TeamSummary[];
onDone: () => void;
};
type DialogLevel =
| { type: 'teammateList'; teamName: string }
| { type: 'teammateDetail'; teamName: string; memberName: string };
/**
* Dialog for viewing teammates in the current team
*/
export function TeamsDialog({ initialTeams, onDone }: Props): React.ReactNode {
// Register as overlay so CancelRequestHandler doesn't intercept escape
useRegisterOverlay('teams-dialog');
// initialTeams is derived from teamContext in PromptInput (no filesystem I/O)
const setAppState = useSetAppState();
// Initialize dialogLevel with first team name if available
const firstTeamName = initialTeams?.[0]?.name ?? '';
const [dialogLevel, setDialogLevel] = useState<DialogLevel>({
type: 'teammateList',
teamName: firstTeamName,
});
const [selectedIndex, setSelectedIndex] = useState(0);
const [refreshKey, setRefreshKey] = useState(0);
// initialTeams is now always provided from PromptInput (derived from teamContext)
// No filesystem I/O needed here
const teammateStatuses = useMemo(() => {
return getTeammateStatuses(dialogLevel.teamName);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dialogLevel.teamName, refreshKey]);
// Periodically refresh to pick up mode changes from teammates
useInterval(() => {
setRefreshKey(k => k + 1);
}, 1000);
const currentTeammate = useMemo(() => {
if (dialogLevel.type !== 'teammateDetail') return null;
return teammateStatuses.find(t => t.name === dialogLevel.memberName) ?? null;
}, [dialogLevel, teammateStatuses]);
// Get isBypassPermissionsModeAvailable from AppState
const isBypassAvailable = useAppState(s => s.toolPermissionContext.isBypassPermissionsModeAvailable);
const goBackToList = (): void => {
setDialogLevel({ type: 'teammateList', teamName: dialogLevel.teamName });
setSelectedIndex(0);
};
// Handler for confirm:cycleMode - cycle teammate permission modes
const handleCycleMode = useCallback(() => {
if (dialogLevel.type === 'teammateDetail' && currentTeammate) {
// Detail view: cycle just this teammate
cycleTeammateMode(currentTeammate, dialogLevel.teamName, isBypassAvailable);
setRefreshKey(k => k + 1);
} else if (dialogLevel.type === 'teammateList' && teammateStatuses.length > 0) {
// List view: cycle all teammates in tandem
cycleAllTeammateModes(teammateStatuses, dialogLevel.teamName, isBypassAvailable);
setRefreshKey(k => k + 1);
}
}, [dialogLevel, currentTeammate, teammateStatuses, isBypassAvailable]);
// Use keybindings for mode cycling
useKeybindings({ 'confirm:cycleMode': handleCycleMode }, { context: 'Confirmation' });
useInput((input, key) => {
// Handle left arrow to go back
if (key.leftArrow) {
if (dialogLevel.type === 'teammateDetail') {
goBackToList();
}
return;
}
// Handle up/down navigation
if (key.upArrow || key.downArrow) {
const maxIndex = getMaxIndex();
if (key.upArrow) {
setSelectedIndex(prev => Math.max(0, prev - 1));
} else {
setSelectedIndex(prev => Math.min(maxIndex, prev + 1));
}
return;
}
// Handle Enter to drill down or view output
if (key.return) {
if (dialogLevel.type === 'teammateList' && teammateStatuses[selectedIndex]) {
setDialogLevel({
type: 'teammateDetail',
teamName: dialogLevel.teamName,
memberName: teammateStatuses[selectedIndex].name,
});
} else if (dialogLevel.type === 'teammateDetail' && currentTeammate) {
// View output - switch to tmux pane
void viewTeammateOutput(
currentTeammate.tmuxPaneId,
currentTeammate.backendType && isPaneBackend(currentTeammate.backendType)
? currentTeammate.backendType
: undefined,
);
onDone();
}
return;
}
// Handle 'k' to kill teammate
if (input === 'k') {
if (dialogLevel.type === 'teammateList' && teammateStatuses[selectedIndex]) {
void killTeammate(
teammateStatuses[selectedIndex].tmuxPaneId,
teammateStatuses[selectedIndex].backendType && isPaneBackend(teammateStatuses[selectedIndex].backendType)
? teammateStatuses[selectedIndex].backendType
: undefined,
dialogLevel.teamName,
teammateStatuses[selectedIndex].agentId,
teammateStatuses[selectedIndex].name,
setAppState,
).then(() => {
setRefreshKey(k => k + 1);
// Adjust selection if needed
setSelectedIndex(prev => Math.max(0, Math.min(prev, teammateStatuses.length - 2)));
});
} else if (dialogLevel.type === 'teammateDetail' && currentTeammate) {
void killTeammate(
currentTeammate.tmuxPaneId,
currentTeammate.backendType && isPaneBackend(currentTeammate.backendType)
? currentTeammate.backendType
: undefined,
dialogLevel.teamName,
currentTeammate.agentId,
currentTeammate.name,
setAppState,
);
goBackToList();
}
return;
}
// Handle 's' for shutdown of selected teammate
if (input === 's') {
if (dialogLevel.type === 'teammateList' && teammateStatuses[selectedIndex]) {
const teammate = teammateStatuses[selectedIndex];
void sendShutdownRequestToMailbox(
teammate.name,
dialogLevel.teamName,
'Graceful shutdown requested by team lead',
);
} else if (dialogLevel.type === 'teammateDetail' && currentTeammate) {
void sendShutdownRequestToMailbox(
currentTeammate.name,
dialogLevel.teamName,
'Graceful shutdown requested by team lead',
);
goBackToList();
}
return;
}
// Handle 'h' to hide/show individual teammate (only for backends that support it)
if (input === 'h') {
const backend = getCachedBackend();
const teammate =
dialogLevel.type === 'teammateList'
? teammateStatuses[selectedIndex]
: dialogLevel.type === 'teammateDetail'
? currentTeammate
: null;
if (teammate && backend?.supportsHideShow) {
void toggleTeammateVisibility(teammate, dialogLevel.teamName).then(() => {
// Force refresh of teammate statuses
setRefreshKey(k => k + 1);
});
if (dialogLevel.type === 'teammateDetail') {
goBackToList();
}
}
return;
}
// Handle 'H' to hide/show all teammates (only for backends that support it)
if (input === 'H' && dialogLevel.type === 'teammateList') {
const backend = getCachedBackend();
if (backend?.supportsHideShow && teammateStatuses.length > 0) {
// If any are visible, hide all. Otherwise, show all.
const anyVisible = teammateStatuses.some(t => !t.isHidden);
void Promise.all(
teammateStatuses.map(t =>
anyVisible ? hideTeammate(t, dialogLevel.teamName) : showTeammate(t, dialogLevel.teamName),
),
).then(() => {
// Force refresh of teammate statuses
setRefreshKey(k => k + 1);
});
}
return;
}
// Handle 'p' to prune (kill) all idle teammates
if (input === 'p' && dialogLevel.type === 'teammateList') {
const idleTeammates = teammateStatuses.filter(t => t.status === 'idle');
if (idleTeammates.length > 0) {
void Promise.all(
idleTeammates.map(t =>
killTeammate(
t.tmuxPaneId,
t.backendType && isPaneBackend(t.backendType) ? t.backendType : undefined,
dialogLevel.teamName,
t.agentId,
t.name,
setAppState,
),
),
).then(() => {
setRefreshKey(k => k + 1);
setSelectedIndex(prev => Math.max(0, Math.min(prev, teammateStatuses.length - idleTeammates.length - 1)));
});
}
return;
}
// Note: Mode cycling (shift+tab) is handled via useKeybindings with confirm:cycleMode action
});
function getMaxIndex(): number {
if (dialogLevel.type === 'teammateList') {
return Math.max(0, teammateStatuses.length - 1);
}
return 0;
}
// Render based on dialog level
if (dialogLevel.type === 'teammateList') {
return (
<TeamDetailView
teamName={dialogLevel.teamName}
teammates={teammateStatuses}
selectedIndex={selectedIndex}
onCancel={onDone}
/>
);
}
if (dialogLevel.type === 'teammateDetail' && currentTeammate) {
return <TeammateDetailView teammate={currentTeammate} teamName={dialogLevel.teamName} onCancel={goBackToList} />;
}
return null;
}
type TeamDetailViewProps = {
teamName: string;
teammates: TeammateStatus[];
selectedIndex: number;
onCancel: () => void;
};
function TeamDetailView({ teamName, teammates, selectedIndex, onCancel }: TeamDetailViewProps): React.ReactNode {
const subtitle = `${teammates.length} ${teammates.length === 1 ? 'teammate' : 'teammates'}`;
// Check if the backend supports hide/show
const supportsHideShow = getCachedBackend()?.supportsHideShow ?? false;
// Get the display text for the cycle mode shortcut
const cycleModeShortcut = useShortcutDisplay('confirm:cycleMode', 'Confirmation', 'shift+tab');
return (
<>
<Dialog title={`Team ${teamName}`} subtitle={subtitle} onCancel={onCancel} color="background" hideInputGuide>
{teammates.length === 0 ? (
<Text dimColor>No teammates</Text>
) : (
<Box flexDirection="column">
{teammates.map((teammate, index) => (
<TeammateListItem key={teammate.agentId} teammate={teammate} isSelected={index === selectedIndex} />
))}
</Box>
)}
</Dialog>
<Box marginLeft={1}>
<Text dimColor>
{figures.arrowUp}/{figures.arrowDown} select · Enter view · k kill · s shutdown · p prune idle
{supportsHideShow && ' · h hide/show · H hide/show all'}
{' · '}
{cycleModeShortcut} sync cycle modes for all · Esc close
</Text>
</Box>
</>
);
}
type TeammateListItemProps = {
teammate: TeammateStatus;
isSelected: boolean;
};
function TeammateListItem({ teammate, isSelected }: TeammateListItemProps): React.ReactNode {
const isIdle = teammate.status === 'idle';
// Only dim if idle AND not selected - selection highlighting takes precedence
const shouldDim = isIdle && !isSelected;
// Get mode display
const mode = teammate.mode ? permissionModeFromString(teammate.mode) : 'default';
const modeSymbol = permissionModeSymbol(mode);
const modeColor = getModeColor(mode);
return (
<Text color={isSelected ? 'suggestion' : undefined} dimColor={shouldDim}>
{isSelected ? figures.pointer + ' ' : ' '}
{teammate.isHidden && <Text dimColor>[hidden] </Text>}
{isIdle && <Text dimColor>[idle] </Text>}
{modeSymbol && <Text color={modeColor}>{modeSymbol} </Text>}@{teammate.name}
{teammate.model && <Text dimColor> ({teammate.model})</Text>}
</Text>
);
}
type TeammateDetailViewProps = {
teammate: TeammateStatus;
teamName: string;
onCancel: () => void;
};
function TeammateDetailView({ teammate, teamName, onCancel }: TeammateDetailViewProps): React.ReactNode {
const [promptExpanded, setPromptExpanded] = useState(false);
// Get the display text for the cycle mode shortcut
const cycleModeShortcut = useShortcutDisplay('confirm:cycleMode', 'Confirmation', 'shift+tab');
const themeColor = teammate.color
? AGENT_COLOR_TO_THEME_COLOR[teammate.color as keyof typeof AGENT_COLOR_TO_THEME_COLOR]
: undefined;
// Get tasks assigned to this teammate
const [teammateTasks, setTeammateTasks] = useState<Task[]>([]);
useEffect(() => {
let cancelled = false;
void listTasks(teamName).then(allTasks => {
if (cancelled) return;
// Filter tasks owned by this teammate (by agentId or name)
setTeammateTasks(allTasks.filter(task => task.owner === teammate.agentId || task.owner === teammate.name));
});
return () => {
cancelled = true;
};
}, [teamName, teammate.agentId, teammate.name]);
useInput(input => {
// Handle 'p' to expand/collapse prompt
if (input === 'p') {
setPromptExpanded(prev => !prev);
}
});
// Determine working directory display
const workingPath = teammate.worktreePath || teammate.cwd;
// Build subtitle with metadata
const subtitleParts: string[] = [];
if (teammate.model) subtitleParts.push(teammate.model);
if (workingPath) {
subtitleParts.push(teammate.worktreePath ? `worktree: ${workingPath}` : workingPath);
}
const subtitle = subtitleParts.join(' · ') || undefined;
// Get mode display for title
const mode = teammate.mode ? permissionModeFromString(teammate.mode) : 'default';
const modeSymbol = permissionModeSymbol(mode);
const modeColor = getModeColor(mode);
// Build title with mode symbol and colored name if applicable
const title = (
<>
{modeSymbol && <Text color={modeColor}>{modeSymbol} </Text>}
{themeColor ? <ThemedText color={themeColor}>{`@${teammate.name}`}</ThemedText> : `@${teammate.name}`}
</>
);
return (
<>
<Dialog title={title} subtitle={subtitle} onCancel={onCancel} color="background" hideInputGuide>
{/* Tasks section */}
{teammateTasks.length > 0 && (
<Box flexDirection="column">
<Text bold>Tasks</Text>
{teammateTasks.map(task => (
<Text key={task.id} color={task.status === 'completed' ? 'success' : undefined}>
{task.status === 'completed' ? figures.tick : '◼'} {task.subject}
</Text>
))}
</Box>
)}
{/* Prompt section */}
{teammate.prompt && (
<Box flexDirection="column">
<Text bold>Prompt</Text>
<Text>
{promptExpanded ? teammate.prompt : truncateToWidth(teammate.prompt, 80)}
{stringWidth(teammate.prompt) > 80 && !promptExpanded && <Text dimColor> (p to expand)</Text>}
</Text>
</Box>
)}
</Dialog>
<Box marginLeft={1}>
<Text dimColor>
{figures.arrowLeft} back · Esc close · k kill · s shutdown
{getCachedBackend()?.supportsHideShow && ' · h hide/show'}
{' · '}
{cycleModeShortcut} cycle mode
</Text>
</Box>
</>
);
}
async function killTeammate(
paneId: string,
backendType: PaneBackendType | undefined,
teamName: string,
teammateId: string,
teammateName: string,
setAppState: (f: (prev: AppState) => AppState) => void,
): Promise<void> {
// Kill the pane using the backend that created it (handles -s / -L flags correctly).
// Wrapped in try/catch so cleanup (removeMemberFromTeam, unassignTeammateTasks,
// setAppState) always runs — matches useInboxPoller.ts error isolation.
if (backendType) {
try {
// Use ensureBackendsRegistered (not detectAndGetBackend) — this process may
// be a teammate that never ran detection, but we only need class imports
// here, not subprocess probes that could throw in a different environment.
await ensureBackendsRegistered();
await getBackendByType(backendType).killPane(paneId, !isInsideTmuxSync());
} catch (error) {
logForDebugging(`[TeamsDialog] Failed to kill pane ${paneId}: ${error}`);
}
} else {
// backendType undefined: old team files predating this field, or in-process.
// Old tmux-file case is a migration gap — the pane is orphaned. In-process
// teammates have no pane to kill, so this is correct for them.
logForDebugging(`[TeamsDialog] Skipping pane kill for ${paneId}: no backendType recorded`);
}
// Remove from team config file
removeMemberFromTeam(teamName, paneId);
// Unassign tasks and build notification message
const { notificationMessage } = await unassignTeammateTasks(teamName, teammateId, teammateName, 'terminated');
// Update AppState to keep status line in sync and notify the lead
setAppState(prev => {
if (!prev.teamContext?.teammates) return prev;
if (!(teammateId in prev.teamContext.teammates)) return prev;
const { [teammateId]: _, ...remainingTeammates } = prev.teamContext.teammates;
return {
...prev,
teamContext: {
...prev.teamContext,
teammates: remainingTeammates,
},
inbox: {
messages: [
...prev.inbox.messages,
{
id: randomUUID(),
from: 'system',
text: jsonStringify({
type: 'teammate_terminated',
message: notificationMessage,
}),
timestamp: new Date().toISOString(),
status: 'pending' as const,
},
],
},
};
});
logForDebugging(`[TeamsDialog] Removed ${teammateId} from teamContext`);
}
async function viewTeammateOutput(paneId: string, backendType: PaneBackendType | undefined): Promise<void> {
if (backendType === 'iterm2') {
// -s is required to target a specific session (ITermBackend.ts:216-217)
await execFileNoThrow(IT2_COMMAND, ['session', 'focus', '-s', paneId]);
} else if (backendType === 'windows-terminal') {
// Windows Terminal spawns each teammate as a separate window/tab; wt.exe
// does not expose an API to focus a pre-existing tab by name. The user
// switches tabs manually (Ctrl+Tab) — dialog closing is enough here.
logForDebugging(`[TeamsDialog] viewTeammateOutput: Windows Terminal pane ${paneId} — manual tab switch required`);
} else {
// External-tmux teammates live on the swarm socket — without -L, this
// targets the default server and silently no-ops. Mirrors runTmuxInSwarm
// in TmuxBackend.ts:85-89.
const args = isInsideTmuxSync()
? ['select-pane', '-t', paneId]
: ['-L', getSwarmSocketName(), 'select-pane', '-t', paneId];
await execFileNoThrow(TMUX_COMMAND, args);
}
}
/**
* Toggle visibility of a teammate pane (hide if visible, show if hidden)
*/
async function toggleTeammateVisibility(teammate: TeammateStatus, teamName: string): Promise<void> {
if (teammate.isHidden) {
await showTeammate(teammate, teamName);
} else {
await hideTeammate(teammate, teamName);
}
}
/**
* Hide a teammate pane using the backend abstraction.
* Only available for ant users (gated for dead code elimination in external builds)
*/
async function hideTeammate(teammate: TeammateStatus, teamName: string): Promise<void> {}
/**
* Show a previously hidden teammate pane using the backend abstraction.
* Only available for ant users (gated for dead code elimination in external builds)
*/
async function showTeammate(teammate: TeammateStatus, teamName: string): Promise<void> {}
/**
* Send a mode change message to a single teammate
* Also updates config.json directly so the UI reflects the change immediately
*/
function sendModeChangeToTeammate(teammateName: string, teamName: string, targetMode: PermissionMode): void {
// Update config.json directly so UI shows the change immediately
setMemberMode(teamName, teammateName, targetMode);
// Also send message so teammate updates their local permission context
const message = createModeSetRequestMessage({
mode: targetMode,
from: 'team-lead',
});
void writeToMailbox(
teammateName,
{
from: 'team-lead',
text: jsonStringify(message),
timestamp: new Date().toISOString(),
},
teamName,
);
logForDebugging(`[TeamsDialog] Sent mode change to ${teammateName}: ${targetMode}`);
}
/**
* Cycle a single teammate's mode
*/
function cycleTeammateMode(teammate: TeammateStatus, teamName: string, isBypassAvailable: boolean): void {
const currentMode = teammate.mode ? permissionModeFromString(teammate.mode) : 'default';
const context = {
...getEmptyToolPermissionContext(),
mode: currentMode,
isBypassPermissionsModeAvailable: isBypassAvailable,
};
const nextMode = getNextPermissionMode(context);
sendModeChangeToTeammate(teammate.name, teamName, nextMode);
}
/**
* Cycle all teammates' modes in tandem
* If modes differ, reset all to default first
* If same, cycle all to next mode
* Uses batch update to avoid race conditions
*/
function cycleAllTeammateModes(teammates: TeammateStatus[], teamName: string, isBypassAvailable: boolean): void {
if (teammates.length === 0) return;
const modes = teammates.map(t => (t.mode ? permissionModeFromString(t.mode) : 'default'));
const allSame = modes.every(m => m === modes[0]);
// Determine target mode for all teammates
const targetMode = !allSame
? 'default'
: getNextPermissionMode({
...getEmptyToolPermissionContext(),
mode: modes[0] ?? 'default',
isBypassPermissionsModeAvailable: isBypassAvailable,
});
// Batch update config.json in a single atomic operation
const modeUpdates = teammates.map(t => ({
memberName: t.name,
mode: targetMode,
}));
setMultipleMemberModes(teamName, modeUpdates);
// Send mailbox messages to each teammate
for (const teammate of teammates) {
const message = createModeSetRequestMessage({
mode: targetMode,
from: 'team-lead',
});
void writeToMailbox(
teammate.name,
{
from: 'team-lead',
text: jsonStringify(message),
timestamp: new Date().toISOString(),
},
teamName,
);
}
logForDebugging(`[TeamsDialog] Sent mode change to all ${teammates.length} teammates: ${targetMode}`);
}