// The Tools panels: a grant's details and trail, the Add and Change access form, // the GitHub App setup, and the connection notices. Moved from the old Tools list // (TASK-733); verbs and copy are unchanged. The rows that opened them are gone. import React from 'react'; import { Trans, useTranslation } from 'react-i18next'; import { localizeRelativeTime, localizeWindow } from '../utils/localizeRelativeTime'; import { ActGlyph } from '../icons/glyphs'; import { PlatformGlyph } from '../icons/platforms'; import { catalogDescription } from '../utils/connectorCatalogDescription'; import GithubInstallWarning from './GithubInstallWarning'; import { grantHarnessNames } from '../utils/harnessCatalog'; import { shortAge, isExpired, isDead, boundAgentOf, entryOffersPrWrite, PER_ENTRY_REVOKE_COPY, } from './toolModel'; import type { ByoCandidate, ByoSandbox, GrantWriteMode, ToolGrant, ToolOutcome, ToolCatalogEntry, HiddenToolConnection, ToolConnection, PodSeat, } from './toolModel'; import type { ToolConnectorsModel } from './useToolConnectors'; import OperatorKeyForm from './OperatorKeyForm'; const G: React.FC<{ children: React.ReactNode }> = ({ children }) => ( ); /** Outcome marks: a category, so a glyph; the word stays in the log line and the title. * * The `superseded` mark is a shield with a SHORT BAR, not the shield-and-check it * first shipped with: the resolution it stands for may be an * approval, a decline or an expiry, and the row beside it carries the verdict — * a check read as "approved" next to a sibling that says `refused`. The bar says * settled without saying how. */ const OutcomeGlyph: React.FC<{ outcome: ToolOutcome }> = ({ outcome }) => { if (outcome === 'ok') return ; if (outcome === 'refused') return ; if (outcome === 'pending_approval') return ; if (outcome === 'superseded') return ; return ; }; /** Mode marks: eye for read, pen for write, shield for write that asks first. */ const ModeGlyph: React.FC<{ mode: GrantWriteMode }> = ({ mode }) => { if (mode === 'read') return ; if (mode === 'write') return ; return ; }; export const useToolPanels = (m: ToolConnectorsModel, accessNoticePage: string | null = null) => { const { t, i18n } = useTranslation(); const { manualRevokeNotice, isGranter, catalog, seats, trail, trailError, selectedId, setSelectedId, draft, setDraft, githubAppSetup, repositoryConnect, setRepositoryConnect, readConnectableRepositories, openRepositoryConnect, submitRepositoryConnect, setGithubAppSetup, staleAfterChange, confirmRevoke, setConfirmRevoke, confirmDisconnect, setConfirmDisconnect, confirmHiddenRemoval, setConfirmHiddenRemoval, busy, error, joinPolicyFixPodId, policyFixedPodId, grants, now, isAdmin, podIds, entryFor, noticeMatchesEntry, toolLabel, podName, memberName, seatLabel, grantPodId, joinList, audienceLabels, irreversibleTools, asksFirst, outcomeLabel, reasonLabel, modeLabel, grantModeLabel, entryGrantModes, entryModeCopy, usedRecently, openDraft, openGithubAppSetup, draftEntry, draftTools, draftPrWrite, draftBoundAgent, startingAudience, selectedAgentIds, draftByoCandidates, draftByoNamed, draftByoKey, draftByoConsented, removeByoAgent, submitDraft, fixJoinPolicy, connectHostedMcp, keyAgents, keyAgentsUnavailable, submitOperatorKey, submitGithubAppSetup, retryStaleRevoke, revoke, removeHiddenConnection, disconnect, setError, } = m; const renderManualRevokeNotice = (entry: ToolCatalogEntry | null) => { if (!manualRevokeNotice || !noticeMatchesEntry(entry)) return null; // Per-entry copy names only what that vendor's page lists; entries without it fall back to the generic line. const context = PER_ENTRY_REVOKE_COPY.has(manualRevokeNotice.entryId) ? manualRevokeNotice.entryId : undefined; return (

