diff --git a/apps/web/tests/feishu-connection.e2e.ts b/apps/web/tests/feishu-connection.e2e.ts index 003c35f2ad..1f3c19192b 100644 --- a/apps/web/tests/feishu-connection.e2e.ts +++ b/apps/web/tests/feishu-connection.e2e.ts @@ -1,8 +1,8 @@ // Web e2e scenario: connecting the Feishu plugin from its page on the Plugins -// page. A stand-in lark-cli plays the CLI's app setup and device sign-in; the -// browser opens each Feishu page the Host offers, the stand-in finishes once -// its page is visited, the section reaches connected, and sign-out returns it -// to disconnected. Zero model calls. +// page. A stand-in lark-cli plays the CLI's app setup and device sign-in; each +// step starts from its own click, the browser opens that step's Feishu page, +// the stand-in finishes once its page is visited, the section reaches +// connected, and sign-out returns it to disconnected. Zero model calls. import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -97,7 +97,7 @@ describe.skipIf(process.platform === 'win32')('web e2e: Feishu plugin connection if (binDir !== undefined) await rm(binDir, { recursive: true, force: true }) }) - it('links an app, signs in from the plugin page, and signs out after confirmation', async () => { + it('links an app, then signs in from a second click, and signs out after confirmation', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-feishu-connection')) await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click() const panel = page.locator('[data-plugin-panel]') @@ -108,7 +108,10 @@ describe.skipIf(process.platform === 'win32')('web e2e: Feishu plugin connection const opened: Page[] = [] context.on('page', (popup) => { opened.push(popup) }) - await section.getByRole('button', { name: '连接飞书', exact: true }).click() + await section.getByRole('button', { name: '关联飞书应用', exact: true }).click() + await page.getByText('飞书应用已关联,下一步登录飞书账号', { exact: true }).waitFor({ timeout: 20_000 }) + expect(opened.map(popup => popup.url())).toEqual([SETUP_URL]) + await section.getByRole('button', { name: '登录飞书账号', exact: true }).click() await expect.poll(() => section.getAttribute('data-feishu-connection'), { timeout: 20_000 }).toBe('connected') expect(opened.map(popup => popup.url())).toEqual([SETUP_URL, SIGN_IN_URL]) await section.getByText('已登录为 测试用户。可以在对话中直接请 Agent 使用飞书。', { exact: true }).waitFor({ timeout: 10_000 }) diff --git a/docs/subsystems/credentials.md b/docs/subsystems/credentials.md index edf5a3799f..4f86d9a2a6 100644 --- a/docs/subsystems/credentials.md +++ b/docs/subsystems/credentials.md @@ -375,11 +375,25 @@ Registers the CLI and skills, and owns the account operations the Plugins page d ```ts cordis-catalog /** - * Check the account, set up an app if none is configured, then sign in. + * Check the account again without changing it. * @returns the operation identity. * @throws while another account operation runs. */ -@Remote connect(): FeishuOperationId +@Remote check(): FeishuOperationId + +/** + * Link an app through the CLI's setup page when none is configured; an existing app is kept. + * @returns the operation identity. + * @throws while another account operation runs. + */ +@Remote linkApp(): FeishuOperationId + +/** + * Sign the linked app's user in through the CLI's authorization page. + * @returns the operation identity. + * @throws while another account operation runs. + */ +@Remote signIn(): FeishuOperationId /** * Sign the default account out, which also signs out the user's own terminal. diff --git a/docs/subsystems/credentials.zh.md b/docs/subsystems/credentials.zh.md index 7978afc31c..e243bf24b2 100644 --- a/docs/subsystems/credentials.zh.md +++ b/docs/subsystems/credentials.zh.md @@ -375,11 +375,25 @@ Registers the CLI and skills, and owns the account operations the Plugins page d ```ts cordis-catalog /** - * Check the account, set up an app if none is configured, then sign in. + * Check the account again without changing it. * @returns the operation identity. * @throws while another account operation runs. */ -@Remote connect(): FeishuOperationId +@Remote check(): FeishuOperationId + +/** + * Link an app through the CLI's setup page when none is configured; an existing app is kept. + * @returns the operation identity. + * @throws while another account operation runs. + */ +@Remote linkApp(): FeishuOperationId + +/** + * Sign the linked app's user in through the CLI's authorization page. + * @returns the operation identity. + * @throws while another account operation runs. + */ +@Remote signIn(): FeishuOperationId /** * Sign the default account out, which also signs out the user's own terminal. diff --git a/packages/client/ui-feishu/README.i18n.yaml b/packages/client/ui-feishu/README.i18n.yaml index 8c51e4287b..da5b946f0a 100644 --- a/packages/client/ui-feishu/README.i18n.yaml +++ b/packages/client/ui-feishu/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-feishu/use-this-package: - en: 65395f9c93c28fda - zh: efcaff7773961365 + en: 9e06cad0d157f3bd + zh: 24717c77856fddc7 /deepseek-ai-dsh-client-ui-feishu/understand-the-implementation: en: 3599958abbfb2f52 zh: 68eae79d08462831 diff --git a/packages/client/ui-feishu/README.md b/packages/client/ui-feishu/README.md index 01e00a3307..df181a5735 100644 --- a/packages/client/ui-feishu/README.md +++ b/packages/client/ui-feishu/README.md @@ -25,18 +25,19 @@ This package is the browser row of the [Feishu plugin](../../connector/feishu/RE ## Use this package -Install the [Feishu plugin bundle](../../connector/feishu/README.md), which inserts this package as the `ui-feishu` row. Opening the plugin's page checks the account, and a tag beside the title reads Not connected, Connecting, Connected, Unconfirmed, or Not running. Switching the plugin on from the list while no account is connected offers **Connect Feishu**, which opens the plugin's page and starts the connection. +Install the [Feishu plugin bundle](../../connector/feishu/README.md), which inserts this package as the `ui-feishu` row. Opening the plugin's page checks the account, and a tag beside the title reads Not connected, Connecting, Connected, Unconfirmed, or Not running. Switching the plugin on from the list while no account is connected offers **Connect Feishu**, which opens the plugin's page and starts the next step. | Section state | Action | |---|---| | Checking connection | None | -| Not connected | **Connect Feishu** links an app when none exists, then signs in | -| Step 1: Link a Feishu app, or Step 2: Sign in to Feishu | The browser that started the connection opens each Feishu page once; **Open authorization page** opens it again, and **Cancel** ends the connection | +| Not connected, no app | **Link Feishu app** opens the Feishu page where the user creates or chooses an app, then stops | +| Not connected, app linked | **Sign in to Feishu** opens the Feishu authorization page | +| Step 1: Link a Feishu app, or Step 2: Sign in to Feishu | The browser that clicked opens the step's Feishu page once; **Open Feishu page** opens it again, and **Cancel** ends the step | | Connected | **Sign out** asks for confirmation, then signs out the CLI's default account | | Cannot confirm sign-in right now | **Retry** runs the connection again and keeps the existing setup and sign-in | | Feishu component not running | The Host's `feishu` row did not load; the section points to the component list for the reason, and **Retry** subscribes to the Host again | -Leaving the page does not cancel a connection, which the Host owns. A failed connection or sign-out shows **The action did not finish. Try again.** in the section; a failed page action shows a toast, and so does a finished connection or sign-out. The section notes that the account is shared with the Feishu CLI in the computer's terminal. +Leaving the page does not cancel a connection, which the Host owns. Each step opens its page from the user's own click, because browsers block a window that opens long after it. A failed step or sign-out shows **The action did not finish. Try again.** in the section; a failed page action shows a toast, and so does a finished app link, sign-in, or sign-out. The section notes that the account is shared with the Feishu CLI in the computer's terminal. ----- diff --git a/packages/client/ui-feishu/README.zh.md b/packages/client/ui-feishu/README.zh.md index 7da7284a0c..480eede13e 100644 --- a/packages/client/ui-feishu/README.zh.md +++ b/packages/client/ui-feishu/README.zh.md @@ -25,18 +25,19 @@ kind: "package-reference" ## 使用本包 -安装[飞书插件 bundle](../../connector/feishu/README.zh.md),它会把本包作为 `ui-feishu` 行插入。打开插件页面会检查账号,标题旁的标签显示未连接、连接中、已连接、待确认或未运行。在列表中开启插件且账号未连接时,会提示**连接飞书**,点击后打开插件页面并开始连接。 +安装[飞书插件 bundle](../../connector/feishu/README.zh.md),它会把本包作为 `ui-feishu` 行插入。打开插件页面会检查账号,标题旁的标签显示未连接、连接中、已连接、待确认或未运行。在列表中开启插件且账号未连接时,会提示**连接飞书**,点击后打开插件页面并开始下一步。 | 区块状态 | 操作 | |---|---| | 正在检查连接 | 无 | -| 未连接 | **连接飞书**在没有应用时先关联应用,然后登录 | -| 第 1 步:关联飞书应用,或第 2 步:登录飞书账号 | 发起连接的浏览器会把每个飞书页面打开一次;**打开授权页面**再次打开,**取消**结束连接 | +| 未连接,没有应用 | **关联飞书应用**打开飞书页面,用户在其中新建或选择应用,完成后停下 | +| 未连接,已关联应用 | **登录飞书账号**打开飞书授权页面 | +| 第 1 步:关联飞书应用,或第 2 步:登录飞书账号 | 点击的浏览器会把这一步的飞书页面打开一次;**打开飞书页面**再次打开,**取消**结束这一步 | | 已连接 | **退出登录**确认后退出 CLI 的默认账号 | | 暂时无法确认登录状态 | **重试**重新运行连接,保留现有配置和登录 | | 飞书组件未运行 | Host 的 `feishu` 行没有加载;区块提示到组件列表查看原因,**重试**重新订阅 Host | -离开页面不会取消连接,连接由 Host 持有。连接或退出登录失败时,区块显示**操作未完成,请重试**;页面操作失败时显示提示,连接或退出登录完成时也会显示提示。区块会说明该账号与这台电脑终端里的飞书 CLI 共用。 +离开页面不会取消连接,连接由 Host 持有。每一步都由用户自己的点击打开页面,因为浏览器会拦截点击很久之后才打开的窗口。某一步或退出登录失败时,区块显示**操作未完成,请重试**;页面操作失败时显示提示,关联应用、登录或退出登录完成时也会显示提示。区块会说明该账号与这台电脑终端里的飞书 CLI 共用。 ----- diff --git a/packages/client/ui-feishu/src/client/FeishuConnection.tsx b/packages/client/ui-feishu/src/client/FeishuConnection.tsx index 2569e7c17f..2e84cd7924 100644 --- a/packages/client/ui-feishu/src/client/FeishuConnection.tsx +++ b/packages/client/ui-feishu/src/client/FeishuConnection.tsx @@ -29,7 +29,7 @@ const BADGE: Record = { * @returns the status line, its actions, and the sign-out confirmation. */ export function FeishuConnectionSection(props: FaceProps): ReactNode { - const { useFeishuConnection, connect, cancel, signOut, openAuthorization, retry, t } = props + const { useFeishuConnection, check, linkApp, signIn, cancel, signOut, openAuthorization, retry, t } = props const snapshot = useFeishuConnection(value => value) const [confirming, setConfirming] = useState(false) const shown = presentConnection(snapshot) @@ -41,8 +41,11 @@ export function FeishuConnectionSection(props: FaceProps): ReactNode { let status = t(`status.${shown.phase === 'connecting' ? 'checking' : shown.phase}`) let detail: string | undefined switch (shown.phase) { - case 'disconnected': actions.push(action('action.connect', connect, 'primary')); detail = t('detail.disconnected'); break - case 'unavailable': actions.push(action('action.retry', connect)); detail = t('detail.unavailable'); break + case 'disconnected': + actions.push(shown.next === 'link-app' ? action('action.linkApp', linkApp, 'primary') : action('action.signIn', signIn, 'primary')) + detail = t(shown.next === 'link-app' ? 'detail.no-app' : 'detail.signed-out') + break + case 'unavailable': actions.push(action('action.retry', check)); detail = t('detail.unavailable'); break case 'stopped': actions.push(action('action.retry', retry)); detail = t('detail.stopped'); break case 'connected': actions.push(action('action.signOut', () => { setConfirming(true) })) @@ -98,8 +101,12 @@ export function FeishuConnectionBadge({ subject, useFeishuConnection, t }: FaceP * @returns a dismissible prompt that starts the connection from the bundle's page. */ export function FeishuConnectionActivation(props: FaceProps & PropsRuntime<'plugins.bundle.activation'>): ReactNode { - const { useFeishuConnection, connect, onDismiss, onOpenDetails, t } = props + const { useFeishuConnection, linkApp, signIn, onDismiss, onOpenDetails, t } = props const phase = useFeishuConnection(value => presentConnection(value).phase) + const next = useFeishuConnection((value) => { + const shown = presentConnection(value) + return shown.phase === 'disconnected' ? shown.next : undefined + }) const needed = phase === 'disconnected' useEffect(() => { if (phase !== 'checking' && !needed) onDismiss() @@ -108,7 +115,11 @@ export function FeishuConnectionActivation(props: FaceProps & PropsRuntime<'plug - + }>

