Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): Slack 授权取消后提供显式重新授权入口 (#2992)
Battleplus78bae15a3e38
diff --git a/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts b/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.tsindex 59af269a5d..d42e9b7ac0 100644--- a/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts+++ b/apps/desktop/src/main/hook-control/__tests__/transport-manager.test.ts@@ -3540,6 +3540,35 @@ describe('多 workspace 绑定(multi-team)', () => {expect(manager.snapshot().pendingBind).toMatchObject({ state: 'pending', teamId: 'T1' });});+ it('重连/重启后回放带 teamId 的终止态: intent 回退为 add, 不被误判为定向重绑', async () => {+ // 场景: 进程重启或重连使内存 pendingBind 丢失, server 回放一个 add 流+ // 的 denied 终止态(带用户所选 team 的 teamId)。此时无法知道原发起意图,+ // fallback 必须保守取 add —— 否则重试会 rebindTeam(teamId) 把授权页固定+ // 到旧 workspace, 用户无法切换完成新增。+ const { manager, sock } = await connectMulti();+ sock.send(serializeHookMessage(makeBindState({ bindings: [T1] })));+ await expect.poll(() => manager.snapshot().bindings.length, { timeout: 3000 }).toBe(1);+ expect(manager.snapshot().pendingBind).toBeNull(); // 本地无在途授权(重启后)++ sock.send(+ serializeHookMessage(+ makeBindUpdate({+ state: 'denied',+ slackUserId: null,+ slackUserName: null,+ message: 'user cancelled',+ teamId: 'T1',+ }),+ ),+ );+ await expect+ .poll(() => manager.snapshot().pendingBind?.state, { timeout: 3000 })+ .toBe('denied');+ // 关键断言: teamId 只描述冲突/所选 team, 不携带重绑意图+ expect(manager.snapshot().pendingBind?.intent).toBe('add');+ expect(manager.snapshot().pendingBind?.teamId).toBe('T1');+ });+it('revoked(teamId, reason=superseded): 行保留标注 displaced, 不弹开关不掉线', async () => {const { manager, store, sock } = await connectMulti();sock.send(serializeHookMessage(makeBindState({ bindings: [T1, T2] })));diff --git a/apps/desktop/src/main/hook-control/manager.ts b/apps/desktop/src/main/hook-control/manager.tsindex 2654f68e8b..36d36648bd 100644--- a/apps/desktop/src/main/hook-control/manager.ts+++ b/apps/desktop/src/main/hook-control/manager.ts@@ -1799,6 +1799,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContreason: null,installUrl: null,teamId: null,+ intent: 'add',};} else {markBindingPending();@@ -1823,6 +1824,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContreason: null,installUrl: null,teamId,+ intent: teamId !== null ? 'rebind' : 'add',};armBindWatchdog();notifyStatus(toView());@@ -1916,6 +1918,7 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookContreason: HOOK_BIND_REASON_ALREADY_BOUND,installUrl: null,teamId,+ intent: 'add',};}if (idx >= 0) multiBindings[idx] = row;@@ -1976,6 +1979,13 @@ export function createHookControlManager(deps: HookControlManagerDeps): HookCont// 授权流早期 server 不带 teamId(用户尚未选 workspace), 保留本地发起时// 记下的目标 team(重绑场景)供 UI 定位teamId: payload.teamId ?? pendingBind?.teamId ?? null,+ // 发起意图在本地记录并全程保留(server 回放/终止态更新都不改写):+ // add 流终止态即使带 teamId 也是新增失败, 重试必须回 add 流程。+ // 进程重启/重连后内存 pendingBind 丢失时 fallback 恒为 add —— 不能靠+ // teamId 猜: rebind 流丢失意图后走 add 授权页不预选, 用户仍能选到目标+ // team 完成重绑(仅少一步预选); add 流被误判 rebind 则授权页固定到旧+ // workspace, 用户无法切换, 完全卡死。两害相权取前者。+ intent: pendingBind?.intent ?? 'add',};// 授权/安装看门狗跟随真实状态(语义同老路径, 见各 arm 函数注释)if (state !== 'pending') clearBindWatchdog();diff --git a/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx b/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsxindex 7c53a9e133..7a7f973d57 100644--- a/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx+++ b/apps/desktop/src/renderer/components/settings/HookConnectionsSection.tsx@@ -50,10 +50,7 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';import { toast } from '@/lib/toast';import { cn } from '@/lib/utils';import { extractIpcError } from '@/utils/ipcError';-import type {- ImDefaultAgentKind,- ImDefaultSettingsState,-} from '../../../shared/imDefaultSettings';+import type { ImDefaultAgentKind, ImDefaultSettingsState } from '../../../shared/imDefaultSettings';import { acknowledgeXUsage, isXUsageAcknowledged } from '@/state/xUsageNotice';import { XUsageGuide } from './XUsageGuide';import {@@ -169,7 +166,11 @@ export function legacyOverrideRows(state: ImDefaultSettingsState): LegacyOverridconst rows: LegacyOverrideRow[] = [];for (const key of state.customizedKeys) {if (key === 'agentKind') {- rows.push({ kind: 'agentKind', current: state.agentKind, fallback: state.defaults.agentKind });+ rows.push({+ kind: 'agentKind',+ current: state.agentKind,+ fallback: state.defaults.agentKind,+ });continue;}if (key === 'permissionMode') {@@ -186,8 +187,11 @@ export function legacyOverrideRows(state: ImDefaultSettingsState): LegacyOverridconst fallback = state.defaults.agents[agent];if (!current || !fallback) continue;// 只列真的不一样的子字段 —— 把三项全列出来会让人以为都被改过。- const fields: Array<{ field: 'model' | 'effort' | 'source'; current: string; fallback: string }> =- [];+ const fields: Array<{+ field: 'model' | 'effort' | 'source';+ current: string;+ fallback: string;+ }> = [];if (current.model !== fallback.model) {fields.push({ field: 'model', current: current.model, fallback: fallback.model });}@@ -336,7 +340,13 @@ function handleRadioGroupKeyDown(e: KeyboardEvent<HTMLDivElement>): void {if (options.length === 0) return;const current = options.indexOf(document.activeElement as HTMLButtonElement);// 焦点还不在任何一项上(例如刚点进容器): 从选中项开始, 没有选中项就从头。- const from = current >= 0 ? current : Math.max(0, options.findIndex((o) => o.getAttribute('aria-checked') === 'true'));+ const from =+ current >= 0+ ? current+ : Math.max(+ 0,+ options.findIndex((o) => o.getAttribute('aria-checked') === 'true'),+ );const next = options[(from + (forward ? 1 : -1) + options.length) % options.length];e.preventDefault();next.focus();@@ -389,7 +399,7 @@ function DefaultWorkspaceRadio({/** 小号胶囊按钮(「复制链接 / 安装 Slack App」共用)。 */const pillBtn =- 'flex h-6 shrink-0 items-center rounded-full border border-[var(--border-default)] px-2.5 text-11 text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)] disabled:opacity-50';+ 'flex h-6 shrink-0 items-center rounded-full border border-[var(--border-default)] px-2.5 text-11 text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)] disabled:opacity-50';const RESERVED_WORKSPACE_ALIASES = new Set([HOOK_CHAT_WORKSPACE_ALIAS,@@ -453,6 +463,8 @@ export function HookConnectionsSection() {* 让授权进度与兜底动作(复制链接 / 安装引导)立即可见。*/const [expandedCard, setExpandedCard] = useState<CindyImCard | null>(null);+ const [slackAuthActionPending, setSlackAuthActionPending] = useState(false);+ const slackAuthActionInFlightRef = useRef(false);const toggleCard = (card: CindyImCard) =>setExpandedCard((current) => (current === card ? null : card));/** Older IPC replies and server pushes must never overwrite a newer view transition. */@@ -521,22 +533,46 @@ export function HookConnectionsSection() {[applyView, t],);+ /** Slack 授权相关动作共用一个门,避免开关/添加/重绑交叉点击创建多轮 OAuth。 */+ const runSlackAuthAction = useCallback(+ (+ action: () => Promise<{ hook: SlackHookView }>,+ errorKey:+ | 'settings.remoteControl.hook.toast.toggleFailed'+ | 'settings.remoteControl.hook.toast.actionFailed',+ expand = false,+ ) => {+ if (slackAuthActionInFlightRef.current) return;+ slackAuthActionInFlightRef.current = true;+ setSlackAuthActionPending(true);+ if (expand) setExpandedCard('slack');+ const requestedAtRevision = ++viewRevisionRef.current;+ void action()+ .then((res) => {+ if (viewRevisionRef.current === requestedAtRevision) applyView(res.hook);+ })+ .catch(() => toast.error(t(errorKey)))+ .finally(() => {+ slackAuthActionInFlightRef.current = false;+ setSlackAuthActionPending(false);+ });+ },+ [applyView, t],+ );+/*** 开关即绑定(即时生效): 开 = 连接, main 连上后自动拉起浏览器 Slack 授权;* 关 = 解除绑定并断开(main 发 bind.revoke), 再开需重新授权。*/const handleToggle = useCallback((enabled: boolean) => {- if (enabled) setExpandedCard('slack');- const requestedAtRevision = ++viewRevisionRef.current;- void window.electronAPI.hookControl- .setEnabled(enabled)- .then((res) => {- if (viewRevisionRef.current === requestedAtRevision) applyView(res.hook);- })- .catch(() => toast.error(t('settings.remoteControl.hook.toast.toggleFailed')));+ runSlackAuthAction(+ () => window.electronAPI.hookControl.setEnabled(enabled),+ 'settings.remoteControl.hook.toast.toggleFailed',+ enabled,+ );},- [applyView, t],+ [runSlackAuthAction],);// ── (multi-team)派生视图 ────────────────────────────────────────────────@@ -573,6 +609,20 @@ export function HookConnectionsSection() {[applyView, t],);+ /** Terminal Slack authorization states restart through the matching main-process flow. */+ const handleReauthorize = useCallback(+ (mode: 'enable' | 'add' | 'rebind', teamId?: string) => {+ const action =+ mode === 'enable'+ ? () => window.electronAPI.hookControl.setEnabled(true)+ : mode === 'rebind' && teamId+ ? () => window.electronAPI.hookControl.rebindTeam(teamId)+ : () => window.electronAPI.hookControl.addBinding();+ runSlackAuthAction(action, 'settings.remoteControl.hook.toast.actionFailed', true);+ },+ [runSlackAuthAction],+ );+/*** 默认工作目录写入(Telegram / X)。*@@ -690,12 +740,15 @@ export function HookConnectionsSection() {if (decision.installUrl) void window.electronAPI.openExternal(decision.installUrl);} else if (decision.multiUi) {// multi-team: 取消只作废这次"添加 workspace"尝试, 既有绑定不受影响- runHookAction(() => window.electronAPI.hookControl.cancelPendingBind());+ runSlackAuthAction(+ () => window.electronAPI.hookControl.cancelPendingBind(),+ 'settings.remoteControl.hook.toast.actionFailed',+ );} else {handleToggle(false);}})();- }, [awaitingInstall, confirm, handleToggle, runHookAction, t]);+ }, [awaitingInstall, confirm, handleToggle, runSlackAuthAction, t]);/*** X 的「用法与公开风险」确认门:绑定成功那一刻拦一次, 让用户明确点过「我明白」。@@ -926,54 +979,54 @@ export function HookConnectionsSection() {bindingState === 'expired' ||bindingState === 'failed' ||bindingState === 'revoked';- // 顶部状态行合并的绑定态(仅连上时有意义; 失败态走下方错误行, 不并进这里;- // "等安装"是保持在线的中间态, 单独给「待安装 App」)。multi-team 分支:+ // 顶部状态行的绑定态独立于 transport: 已绑定账号在重连/错误/待机时仍是已绑定。+ // 失败态走下方错误行; "等安装"单独给「待安装 App」。multi-team 分支:// 单个绑定沿用「已绑定 {team} @{user}」; 多个绑定/有待处理项给数量摘要。- const bindingLabel =- hook.status !== 'connected'- ? null- : multiUi- ? activeTeams.length === 1 && pendingIssueCount === 0- ? t('settings.remoteControl.hook.statusBoundTeam', {- name: activeTeams[0].slackUserName ?? activeTeams[0].slackUserId,- team: activeTeams[0].teamName ?? activeTeams[0].teamId,- })- : activeTeams.length > 0- ? `${t('settings.remoteControl.hook.multi.statusWorkspaces', { count: activeTeams.length })}${- pendingIssueCount > 0- ? t('settings.remoteControl.hook.multi.statusPendingSuffix', {- count: pendingIssueCount,- })- : ''- }`- : hook.pendingBind?.state === 'pending'- ? t('settings.remoteControl.hook.authorizing')- : isNotInstalled- ? t('settings.remoteControl.hook.notInstalled.status')- : t('settings.remoteControl.hook.statusUnbound')- : bindingState === 'confirmed'- ? hook.binding?.teamName- ? t('settings.remoteControl.hook.statusBoundTeam', {- name: hook.binding?.slackUserName ?? hook.binding?.slackUserId ?? '',- team: hook.binding.teamName,- })- : t('settings.remoteControl.hook.statusBound', {- name: hook.binding?.slackUserName ?? hook.binding?.slackUserId ?? '',- })- : bindingState === 'pending'- ? t('settings.remoteControl.hook.authorizing')- : isNotInstalled- ? t('settings.remoteControl.hook.notInstalled.status')- : t('settings.remoteControl.hook.statusUnbound');+ const bindingLabel = multiUi+ ? activeTeams.length === 1 && pendingIssueCount === 0+ ? t('settings.remoteControl.hook.statusBoundTeam', {+ name: activeTeams[0].slackUserName ?? activeTeams[0].slackUserId,+ team: activeTeams[0].teamName ?? activeTeams[0].teamId,+ })+ : activeTeams.length > 0+ ? `${t('settings.remoteControl.hook.multi.statusWorkspaces', { count: activeTeams.length })}${+ pendingIssueCount > 0+ ? t('settings.remoteControl.hook.multi.statusPendingSuffix', {+ count: pendingIssueCount,+ })+ : ''+ }`+ : hook.pendingBind?.state === 'pending'+ ? t('settings.remoteControl.hook.authorizing')+ : isNotInstalled+ ? t('settings.remoteControl.hook.notInstalled.status')+ : t('settings.remoteControl.hook.statusUnbound')+ : bindingState === 'confirmed'+ ? hook.binding?.teamName+ ? t('settings.remoteControl.hook.statusBoundTeam', {+ name: hook.binding?.slackUserName ?? hook.binding?.slackUserId ?? '',+ team: hook.binding.teamName,+ })+ : t('settings.remoteControl.hook.statusBound', {+ name: hook.binding?.slackUserName ?? hook.binding?.slackUserId ?? '',+ })+ : bindingState === 'pending'+ ? t('settings.remoteControl.hook.authorizing')+ : isNotInstalled+ ? t('settings.remoteControl.hook.notInstalled.status')+ : t('settings.remoteControl.hook.statusUnbound');/*** Slack 卡收起行摘要: 关闭态且本地还留有绑定(multi-team 关开关不清绑定)* 时给「已关闭 · N 个 workspace 绑定已保留」, 其余用绑定摘要(连接状态由* 徽章单独承载, 不再拼接)。*/- const slackSummary =+ const slackBindingSummary =!hook.enabled && multiUi && hook.bindings.length > 0? t('settings.remoteControl.hook.multi.statusOffKept', { count: hook.bindings.length }): bindingLabel;+ const slackSummary = t('settings.remoteControl.hook.accountStatus', {+ status: slackBindingSummary ?? t('settings.remoteControl.hook.statusUnbound'),+ });// transport 的稳定错误标识换成人话;其它瞬时网络错误保留原文供诊断。const errorText =hook.lastError === 'not logged in'@@ -1197,91 +1250,91 @@ export function HookConnectionsSection() {}: {})}>- {/* 内置「对话」伪目录: 与真实目录同级, 常驻第一位, 不可改名/删除;+ {/* 内置「对话」伪目录: 与真实目录同级, 常驻第一位, 不可改名/删除;Slack 那头对应保留别名 chat, 偏好与 /model 选 chat 同一份 */}- <div className="flex flex-col gap-2 rounded-xl border border-[var(--border-default)] p-2.5">- <div className="flex items-center gap-1.5">- {defaultWorkspace?.mode === 'row' ? (- <DefaultWorkspaceRadio- selected={defaultWorkspace.value === null}- label={t('settings.remoteControl.hook.form.defaultWorkspaceRadioAria', {- name: t('settings.tina.chat.title'),- })}- onSelect={() => void setProviderDefaultWorkspace(defaultWorkspace.provider, null)}- />- ) : null}- <span className="w-36 shrink-0 px-2.5 py-1.5 text-13 font-medium text-[var(--text-primary)]">- {t('settings.tina.chat.title')}- </span>- <span className="min-w-0 flex-1 truncate text-12 text-[var(--text-tertiary)]">- {t('settings.tina.chat.description')}- </span>- </div>- <WorkspacePrefsEditor- alias={HOOK_CHAT_WORKSPACE_ALIAS}- state={prefsState}- maxVisibleModelRows={chatMaxVisibleModelRows}- />- </div>- {rows.map((row, i) => (- <div- key={row.dir}- className="flex flex-col gap-2 rounded-xl border border-[var(--border-default)] p-2.5"- >+ <div className="flex flex-col gap-2 rounded-xl border border-[var(--border-default)] p-2.5"><div className="flex items-center gap-1.5">{defaultWorkspace?.mode === 'row' ? (<DefaultWorkspaceRadio- // **只认已保存的 alias → dir 映射**, 不看输入框里的临时值: 别名改了- // 但还没 blur 落盘时, 拿它当选中判据会把未保存的名字显示成已选中,- // 点下去还会把 workspaces 里不存在的别名发给 store(直接抛校验错)。- // 未保存的新行(还没有对应映射)不给选 —— 先落盘再设默认。- selected={- savedAliasOf(row.dir) !== null &&- defaultWorkspace.value === savedAliasOf(row.dir)- }- disabled={savedAliasOf(row.dir) === null}+ selected={defaultWorkspace.value === null}label={t('settings.remoteControl.hook.form.defaultWorkspaceRadioAria', {- name: savedAliasOf(row.dir) ?? row.alias.trim(),+ name: t('settings.tina.chat.title'),})}- onSelect={() => {- const saved = savedAliasOf(row.dir);- if (saved === null) return;- void setProviderDefaultWorkspace(defaultWorkspace.provider, saved);- }}+ onSelect={() => void setProviderDefaultWorkspace(defaultWorkspace.provider, null)}/>) : null}- <input- value={row.alias}- onChange={(e) => {- const next = rows.slice();- next[i] = { ...next[i], alias: e.target.value };- setRows(next);- }}- onBlur={() => void saveWorkspaces(rows)}- maxLength={32}- className="shrink-0 w-36 rounded-lg border border-transparent px-2.5 py-1.5 text-13 text-[var(--settings-input-text)] bg-transparent outline-none hover:border-[var(--border-default)] focus:border-[var(--border-default)] transition-colors"- />- <button- type="button"- onClick={() => void handleChangeDir(i)}- title={t('settings.remoteControl.hook.form.changeDir')}- className="min-w-0 flex-1 truncate text-left text-12 text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-primary)]"- >- {row.dir}- </button>- <button- type="button"- onClick={() => void handleRemoveWorkspace(i)}- aria-label={t('settings.remoteControl.hook.form.removeWorkspace')}- className="shrink-0 rounded-md p-1.5 text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-primary)]"- >- <Trash2 size={13} />- </button>+ <span className="w-36 shrink-0 px-2.5 py-1.5 text-13 font-medium text-[var(--text-primary)]">+ {t('settings.tina.chat.title')}+ </span>+ <span className="min-w-0 flex-1 truncate text-12 text-[var(--text-tertiary)]">+ {t('settings.tina.chat.description')}+ </span></div>- {/* 会话偏好编辑行: 偏好按别名归属(与 Slack /model 卡同键) */}- <WorkspacePrefsEditor alias={row.alias.trim()} state={prefsState} />+ <WorkspacePrefsEditor+ alias={HOOK_CHAT_WORKSPACE_ALIAS}+ state={prefsState}+ maxVisibleModelRows={chatMaxVisibleModelRows}+ /></div>- ))}+ {rows.map((row, i) => (+ <div+ key={row.dir}+ className="flex flex-col gap-2 rounded-xl border border-[var(--border-default)] p-2.5"+ >+ <div className="flex items-center gap-1.5">+ {defaultWorkspace?.mode === 'row' ? (+ <DefaultWorkspaceRadio+ // **只认已保存的 alias → dir 映射**, 不看输入框里的临时值: 别名改了+ // 但还没 blur 落盘时, 拿它当选中判据会把未保存的名字显示成已选中,+ // 点下去还会把 workspaces 里不存在的别名发给 store(直接抛校验错)。+ // 未保存的新行(还没有对应映射)不给选 —— 先落盘再设默认。+ selected={+ savedAliasOf(row.dir) !== null &&+ defaultWorkspace.value === savedAliasOf(row.dir)+ }+ disabled={savedAliasOf(row.dir) === null}+ label={t('settings.remoteControl.hook.form.defaultWorkspaceRadioAria', {+ name: savedAliasOf(row.dir) ?? row.alias.trim(),+ })}+ onSelect={() => {+ const saved = savedAliasOf(row.dir);+ if (saved === null) return;+ void setProviderDefaultWorkspace(defaultWorkspace.provider, saved);+ }}+ />+ ) : null}+ <input+ value={row.alias}+ onChange={(e) => {+ const next = rows.slice();+ next[i] = { ...next[i], alias: e.target.value };+ setRows(next);+ }}+ onBlur={() => void saveWorkspaces(rows)}+ maxLength={32}+ className="shrink-0 w-36 rounded-lg border border-transparent px-2.5 py-1.5 text-13 text-[var(--settings-input-text)] bg-transparent outline-none hover:border-[var(--border-default)] focus:border-[var(--border-default)] transition-colors"+ />+ <button+ type="button"+ onClick={() => void handleChangeDir(i)}+ title={t('settings.remoteControl.hook.form.changeDir')}+ className="min-w-0 flex-1 truncate text-left text-12 text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-primary)]"+ >+ {row.dir}+ </button>+ <button+ type="button"+ onClick={() => void handleRemoveWorkspace(i)}+ aria-label={t('settings.remoteControl.hook.form.removeWorkspace')}+ className="shrink-0 rounded-md p-1.5 text-[var(--text-tertiary)] transition-colors hover:text-[var(--text-primary)]"+ >+ <Trash2 size={13} />+ </button>+ </div>+ {/* 会话偏好编辑行: 偏好按别名归属(与 Slack /model 卡同键) */}+ <WorkspacePrefsEditor alias={row.alias.trim()} state={prefsState} />+ </div>+ ))}</div><buttontype="button"@@ -1511,12 +1564,15 @@ export function HookConnectionsSection() {status={<ChannelStatusBadgetone={transportBadgeTone(hook.status)}- label={t(`settings.remoteControl.hook.status.${hook.status}`)}+ label={t('settings.remoteControl.hook.transportStatus', {+ status: t(`settings.remoteControl.hook.status.${hook.status}`),+ })}/>}headerAction={<Switchchecked={toggleChecked}+ disabled={slackAuthActionPending}onCheckedChange={(next) => {// 在途态(视觉关、意图开)点击会回传 next=true, 语义是"取消本轮// 授权/等待"而非重复开启 —— 统一关回; 其余情况按点击意图直传@@ -1599,13 +1655,30 @@ export function HookConnectionsSection() {) : null}{/* 取消授权 / 授权失败 / 超时 / 被新设备顶掉: 开关已自动弹回, 显示原因;- 绑定记录保留, 重新打开开关即自动重连并(未绑定时)重新发起授权 */}+ 绑定记录保留, 显式重新授权入口复用开关的启用与浏览器授权流程 */}{!multiUi && isBindingFailure && !isNotInstalled ? (<div className="flex flex-col gap-1">- <span className="text-11 leading-relaxed text-[var(--error-fg)]">- {hook.binding?.message ??- t(`settings.remoteControl.hook.binding.state.${bindingState}`)}- </span>+ <div className="flex items-center gap-2">+ <span className="min-w-0 flex-1 text-11 leading-relaxed text-[var(--error-fg)]">+ {bindingState === 'denied'+ ? t('settings.remoteControl.hook.binding.state.denied')+ : (hook.binding?.message ??+ t(`settings.remoteControl.hook.binding.state.${bindingState}`))}+ </span>+ <button+ type="button"+ onClick={() => handleReauthorize('enable')}+ disabled={slackAuthActionPending}+ aria-busy={slackAuthActionPending}+ className={pillBtn}+ >+ {t(+ slackAuthActionPending+ ? 'settings.remoteControl.hook.binding.reauthorizing'+ : 'settings.remoteControl.hook.binding.reauthorize',+ )}+ </button>+ </div><span className="text-11 leading-relaxed text-[var(--text-tertiary)]">{t('settings.remoteControl.hook.binding.retryHint')}</span>@@ -1621,10 +1694,27 @@ export function HookConnectionsSection() {hook.pendingBind !== null &&hook.pendingBind.state !== 'pending' ? (<div className="flex flex-col gap-1">- <span className="text-11 leading-relaxed text-[var(--error-fg)]">- {hook.pendingBind.message ??- t(`settings.remoteControl.hook.binding.state.${hook.pendingBind.state}`)}- </span>+ <div className="flex items-center gap-2">+ <span className="min-w-0 flex-1 text-11 leading-relaxed text-[var(--error-fg)]">+ {hook.pendingBind.state === 'denied'+ ? t('settings.remoteControl.hook.binding.state.denied')+ : (hook.pendingBind.message ??+ t(`settings.remoteControl.hook.binding.state.${hook.pendingBind.state}`))}+ </span>+ <button+ type="button"+ onClick={() => handleReauthorize('enable')}+ disabled={slackAuthActionPending}+ aria-busy={slackAuthActionPending}+ className={pillBtn}+ >+ {t(+ slackAuthActionPending+ ? 'settings.remoteControl.hook.binding.reauthorizing'+ : 'settings.remoteControl.hook.binding.reauthorize',+ )}+ </button>+ </div><span className="text-11 leading-relaxed text-[var(--text-tertiary)]">{t('settings.remoteControl.hook.binding.retryHint')}</span>@@ -1659,8 +1749,13 @@ export function HookConnectionsSection() {<buttontype="button"onClick={() =>- runHookAction(() => window.electronAPI.hookControl.rebindTeam(b.teamId))+ runSlackAuthAction(+ () => window.electronAPI.hookControl.rebindTeam(b.teamId),+ 'settings.remoteControl.hook.toast.actionFailed',+ true,+ )}+ disabled={slackAuthActionPending}className={pillBtn}>{t('settings.remoteControl.hook.multi.rebind')}@@ -1690,8 +1785,12 @@ export function HookConnectionsSection() {<buttontype="button"onClick={() =>- runHookAction(() => window.electronAPI.hookControl.cancelPendingBind())+ runSlackAuthAction(+ () => window.electronAPI.hookControl.cancelPendingBind(),+ 'settings.remoteControl.hook.toast.actionFailed',+ )}+ disabled={slackAuthActionPending}className={pillBtn}>{t('settings.remoteControl.hook.multi.cancelPending')}@@ -1724,8 +1823,12 @@ export function HookConnectionsSection() {<buttontype="button"onClick={() =>- runHookAction(() => window.electronAPI.hookControl.cancelPendingBind())+ runSlackAuthAction(+ () => window.electronAPI.hookControl.cancelPendingBind(),+ 'settings.remoteControl.hook.toast.actionFailed',+ )}+ disabled={slackAuthActionPending}className={pillBtn}>{t('settings.remoteControl.hook.multi.cancelPending')}@@ -1750,14 +1853,44 @@ export function HookConnectionsSection() {hook.pendingBind.teamId ??'',})- : (hook.pendingBind.message ??- t(`settings.remoteControl.hook.binding.state.${hook.pendingBind.state}`))}+ : hook.pendingBind.state === 'denied'+ ? t('settings.remoteControl.hook.binding.state.denied')+ : (hook.pendingBind.message ??+ t(`settings.remoteControl.hook.binding.state.${hook.pendingBind.state}`))}</span>+ <button+ type="button"+ onClick={() => {+ const pending = hook.pendingBind;+ // 重试入口由发起意图决定, 不能靠 teamId 猜: add 流的终止态+ // (denied/expired/failed/already-bound)即使 server 回显 teamId+ // 也是「新增」失败, 重试必须回 add 流程让授权页可切换 workspace;+ // 只有发起时就 pin 到 team 的定向重绑才走 rebindTeam。+ const rebindIntent = pending?.intent === 'rebind';+ handleReauthorize(+ rebindIntent ? 'rebind' : 'add',+ rebindIntent ? pending?.teamId ?? undefined : undefined,+ );+ }}+ disabled={slackAuthActionPending}+ aria-busy={slackAuthActionPending}+ className={pillBtn}+ >+ {t(+ slackAuthActionPending+ ? 'settings.remoteControl.hook.binding.reauthorizing'+ : 'settings.remoteControl.hook.binding.reauthorize',+ )}+ </button><buttontype="button"onClick={() =>- runHookAction(() => window.electronAPI.hookControl.cancelPendingBind())+ runSlackAuthAction(+ () => window.electronAPI.hookControl.cancelPendingBind(),+ 'settings.remoteControl.hook.toast.actionFailed',+ )}+ disabled={slackAuthActionPending}className={pillBtn}>{t('settings.remoteControl.hook.multi.dismiss')}@@ -1767,8 +1900,15 @@ export function HookConnectionsSection() {{hook.serverMultiTeam ? (<buttontype="button"- onClick={() => runHookAction(() => window.electronAPI.hookControl.addBinding())}- className="flex h-7 w-fit items-center gap-1.5 rounded-full border border-[var(--border-default)] px-3 text-12 text-[var(--text-secondary)] transition-colors hover:text-[var(--text-primary)]"+ onClick={() =>+ runSlackAuthAction(+ () => window.electronAPI.hookControl.addBinding(),+ 'settings.remoteControl.hook.toast.actionFailed',+ true,+ )+ }+ disabled={slackAuthActionPending}+ className={`${pillBtn} h-7 gap-1.5 px-3 text-12`}><Plus size={12} />{t('settings.remoteControl.hook.multi.addWorkspace')}diff --git a/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx b/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsxindex e48ad1385d..93af3f8b36 100644--- a/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx+++ b/apps/desktop/src/renderer/components/settings/__tests__/HookConnectionsSection.test.tsx@@ -13,6 +13,8 @@ const ipc = vi.hoisted(() => ({providerBindStart: vi.fn(),providerBindCancel: vi.fn(),providerBindRevoke: vi.fn(),+ addBinding: vi.fn(),+ rebindTeam: vi.fn(),cancelPendingBind: vi.fn(),revokeTeam: vi.fn(),openProviderAction: vi.fn(),@@ -165,6 +167,9 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {ipc.setEnabled.mockResolvedValue({ hook: BASE_HOOK });ipc.setLifecycleAnnouncement.mockResolvedValue({ hook: BASE_HOOK });ipc.providerBindRevoke.mockResolvedValue({ hook: BASE_HOOK });+ ipc.addBinding.mockResolvedValue({ hook: BASE_HOOK });+ ipc.rebindTeam.mockResolvedValue({ hook: BASE_HOOK });+ ipc.cancelPendingBind.mockResolvedValue({ hook: BASE_HOOK });ipc.revokeTeam.mockResolvedValue({ hook: BASE_HOOK });ipc.openProviderAction.mockResolvedValue(undefined);// 默认: 没有存量 global override(绝大多数设备) —— 收尾入口一次都不该露出来@@ -180,6 +185,8 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {providerBindStart: ipc.providerBindStart,providerBindCancel: ipc.providerBindCancel,providerBindRevoke: ipc.providerBindRevoke,+ addBinding: ipc.addBinding,+ rebindTeam: ipc.rebindTeam,cancelPendingBind: ipc.cancelPendingBind,revokeTeam: ipc.revokeTeam,openProviderAction: ipc.openProviderAction,@@ -509,6 +516,12 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {render(<HookConnectionsSection />);await waitFor(() => expect(dialog.confirm).toHaveBeenCalledOnce());+ await expandChannelCard(SLACK_CARD);+ expect(+ screen.queryByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ ).toBeNull();act(() => {pushStatus?.(awaitingInstall('https://hook.example.test/slack/install?team=NEW'));});@@ -546,6 +559,7 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {reason: 'not-installed',installUrl: `https://hook.example.test/slack/install?team=${teamId}`,teamId,+ intent: 'add',},binding: {state: 'failed',@@ -598,6 +612,7 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {reason: 'not-installed',installUrl: 'https://hook.example.test/slack/install?team=TEAM_A',teamId: 'TEAM_A',+ intent: 'add',},binding: {state: 'failed',@@ -636,6 +651,565 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {expect(ipc.openExternal).toHaveBeenCalledOnce();});+ it('offers a direct Slack reauthorization action after single-workspace authorization is denied', async () => {+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ status: 'connected',+ binding: {+ state: 'denied',+ slackUserId: null,+ slackUserName: null,+ message: 'server-specific cancellation text',+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamName: null,+ },+ },+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ expect(+ await screen.findByText('settings.remoteControl.hook.binding.state.denied'),+ ).toBeTruthy();+ expect(screen.queryByText('server-specific cancellation text')).toBeNull();+ expect(tCalls).toContainEqual({+ key: 'settings.remoteControl.hook.transportStatus',+ vars: { status: 'settings.remoteControl.hook.status.connected' },+ });+ expect(tCalls).toContainEqual({+ key: 'settings.remoteControl.hook.accountStatus',+ vars: { status: 'settings.remoteControl.hook.statusUnbound' },+ });+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );++ await waitFor(() => expect(ipc.setEnabled).toHaveBeenCalledWith(true));+ expect(ipc.addBinding).not.toHaveBeenCalled();+ });++ it('keeps the confirmed Slack account visible while the transport reconnects', async () => {+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ enabled: true,+ status: 'connecting',+ binding: {+ state: 'confirmed',+ slackUserId: 'USER_BOUND',+ slackUserName: 'bound-user',+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamName: 'Bound workspace',+ },+ },+ });++ render(<HookConnectionsSection />);+ await waitFor(() =>+ expect(tCalls).toContainEqual({+ key: 'settings.remoteControl.hook.accountStatus',+ vars: { status: 'settings.remoteControl.hook.statusBoundTeam' },+ }),+ );+ expect(tCalls).toContainEqual({+ key: 'settings.remoteControl.hook.transportStatus',+ vars: { status: 'settings.remoteControl.hook.status.connecting' },+ });+ });++ it('keeps active Slack workspaces visible while the multi-workspace transport is offline', async () => {+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ enabled: true,+ status: 'error',+ lastError: 'network unavailable',+ serverMultiTeam: true,+ bindings: [+ {+ teamId: 'TEAM_BOUND',+ teamName: 'Bound workspace',+ slackUserId: 'USER_BOUND',+ slackUserName: 'bound-user',+ displaced: false,+ },+ ],+ },+ });++ render(<HookConnectionsSection />);+ await waitFor(() =>+ expect(tCalls).toContainEqual({+ key: 'settings.remoteControl.hook.accountStatus',+ vars: { status: 'settings.remoteControl.hook.statusBoundTeam' },+ }),+ );+ expect(tCalls).toContainEqual({+ key: 'settings.remoteControl.hook.transportStatus',+ vars: { status: 'settings.remoteControl.hook.status.error' },+ });+ });++ it('allows only one Slack reauthorization request while the action is in flight', async () => {+ let resolveEnable: ((value: { hook: SlackHookView }) => void) | undefined;+ ipc.setEnabled.mockReturnValue(+ new Promise<{ hook: SlackHookView }>((resolve) => {+ resolveEnable = resolve;+ }),+ );+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ status: 'connected',+ binding: {+ state: 'expired',+ slackUserId: null,+ slackUserName: null,+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamName: null,+ },+ },+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ const button = await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ });+ fireEvent.click(button);+ fireEvent.click(button);++ expect(ipc.setEnabled).toHaveBeenCalledTimes(1);+ expect(button).toHaveProperty('disabled', true);+ expect(button.getAttribute('aria-busy')).toBe('true');+ // The button is disabled while the action is in flight, so it must not be focusable.+ button.focus();+ expect(document.activeElement).not.toBe(button);+ await act(async () => {+ resolveEnable?.({ hook: BASE_HOOK });+ await Promise.resolve();+ });+ });++ it('does not let a stale reauthorization reply replace a newer Slack push', async () => {+ let pushStatus: ((view: SlackHookView) => void) | undefined;+ let resolveEnable: ((value: { hook: SlackHookView }) => void) | undefined;+ const deniedHook: SlackHookView = {+ ...BASE_HOOK,+ status: 'connected',+ binding: {+ state: 'denied',+ slackUserId: null,+ slackUserName: null,+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamName: null,+ },+ };+ ipc.get.mockResolvedValue({ hook: deniedHook });+ ipc.setEnabled.mockReturnValue(+ new Promise<{ hook: SlackHookView }>((resolve) => {+ resolveEnable = resolve;+ }),+ );+ ipc.onStatusChanged.mockImplementation((listener: (view: SlackHookView) => void) => {+ pushStatus = listener;+ return () => {};+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );+ act(() => {+ pushStatus?.({+ ...BASE_HOOK,+ enabled: true,+ status: 'connected',+ binding: {+ state: 'confirmed',+ slackUserId: 'USER_NEW',+ slackUserName: 'new-user',+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamName: 'New workspace',+ },+ });+ });+ await act(async () => {+ resolveEnable?.({ hook: deniedHook });+ await Promise.resolve();+ });++ expect(+ screen.queryByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ ).toBeNull();+ });++ it('restarts the initial multi-workspace authorization through the existing enable flow', async () => {+ const denied = {+ state: 'denied' as const,+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamId: null,+ intent: 'add',+ };+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ status: 'connected',+ serverMultiTeam: true,+ pendingBind: denied,+ binding: {+ ...denied,+ slackUserId: null,+ slackUserName: null,+ teamName: null,+ },+ },+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );++ await waitFor(() => expect(ipc.setEnabled).toHaveBeenCalledWith(true));+ expect(ipc.addBinding).not.toHaveBeenCalled();+ });++ it('retries a failed additional Slack workspace without disturbing active bindings', async () => {+ const denied = {+ state: 'denied' as const,+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamId: null,+ intent: 'add',+ };+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ enabled: true,+ status: 'connected',+ serverMultiTeam: true,+ bindings: [+ {+ teamId: 'TEAM_ACTIVE',+ teamName: 'Active workspace',+ slackUserId: 'USER_ACTIVE',+ slackUserName: 'active-user',+ displaced: false,+ },+ ],+ pendingBind: denied,+ binding: {+ ...denied,+ slackUserId: null,+ slackUserName: null,+ teamName: null,+ },+ },+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );++ await waitFor(() => expect(ipc.addBinding).toHaveBeenCalledOnce());+ expect(ipc.setEnabled).not.toHaveBeenCalled();+ });++ it('retries a pinned Slack workspace authorization with rebindTeam', async () => {+ const denied = {+ state: 'denied' as const,+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamId: 'TEAM_PINNED',+ intent: 'rebind',+ };+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ enabled: true,+ status: 'connected',+ serverMultiTeam: true,+ bindings: [+ {+ teamId: 'TEAM_ACTIVE',+ teamName: 'Active workspace',+ slackUserId: 'USER_ACTIVE',+ slackUserName: 'active-user',+ displaced: false,+ },+ ],+ pendingBind: denied,+ binding: {+ ...denied,+ slackUserId: null,+ slackUserName: null,+ teamName: null,+ },+ },+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );++ await waitFor(() => expect(ipc.rebindTeam).toHaveBeenCalledWith('TEAM_PINNED'));+ expect(ipc.addBinding).not.toHaveBeenCalled();+ expect(ipc.setEnabled).not.toHaveBeenCalled();+ });++ // The server may include the collided teamId in an add failure; that identity+ // describes the conflict, not a request to pin the next OAuth flow to that team.+ it('re-runs the add flow instead of rebinding when an add attempt fails as already-bound', async () => {+ const alreadyBound = {+ state: 'failed' as const,+ message: null,+ authorizeUrl: null,+ reason: 'already-bound',+ installUrl: null,+ teamId: 'TEAM_ACTIVE',+ intent: 'add',+ };+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ enabled: true,+ status: 'connected',+ serverMultiTeam: true,+ bindings: [+ {+ teamId: 'TEAM_ACTIVE',+ teamName: 'Active workspace',+ slackUserId: 'USER_ACTIVE',+ slackUserName: 'active-user',+ displaced: false,+ },+ ],+ pendingBind: alreadyBound,+ binding: {+ ...alreadyBound,+ slackUserId: null,+ slackUserName: null,+ teamName: null,+ },+ },+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );++ await waitFor(() => expect(ipc.addBinding).toHaveBeenCalledOnce());+ expect(ipc.rebindTeam).not.toHaveBeenCalled();+ expect(ipc.setEnabled).not.toHaveBeenCalled();+ });++ // An add attempt that ends denied/expired/failed also carries the collided+ // teamId from the server reply; the retry must stay in the add flow so the+ // user can pick a different workspace, not pin the OAuth page to that team.+ it('keeps the retry in the add flow when a terminal add state echoes a teamId', async () => {+ const deniedWithTeam = {+ state: 'denied' as const,+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamId: 'TEAM_ECHOED',+ intent: 'add' as const,+ };+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ enabled: true,+ status: 'connected',+ serverMultiTeam: true,+ bindings: [+ {+ teamId: 'TEAM_ACTIVE',+ teamName: 'Active workspace',+ slackUserId: 'USER_ACTIVE',+ slackUserName: 'active-user',+ displaced: false,+ },+ ],+ pendingBind: deniedWithTeam,+ binding: {+ ...deniedWithTeam,+ slackUserId: null,+ slackUserName: null,+ teamName: null,+ },+ },+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );++ await waitFor(() => expect(ipc.addBinding).toHaveBeenCalledOnce());+ expect(ipc.rebindTeam).not.toHaveBeenCalled();+ expect(ipc.setEnabled).not.toHaveBeenCalled();+ });++ it('blocks conflicting Slack authorization controls while reauthorization is in flight', async () => {+ let resolveAdd: ((value: { hook: SlackHookView }) => void) | undefined;+ ipc.addBinding.mockReturnValue(+ new Promise<{ hook: SlackHookView }>((resolve) => {+ resolveAdd = resolve;+ }),+ );+ const denied = {+ state: 'denied' as const,+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamId: null,+ intent: 'add',+ };+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ enabled: true,+ status: 'connected',+ serverMultiTeam: true,+ bindings: [+ {+ teamId: 'TEAM_ACTIVE',+ teamName: 'Active workspace',+ slackUserId: 'USER_ACTIVE',+ slackUserName: 'active-user',+ displaced: false,+ },+ ],+ pendingBind: denied,+ binding: {+ ...denied,+ slackUserId: null,+ slackUserName: null,+ teamName: null,+ },+ },+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );+ const toggle = screen.getByRole('switch', {+ name: 'settings.remoteControl.hook.toggleAria',+ });+ const addWorkspace = screen.getByRole('button', {+ name: 'settings.remoteControl.hook.multi.addWorkspace',+ });+ const dismiss = screen.getByRole('button', {+ name: 'settings.remoteControl.hook.multi.dismiss',+ });+ expect(toggle).toHaveProperty('disabled', true);+ expect(addWorkspace).toHaveProperty('disabled', true);+ expect(dismiss).toHaveProperty('disabled', true);+ fireEvent.click(toggle);+ fireEvent.click(addWorkspace);+ fireEvent.click(dismiss);++ expect(ipc.addBinding).toHaveBeenCalledTimes(1);+ expect(ipc.setEnabled).not.toHaveBeenCalled();+ expect(ipc.cancelPendingBind).not.toHaveBeenCalled();+ await act(async () => {+ resolveAdd?.({ hook: BASE_HOOK });+ await Promise.resolve();+ });+ });++ it('unlocks Slack reauthorization after an IPC failure', async () => {+ ipc.setEnabled+ .mockRejectedValueOnce(new Error('offline'))+ .mockResolvedValueOnce({ hook: BASE_HOOK });+ ipc.get.mockResolvedValue({+ hook: {+ ...BASE_HOOK,+ status: 'connected',+ binding: {+ state: 'expired',+ slackUserId: null,+ slackUserName: null,+ message: null,+ authorizeUrl: null,+ reason: null,+ installUrl: null,+ teamName: null,+ },+ },+ });++ render(<HookConnectionsSection />);+ await expandChannelCard(SLACK_CARD);+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );+ await waitFor(() => expect(toast.error).toHaveBeenCalledOnce());+ fireEvent.click(+ await screen.findByRole('button', {+ name: 'settings.remoteControl.hook.binding.reauthorize',+ }),+ );++ await waitFor(() => expect(ipc.setEnabled).toHaveBeenCalledTimes(2));+ });+it('shows the actionable Telegram transport error instead of only a generic failure', async () => {ipc.get.mockResolvedValue({hook: {@@ -1295,9 +1869,7 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {ipc.get.mockResolvedValue({ hook: xUnboundHook() });render(<HookConnectionsSection />);await expandChannelCard(TELEGRAM_CARD);- expect(- screen.queryByText('settings.remoteControl.hook.x.guide.riskPublicBody'),- ).toBeNull();+ expect(screen.queryByText('settings.remoteControl.hook.x.guide.riskPublicBody')).toBeNull();});it('说明区可选可复制: 弹窗根节点带 select-none, 不覆盖就复制不了 @askmycindy', async () => {@@ -1312,9 +1884,9 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {// 三组共同的祖先就是 XUsageGuide 的根const root = body.closest('.select-text');expect(root, 'XUsageGuide 根节点必须带 select-text 覆盖弹窗的 select-none').not.toBeNull();- expect(- root?.textContent?.includes('settings.remoteControl.hook.x.guide.withdrawBody'),- ).toBe(true);+ expect(root?.textContent?.includes('settings.remoteControl.hook.x.guide.withdrawBody')).toBe(+ true,+ );});it('说明区没有任何小于 12px 的字号: 这是逐句阅读的正文, 不是辅助标签', async () => {@@ -1328,9 +1900,9 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {ipc.get.mockResolvedValue({ hook: xUnboundHook() });render(<HookConnectionsSection />);await expandChannelCard(X_CARD);- const root = (- await screen.findByText('settings.remoteControl.hook.x.guide.usageBody')- ).closest('.select-text');+ const root = (await screen.findByText('settings.remoteControl.hook.x.guide.usageBody')).closest(+ '.select-text',+ );expect(root).not.toBeNull();const tooSmall: string[] = [];@@ -1360,9 +1932,7 @@ describe('HookConnectionsSection binding actions (Telegram / X)', () => {'withdrawLabel','withdrawBody',]) {- expect(- await screen.findByText(`settings.remoteControl.hook.x.guide.${key}`),- ).toBeTruthy();+ expect(await screen.findByText(`settings.remoteControl.hook.x.guide.${key}`)).toBeTruthy();}});diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7ea7db2cd6..9722bfa439 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3184,12 +3184,14 @@"copyLink": "Copy link","copied": "Link copied","state": {- "denied": "Authorization was cancelled on the Slack page",+ "denied": "Slack authorization was cancelled; the account is not linked","expired": "Authorization timed out, please reconnect","failed": "Binding failed","revoked": "Binding revoked"},- "retryHint": "Turn the switch back on to reconnect and link again."+ "reauthorize": "Reauthorize Slack",+ "reauthorizing": "Reauthorizing Slack…",+ "retryHint": "Reauthorize Slack to reconnect and link the account."},"toast": {"saveFailed": "Failed to save",@@ -3199,6 +3201,8 @@"loginRequired": "Sign in to your {{appName}} account first; the connection resumes automatically after login.","standbyHint": "Another Cindy instance on this computer is using the Slack connection. Close it, then turn this switch back on to take over.","authorizing": "Authorizing…",+ "transportStatus": "Transport: {{status}}",+ "accountStatus": "Slack Account: {{status}}","statusBound": "Linked as @{{name}}","statusBoundTeam": "Linked to {{team}} as @{{name}}","statusUnbound": "Not linked",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 191551ce88..8b7c541290 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3183,12 +3183,14 @@"copyLink": "リンクをコピー","copied": "リンクをコピーしました","state": {- "denied": "Slack の認可ページで認可がキャンセルされました",+ "denied": "Slack の認可はキャンセルされ、アカウントはまだ連携されていません","expired": "認可がタイムアウトしました。再接続してください","failed": "連携に失敗しました","revoked": "連携が解除されました"},- "retryHint": "スイッチをもう一度オンにすると再接続して連携し直せます。"+ "reauthorize": "Slack を再認可",+ "reauthorizing": "Slack を再認可しています…",+ "retryHint": "Slack を再認可すると再接続して連携し直せます。"},"toast": {"saveFailed": "保存に失敗しました",@@ -3198,6 +3200,8 @@"loginRequired": "先に {{appName}} アカウントにログインしてください。ログイン後、接続は自動的に復旧します。","standbyHint": "このコンピューター上の別の Cindy インスタンスが Slack 接続を使用しています。それを閉じてから、このスイッチをもう一度オンにすると引き継げます。","authorizing": "認可中…",+ "transportStatus": "通信接続:{{status}}",+ "accountStatus": "Slack アカウント:{{status}}","statusBound": "連携済み @{{name}}","statusBoundTeam": "{{team}} に連携済み @{{name}}","statusUnbound": "未連携",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex e5bda4178d..f25cee0dce 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3183,12 +3183,14 @@"copyLink": "링크 복사","copied": "링크를 복사했습니다","state": {- "denied": "Slack 인증 페이지에서 인증이 취소되었습니다",+ "denied": "Slack 인증이 취소되어 계정이 아직 연동되지 않았습니다","expired": "인증 시간이 초과되었습니다. 다시 연결하세요","failed": "연동에 실패했습니다","revoked": "연동이 해제되었습니다"},- "retryHint": "스위치를 다시 켜면 재연결하여 다시 연동합니다."+ "reauthorize": "Slack 재인증",+ "reauthorizing": "Slack 재인증 중…",+ "retryHint": "Slack을 재인증하면 다시 연결하고 계정을 연동합니다."},"toast": {"saveFailed": "저장 실패",@@ -3198,6 +3200,8 @@"loginRequired": "먼저 {{appName}} 계정에 로그인하세요. 로그인 후 연결이 자동으로 복구됩니다.","standbyHint": "이 컴퓨터의 다른 Cindy 인스턴스가 Slack 연결을 사용 중입니다. 해당 인스턴스를 닫은 뒤 이 스위치를 다시 켜면 연결을 이어받을 수 있습니다.","authorizing": "인증 중…",+ "transportStatus": "전송 연결: {{status}}",+ "accountStatus": "Slack 계정: {{status}}","statusBound": "연동됨 @{{name}}","statusBoundTeam": "{{team}}에 연동됨 @{{name}}","statusUnbound": "미연동",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex bd389b2f41..f0ee4dd4c6 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3183,12 +3183,14 @@"copyLink": "复制链接","copied": "链接已复制","state": {- "denied": "在 Slack 授权页取消了授权",+ "denied": "Slack 授权已取消,账号尚未绑定","expired": "授权超时,请重新连接","failed": "绑定失败","revoked": "绑定已解除"},- "retryHint": "重新打开开关即可再次连接并绑定。"+ "reauthorize": "重新授权 Slack",+ "reauthorizing": "正在重新授权 Slack…",+ "retryHint": "重新授权 Slack 即可再次连接并绑定。"},"toast": {"saveFailed": "保存失败",@@ -3198,6 +3200,8 @@"loginRequired": "需要先登录 {{appName}} 账号,连接会在登录后自动恢复。","standbyHint": "本机另一 Cindy 实例正在使用 Slack 连接。关闭它后,重新打开此开关即可接管。","authorizing": "授权中…",+ "transportStatus": "传输连接:{{status}}",+ "accountStatus": "Slack 账号:{{status}}","statusBound": "已绑定 @{{name}}","statusBoundTeam": "已绑定 {{team}} @{{name}}","statusUnbound": "未绑定",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 3ac43858f7..1ef9ef405c 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -3183,12 +3183,14 @@"copyLink": "複製連結","copied": "連結已複製","state": {- "denied": "在 Slack 授權頁取消了授權",+ "denied": "Slack 授權已取消,帳號尚未繫結","expired": "授權超時,請重新連線","failed": "繫結失敗","revoked": "繫結已解除"},- "retryHint": "重新開啟開關即可再次連線並繫結。"+ "reauthorize": "重新授權 Slack",+ "reauthorizing": "正在重新授權 Slack…",+ "retryHint": "重新授權 Slack 即可再次連線並繫結。"},"toast": {"saveFailed": "儲存失敗",@@ -3198,6 +3200,8 @@"loginRequired": "需要先登入 {{appName}} 帳號,連線會在登入後自動恢復。","standbyHint": "本機另一 Cindy 例項正在使用 Slack 連線。關閉它後,重新開啟此開關即可接管。","authorizing": "授權中…",+ "transportStatus": "傳輸連線:{{status}}",+ "accountStatus": "Slack 帳號:{{status}}","statusBound": "已繫結 @{{name}}","statusBoundTeam": "已繫結 {{team}} @{{name}}","statusUnbound": "未繫結",diff --git a/apps/desktop/src/shared/hookControlIpc.ts b/apps/desktop/src/shared/hookControlIpc.tsindex 6209dde6ba..2a18b28627 100644--- a/apps/desktop/src/shared/hookControlIpc.ts+++ b/apps/desktop/src/shared/hookControlIpc.ts@@ -259,6 +259,13 @@ export interface HookPendingBindView {installUrl: string | null;/** 重绑指定 team 时的目标 team; 添加新 workspace 时 null。 */teamId: string | null;+ /**+ * 本次授权流的发起意图 —— 决定终止态重试走哪个入口。add = 添加新+ * workspace(重试回 addBinding, 授权页可切换); rebind = 定向重绑指定+ * team(重试 pin 到 teamId)。不能靠 teamId 推断: add 流授权中途 server+ * 也会回显用户所选 team 的 teamId(含 denied/expired/failed 终止态)。+ */+ intent: 'add' | 'rebind';}/**