{t('connectors.hostedMcpManualRevoke', { defaultValue: 'Your previous {{provider}} account may still have Commonly connected. Switch to it on {{provider}}, then remove Commonly there.', context, provider: manualRevokeNotice.provider, })}{' '} {t('connectors.hostedMcpReviewAuthorization', { defaultValue: "Open {{provider}}'s connected apps", context, provider: manualRevokeNotice.provider, })}

); }; const agentNameById = (agentId?: string): string => { if (!agentId) return ''; const seat = Object.values(seats).flat().find((candidate) => candidate.userId === agentId); return seat?.displayName || seat?.name || ''; }; // Names one hosted connection: a key row by its agent, the sign-in as such, // and both by when. Null when the server did not describe the row (no // connectedAt), so it cannot be told apart. const connectionLabel = (connection: ToolConnection): string | null => { if (!connection.connectedAt || Number.isNaN(Date.parse(connection.connectedAt))) return null; const date = new Date(connection.connectedAt).toLocaleDateString(i18n.language, { month: 'short', day: 'numeric' }); const separator = t('tools.connectionSeparator', { defaultValue: ' · ' }); if (connection.agentId) { return [t('tools.connectionKey', { defaultValue: 'Key' }), agentNameById(connection.agentId), date].filter(Boolean).join(separator); } return [t('tools.connectionSignedIn', { defaultValue: 'Signed in' }), date].join(separator); }; // Hosted connections only: a GitHub App connection is the instance's, not the viewer's to drop. const renderDisconnect = (entry: ToolCatalogEntry | null, variant: 'row' | 'aside') => { const hosted = entry && entry.connectionType === 'hosted-mcp' ? entry.connections : []; if (!entry || hosted.length === 0) return null; // A lone key row still names its agent, so the person can see whose key it is. if (hosted.length === 1 && !(hosted[0].agentId && connectionLabel(hosted[0]))) { const button = renderDisconnectOne(entry, hosted[0], variant, null); return variant === 'aside' ?
{button}
: button; } // Several connections: each is named, so each gets its own Disconnect. A // connection that cannot be told apart (the server did not describe it, or // it reads the same as another) gets none rather than one that might drop // the wrong connection. const labelled = hosted.map((connection) => ({ connection, label: connectionLabel(connection) })); const labels = labelled.map((row) => row.label); if (labels.some((label) => !label) || new Set(labels).size < labels.length) return null; return ( <> {labelled.map(({ connection, label }) => (variant === 'aside' ? (
{label} {renderDisconnectOne(entry, connection, variant, label)}
) : ( {label} {renderDisconnectOne(entry, connection, variant, label)} )))} ); }; const renderDisconnectOne = (entry: ToolCatalogEntry, connection: ToolConnection, variant: 'row' | 'aside', label: string | null) => { const cls = variant === 'row' ? 'v2-connector-row__action v2-connector-row__action--secondary' : 'v2-connector-aside__secondary'; if (confirmDisconnect === connection.connectionId) { return ( <> ); } return ( ); }; const renderHiddenConnection = (connection: HiddenToolConnection) => (
{t('tools.existingConnection', { defaultValue: 'existing connection' })} {t('tools.noLongerOffered', { defaultValue: 'This connector is no longer offered here.' })} {connection.revokePage && {t('tools.reviewProviderAccess', { defaultValue: 'Review access at {{label}}', label: connection.label })}} {confirmHiddenRemoval === connection.connectionId ? ( <> ) : ( )}
); const renderRow = (grant: ToolGrant) => { const dead = isDead(grant, now); const podId = grantPodId(grant); const granter = memberName(grant.grantedBy); const isSelected = selectedId === grant.grantId; const entry = entryFor(grant); const label = toolLabel(grant); // A grant the catalogue no longer covers keeps the server-named connector's glyph (TASK-753). const glyph = entry?.installableId || grant.connector?.id; const noticeGrantId = noticeMatchesEntry(entry) ? (grants || []).find((candidate) => ( !isDead(candidate, now) && entryFor(candidate)?.installableId === entry?.installableId ))?.grantId : null; // What the grant was given TO, which is a seat when the target is a seat. It // is not the row's location: the kicker and the accessible name both name the // pod the row lives in, so a seat grant under Ops has a sentence reading // `granted to Reed` in a row announced as `View GitHub in Ops`. Sharing one // label between the two put the seat's name where the location belongs // (TASK-179, ux-lead's gate at 07873c19) — two nouns, so two expressions. const targetLabel = grant.target.kind === 'pod' ? podName(grant.target.id) : seatLabel(podId, grant.target.id); // Direction A rule 3: `pod · verb age` — the verb from a key, the age from the timestamp. const when = t('tools.grantedAge', { defaultValue: 'granted {{age}}', age: shortAge(grant.createdAt, now, t) }); const kicker = `${podId ? podName(podId) : seatLabel(null, grant.target.id)} · ${when}`; const revokedBy = grant.revokedBy ? memberName(grant.revokedBy) : null; const line2 = dead ? (grant.revokedAt ? (revokedBy ? t('tools.revokedByLine', { defaultValue: 'revoked by {{member}} {{rel}}', member: revokedBy, rel: localizeRelativeTime(grant.revokedAt, t, { now, pastEvent: true }) }) : t('tools.revokedLine', { defaultValue: 'revoked {{rel}}', rel: localizeRelativeTime(grant.revokedAt, t, { now, pastEvent: true }) })) : t('tools.expiredLine', { defaultValue: 'expired {{rel}}', rel: localizeRelativeTime(grant.expiresAt, t, { now }) })) // Direction A rule 1: the write mode is the glyph beside this line; its words ride the 390 kicker. // One interpolated key, not `{{agents}}` + a separate 'may use it': a language // that orders the clause differently needs the whole sentence (TASK-164). The // rendered English is unchanged. // An empty audience is its own sentence, not the interpolated one with an empty // subject: zh writes 「没有智能体可以使用」 with no space, which `{{agents}} 可以使用` // cannot produce (TASK-179). : (grant.effectiveAudience.length === 0 ? t('tools.nobodyMayUse', { defaultValue: 'nobody may use it' }) : t('tools.mayUse', { defaultValue: '{{agents}} may use it', agents: audienceLabels(grant) })); return (
{dead && entry && isGranter(grant) ? ( // Grant again is the granter's too: the mint 403s anyone but the Connection's owner. ) : ( // Direction A rule 2: Manage is housekeeping beside the row's word, so it is the gear. )} {noticeGrantId === grant.grantId && renderManualRevokeNotice(entry)}
); }; // Where the person who connected a hosted entry picks what it reaches (for // GitHub, the App's install page). Shown on the offer and on the details of // their live grant, since a grant takes the entry off the offer list. // For an operator-key entry the same page is where the key is made, and the // key's scopes are what bound its reach. const renderAccessLink = (entry: ToolCatalogEntry) => ( {entry.credentialMode === 'operator_key' ? t('tools.operatorKey.createKey', { label: entry.label }) : t('tools.chooseAccess', { defaultValue: 'Choose what {{label}} can reach', label: entry.label })} ); // The page's own access notice stays up behind a popover and travels into // every drawer, so a panel for the same install page would only repeat it. const renderGithubWarning = (entry: ToolCatalogEntry) => ( entry.accessPage === accessNoticePage ? null : {renderAccessLink(entry)} ); // An operator-key entry holds one connection per agent (TASK-330), so it // stays open to a key for each of the person's agents that has none yet. An // OAuth entry is connected once, by `connections.length`. const keylessAgents = (entry: ToolCatalogEntry) => { const keyed = new Set(entry.connections.map((connection) => connection.agentId).filter(Boolean)); return keyAgents.filter((agent) => !keyed.has(agent.userId)); }; // The paste-a-key form while any of the person's agents has no key on this // operator-key entry. It is offered on a granted entry too: one agent's key // being granted says nothing about the next agent's. const renderKeyForm = (entry: ToolCatalogEntry) => { const takesKey = entry.connectionType === 'hosted-mcp' && Boolean(entry.entryId) && entry.credentialMode === 'operator_key'; const keyable = takesKey && entry.available ? keylessAgents(entry) : []; return keyable.length > 0 ? : null; }; // Where to make the key, for a granted entry's drawer, which skips the // ungranted offer and its renderEntryNote. Ungranted, renderEntryNote // carries the same two lines. const renderKeyGuidance = (entry: ToolCatalogEntry) => ( <> {entry.connectNotice &&

{entry.connectNotice}

} {entry.accessPage &&

{renderAccessLink(entry)}

} ); const renderRepositoryConnectAction = (entry: ToolCatalogEntry) => (entry.available && entry.repositoryConnect ? ( ) : null); // What a person can do with an entry that has no live grant: the verbs of the // old "Not yet" row, shared by the tile's popover. const renderEntryActions = (entry: ToolCatalogEntry) => { const canAdd = entry.available && entry.connections.length > 0 && podIds.length > 0; const canInstallGithubApp = isAdmin && entry.installableId === 'github' && entry.available && entry.connections.length === 0; // A hosted entry is connected by the person who will grant it (§1: member // mode), so the action belongs on the tile and needs no admin. const isHosted = entry.connectionType === 'hosted-mcp' && Boolean(entry.entryId); const takesKey = isHosted && entry.credentialMode === 'operator_key'; const canConnectHosted = isHosted && !takesKey && entry.available && entry.connections.length === 0; return ( <> {renderKeyForm(entry)} {!entry.available && ( {t('tools.ask', { defaultValue: 'Ask' })} )} {canConnectHosted && ( )} {canAdd && ( )} {renderDisconnect(entry, 'row')} {renderRepositoryConnectAction(entry)} {canInstallGithubApp && ( )} ); }; // F213: the form offers Linear no write, so the line says that. When write // mode returns, a connection made before write access needs reconnecting: the // server refuses it the mode, and the page cannot see a connection's scope. const renderLinearWriteNote = (entry: ToolCatalogEntry) => ( entry.connectionType === 'hosted-mcp' && entry.entryId === 'linear' && entry.connections.length > 0 ?

