feat(wecom): connect WeCom from its plugin page

Add the WeCom plugin bundle and its Plugins page row: the authorization
section, the title tag, guidance after the bundle is switched on, and
connection notices, following the Feishu plugin page. An initial check that
fails offers a retry instead of an endless check.
This commit is contained in:
gengruilin committed 2026-10-14 13:33:50 +08:00
1 parent 1f149bcc79
commit 002c10f71f
9 files changed
+478

No files matched your search

@@ -0,0 +1,51 @@
.section {
display: flex;
flex-direction: column;
gap: 8px;
}
.title {
margin: 0 0 4px;
font-size: 14px;
line-height: 20px;
font-weight: 500;
}
.status {
display: flex;
align-items: center;
gap: 8px;
min-height: 28px;
}
.label {
font-size: 13px;
line-height: 20px;
color: var(--dsw-alias-label-primary);
}
.actions {
display: flex;
gap: 8px;
margin-left: auto;
}
.detail,
.hint,
.failure {
margin: 0;
font-size: 13px;
line-height: 20px;
}
.detail {
color: var(--dsw-alias-label-secondary);
}
.hint {
color: var(--dsw-alias-label-tertiary);
}
.failure {
color: var(--dsw-alias-state-error-primary);
}
@@ -0,0 +1,98 @@
import { useEffect, type ReactNode } from 'react'
import { Button, IconWarningOutlineRegular, Modal, StateDot, Tag, Toast, type StateDotState, type TagTone } from '@deepseek-ai/dsh-client-ui-primitives'
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
import { WECOM_PACKAGE, presentConnection, type ConnectionFace, type ConnectionPresentation } from './connection.ts'
import type { NS, WecomKey } from './locales.ts'
import css from './WecomConnection.module.css'
type Phase = ConnectionPresentation['phase']
type FaceProps = InjectFace<ConnectionFace> & PropsLocale<typeof NS>
const TONE: Record<Phase, StateDotState> = {
checking: 'ongoing', connecting: 'ongoing', connected: 'done', disconnected: 'idle', unavailable: 'warning', stopped: 'warning',
}
const BADGE: Record<Phase, readonly [WecomKey, TagTone] | undefined> = {
checking: undefined,
connecting: ['badge.connecting', 'info'],
connected: ['badge.connected', 'success'],
disconnected: ['badge.disconnected', 'outline'],
unavailable: ['badge.unavailable', 'warning'],
stopped: ['badge.stopped', 'warning'],
}
export function WecomConnectionSection(props: FaceProps): ReactNode {
const { useWecomConnection, check, connect, cancel, openAuthorization, retry, t } = props
const snapshot = useWecomConnection(value => value)
const shown = presentConnection(snapshot)
const disabled = snapshot.busy || (!snapshot.linked && shown.phase !== 'stopped')
const action = (label: WecomKey, onClick: () => void, variant: 'primary' | 'outline' | 'ghost' = 'outline'): ReactNode =>
<Button key={label} variant={variant} size="sm" disabled={disabled} onClick={onClick}>{t(label)}</Button>
const actions: 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', check)); detail = t('detail.unavailable'); break
case 'stopped': actions.push(action('action.retry', retry)); detail = t('detail.stopped'); break
case 'connected': detail = t('detail.connected'); break
case 'connecting':
status = t(`step.${shown.step}`)
if (shown.url !== undefined) {
actions.push(action('action.open', openAuthorization, 'primary'))
detail = t('detail.authorizing')
}
if (shown.cancellable) actions.push(action('action.cancel', cancel, 'ghost'))
break
case 'checking': break
}
return (
<div className={css.section} data-wecom-connection={shown.phase}>
<h4 className={css.title}>{t('section.title')}</h4>
<div className={css.status}>
<StateDot state={TONE[shown.phase]} />
<span className={css.label}>{status}</span>
<div className={css.actions}>{actions}</div>
</div>
{detail === undefined ? null : <p className={css.detail}>{detail}</p>}
{'failed' in shown && shown.failed ? <p className={css.failure} role="alert">{t('failed')}</p> : null}
<p className={css.hint}>{t('hint')}</p>
</div>
)
}
export function WecomConnectionBadge({ subject, useWecomConnection, t }: FaceProps & PropsRuntime<'plugins.detail.badge'>): ReactNode {
const phase = useWecomConnection(value => presentConnection(value).phase)
if (subject.kind === 'item' || subject.pkg.name !== WECOM_PACKAGE || !subject.pkg.enabled) return null
const badge = BADGE[phase]
return badge === undefined ? null : <Tag tone={badge[1]}>{t(badge[0])}</Tag>
}
export function WecomConnectionActivation(props: FaceProps & PropsRuntime<'plugins.bundle.activation'>): ReactNode {
const { useWecomConnection, connect, onDismiss, onOpenDetails, t } = props
const phase = useWecomConnection(value => presentConnection(value).phase)
const needed = phase === 'disconnected'
useEffect(() => {
if (phase !== 'checking' && !needed) onDismiss()
}, [phase, needed, onDismiss])
return (
<Modal open={needed} title={t('activation.title')} closeLabel={t('close')} onClose={onDismiss}
footer={<>
<Button variant="ghost" onClick={onDismiss}>{t('activation.later')}</Button>
<Button variant="primary" data-modal-autofocus onClick={() => { onOpenDetails(); connect() }}>{t('action.connect')}</Button>
</>}>
<p>{t('activation.body')}</p>
</Modal>
)
}
export function WecomConnectionToast({ useWecomConnection, dismissNotice, t }: FaceProps): ReactNode {
const notice = useWecomConnection(value => value.notice)
if (notice === undefined) return null
const failed = notice.kind === 'action-failed'
return (
<Toast key={notice.seq} text={t(`notice.${notice.kind}`)} onDone={dismissNotice}
{...failed ? { icon: <IconWarningOutlineRegular /> } : { tone: 'success' as const }} />
)
}
@@ -0,0 +1,195 @@
import type { Context } from '@deepseek-ai/cordis'
import type { RemoteStream } from '@deepseek-ai/dsh-api-gateway/client'
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
import type { HostObservable } from '@deepseek-ai/dsh-client-ui-slots'
import type { WecomOperationId, WecomState } from '@deepseek-ai/dsh-wecom-cli/types'
import type { RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { assertNever } from '@deepseek-ai/dsh-util-values'
export const WECOM_PACKAGE = '@deepseek-ai/dsh-wecom'
export interface ConnectionNotice {
readonly seq: number
readonly kind: 'connected' | 'action-failed'
}
export interface ConnectionSnapshot {
readonly wecom: WecomState | undefined
readonly linked: boolean
readonly stopped: boolean
readonly busy: boolean
readonly notice: ConnectionNotice | undefined
}
export type ConnectionStep = 'authorizing' | 'connecting'
export type ConnectionPresentation =
| { readonly phase: 'checking' | 'stopped' }
| { readonly phase: 'disconnected' | 'unavailable' | 'connected'; readonly failed: boolean }
| {
readonly phase: 'connecting'
readonly step: ConnectionStep
readonly operation: WecomOperationId
readonly url: string | undefined
readonly cancellable: boolean
}
export interface ConnectionFace {
hooks: { wecomConnection: HostObservable<ConnectionSnapshot> }
check(): void
connect(): void
cancel(): void
openAuthorization(): void
retry(): void
dismissNotice(): void
}
export function presentConnection(snapshot: Pick<ConnectionSnapshot, 'wecom' | 'stopped'>): ConnectionPresentation {
if (snapshot.stopped) return { phase: 'stopped' }
const state = snapshot.wecom
const operation = state?.operation
if (state === undefined || operation?.kind === 'check') return { phase: 'checking' }
if (operation !== undefined) {
return {
phase: 'connecting',
step: operation.phase === 'authorizing' ? 'authorizing' : 'connecting',
operation: operation.id,
url: operation.authorizationUrl,
cancellable: operation.phase !== 'cancelling',
}
}
const failed = state.result?.outcome === 'failed'
switch (state.account.state) {
case 'unchecked': return failed ? { phase: 'unavailable', failed } : { phase: 'checking' }
case 'unauthorized': return { phase: 'disconnected', failed }
case 'authorized': return { phase: 'connected', failed }
/* v8 ignore next -- closed account state union */
default: return assertNever(state.account.state)
}
}
function openAuthorizationPage(url: string | undefined): void {
if (url !== undefined && URL.canParse(url) && new URL(url).protocol === 'https:') window.open(url, '_blank', 'noopener,noreferrer')
}
async function settle<T>(call: Promise<RemoteResult<T>>): Promise<T> {
const result = await call
if (!result.ok) throw new Error(result.error.message)
return result.value
}
export class WecomConnection {
readonly state: SnapshotStore<ConnectionSnapshot> = createSnapshotStore<ConnectionSnapshot>({
wecom: undefined, linked: false, stopped: false, busy: false, notice: undefined,
})
private started: WecomOperationId | undefined
private readonly opened = new Set<string>()
private seq = 0
private disposed = false
private stream!: RemoteStream<WecomState>
private observing!: Promise<void>
constructor(private readonly ctx: Context) {
this.subscribe()
}
face(): ConnectionFace {
return {
hooks: { wecomConnection: this.state },
check: () => { void this.start(() => this.ctx.remote.wecom.check()) },
connect: () => { void this.start(() => this.ctx.remote.wecom.connect()) },
cancel: () => { void this.cancel() },
openAuthorization: () => {
const shown = presentConnection(this.state.getSnapshot())
if (shown.phase === 'connecting') openAuthorizationPage(shown.url)
},
retry: () => { void this.retry() },
dismissNotice: () => { this.patch({ notice: undefined }) },
}
}
async dispose(): Promise<void> {
this.disposed = true
await this.stream.dispose()
await this.observing
}
private subscribe(): void {
this.stream = this.ctx.remote.$stream<WecomState>({
name: 'WeCom connection', open: signal => this.ctx.remote.wecom.follow(signal),
ended: () => new Error('WeCom connection stream ended'),
carrierFailed: () => { this.patch({ linked: false }) },
})
this.observing = this.observe(this.stream)
}
private async observe(stream: RemoteStream<WecomState>): Promise<void> {
try {
for await (const item of stream) {
this.patch({ wecom: item.value, linked: true })
this.follow(item.value)
item.accept()
}
} catch {
if (!this.disposed) this.patch({ linked: false, stopped: true })
}
}
private async retry(): Promise<void> {
if (this.disposed || !this.state.getSnapshot().stopped) return
await this.stream.dispose()
await this.observing
this.patch({ wecom: undefined, stopped: false })
this.subscribe()
}
private follow(state: WecomState): void {
const operation = state.operation
if (operation !== undefined && operation.id === this.started && operation.authorizationUrl !== undefined
&& !this.opened.has(operation.authorizationUrl)) {
this.opened.add(operation.authorizationUrl)
openAuthorizationPage(operation.authorizationUrl)
}
const result = state.result
if (result === undefined || result.id !== this.started) return
this.started = undefined
if (result.outcome === 'succeeded' && result.kind === 'connect') this.notify('connected')
}
private async start(call: () => Promise<RemoteResult<WecomOperationId>>): Promise<void> {
await this.run(async () => {
this.started = await settle(call())
const current = this.state.getSnapshot().wecom
if (current !== undefined) this.follow(current)
})
}
private async cancel(): Promise<void> {
const shown = presentConnection(this.state.getSnapshot())
if (shown.phase !== 'connecting' || !shown.cancellable) return
await this.run(async () => { await settle(this.ctx.remote.wecom.cancel(shown.operation)) })
}
private async run(operation: () => Promise<void>): Promise<void> {
if (this.state.getSnapshot().busy) return
this.patch({ busy: true })
try {
await operation()
} catch {
this.notify('action-failed')
} finally {
this.patch({ busy: false })
}
}
private patch(change: Partial<ConnectionSnapshot>): void {
this.state.set({ ...this.state.getSnapshot(), ...change })
}
private notify(kind: ConnectionNotice['kind']): void {
if (this.disposed) return
this.seq += 1
this.patch({ notice: { seq: this.seq, kind } })
}
}
@@ -0,0 +1,44 @@
import type { Context } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-api-remotes/client'
import type {} from '@deepseek-ai/dsh-client-locale/client'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
import type {} from '@deepseek-ai/dsh-client-ui-renderer/client'
import wecomRemote from '@deepseek-ai/dsh-wecom-cli/remote'
import { WECOM_PACKAGE, WecomConnection } from './connection.ts'
import { en, NS, zh } from './locales.ts'
import { WecomConnectionActivation, WecomConnectionBadge, WecomConnectionSection, WecomConnectionToast } from './WecomConnection.tsx'
export const inject = ['remote', 'slots', 'locale']
function registerUi(ctx: Context): void {
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'wecom: dictionaries')
const connection = new WecomConnection(ctx)
ctx.effect(() => async () => { await connection.dispose() }, 'wecom: connection')
const face = connection.face()
ctx.slots.inject('plugins.bundle.config', () => ctx.slots.register({
name: 'plugins.bundle.config', key: WECOM_PACKAGE, locale: NS, inject: () => face,
}, WecomConnectionSection))
ctx.slots.inject('plugins.bundle.activation', () => ctx.slots.register({
name: 'plugins.bundle.activation', key: WECOM_PACKAGE, locale: NS, inject: () => face,
}, WecomConnectionActivation))
ctx.slots.inject('plugins.detail.badge', () => ctx.slots.register({
name: 'plugins.detail.badge', id: 'wecom.connection', locale: NS, inject: () => face,
}, WecomConnectionBadge))
ctx.slots.inject('shell.overlay', () => ctx.slots.register({
name: 'shell.overlay', id: 'wecom.connection-toast', locale: NS, inject: () => face,
}, WecomConnectionToast))
}
export async function apply(ctx: Context): Promise<() => Promise<void>> {
const disposeRemote = await ctx.remote.$mount(wecomRemote)
const ui = ctx.inject(['remote.wecom', 'slots', 'locale'], registerUi)
try {
await ui
} catch (error) {
await ui.dispose()
await disposeRemote()
throw error
}
return async () => { await ui.dispose(); await disposeRemote() }
}
@@ -0,0 +1,77 @@
import type {} from '@deepseek-ai/dsh-client-ui-slots'
export const NS = 'wecom'
export const zh = {
'section.title': '企业微信授权',
'status.checking': '正在检查授权',
'status.disconnected': '未授权',
'status.unavailable': '暂时无法读取授权状态',
'status.connected': '已授权',
'status.stopped': '企业微信组件未运行',
'step.authorizing': '等待扫码授权',
'step.connecting': '正在确认授权',
'detail.disconnected': '用企业微信扫码绑定一个智能机器人。授权后,可以在对话中通过这个机器人使用企业微信的文档、日程、会议、待办和消息等功能。',
'detail.unavailable': '没能读取 wecom-cli 的授权状态,可以稍后重试。',
'detail.stopped': '“企业微信 CLI 与技能”组件没有运行,可以在下方组件列表查看原因,处理后重试。',
'detail.connected': '可以在对话中直接请 Agent 使用企业微信。',
'detail.authorizing': '在打开的页面中用企业微信扫码并确认,完成后回到这里查看结果。页面没有打开时,点击“打开扫码页面”。',
hint: '授权与这台电脑终端里的 wecom-cli 共用;关闭插件不会解除授权。',
failed: '操作未完成,请重试',
'action.connect': '连接企业微信',
'action.open': '打开扫码页面',
'action.cancel': '取消',
'action.retry': '重试',
'badge.connected': '已授权',
'badge.disconnected': '未授权',
'badge.connecting': '授权中',
'badge.unavailable': '待确认',
'badge.stopped': '未运行',
'activation.title': '连接企业微信',
'activation.body': '企业微信插件已开启。扫码授权后,就可以在对话中使用它。',
'activation.later': '稍后',
'notice.connected': '企业微信已授权',
'notice.action-failed': '操作未完成,请重试',
close: '关闭',
}
export type WecomKey = keyof typeof zh
export const en: Record<WecomKey, string> = {
'section.title': 'WeCom authorization',
'status.checking': 'Checking authorization',
'status.disconnected': 'Not authorized',
'status.unavailable': 'Cannot read authorization right now',
'status.connected': 'Authorized',
'status.stopped': 'WeCom component not running',
'step.authorizing': 'Waiting for the QR code scan',
'step.connecting': 'Confirming authorization',
'detail.disconnected': 'Scan a QR code with WeCom to bind a smart bot. After that, you can use WeCom docs, calendar, meetings, to-dos, messages, and other features through this bot in conversations.',
'detail.unavailable': 'The wecom-cli authorization could not be read. Try again later.',
'detail.stopped': 'The WeCom CLI and skills component is not running. See the component list below for the reason, then retry.',
'detail.connected': 'Ask the agent to use WeCom directly in a conversation.',
'detail.authorizing': 'Scan the QR code with WeCom on the page that opened and confirm, then come back here to see the result. If the page did not open, select Open QR code page.',
hint: 'The authorization is shared with wecom-cli in this computer\'s terminal. Turning the plugin off does not revoke it.',
failed: 'The action did not finish. Try again.',
'action.connect': 'Connect WeCom',
'action.open': 'Open QR code page',
'action.cancel': 'Cancel',
'action.retry': 'Retry',
'badge.connected': 'Authorized',
'badge.disconnected': 'Not authorized',
'badge.connecting': 'Authorizing',
'badge.unavailable': 'Unconfirmed',
'badge.stopped': 'Not running',
'activation.title': 'Connect WeCom',
'activation.body': 'The WeCom plugin is on. Scan a QR code to authorize it, then use it in conversations.',
'activation.later': 'Later',
'notice.connected': 'WeCom authorized',
'notice.action-failed': 'The action did not finish. Try again.',
close: 'Close',
}
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface LocaleNamespaceMap {
'wecom': WecomKey
}
}
+6
View File
@@ -0,0 +1,6 @@
declare module '*.module.css' {
const classes: Record<string, string>
export default classes
}
declare module '*.css'
+1
View File
@@ -0,0 +1 @@
export function apply(): void {}
@@ -0,0 +1,5 @@
- insert:
- id: wecom
name: '@deepseek-ai/dsh-wecom-cli'
- id: ui-wecom
name: '@deepseek-ai/dsh-client-ui-wecom'
+1
View File
@@ -0,0 +1 @@
export {}