{t('activation.body')}

diff --git a/packages/client/ui-feishu/src/client/connection.ts b/packages/client/ui-feishu/src/client/connection.ts index 5c876e06f4..6a1abd670a 100644 --- a/packages/client/ui-feishu/src/client/connection.ts +++ b/packages/client/ui-feishu/src/client/connection.ts @@ -13,7 +13,7 @@ export const FEISHU_PACKAGE = '@deepseek-ai/dsh-feishu' /** A transient outcome the page reports outside its own lifetime. */ export interface ConnectionNotice { readonly seq: number - readonly kind: 'connected' | 'signed-out' | 'action-failed' + readonly kind: 'app-linked' | 'connected' | 'signed-out' | 'action-failed' } /** The page's whole view: the Host's account view plus this browser's pending action and notice. */ @@ -29,13 +29,16 @@ export interface ConnectionSnapshot { readonly notice: ConnectionNotice | undefined } +const NOTICE = { 'link-app': 'app-linked', 'sign-in': 'connected', 'sign-out': 'signed-out' } as const + /** The step a connection or sign-out in progress shows. */ export type ConnectionStep = 'configuring' | 'authorizing' | 'connecting' | 'signing-out' /** What the user sees about the connection, derived from the Host's view alone. */ export type ConnectionPresentation = | { readonly phase: 'checking' | 'stopped' } - | { readonly phase: 'disconnected' | 'unavailable'; readonly failed: boolean } + | { readonly phase: 'disconnected'; readonly next: 'link-app' | 'sign-in'; readonly failed: boolean } + | { readonly phase: 'unavailable'; readonly failed: boolean } | { readonly phase: 'connected'; readonly userName: string | undefined; readonly failed: boolean } | { readonly phase: 'connecting' @@ -48,7 +51,12 @@ export type ConnectionPresentation = /** Page-facing actions and the snapshot hook the slot entries inject. */ export interface ConnectionFace { hooks: { feishuConnection: HostObservable } - connect(): void + /** Check the account again. */ + check(): void + /** Link an app when none is configured. */ + linkApp(): void + /** Sign the linked app's user in. */ + signIn(): void cancel(): void signOut(): void openAuthorization(): void @@ -85,7 +93,7 @@ export function presentConnection(snapshot: Pick { void this.start(() => this.ctx.remote.feishu.connect()) }, + check: () => { void this.start(() => this.ctx.remote.feishu.check()) }, + linkApp: () => { void this.start(() => this.ctx.remote.feishu.linkApp()) }, + signIn: () => { void this.start(() => this.ctx.remote.feishu.signIn()) }, signOut: () => { void this.start(() => this.ctx.remote.feishu.signOut()) }, cancel: () => { void this.cancel() }, openAuthorization: () => { @@ -197,7 +207,7 @@ export class FeishuConnection { const result = state.result if (result === undefined || result.id !== this.started) return this.started = undefined - if (result.outcome === 'succeeded') this.notify(result.kind === 'sign-out' ? 'signed-out' : 'connected') + if (result.outcome === 'succeeded' && result.kind !== 'check') this.notify(NOTICE[result.kind]) } private async start(call: () => Promise>): Promise { diff --git a/packages/client/ui-feishu/src/client/locales.ts b/packages/client/ui-feishu/src/client/locales.ts index 13c29fd165..72f86b7976 100644 --- a/packages/client/ui-feishu/src/client/locales.ts +++ b/packages/client/ui-feishu/src/client/locales.ts @@ -16,17 +16,20 @@ export const zh = { 'step.authorizing': '第 2 步:登录飞书账号', 'step.connecting': '正在连接', 'step.signing-out': '正在退出登录', - 'detail.disconnected': '连接后,可以在对话中使用飞书文档、消息及其他你授权的功能。首次连接会先关联一个飞书应用。', + 'detail.no-app': '先关联一个飞书应用(可以新建,也可以选择已有应用),再登录飞书账号。连接后,可以在对话中使用飞书文档、消息及其他你授权的功能。', + 'detail.signed-out': '已关联飞书应用。登录飞书账号后,就可以在对话中使用飞书。', 'detail.unavailable': '已保留现有配置和登录,可以稍后重试。', 'detail.stopped': '“飞书 CLI 与技能”组件没有运行,可以在下方组件列表查看原因,处理后重试。', 'detail.connected': '可以在对话中直接请 Agent 使用飞书。', 'detail.connectedAs': '已登录为 {name}。可以在对话中直接请 Agent 使用飞书。', - 'detail.configuring': '已打开飞书页面。在页面中创建或选择应用后,回到这里继续。', - 'detail.authorizing': '已打开飞书授权页面。确认后回到这里查看结果。', + 'detail.configuring': '在打开的飞书页面中新建或选择应用,完成后回到这里登录。页面没有打开时,点击“打开飞书页面”。', + 'detail.authorizing': '在打开的飞书页面中确认授权,完成后回到这里查看结果。页面没有打开时,点击“打开飞书页面”。', hint: '飞书账号与这台电脑终端里的飞书 CLI 共用。', failed: '操作未完成,请重试', 'action.connect': '连接飞书', - 'action.open': '打开授权页面', + 'action.linkApp': '关联飞书应用', + 'action.signIn': '登录飞书账号', + 'action.open': '打开飞书页面', 'action.cancel': '取消', 'action.signOut': '退出登录', 'action.retry': '重试', @@ -40,6 +43,7 @@ export const zh = { 'activation.title': '连接飞书账号', 'activation.body': '飞书插件已开启。连接你的飞书账号后,就可以在对话中使用它。', 'activation.later': '稍后', + 'notice.app-linked': '飞书应用已关联,下一步登录飞书账号', 'notice.connected': '飞书已连接', 'notice.signed-out': '已退出飞书登录', 'notice.action-failed': '操作未完成,请重试', @@ -61,17 +65,20 @@ export const en: Record = { 'step.authorizing': 'Step 2: Sign in to Feishu', 'step.connecting': 'Connecting', 'step.signing-out': 'Signing out', - 'detail.disconnected': 'Connect to use Feishu docs, messages, and other features you authorize in conversations. The first connection links a Feishu app.', + 'detail.no-app': 'Link a Feishu app first, either a new one or one you already have, then sign in to Feishu. After that, you can use Feishu docs, messages, and other features you authorize in conversations.', + 'detail.signed-out': 'A Feishu app is linked. Sign in to Feishu to use it in conversations.', 'detail.unavailable': 'The existing setup and sign-in are kept. Try again later.', 'detail.stopped': 'The Feishu CLI and skills component is not running. See the component list below for the reason, then retry.', 'detail.connected': 'Ask the agent to use Feishu directly in a conversation.', 'detail.connectedAs': 'Signed in as {name}. Ask the agent to use Feishu directly in a conversation.', - 'detail.configuring': 'The Feishu page is open. Create or choose an app there, then come back here.', - 'detail.authorizing': 'The Feishu authorization page is open. Confirm there, then come back here to see the result.', + 'detail.configuring': 'Create or choose an app on the Feishu page, then come back here to sign in. If the page did not open, select Open Feishu page.', + 'detail.authorizing': 'Confirm the authorization on the Feishu page, then come back here to see the result. If the page did not open, select Open Feishu page.', hint: 'The Feishu account is shared with the Feishu CLI in this computer\'s terminal.', failed: 'The action did not finish. Try again.', 'action.connect': 'Connect Feishu', - 'action.open': 'Open authorization page', + 'action.linkApp': 'Link Feishu app', + 'action.signIn': 'Sign in to Feishu', + 'action.open': 'Open Feishu page', 'action.cancel': 'Cancel', 'action.signOut': 'Sign out', 'action.retry': 'Retry', @@ -85,6 +92,7 @@ export const en: Record = { 'activation.title': 'Connect your Feishu account', 'activation.body': 'The Feishu plugin is on. Connect your Feishu account to use it in conversations.', 'activation.later': 'Later', + 'notice.app-linked': 'Feishu app linked. Next, sign in to Feishu.', 'notice.connected': 'Feishu connected', 'notice.signed-out': 'Signed out of Feishu', 'notice.action-failed': 'The action did not finish. Try again.', diff --git a/packages/client/ui-feishu/tests/components.client.spec.tsx b/packages/client/ui-feishu/tests/components.client.spec.tsx index bb7cda4dc5..4463702ac0 100644 --- a/packages/client/ui-feishu/tests/components.client.spec.tsx +++ b/packages/client/ui-feishu/tests/components.client.spec.tsx @@ -21,7 +21,8 @@ function fixture(feishu?: FeishuState) { const state = createSnapshotStore({ feishu, linked: true, stopped: false, busy: false, notice: undefined }) const face = { useFeishuConnection: bindSnapshotSelector(state), - connect: vi.fn(), cancel: vi.fn(), signOut: vi.fn(), openAuthorization: vi.fn(), retry: vi.fn(), dismissNotice: vi.fn(), + check: vi.fn(), linkApp: vi.fn(), signIn: vi.fn(), cancel: vi.fn(), signOut: vi.fn(), + openAuthorization: vi.fn(), retry: vi.fn(), dismissNotice: vi.fn(), t: makeTranslate(zh), } return { face, set: (change: Partial) => { act(() => { state.set({ ...state.getSnapshot(), ...change }) }) } } @@ -34,15 +35,20 @@ const text = (key: keyof typeof zh, values: Record = {}) => it('offers the next step for each state', () => { const b = fixture({ account: { state: 'unconfigured' } }) render() - expect(screen.getByText(zh['detail.disconnected'])).toBeTruthy() + expect(screen.getByText(zh['detail.no-app'])).toBeTruthy() expect(screen.getByText(zh.hint)).toBeTruthy() - fireEvent.click(button(zh['action.connect'])) - expect(b.face.connect).toHaveBeenCalledOnce() + fireEvent.click(button(zh['action.linkApp'])) + expect(b.face.linkApp).toHaveBeenCalledOnce() - b.set({ feishu: { account: { state: 'signed-out' }, operation: { id: OP, kind: 'connect', phase: 'configuring' } } }) + b.set({ feishu: { account: { state: 'unconfigured' }, operation: { id: OP, kind: 'link-app', phase: 'configuring' } } }) expect(screen.getByText(zh['step.configuring'])).toBeTruthy() expect(screen.queryByRole('button', { name: zh['action.open'] })).toBeNull() - b.set({ feishu: { account: { state: 'signed-out' }, operation: { id: OP, kind: 'connect', phase: 'authorizing', authorizationUrl: 'https://x.feishu.cn' } } }) + b.set({ feishu: { account: { state: 'signed-out' } } }) + expect(screen.getByText(zh['detail.signed-out'])).toBeTruthy() + fireEvent.click(button(zh['action.signIn'])) + expect(b.face.signIn).toHaveBeenCalledOnce() + + b.set({ feishu: { account: { state: 'signed-out' }, operation: { id: OP, kind: 'sign-in', phase: 'authorizing', authorizationUrl: 'https://x.feishu.cn' } } }) expect(screen.getByText(zh['detail.authorizing'])).toBeTruthy() fireEvent.click(button(zh['action.open'])) fireEvent.click(button(zh['action.cancel'])) @@ -54,13 +60,13 @@ it('offers the next step for each state', () => { expect(screen.queryByRole('button', { name: zh['action.cancel'] })).toBeNull() expect(document.querySelector('[data-feishu-connection="connecting"] p')?.textContent).toBe(zh.hint) - b.set({ feishu: { account: { state: 'signed-out' }, result: { id: OP, kind: 'connect', outcome: 'failed' } } }) + b.set({ feishu: { account: { state: 'signed-out' }, result: { id: OP, kind: 'sign-in', outcome: 'failed' } } }) expect(screen.getByRole('alert').textContent).toBe(zh.failed) b.set({ feishu: { account: { state: 'unverified' } } }) expect(screen.getByText(zh['detail.unavailable'])).toBeTruthy() fireEvent.click(button(zh['action.retry'])) - expect(b.face.connect).toHaveBeenCalledTimes(2) + expect(b.face.check).toHaveBeenCalledOnce() b.set({ feishu: undefined }) expect(screen.getByText(zh['status.checking'])).toBeTruthy() @@ -100,9 +106,9 @@ it('disables actions while one is pending or the Host stream is offline', () => const b = fixture({ account: { state: 'unconfigured' } }) render() b.set({ busy: true }) - expect(button(zh['action.connect']).hasAttribute('disabled')).toBe(true) + expect(button(zh['action.linkApp']).hasAttribute('disabled')).toBe(true) b.set({ busy: false, linked: false }) - expect(button(zh['action.connect']).hasAttribute('disabled')).toBe(true) + expect(button(zh['action.linkApp']).hasAttribute('disabled')).toBe(true) }) it('tags only the enabled Feishu bundle', () => { @@ -125,16 +131,19 @@ it('tags only the enabled Feishu bundle', () => { expect(document.body.textContent).toBe('') }) -it('guides a newly enabled bundle to connect, and steps aside once connected', () => { +it.each<[string, FeishuState, 'linkApp' | 'signIn']>([ + ['links an app first', { account: { state: 'unconfigured' } }, 'linkApp'], + ['signs in to a linked app', { account: { state: 'signed-out' } }, 'signIn'], +])('guides a newly enabled bundle to its next step: %s, and steps aside once connected', (_name, state, step) => { const b = fixture() const onDismiss = vi.fn(), onOpenDetails = vi.fn() const props = { ...b.face, packageName: '@deepseek-ai/dsh-feishu', onDismiss, onOpenDetails } as ComponentProps render() expect(screen.queryByText(zh['activation.body'])).toBeNull() - b.set({ feishu: { account: { state: 'signed-out' } } }) + b.set({ feishu: state }) fireEvent.click(button(zh['action.connect'])) expect(onOpenDetails).toHaveBeenCalledOnce() - expect(b.face.connect).toHaveBeenCalledOnce() + expect(b.face[step]).toHaveBeenCalledOnce() expect(onDismiss).not.toHaveBeenCalled() b.set({ feishu: { account: { state: 'connected' } } }) expect(onDismiss).toHaveBeenCalledOnce() diff --git a/packages/client/ui-feishu/tests/connection.client.spec.ts b/packages/client/ui-feishu/tests/connection.client.spec.ts index 44cf0b2f94..2564a78ded 100644 --- a/packages/client/ui-feishu/tests/connection.client.spec.ts +++ b/packages/client/ui-feishu/tests/connection.client.spec.ts @@ -22,15 +22,16 @@ it.each<[string, FeishuState | undefined, ReturnType]> ['no view yet', undefined, { phase: 'checking' }], ['an unchecked account', { account: { state: 'unchecked' } }, { phase: 'checking' }], ['a check', { ...SIGNED_OUT, operation: operation('check', 'checking') }, { phase: 'checking' }], - ['no app', { account: { state: 'unconfigured' } }, { phase: 'disconnected', failed: false }], - ['a failed connection', { ...SIGNED_OUT, result: { id: OP, kind: 'connect', outcome: 'failed' } }, { phase: 'disconnected', failed: true }], + ['no app', { account: { state: 'unconfigured' } }, { phase: 'disconnected', next: 'link-app', failed: false }], + ['a linked app', SIGNED_OUT, { phase: 'disconnected', next: 'sign-in', failed: false }], + ['a failed sign-in', { ...SIGNED_OUT, result: { id: OP, kind: 'sign-in', outcome: 'failed' } }, { phase: 'disconnected', next: 'sign-in', failed: true }], ['an unconfirmed sign-in', { account: { state: 'unverified' } }, { phase: 'unavailable', failed: false }], ['a connection', { account: { state: 'connected', userName: '张三' } }, { phase: 'connected', userName: '张三', failed: false }], - ['app setup', { ...SIGNED_OUT, operation: operation('connect', 'configuring', 'https://open.feishu.cn/x') }, connecting('configuring', 'https://open.feishu.cn/x', true)], - ['sign-in', { ...SIGNED_OUT, operation: operation('connect', 'authorizing') }, connecting('authorizing', undefined, true)], - ['a connection check', { ...SIGNED_OUT, operation: operation('connect', 'checking') }, connecting('connecting', undefined, true)], - ['verification', { ...SIGNED_OUT, operation: operation('connect', 'verifying') }, connecting('connecting', undefined, true)], - ['cancellation', { ...SIGNED_OUT, operation: operation('connect', 'cancelling') }, connecting('connecting', undefined, false)], + ['app setup', { ...SIGNED_OUT, operation: operation('link-app', 'configuring', 'https://open.feishu.cn/x') }, connecting('configuring', 'https://open.feishu.cn/x', true)], + ['sign-in', { ...SIGNED_OUT, operation: operation('sign-in', 'authorizing') }, connecting('authorizing', undefined, true)], + ['an app link check', { ...SIGNED_OUT, operation: operation('link-app', 'checking') }, connecting('connecting', undefined, true)], + ['verification', { ...SIGNED_OUT, operation: operation('sign-in', 'verifying') }, connecting('connecting', undefined, true)], + ['cancellation', { ...SIGNED_OUT, operation: operation('sign-in', 'cancelling') }, connecting('connecting', undefined, false)], ['sign-out', { ...SIGNED_OUT, operation: operation('sign-out', 'signing-out') }, connecting('signing-out', undefined, false)], ['a sign-out check', { ...SIGNED_OUT, operation: operation('sign-out', 'checking') }, connecting('signing-out', undefined, false)], ])('presents %s', (name, state, expected) => { @@ -57,7 +58,9 @@ function fixture() { const ok = (value: T) => ({ ok: true as const, value }) const remote = { follow: vi.fn(), - connect: vi.fn(async () => ok(OP)), + check: vi.fn(async () => ok(OP)), + linkApp: vi.fn(async () => ok(OP)), + signIn: vi.fn(async () => ok(OP)), signOut: vi.fn(async () => ok(OP)), cancel: vi.fn(async () => ok(undefined)), } @@ -104,45 +107,65 @@ it('mirrors the Host view and opens the Host stream', async () => { expect(b.snapshot().linked).toBe(false) }) -it('opens each new link of the connection this browser started once, then reports the connection', async () => { +it('opens each new link of an operation this browser started once, then reports each finished step', async () => { const b = fixture() - await b.publish(SIGNED_OUT) - b.face.connect() + const NO_APP: FeishuState = { account: { state: 'unconfigured' } } + await b.publish(NO_APP) + b.face.linkApp() await settle(b) - await b.publish({ ...SIGNED_OUT, operation: operation('connect', 'configuring', 'https://open.feishu.cn/app') }) - await b.publish({ ...SIGNED_OUT, operation: operation('connect', 'configuring', 'https://open.feishu.cn/app') }) - await b.publish({ ...SIGNED_OUT, operation: operation('connect', 'authorizing', 'https://accounts.feishu.cn/device') }) + expect(b.remote.linkApp).toHaveBeenCalledOnce() + await b.publish({ ...NO_APP, operation: operation('link-app', 'configuring', 'https://open.feishu.cn/app') }) + await b.publish({ ...NO_APP, operation: operation('link-app', 'configuring', 'https://open.feishu.cn/app') }) + expect(b.open.mock.calls.map(call => call[0])).toEqual(['https://open.feishu.cn/app']) + await b.publish({ ...SIGNED_OUT, result: { id: OP, kind: 'link-app', outcome: 'succeeded' } }) + expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'app-linked' }) + + const SIGN_IN = 'op-2' as FeishuOperationId + b.remote.signIn.mockResolvedValueOnce({ ok: true, value: SIGN_IN }) + b.face.signIn() + await settle(b) + await b.publish({ ...SIGNED_OUT, operation: operation('sign-in', 'authorizing', 'https://accounts.feishu.cn/device', SIGN_IN) }) expect(b.open.mock.calls.map(call => call[0])).toEqual(['https://open.feishu.cn/app', 'https://accounts.feishu.cn/device']) b.face.openAuthorization() expect(b.open).toHaveBeenCalledTimes(3) - await b.publish({ account: { state: 'connected' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) - expect(b.snapshot().notice).toEqual({ seq: 1, kind: 'connected' }) - await b.publish({ account: { state: 'connected' }, result: { id: OP, kind: 'connect', outcome: 'succeeded' } }) - expect(b.snapshot().notice?.seq).toBe(1) + await b.publish({ account: { state: 'connected' }, result: { id: SIGN_IN, kind: 'sign-in', outcome: 'succeeded' } }) + expect(b.snapshot().notice).toEqual({ seq: 2, kind: 'connected' }) + await b.publish({ account: { state: 'connected' }, result: { id: SIGN_IN, kind: 'sign-in', outcome: 'succeeded' } }) + expect(b.snapshot().notice?.seq).toBe(2) b.face.dismissNotice() expect(b.snapshot().notice).toBeUndefined() }) +it('checks again without a notice', async () => { + const b = fixture() + await b.publish({ account: { state: 'unverified' } }) + b.face.check() + await settle(b) + expect(b.remote.check).toHaveBeenCalledOnce() + await b.publish({ ...SIGNED_OUT, result: { id: OP, kind: 'check', outcome: 'succeeded' } }) + expect(b.snapshot().notice).toBeUndefined() +}) + it('opens a link the stream reported before the start answered, never a foreign operation, and only over HTTPS', async () => { const b = fixture() const answer = Promise.withResolvers<{ ok: true; value: FeishuOperationId }>() - b.remote.connect.mockReturnValueOnce(answer.promise) - await b.publish({ ...SIGNED_OUT, operation: operation('connect', 'authorizing', 'https://accounts.feishu.cn/other', 'other' as FeishuOperationId) }) - b.face.connect() - await b.publish({ ...SIGNED_OUT, operation: operation('connect', 'authorizing', 'https://accounts.feishu.cn/device') }) + b.remote.signIn.mockReturnValueOnce(answer.promise) + await b.publish({ ...SIGNED_OUT, operation: operation('sign-in', 'authorizing', 'https://accounts.feishu.cn/other', 'other' as FeishuOperationId) }) + b.face.signIn() + await b.publish({ ...SIGNED_OUT, operation: operation('sign-in', 'authorizing', 'https://accounts.feishu.cn/device') }) expect(b.open).not.toHaveBeenCalled() answer.resolve({ ok: true, value: OP }) await vi.waitFor(() => { expect(b.open).toHaveBeenCalledWith('https://accounts.feishu.cn/device', '_blank', 'noopener,noreferrer') }) - await b.publish({ ...SIGNED_OUT, operation: operation('connect', 'authorizing', 'http://accounts.feishu.cn/device') }) + await b.publish({ ...SIGNED_OUT, operation: operation('sign-in', 'authorizing', 'http://accounts.feishu.cn/device') }) b.face.openAuthorization() expect(b.open).toHaveBeenCalledOnce() }) -it('starts before the first view and reports no notice for a failed connection', async () => { +it('starts before the first view and reports no notice for a failed sign-in', async () => { const b = fixture() - b.face.connect() + b.face.signIn() await settle(b) - await b.publish({ ...SIGNED_OUT, result: { id: OP, kind: 'connect', outcome: 'failed' } }) + await b.publish({ ...SIGNED_OUT, result: { id: OP, kind: 'sign-in', outcome: 'failed' } }) expect(b.snapshot().notice).toBeUndefined() }) @@ -158,7 +181,7 @@ it('cancels only a cancellable operation and reports a finished sign-out', async expect(b.remote.cancel).not.toHaveBeenCalled() await b.publish({ account: { state: 'signed-out' }, result: { id: OP, kind: 'sign-out', outcome: 'succeeded' } }) expect(b.snapshot().notice?.kind).toBe('signed-out') - await b.publish({ ...SIGNED_OUT, operation: operation('connect', 'authorizing') }) + await b.publish({ ...SIGNED_OUT, operation: operation('sign-in', 'authorizing') }) b.face.cancel() await settle(b) expect(b.remote.cancel).toHaveBeenCalledWith(OP) @@ -167,8 +190,8 @@ it('cancels only a cancellable operation and reports a finished sign-out', async it('reports a failed action once and ignores overlapping clicks', async () => { const b = fixture() await b.publish(SIGNED_OUT) - b.remote.connect.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } as never) - b.face.connect() + b.remote.signIn.mockResolvedValueOnce({ ok: false, error: new RemoteError('gateway/internal', 'offline', {}) } as never) + b.face.signIn() b.face.signOut() await vi.waitFor(() => { expect(b.snapshot().notice?.kind).toBe('action-failed') }) expect(b.remote.signOut).not.toHaveBeenCalled() diff --git a/packages/connector/feishu-cli/README.i18n.yaml b/packages/connector/feishu-cli/README.i18n.yaml index 47418d81ff..a0ef6aab45 100644 --- a/packages/connector/feishu-cli/README.i18n.yaml +++ b/packages/connector/feishu-cli/README.i18n.yaml @@ -24,8 +24,8 @@ en: f0d233dd69bb21c7 zh: 4aedc72d52cd0523 /deepseek-ai-dsh-feishu-cli/use-this-package/account-operations: - en: 8e9d5bef6ddbe83e - zh: 5705e3108b95d574 + en: bd530fefb8162071 + zh: ee545c54e29317ab /deepseek-ai-dsh-feishu-cli/use-this-package/configure: en: 2aa0db3a03b797f8 zh: 6d63b0c12de0b97c diff --git a/packages/connector/feishu-cli/README.md b/packages/connector/feishu-cli/README.md index 0f097d2601..baa4962382 100644 --- a/packages/connector/feishu-cli/README.md +++ b/packages/connector/feishu-cli/README.md @@ -38,12 +38,14 @@ Turning the row off in Plugin Manager withdraws the skills and the private PATH ### Account operations -The `feishu` Remote serves the Plugins page. It runs at most one account operation at a time, owned by the Host, so leaving the page does not cancel it. +The `feishu` Remote serves the Plugins page. It runs at most one account operation at a time, owned by the Host, so leaving the page does not cancel it. Linking an app and signing in are separate operations, so the page starts each one from its own click. | Method | Effect | |---|---| | `follow(signal)` | Streams the account, the operation in progress, and the last result; each new follower starts a check when no operation runs | -| `connect()` | Checks the account, runs `config init --new` when no app is configured, then `auth login --json`, and checks that the same user is signed in; returns the operation id | +| `check()` | Checks the account again; returns the operation id | +| `linkApp()` | Runs `config init --new` when no app is configured and keeps an existing app; it does not sign in | +| `signIn()` | Runs `auth login --json` for the linked app and checks that the same user is signed in | | `signOut()` | Runs `auth logout --json`, which also signs out the user's own terminal, then checks again | | `cancel(id)` | Cancels that operation and waits for its command to exit; a finished id is ignored | diff --git a/packages/connector/feishu-cli/README.zh.md b/packages/connector/feishu-cli/README.zh.md index d48e0a64bf..527758cc78 100644 --- a/packages/connector/feishu-cli/README.zh.md +++ b/packages/connector/feishu-cli/README.zh.md @@ -38,12 +38,14 @@ kind: "package-reference" ### 账号操作 -`feishu` Remote 为插件页服务。它同一时间最多运行一个由 Host 持有的账号操作,因此离开页面不会取消操作。 +`feishu` Remote 为插件页服务。它同一时间最多运行一个由 Host 持有的账号操作,因此离开页面不会取消操作。关联应用和登录是两个独立操作,页面分别由各自的一次点击发起。 | 方法 | 作用 | |---|---| | `follow(signal)` | 推送账号、进行中的操作和最近一次结果;没有操作运行时,每个新订阅者会触发一次检查 | -| `connect()` | 检查账号;未配置应用时运行 `config init --new`,然后运行 `auth login --json`,并确认登录的是同一个用户;返回操作 id | +| `check()` | 重新检查账号;返回操作 id | +| `linkApp()` | 未配置应用时运行 `config init --new`,已有应用则保留;不会登录 | +| `signIn()` | 为已关联的应用运行 `auth login --json`,并确认登录的是同一个用户 | | `signOut()` | 运行 `auth logout --json`,同时退出用户自己终端里的登录,然后重新检查 | | `cancel(id)` | 取消该操作并等待其命令退出;已结束的 id 会被忽略 | diff --git a/packages/connector/feishu-cli/package.json b/packages/connector/feishu-cli/package.json index 9ede71f1f3..4839f0aeca 100644 --- a/packages/connector/feishu-cli/package.json +++ b/packages/connector/feishu-cli/package.json @@ -46,6 +46,7 @@ "dependencies": { "@deepseek-ai/dsh-brand": "workspace:*", "@deepseek-ai/dsh-timeout": "workspace:*", + "@deepseek-ai/dsh-util-values": "workspace:*", "@deepseek-ai/schemastery": "workspace:~", "@larksuite/cli": "1.0.97", "zod": "^4.4.3" diff --git a/packages/connector/feishu-cli/src/account.ts b/packages/connector/feishu-cli/src/account.ts index cfdd93f5da..1e6045d601 100644 --- a/packages/connector/feishu-cli/src/account.ts +++ b/packages/connector/feishu-cli/src/account.ts @@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto' import { brandString } from '@deepseek-ai/dsh-brand' import z from 'zod' +import { assertNever } from '@deepseek-ai/dsh-util-values' import { parseJson, type FeishuCli } from './cli.ts' import type { FeishuAccountState, FeishuOperationId, FeishuOperationResult, FeishuOperationState, FeishuState } from './types.ts' @@ -138,30 +139,42 @@ export class FeishuAccount { } private async perform(operation: Operation, signal: AbortSignal): Promise { - if (operation.kind === 'sign-out') { - this.stage(operation, 'signing-out') - const result = await this.cli.run(['auth', 'logout', '--json'], signal, { timeoutMs: this.limits.commandTimeoutMs }) - if (result.exitCode !== 0) throw new Error('feishu: auth logout failed') - await this.check(signal) - return - } - let found = await this.check(signal) - if (operation.kind === 'check' || found.account.state === 'connected') return - if (found.account.state === 'unconfigured') { - this.stage(operation, 'configuring') - const setup = await this.cli.run(['config', 'init', '--new'], signal, { - timeoutMs: this.limits.authorizationTimeoutMs, - onLine: (stream, line) => { - const link = stream === 'stderr' && operation.authorizationUrl === undefined ? CONFIG_LINK.exec(line) : null - if (link !== null) this.offer(operation, link[1] as string) - }, - }) - if (setup.exitCode !== 0) throw new Error('feishu: config init failed') - this.stage(operation, 'checking') - found = await this.check(signal) - if (found.account.state === 'unconfigured') throw new Error('feishu: config init left no app') - if (found.account.state === 'connected') return + switch (operation.kind) { + case 'check': + await this.check(signal) + return + case 'link-app': return this.linkApp(operation, signal) + case 'sign-in': return this.signIn(operation, signal) + case 'sign-out': { + this.stage(operation, 'signing-out') + const result = await this.cli.run(['auth', 'logout', '--json'], signal, { timeoutMs: this.limits.commandTimeoutMs }) + if (result.exitCode !== 0) throw new Error('feishu: auth logout failed') + await this.check(signal) + return + } + /* v8 ignore next -- closed operation kind union */ + default: return assertNever(operation.kind) } + } + + /** Link an app through the CLI's setup page when none is configured; sign-in is a separate operation. */ + private async linkApp(operation: Operation, signal: AbortSignal): Promise { + if ((await this.check(signal)).account.state !== 'unconfigured') return + this.stage(operation, 'configuring') + const setup = await this.cli.run(['config', 'init', '--new'], signal, { + timeoutMs: this.limits.authorizationTimeoutMs, + onLine: (stream, line) => { + const link = stream === 'stderr' && operation.authorizationUrl === undefined ? CONFIG_LINK.exec(line) : null + if (link !== null) this.offer(operation, link[1] as string) + }, + }) + if (setup.exitCode !== 0) throw new Error('feishu: config init failed') + this.stage(operation, 'checking') + if ((await this.check(signal)).account.state === 'unconfigured') throw new Error('feishu: config init left no app') + } + + /** Sign the configured app's user in, then confirm the CLI's default account is that user. */ + private async signIn(operation: Operation, signal: AbortSignal): Promise { this.stage(operation, 'authorizing') let complete: z.infer | undefined const login = await this.cli.run(['auth', 'login', '--json'], signal, { @@ -180,7 +193,7 @@ export class FeishuAccount { throw new Error('feishu: auth login did not complete') } this.stage(operation, 'verifying') - found = await this.check(signal) + const found = await this.check(signal) if (found.account.state !== 'connected' || found.openId !== complete.user_open_id) throw new Error('feishu: sign-in did not verify') } diff --git a/packages/connector/feishu-cli/src/index.ts b/packages/connector/feishu-cli/src/index.ts index 2ded620b81..da63d7246c 100644 --- a/packages/connector/feishu-cli/src/index.ts +++ b/packages/connector/feishu-cli/src/index.ts @@ -74,13 +74,33 @@ export default class Feishu extends TypertRemoteService { } /** - * Check the account, set up an app if none is configured, then sign in. + * Check the account again without changing it. * @returns the operation identity. * @throws while another account operation runs. */ @Remote - connect(): FeishuOperationId { - return this.account.start('connect') + check(): FeishuOperationId { + return this.account.start('check') + } + + /** + * Link an app through the CLI's setup page when none is configured; an existing app is kept. + * @returns the operation identity. + * @throws while another account operation runs. + */ + @Remote + linkApp(): FeishuOperationId { + return this.account.start('link-app') + } + + /** + * Sign the linked app's user in through the CLI's authorization page. + * @returns the operation identity. + * @throws while another account operation runs. + */ + @Remote + signIn(): FeishuOperationId { + return this.account.start('sign-in') } /** diff --git a/packages/connector/feishu-cli/src/types.ts b/packages/connector/feishu-cli/src/types.ts index 203e103c94..8d2e7a4e74 100644 --- a/packages/connector/feishu-cli/src/types.ts +++ b/packages/connector/feishu-cli/src/types.ts @@ -13,7 +13,7 @@ export type FeishuAccountState = /** The account operation in progress; links are restricted to HTTPS Feishu and Lark hosts. */ export interface FeishuOperationState { readonly id: FeishuOperationId - readonly kind: 'check' | 'connect' | 'sign-out' + readonly kind: 'check' | 'link-app' | 'sign-in' | 'sign-out' readonly phase: 'checking' | 'configuring' | 'authorizing' | 'verifying' | 'signing-out' | 'cancelling' readonly authorizationUrl?: string } diff --git a/packages/connector/feishu-cli/tests/account.spec.ts b/packages/connector/feishu-cli/tests/account.spec.ts index 092e0dbe11..395e9e90b4 100644 --- a/packages/connector/feishu-cli/tests/account.spec.ts +++ b/packages/connector/feishu-cli/tests/account.spec.ts @@ -1,4 +1,4 @@ -/** Account operations over a scripted lark-cli: checks, connection, sign-out, cancellation, and the Remote wiring. */ +/** Account operations over a scripted lark-cli: checks, app linking, sign-in, sign-out, cancellation, and the Remote wiring. */ import { rm } from 'node:fs/promises' import { Context } from '@deepseek-ai/cordis' import SkillRegistry from '@deepseek-ai/dsh-skill' @@ -86,58 +86,63 @@ describe('FeishuAccount', () => { expect(await settled(account.start('check'))).toMatchObject({ account: { state: 'unchecked' }, result: { outcome: 'failed' } }) }) - it('links an app, signs in, and offers each trusted link', async () => { - script[STATUS] = [NOT_CONFIGURED, SIGNED_OUT, CONNECTED] + it('links an app through its setup page, offers only a trusted link, and stops before sign-in', async () => { + script[STATUS] = [NOT_CONFIGURED, SIGNED_OUT] const setup = Promise.withResolvers() - const signIn = Promise.withResolvers() script['config init --new'] = (process) => { setup.resolve(process) } - script['auth login --json'] = (process) => { signIn.resolve(process) } - const id = account.start('connect') + const id = account.start('link-app') const configuring = await setup.promise configuring.write('stderr', 'Open this link:\n http://open.feishu.cn/page/cli?x=1\n https://evil.example/page\n') configuring.write('stderr', ' https://open.feishu.cn/page/cli?x=2\n https://open.feishu.cn/page/cli?x=3\n') await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'configuring', authorizationUrl: 'https://open.feishu.cn/page/cli?x=2' }) }) configuring.reply({}) + expect(await settled(id)).toEqual({ account: { state: 'signed-out' }, result: { id, kind: 'link-app', outcome: 'succeeded' } }) + expect(commands()).toEqual([STATUS, 'config init --new', STATUS]) + }) + + it('keeps an app that is already linked', async () => { + script[STATUS] = [SIGNED_OUT] + expect((await settled(account.start('link-app'))).result?.outcome).toBe('succeeded') + expect(commands()).toEqual([STATUS]) + }) + + it('signs in through the authorization page and accepts a sign-in that leaves permissions ungranted', async () => { + script[STATUS] = [CONNECTED] + const signIn = Promise.withResolvers() + script['auth login --json'] = (process) => { signIn.resolve(process) } + + const id = account.start('sign-in') + expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'authorizing' }) const authorizing = await signIn.promise const invalid = JSON.stringify({ event: 'device_authorization', verification_uri_complete: 'not a url' }) authorizing.write('stdout', `progress\n{"event":"other"}\n${invalid}\n${LOGIN_LINK}\n`) await vi.waitFor(() => { expect(account.snapshot().operation).toMatchObject({ phase: 'authorizing', authorizationUrl: 'https://accounts.feishu.cn/oauth/device?code=1' }) }) authorizing.reply({ stdout: login(['im:message']) + '\n', exitCode: 3 }) - expect(await settled(id)).toEqual({ account: { state: 'connected', userName: '张三' }, result: { id, kind: 'connect', outcome: 'succeeded' } }) - expect(commands()).toEqual([STATUS, 'config init --new', STATUS, 'auth login --json', STATUS]) + expect(await settled(id)).toEqual({ account: { state: 'connected', userName: '张三' }, result: { id, kind: 'sign-in', outcome: 'succeeded' } }) + expect(commands()).toEqual(['auth login --json', STATUS]) }) - it.each<[string, CliReply[], string[]]>([ - ['an already connected account', [CONNECTED], [STATUS]], - ['an app setup that also signed in', [NOT_CONFIGURED, CONNECTED], [STATUS, 'config init --new', STATUS]], - ])('stops early for %s', async (_name, replies, expected) => { - script[STATUS] = replies - script['config init --new'] = [{}] - expect((await settled(account.start('connect'))).result?.outcome).toBe('succeeded') - expect(commands()).toEqual(expected) - }) - - it.each<[string, Record]>([ - ['a failed app setup', { [STATUS]: [NOT_CONFIGURED], 'config init --new': [{ exitCode: 1 }] }], - ['an app setup that left no app', { [STATUS]: [NOT_CONFIGURED, NOT_CONFIGURED], 'config init --new': [{}] }], - ['a sign-in without completion', { [STATUS]: [SIGNED_OUT], 'auth login --json': [{ stdout: LOGIN_LINK + '\n' }] }], - ['a failed sign-in', { [STATUS]: [SIGNED_OUT], 'auth login --json': [{ stdout: login() + '\n', exitCode: 1 }] }], - ['a partial sign-in that reports no missing permission', { [STATUS]: [SIGNED_OUT], 'auth login --json': [{ stdout: login() + '\n', exitCode: 3 }] }], - ['a different signed-in user', { [STATUS]: [SIGNED_OUT, CONNECTED], 'auth login --json': [{ stdout: login([], 'ou_2') + '\n' }] }], - ['an unverified sign-in', { [STATUS]: [SIGNED_OUT, SIGNED_OUT], 'auth login --json': [{ stdout: login() + '\n' }] }], - ])('fails the connection on %s', async (_name, replies) => { + it.each<[string, 'link-app' | 'sign-in', Record]>([ + ['a failed app setup', 'link-app', { [STATUS]: [NOT_CONFIGURED], 'config init --new': [{ exitCode: 1 }] }], + ['an app setup that left no app', 'link-app', { [STATUS]: [NOT_CONFIGURED, NOT_CONFIGURED], 'config init --new': [{}] }], + ['a sign-in without completion', 'sign-in', { 'auth login --json': [{ stdout: LOGIN_LINK + '\n' }] }], + ['a failed sign-in', 'sign-in', { 'auth login --json': [{ stdout: login() + '\n', exitCode: 1 }] }], + ['a partial sign-in that reports no missing permission', 'sign-in', { 'auth login --json': [{ stdout: login() + '\n', exitCode: 3 }] }], + ['a different signed-in user', 'sign-in', { [STATUS]: [CONNECTED], 'auth login --json': [{ stdout: login([], 'ou_2') + '\n' }] }], + ['an unverified sign-in', 'sign-in', { [STATUS]: [SIGNED_OUT], 'auth login --json': [{ stdout: login() + '\n' }] }], + ])('fails on %s', async (_name, kind, replies) => { Object.assign(script, replies) - expect((await settled(account.start('connect'))).result).toMatchObject({ kind: 'connect', outcome: 'failed' }) + expect((await settled(account.start(kind))).result).toMatchObject({ kind, outcome: 'failed' }) }) it('cancels only the named operation, withdraws its link, and ignores later output', async () => { script[STATUS] = [SIGNED_OUT] const signIn = Promise.withResolvers() script['auth login --json'] = (process) => { process.write('stdout', LOGIN_LINK + '\n'); signIn.resolve(process) } - const id = account.start('connect') + const id = account.start('sign-in') await vi.waitFor(() => { expect(account.snapshot().operation?.authorizationUrl).toBeDefined() }) await account.cancel('other' as FeishuOperationId) expect(account.snapshot().operation?.phase).toBe('authorizing') @@ -145,18 +150,18 @@ describe('FeishuAccount', () => { const process = await signIn.promise process.holdExit = true const cancelling = account.cancel(id) - expect(account.snapshot().operation).toEqual({ id, kind: 'connect', phase: 'cancelling' }) + expect(account.snapshot().operation).toEqual({ id, kind: 'sign-in', phase: 'cancelling' }) process.write('stdout', LOGIN_LINK + '\n') process.release() await cancelling - expect(account.snapshot()).toEqual({ account: { state: 'signed-out' }, result: { id, kind: 'connect', outcome: 'cancelled' } }) + expect(account.snapshot()).toEqual({ account: { state: 'unchecked' }, result: { id, kind: 'sign-in', outcome: 'cancelled' } }) }) it('runs one operation at a time and refreshes only when idle', async () => { const gate = Promise.withResolvers() script[STATUS] = (process) => { gate.resolve(process) } const id = account.start('check') - expect(() => account.start('connect')).toThrow('another account operation is in progress') + expect(() => account.start('sign-in')).toThrow('another account operation is in progress') account.refresh() expect(subprocess.processes).toHaveLength(0) ;(await gate.promise).reply(CONNECTED) @@ -181,7 +186,7 @@ describe('FeishuAccount', () => { await vi.waitFor(() => { expect(subprocess.processes).toHaveLength(1) }) await account.dispose() expect(subprocess.processes[0]?.terminated).toBe(true) - expect(() => account.start('connect')).toThrow('plugin disposed') + expect(() => account.start('link-app')).toThrow('plugin disposed') account.refresh() await account.dispose() expect(subprocess.processes).toHaveLength(1) @@ -193,7 +198,7 @@ describe('Feishu Remote', () => { await ctx.plugin(Feishu, { ...LIMITS, binDir }) }) - it('checks for each new follower, streams each change, and starts connections and sign-outs', async () => { + it('checks for each new follower, streams each change, and starts checks, app links, sign-ins, and sign-outs', async () => { script[STATUS] = [SIGNED_OUT] const leave = new AbortController() const seen: FeishuState[] = [] @@ -209,12 +214,15 @@ describe('Feishu Remote', () => { script['auth logout --json'] = [{ stdout: '{"ok":true}' }] const signingOut = ctx.feishu.signOut() - expect(() => ctx.feishu.connect()).toThrow('another account operation is in progress') + expect(() => ctx.feishu.signIn()).toThrow('another account operation is in progress') await ctx.feishu.cancel(signingOut) + script[STATUS] = [SIGNED_OUT] + await ctx.feishu.cancel(ctx.feishu.check()) + await ctx.feishu.cancel(ctx.feishu.linkApp()) script['auth login --json'] = () => {} - const connecting = ctx.feishu.connect() + const signingIn = ctx.feishu.signIn() await vi.waitFor(() => { expect(commands().at(-1)).toBe('auth login --json') }) - await ctx.feishu.cancel(connecting) + await ctx.feishu.cancel(signingIn) expect(subprocess.processes.at(-1)?.terminated).toBe(true) }) diff --git a/packages/connector/feishu-cli/tsconfig.json b/packages/connector/feishu-cli/tsconfig.json index a6d859b34c..f3c1087206 100644 --- a/packages/connector/feishu-cli/tsconfig.json +++ b/packages/connector/feishu-cli/tsconfig.json @@ -20,6 +20,9 @@ { "path": "../../util/timeout" }, + { + "path": "../../util/values" + }, { "path": "../../typert/protocol" }, diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index fedbf0dfe1..0d51b98001 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -1163,8 +1163,22 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ description: 'Registers the CLI and skills, and owns the account operations the Plugins page drives.', methods: [ { - signature: '@Remote connect(): FeishuOperationId', - description: 'Check the account, set up an app if none is configured, then sign in.', + signature: '@Remote check(): FeishuOperationId', + description: 'Check the account again without changing it.', + parameters: [], + returns: 'the operation identity.', + throws: ['while another account operation runs.'], + }, + { + signature: '@Remote linkApp(): FeishuOperationId', + description: 'Link an app through the CLI\'s setup page when none is configured; an existing app is kept.', + parameters: [], + returns: 'the operation identity.', + throws: ['while another account operation runs.'], + }, + { + signature: '@Remote signIn(): FeishuOperationId', + description: 'Sign the linked app\'s user in through the CLI\'s authorization page.', parameters: [], returns: 'the operation identity.', throws: ['while another account operation runs.'], @@ -6183,7 +6197,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'FeishuOperationState', - declaration: 'export interface FeishuOperationState {\n readonly id: FeishuOperationId;\n readonly kind: \'check\' | \'connect\' | \'sign-out\';\n readonly phase: \'checking\' | \'configuring\' | \'authorizing\' | \'verifying\' | \'signing-out\' | \'cancelling\';\n readonly authorizationUrl?: string;\n}', + declaration: 'export interface FeishuOperationState {\n readonly id: FeishuOperationId;\n readonly kind: \'check\' | \'link-app\' | \'sign-in\' | \'sign-out\';\n readonly phase: \'checking\' | \'configuring\' | \'authorizing\' | \'verifying\' | \'signing-out\' | \'cancelling\';\n readonly authorizationUrl?: string;\n}', }, { name: 'FeishuState', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 51f4bf0bb2..2b35ae920e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7309,6 +7309,9 @@ importers: '@deepseek-ai/dsh-timeout': specifier: workspace:* version: link:../../util/timeout + '@deepseek-ai/dsh-util-values': + specifier: workspace:* + version: link:../../util/values '@deepseek-ai/schemastery': specifier: link:../../../vendor/schemastery version: link:../../../vendor/schemastery