{t('tools.linearWriteReconnect')}

: null ); // TASK-782: a connection whose account saw nothing to search at connect. // A warning, never a block: the person may add a project afterwards. const renderReachNote = (entry: ToolCatalogEntry, connections: ToolConnection[]) => ( connections.some((connection) => connection.reach === 'none') ?

{t('tools.reachNone', { label: entry.label })}

: null ); // The one line under an entry's name that says what is left to do before it // works: connect your own account, ask an admin, or the modes it grants. const renderEntryNote = (entry: ToolCatalogEntry) => { const isHosted = entry.connectionType === 'hosted-mcp' && Boolean(entry.entryId); const takesKey = isHosted && entry.credentialMode === 'operator_key'; const canConnectHosted = isHosted && !takesKey && entry.available && entry.connections.length === 0; const keyable = takesKey && entry.available ? keylessAgents(entry) : []; const unconnectedNote = () => { if (takesKey) { if (keyAgents.length === 0 && keyAgentsUnavailable) return t('tools.operatorKey.agentsUnavailable'); return keyAgents.length === 0 ? t('tools.operatorKey.noAgents') : t('tools.operatorKey.note'); } if (isHosted) return t('tools.connectOwn', { defaultValue: 'connect your own {{label}} account', label: entry.label }); return entry.repositoryConnect ? t('tools.repoConnect.note', { defaultValue: 'connect a repository first' }) : t('tools.noConnection', { defaultValue: 'install the GitHub App first · an admin does this once' }); }; return ( <> {entry.available && (

{entry.connections.length === 0 ? unconnectedNote() : entryModeCopy(entry)}

)} {renderLinearWriteNote(entry)} {renderReachNote(entry, entry.connections)} {(canConnectHosted || keyable.length > 0) && entry.connectNotice &&

{entry.connectNotice}

} {isHosted && entry.available && entry.accessPage && (entry.entryId === 'github-mcp' ? renderGithubWarning(entry) :

{renderAccessLink(entry)}

)} {renderManualRevokeNotice(entry)} ); }; const renderGithubAppSetup = () => { if (!githubAppSetup) return null; return ( ); }; // F221: a person connects a repository of their own. GitHub comes first: the // list and the proof both read that person's token, and the hosted GitHub // entry holds both the sign-in and the page that installs the App. const renderRepositoryConnect = () => { if (!repositoryConnect) return null; const { status, repositories, truncated, selected } = repositoryConnect; const githubEntry = catalog.find((entry) => entry.entryId === 'github-mcp'); // The list can hold public repositories, and a single row comes picked, so // the step names what Connect will connect. const picked = repositories.find(({ owner, repo }) => `${owner}/${repo}` === selected); return ( ); }; // F94: the disclosure for one agent that runs outside Commonly. The server // records 'confined' only on evidence, so anything else reads as no sandbox. const byoAgentLabel = (agent: ByoCandidate) => agentNameById(agent.userId) || agent.agentName; const byoConsentLine = (agent: ByoCandidate) => (agent.sandbox !== 'confined' ? t('tools.byo.consentNoSandbox', { agent: byoAgentLabel(agent) }) : t('tools.byo.consent', { agent: byoAgentLabel(agent) })); const byoReason = (agent: ByoCandidate) => (agent.reason === 'unconfined_host' ? t('tools.byo.reasonUnconfinedHost') : t('tools.byo.reasonAdapterUnsupported', { harnesses: grantHarnessNames(t) })); const byoNamedLine = (name: string, sandbox: ByoSandbox | undefined) => (sandbox !== 'confined' ? t('tools.byo.namedNoSandbox', { agent: name }) : t('tools.byo.named', { agent: name })); const renderDraft = () => { if (!draft || !draftEntry) return null; const podSeats = seats[draft.podId] || []; // A key connection offers only its own agent: the route refuses any other. // The viewer's agents that run outside Commonly join the roster when it hid them. const byoOnly: PodSeat[] = draftByoCandidates .filter((agent) => !podSeats.some((seat) => seat.userId === agent.userId)) .map((agent) => ({ userId: agent.userId, name: agent.agentName, instanceId: agent.instanceId })); const allSeats = [...podSeats, ...byoOnly]; const offeredSeats = draftBoundAgent ? allSeats.filter((seat) => seat.userId === draftBoundAgent) : allSeats; const naming = draftByoNamed.length > 0; const boundAbsent = Boolean(draftBoundAgent) && offeredSeats.length === 0; const boundName = draftBoundAgent ? (agentNameById(draftBoundAgent) || memberName(draftBoundAgent)) : null; // A key grant whose key was removed opens with no key chosen (openDraft): // the picker shows even for one remaining key, and the seats wait for a key. const keyPending = draftEntry.credentialMode === 'operator_key' && !draft.connectionId; const tools = draftTools(draftEntry, draft.writeMode, draftPrWrite, draft.prTools); const irreversible = irreversibleTools(draftEntry, tools); const asks = draftPrWrite ? t('tools.asksPrWrite', { defaultValue: 'every commit, push and pull request asks you first' }) : draft.writeMode === 'read' ? t('tools.asksNothing', { defaultValue: 'nothing asks first' }) : draft.writeMode === 'write-with-confirm' ? t('tools.asksEveryWrite', { defaultValue: 'a write would ask first' }) : (irreversible.length ? t('tools.asksList', { defaultValue: '{{tools}} ask first', tools: joinList(irreversible) }) : t('tools.asksNothing', { defaultValue: 'nothing asks first' })); return ( ); }; const renderAside = (grant: ToolGrant) => { const dead = isDead(grant, now); const podId = grantPodId(grant); const granter = memberName(grant.grantedBy); const revokedBy = memberName(grant.revokedBy); const entry = entryFor(grant); const counts = trail?.counts; return ( ); }; return { renderRepositoryConnect, renderRepositoryConnectAction, renderManualRevokeNotice, renderLinearWriteNote, renderDisconnect, renderHiddenConnection, renderRow, renderAccessLink, renderKeyForm, renderKeyGuidance, renderEntryActions, renderEntryNote, renderGithubAppSetup, renderDraft, renderAside }; };