-
+ return
+
+
{label}
diff --git a/plugins/ipollowork-suite/src/client/organization-recipients.tsx b/plugins/ipollowork-suite/src/client/organization-recipients.tsx
index 97aa032d52..1efe9f7946 100644
--- a/plugins/ipollowork-suite/src/client/organization-recipients.tsx
+++ b/plugins/ipollowork-suite/src/client/organization-recipients.tsx
@@ -1,6 +1,7 @@
-import { useState } from "react";
+import { useEffect, useId, useRef, useState } from "react";
import { IconCheckOutlineRegular } from "@deepseek-ai/dsh-client-ui-primitives";
-import { SearchInput } from "../../../_shared/ui/controls.tsx";
+import { FieldPopover, FormButton, SearchInput } from "../../../_shared/ui/controls.tsx";
+import { ChevronDown, lineStroke } from "../../../_shared/ui/icons.ts";
import type { EnterpriseDetail } from "../shared/enterprise.ts";
import { format, type EnterpriseLabels } from "./enterprise-locale.ts";
import { DirectoryStatus, useMemberDirectory, type Call } from "./enterprise-ui.tsx";
@@ -16,8 +17,7 @@ export function EmployeeRecipients({
}) {
const [query, setQuery] = useState("");
const directory = useMemberDirectory(enterpriseId, call, revision, { query, active: true });
- const people = directory.data?.items.filter(member => member.userId !== excludeUserId &&
- (!managersHaveAccess || member.role === "member" || selected.includes(member.userId))) ?? [];
+ const people = directory.data?.items.filter(member => member.userId !== excludeUserId) ?? [];
return
{t.employeeRecipients} · {format(t.peopleCount, { count: selected.length })}
{people.map(person => {
const checked = selected.includes(person.userId);
+ const alreadyGranted = managersHaveAccess && person.role !== "member" && !checked;
const department = detail.departments.find(item => item.id === person.departmentId);
return ;
})}
@@ -42,3 +44,52 @@ export function EmployeeRecipients({
}
;
}
+
+export function DepartmentRecipients({ departments, selected, change, disabled, t }: {
+ departments: EnterpriseDetail["departments"]; selected: string[]; change(next: string[]): void;
+ disabled: boolean; t: EnterpriseLabels;
+}) {
+ const id = useId();
+ const anchor = "--ipw-departments-" + id.replaceAll(":", "");
+ const picker = useRef
(null);
+ const trigger = useRef(null);
+ const [open, setOpen] = useState(false);
+ const shown = open && !disabled;
+ useEffect(() => {
+ if (!shown) return;
+ const closeOutside = (event: PointerEvent) => {
+ if (event.target instanceof Node && !picker.current?.contains(event.target)) setOpen(false);
+ };
+ document.addEventListener("pointerdown", closeOutside);
+ return () => document.removeEventListener("pointerdown", closeOutside);
+ }, [shown]);
+ if (!departments.length) return {t.noDepartments}
;
+ const summary = selected.length ? format(t.departmentSelectionCount, { count: selected.length }) : t.chooseDepartments;
+ return {
+ if (event.relatedTarget instanceof Node && !event.currentTarget.contains(event.relatedTarget)) setOpen(false);
+ }} onKeyDown={event => {
+ if (!shown || event.key !== "Escape") return;
+ event.preventDefault();
+ event.stopPropagation();
+ setOpen(false);
+ trigger.current?.focus();
+ }}>
+
setOpen(value => !value)}>
+ {summary}
+
+ {shown &&
+
+ {departments.map(department => {
+ const checked = selected.includes(department.id);
+ return ;
+ })}
+
+ }
+
;
+}
diff --git a/plugins/ipollowork-suite/src/client/suite.module.css b/plugins/ipollowork-suite/src/client/suite.module.css
index b5992184aa..548e53edf7 100644
--- a/plugins/ipollowork-suite/src/client/suite.module.css
+++ b/plugins/ipollowork-suite/src/client/suite.module.css
@@ -535,15 +535,20 @@ button.rowMain:focus-visible { outline:2px solid var(--dsw-alias-border-selected
.accessDot[data-scope='some'] { background:var(--g-brand-accent, var(--g-brand)); }
.accessDialog { display:flex;flex-direction:column;gap:18px;font-size:13px;color:var(--ipw-text); }
.accessDialog h3 { margin:0 0 8px;font-size:12px;font-weight:500;color:var(--ipw-muted); }
-.accessDialog .filterChip { color:var(--ipw-muted);background:var(--ipw-muted-surface); }
-.accessDialog .filterChip[aria-pressed='true'] { color:var(--ipw-accent);background:var(--ipw-wash);box-shadow:inset 0 0 0 .5px color-mix(in srgb,var(--ipw-accent) 35%,transparent); }
-.accessDialog .chipRow { flex:none; }
+.departmentRecipientField { display:grid;gap:8px; }
+.departmentOptions { display:grid;gap:2px;padding:6px;box-sizing:border-box;max-height:240px;overflow:auto;
+ background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);border:1px solid var(--ipw-border);
+ border-radius:16px;font-size:13px; }
+.departmentOptions label { display:flex;align-items:center;gap:8px;min-height:32px;padding:4px 8px;
+ border-radius:8px;box-sizing:border-box;overflow-wrap:anywhere;cursor:pointer; }
+.departmentOptions label:hover { background:var(--ipw-muted-surface); }
+.departmentOptions input { flex:none;margin:0; }
.recipientSearch { inline-size:100%;margin-block-end:6px; }
.pickList { display:flex;flex-direction:column;max-height:220px;overflow:auto;margin:0 -6px; }
.pickRow { display:flex;align-items:center;gap:10px;min-height:42px;padding:6px;border:0;border-radius:10px;background:transparent;font:inherit;color:inherit;text-align:left;cursor:pointer; }
.pickRow > span:not([data-ipw-monogram]) { flex:1;min-width:0;display:flex;flex-direction:column; }
.pickRow strong { font-size:13px;font-weight:500; }
-.pickRow small { font-size:11.5px;color:var(--ipw-muted); }
+.pickRow small { font-size:11.5px;color:var(--ipw-muted);overflow-wrap:anywhere; }
.pickRow:disabled { cursor:default;opacity:.6; }
.pickCheck { display:grid;place-items:center;width:18px;height:18px;border-radius:50%;color:#fff;box-shadow:inset 0 0 0 1px var(--ipw-border); }
.pickRow[aria-pressed='true'] .pickCheck { background:var(--ipw-accent);box-shadow:none; }
@@ -608,7 +613,7 @@ button.rowMain:focus-visible { outline:2px solid var(--dsw-alias-border-selected
.modelPicker > div { display:flex;flex-wrap:wrap;gap:6px; }
.modelPicker button { display:inline-flex;align-items:center;gap:4px;height:26px;padding:0 10px;border:0;border-radius:999px;font:inherit;font-size:11.5px;color:var(--ipw-muted);background:var(--ipw-muted-surface);cursor:pointer; }
.modelPicker button[aria-pressed='true'] { color:var(--ipw-accent);background:var(--ipw-wash);box-shadow:inset 0 0 0 .5px color-mix(in srgb,var(--ipw-accent) 35%,transparent); }
-:global(body[data-ds-dark-theme]) .accessDialog .filterChip[aria-pressed='true'],:global(body[data-ds-dark-theme]) .modelPicker button[aria-pressed='true'],:global(body[data-ds-dark-theme]) .inlineTest,:global(body[data-ds-dark-theme]) .stackField:focus-within > span { color:var(--ipw-accent); }
+:global(body[data-ds-dark-theme]) .modelPicker button[aria-pressed='true'],:global(body[data-ds-dark-theme]) .inlineTest,:global(body[data-ds-dark-theme]) .stackField:focus-within > span { color:var(--ipw-accent); }
@media (hover:hover) { .departmentItem:not([aria-current]):hover,.pickRow:not(:disabled):hover { background:var(--g-hover, var(--ipw-muted-surface)); }.dropZone:hover { color:var(--g-ink); }.avatarChip button:hover { color:var(--g-ink);background:var(--g-track); }.accessPill:not([data-static]):hover { color:var(--g-ink); } }
@media (max-width:720px) { .departmentLayout { grid-template-columns:1fr; }.departmentNav { position:static;flex-direction:row;overflow-x:auto; }.departmentItem { flex-shrink:0; }.departmentAdd { flex-shrink:0;min-width:140px;margin-top:0; }.accessPill { max-width:140px; }.tabActions { flex-direction:column;align-items:stretch; } }
@media (prefers-reduced-motion:reduce) { .toggle,.toggle span,.dropZone { transition:none; } }
diff --git a/plugins/ipollowork-suite/src/host/account.ts b/plugins/ipollowork-suite/src/host/account.ts
index 46ff5e8d2a..c7f0d0c6b9 100644
--- a/plugins/ipollowork-suite/src/host/account.ts
+++ b/plugins/ipollowork-suite/src/host/account.ts
@@ -10,6 +10,7 @@ import { AppDataRejection, InvitationRosterRejection, ModelServiceError, StageRe
import { desktopEnterprise, hasEnterpriseDesktop } from "./desktop-enterprise.ts";
const KEY = "ipollowork-suite/account";
+const signInPath = "/api/auth/sign-in/email";
type Grant = { version: 1; origin: string; token: string };
type HostAccountState = AccountState & { origin: string };
@@ -46,8 +47,12 @@ function connectionFailure(cause: unknown) {
return { code: "IPW_ACCOUNT_TLS_FAILED", retry: false };
if (codes.length && codes.every(code => timeoutCodes.has(code)))
return { code: "IPW_ACCOUNT_TIMEOUT", retry: true };
- if (cause.message === "terminated" || codes.some(code => socketCodes.has(code)))
- return { code: "IPW_ACCOUNT_CONNECTION_FAILED", retry: true };
+ if (cause.message === "terminated" || codes.some(code => socketCodes.has(code))) {
+ const beforeSecureConnection = cause.message === "fetch failed" && underlying instanceof Error
+ && "code" in underlying && underlying.code === "ECONNRESET"
+ && underlying.message === "Client network socket disconnected before secure TLS connection was established";
+ return { code: "IPW_ACCOUNT_CONNECTION_FAILED", retry: true, beforeSecureConnection };
+ }
return { code: "IPW_ACCOUNT_UNAVAILABLE", retry: codes.length === 0 };
}
@@ -159,8 +164,11 @@ export class AccountService {
if (deadline.aborted) throw new SuiteError("IPW_ACCOUNT_TIMEOUT", 504, { cause });
const attemptTimedOut = first?.aborted && attemptSignal.reason === first.reason;
const connection = connectionFailure(cause);
- if (read && attempt === 0 && (attemptTimedOut || connection?.retry
- || (cause instanceof SuiteError && retryableAccountReads.has(cause.code)))) {
+ const retryRead = read && (attemptTimedOut || connection?.retry
+ || (cause instanceof SuiteError && retryableAccountReads.has(cause.code)));
+ // An HTTPS sign-in can be retried only when TLS failed before any credentials could be sent.
+ const retrySignIn = path === signInPath && response === undefined && connection?.beforeSecureConnection;
+ if (attempt === 0 && (retryRead || retrySignIn)) {
const wait = accountRetryDelay(response);
if (wait <= 2000) {
await delay(wait, undefined, { signal: requestSignal }).catch(error => {
@@ -212,7 +220,7 @@ export class AccountService {
throw new SuiteError("IPW_EMAIL_IN_USE", 409);
throw new SuiteError("IPW_REGISTRATION_REJECTED", 400);
}
- if (path === "/api/auth/sign-in/email" && [400, 401].includes(response.status)) {
+ if (path === signInPath && [400, 401].includes(response.status)) {
const failure = await readJson(response, maximum).catch(() => undefined);
if (object(failure) && ["INVALID_EMAIL_OR_PASSWORD", "INVALID_EMAIL"].some(code => failure.code === code))
throw new SuiteError("IPW_INVALID_LOGIN", 401);
@@ -554,7 +562,7 @@ export class AccountService {
input.password.length > 1024
)
throw new SuiteError("IPW_INVALID_LOGIN");
- return this.authenticate("/api/auth/sign-in/email", {
+ return this.authenticate(signInPath, {
email: input.email.trim(),
password: input.password,
});
diff --git a/plugins/ipollowork-suite/src/ported/client.tsx b/plugins/ipollowork-suite/src/ported/client.tsx
index a54fdfd888..9d7366fc8f 100644
--- a/plugins/ipollowork-suite/src/ported/client.tsx
+++ b/plugins/ipollowork-suite/src/ported/client.tsx
@@ -1,7 +1,7 @@
import React, { useEffect, useRef, useState, useSyncExternalStore, type ComponentType } from 'react'
import { Button, Input } from '@deepseek-ai/dsh-client-ui-primitives'
import { pluginGlyph } from './icons.ts'
-import type { BundleState } from './contracts.ts'
+import { socialLoginPlugins, type BundleState } from './contracts.ts'
interface NativeClient {
effect(effect: () => void | (() => void), label?: string): unknown;
@@ -18,6 +18,16 @@ const workbenchLinkOrigins: Readonly> = {
'wechat-channels-ops': ['https://channels.weixin.qq.com'],
'xiaohongshu-ops': ['https://www.xiaohongshu.com', 'https://creator.xiaohongshu.com'],
}
+type DesktopSocialLoginArgs = { plugin: string; workspace: string; sessionId: string; browserProfileId: string }
+type DesktopSocialLogin = (args: DesktopSocialLoginArgs & { startAtQr?: true }) => Promise
+function desktopSocialLogin(plugin: string) {
+ const desktop = (window as Window & { dshDesktop?: { socialLogin?: DesktopSocialLogin; socialLoginQrEntry?: true } }).dshDesktop
+ const open = desktop?.socialLogin
+ if (!socialLoginPlugins.has(plugin) || typeof open !== 'function') return undefined
+ return (args: DesktopSocialLoginArgs, startAtQr = false) => open(
+ desktop?.socialLoginQrEntry && startAtQr ? { ...args, startAtQr: true } : args,
+ )
+}
const styles = `
.ipw-ported{height:100%;min-width:0;display:flex;flex-direction:column;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base);font:var(--dsw-font-body,13px/1.5 system-ui)}
.ipw-ported header{display:flex;flex-wrap:wrap;align-items:center;gap:12px;padding:16px;padding-top:max(16px,var(--dsh-frame-top-clearance,0px));border-bottom:1px solid var(--dsw-alias-border-l1)}
@@ -108,7 +118,7 @@ function Panel({ ctx, manifest }: { ctx: NativeClient; manifest: DisplayManifest
const target = frame.current?.contentWindow, version = generation.current
const respond = (result: unknown, error = false) => { if (version === generation.current) target?.postMessage({ jsonrpc: '2.0', id: value.id, ...(error ? { error: { code: -32602, message: String(result) } } : { result }) }, window.location.origin) }
try {
- if (value.method === 'ui/initialize') { const sessionId = await sessionFor(); respond({ protocolVersion: '2025-11-21', hostInfo: { name: 'iPolloWork', version: '1' }, hostCapabilities: { message: true, tools: {} }, hostContext: { theme, locale: language, workspaceId: workspace, 'ai.ipollo/workspace': { workspaceId: workspace, sessionId } } }); return }
+ if (value.method === 'ui/initialize') { const sessionId = await sessionFor(); respond({ protocolVersion: '2025-11-21', hostInfo: { name: 'iPolloWork', version: '1' }, hostCapabilities: { message: true, tools: {}, experimental: { 'ai.ipollo/desktop-account-login': Boolean(desktopSocialLogin(manifest.id)) } }, hostContext: { theme, locale: language, workspaceId: workspace, 'ai.ipollo/workspace': { workspaceId: workspace, sessionId } } }); return }
if (value.method === 'ui/update-model-context') { context.current = JSON.stringify(value.params ?? {}).slice(0, 32_000); respond({}); return }
if (value.method === 'ui/message') {
const parts = value.params?.content
@@ -126,6 +136,18 @@ function Panel({ ctx, manifest }: { ctx: NativeClient; manifest: DisplayManifest
respond({ isError: false, browser: 'external', automaticRecognition: false })
return
}
+ if (value.method === 'ui/account-login') {
+ const openLogin = desktopSocialLogin(manifest.id)
+ const browserProfileId = value.params?.browserProfileId
+ if (!openLogin || !workspace || typeof browserProfileId !== 'string' || !/^[a-f\d-]{36}$/i.test(browserProfileId)) {
+ respond({ status: 'unavailable' }); return
+ }
+ const sessionId = await sessionFor()
+ if (version !== generation.current) return
+ const startAtQr = manifest.id === 'wechat-channels-ops' && value.params?.startAtQr === true
+ respond({ status: await openLogin({ plugin: manifest.id, workspace, sessionId, browserProfileId }, startAtQr) })
+ return
+ }
if (value.method === 'tools/call') {
const name = value.params?.name
const action = state?.actions.find(item => item.id === name)
diff --git a/plugins/ipollowork-suite/src/ported/contracts.ts b/plugins/ipollowork-suite/src/ported/contracts.ts
index 50b5cfea47..bc3731109c 100644
--- a/plugins/ipollowork-suite/src/ported/contracts.ts
+++ b/plugins/ipollowork-suite/src/ported/contracts.ts
@@ -46,3 +46,5 @@ export interface BundleState {
connections: { accountId: string; methodId: string; status: string; active: boolean }[];
skills: { id: string; title: string }[];
}
+
+export const socialLoginPlugins = new Set(['douyin-ops', 'wechat-channels-ops', 'xiaohongshu-ops'])
diff --git a/plugins/ipollowork-suite/src/ported/host.ts b/plugins/ipollowork-suite/src/ported/host.ts
index ca911024e8..c55d25bb88 100644
--- a/plugins/ipollowork-suite/src/ported/host.ts
+++ b/plugins/ipollowork-suite/src/ported/host.ts
@@ -16,7 +16,7 @@ import { homedir } from 'node:os'
import { randomUUID } from 'node:crypto'
import { pathToFileURL } from 'node:url'
import { bundleAuthorization } from './credentials.ts'
-import { manifestSchema, type ActionContext, type BusinessRuntime, type BusinessService, type BundleState } from './contracts.ts'
+import { manifestSchema, socialLoginPlugins, type ActionContext, type BusinessRuntime, type BusinessService, type BundleState } from './contracts.ts'
import { capabilityActions } from './media.ts'
import { frameStyle } from './frame-style.ts'
@@ -27,6 +27,11 @@ function frameSetup(nonce = '', prefix = ''): string {
}
const callSchema = z.object({ workspace: z.string().min(1), sessionId: z.string().optional(), resource: z.string(), action: z.string(), input: z.record(z.string(), z.unknown()).default({}) }).strict()
+const socialObservation = z.object({
+ type: z.literal('ipollo-social-login'), requestId: z.number().int().positive(),
+ input: z.object({ plugin: z.string(), workspace: z.string().min(1), sessionId: z.string().min(1),
+ browserProfileId: z.uuid(), url: z.string().max(2000), tree: z.string().min(1).max(25_000) }).strict(),
+})
const mime: Record = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.woff2': 'font/woff2' }
const json = (res: ServerResponse, status: number, value: unknown) => { res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store' }); res.end(JSON.stringify(value)) }
async function body(req: IncomingMessage): Promise {
@@ -91,6 +96,28 @@ export async function applyBundle(ctx: Context, raw: unknown, root: string): Pro
if (!actionFn) throw new Error('Plugin action unavailable')
return actionFn(input, context)
}
+ const observer = socialLoginPlugins.has(manifest.id) && actions.find(action => action.id === 'observe-browser-session')
+ if (observer && process.send) ctx.effect(() => {
+ const receive = (message: unknown): void => {
+ const parsed = socialObservation.safeParse(message)
+ if (!parsed.success || parsed.data.input.plugin !== manifest.id) return
+ const { requestId, input: { workspace: id, sessionId, browserProfileId, url, tree } } = parsed.data
+ const reply = (result: 'waiting' | 'connected' | 'mismatch' | 'duplicate', error?: string): void => {
+ if (process.connected) process.send?.({ type: 'ipollo-social-login', requestId, result, error }, () => {})
+ }
+ void (async () => {
+ const current = workspace(id)
+ if (!current.sessionIds.some(candidate => candidate === sessionId)) throw new Error('Invalid desktop login session')
+ const value = z.object({ connected: z.boolean(), reason: z.string().optional() }).parse(
+ await invoke(id, observer.resource, observer.id, { browserProfileId, url, tree },
+ { directory: current.path, workspaceId: id, sessionId, signal: lifetime.signal }))
+ reply(value.connected ? 'connected' : value.reason === 'duplicate' ? 'duplicate'
+ : value.reason === 'account_mismatch' || value.reason === 'identity_mismatch' ? 'mismatch' : 'waiting')
+ })().catch(() => reply('waiting', 'Account recognition unavailable'))
+ }
+ process.on('message', receive)
+ return () => { process.off('message', receive) }
+ }, 'ported plugin: desktop account recognition')
ctx.effect(() => async () => {
lifetime.abort(); for (const request of pending) request.destroy()
await Promise.allSettled([...services.values()].map(async value => (await value).dispose?.()))
diff --git a/plugins/ipollowork-suite/tests/account.test.ts b/plugins/ipollowork-suite/tests/account.test.ts
index d93635b9df..a03fb74dbd 100644
--- a/plugins/ipollowork-suite/tests/account.test.ts
+++ b/plugins/ipollowork-suite/tests/account.test.ts
@@ -85,6 +85,35 @@ test('account diagnostics distinguish DNS, secure connection, and timeout failur
}
})
+test('sign-in retries a pre-TLS disconnect once and preserves the credential rejection', async () => {
+ const fixture = credentials()
+ const input = { email: user.email, password: 'wrong-password-for-test' }
+ let calls = 0
+ const account = new AccountService(fixture.store, config, new AbortController().signal, async (url, options) => {
+ assert.equal(new URL(String(url)).pathname, '/api/auth/sign-in/email')
+ assert.equal(options?.method, 'POST')
+ assert.deepEqual(JSON.parse(String(options?.body)), input)
+ if (++calls === 1) {
+ const cause = Object.assign(new Error('Client network socket disconnected before secure TLS connection was established'), { code: 'ECONNRESET' })
+ throw new TypeError('fetch failed', { cause })
+ }
+ return json({ code: 'INVALID_EMAIL_OR_PASSWORD' }, 401)
+ })
+ await assert.rejects(account.signIn(input), { code: 'IPW_INVALID_LOGIN', status: 401 })
+ assert.equal(calls, 2)
+ assert.equal(fixture.record(), undefined)
+})
+
+test('sign-in does not replay a reset when the request may have already been sent', async () => {
+ let calls = 0
+ const account = new AccountService(credentials().store, config, new AbortController().signal, async () => {
+ calls++
+ throw new TypeError('fetch failed', { cause: Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }) })
+ })
+ await assert.rejects(account.signIn({ email: user.email, password: 'test-password' }), { code: 'IPW_ACCOUNT_CONNECTION_FAILED' })
+ assert.equal(calls, 1)
+})
+
test('a stalled catalog attempt leaves time for one retry inside the original deadline', async () => {
const stalledConfig = resolveConfig({ accountOrigin: config.accountOrigin, requestTimeoutMs: 5000 })
let calls = 0
diff --git a/plugins/ipollowork-suite/tests/project-ui.test.mjs b/plugins/ipollowork-suite/tests/project-ui.test.mjs
index 94b88bd8f4..85e5bd2f39 100644
--- a/plugins/ipollowork-suite/tests/project-ui.test.mjs
+++ b/plugins/ipollowork-suite/tests/project-ui.test.mjs
@@ -130,7 +130,12 @@ test('project sharing offers all scopes and keeps individual permission edits',a
scope.dispatchEvent(new ui.dom.window.Event('change',{bubbles:true}))
})
assert.equal(ui.button('Save').disabled,true)
- await act(async()=>ui.button('Engineering').click())
+ const picker=scope.closest('[role="dialog"]').querySelector('button[aria-label^="departmentRecipients"]')
+ await act(async()=>picker.click())
+ assert.equal(picker.getAttribute('aria-expanded'),'true')
+ const department=scope.closest('[role="dialog"]').querySelector('[role="group"][aria-label="departmentRecipients"] input[type="checkbox"]')
+ await act(async()=>department.click())
+ assert.equal(department.checked,true)
await act(async()=>ui.button('Save').click())
assert.deepEqual(JSON.parse(JSON.stringify(writes)),[
{method:'PATCH',data:[{subjectId:'member',role:'maintain'}]},
diff --git a/plugins/wechat-channels-ops/README.md b/plugins/wechat-channels-ops/README.md
index ee1972da00..81340c976c 100644
--- a/plugins/wechat-channels-ops/README.md
+++ b/plugins/wechat-channels-ops/README.md
@@ -2,4 +2,6 @@
Native DSH bundle migrated from `wechat-channels-ops` 0.1.16. Install its .tgz through iPolloWork Market or the native DSH Plugin Manager. Choose a registered workspace before opening the workbench. Credentials use the native Host credential store; existing local business data is retained. Disable/uninstall releases tools, Skills, routes and child services while retaining data.
-Build with `npm run build`; run `npm run check` and `npm run pack:check` before packaging. See the repository migration inventory for capability-specific verification and limitations.
+In iPolloWork Desktop with account login support, choose Add by QR code and scan the official code in WeChat. The workbench verifies the account on the Channels dashboard. Use Continue login or Check login to reuse an existing account session. If a local proxy delays the page and the desktop toolbar offers Retry directly, use it to reach the official WeChat login and its resources in the same account session.
+
+Build with `npm run build`. Run `npm run check` and `npm run pack:check` before packaging. See the repository migration inventory for capability-specific verification and limitations.
diff --git a/plugins/wechat-channels-ops/README.zh.md b/plugins/wechat-channels-ops/README.zh.md
index 9c3c94153d..0e33e0a897 100644
--- a/plugins/wechat-channels-ops/README.zh.md
+++ b/plugins/wechat-channels-ops/README.zh.md
@@ -2,4 +2,6 @@
从多引擎分支 `wechat-channels-ops` 0.1.16 移植的 DSH 原生插件。通过 iPolloWork 市场或原生插件管理器安装 .tgz,选择已有工作区后打开工作台。凭据由原生 Host 凭据提供方保存,保留旧版本地业务数据。停用或卸载释放工具、Skill、路由和子服务,保留用户文件。
+在支持账号登录的 iPolloWork 桌面版中,点击「扫码添加账号」并用微信扫描官方二维码。工作台从视频号助手核对账号,已有账号用「继续登录」或「检查登录」可复用原会话。如果本机代理导致页面加载缓慢,且登录窗口提供「直连重试」,可在同一账号会话内直连微信登录页及其资源。
+
运行 `npm run build`、`npm run check`、`npm run pack:check`。各能力的验收与限制见仓库迁移清单。
diff --git a/plugins/wechat-channels-ops/business/service/operations.mjs b/plugins/wechat-channels-ops/business/service/operations.mjs
index 1f1aa80b99..671862eb61 100644
--- a/plugins/wechat-channels-ops/business/service/operations.mjs
+++ b/plugins/wechat-channels-ops/business/service/operations.mjs
@@ -4,6 +4,17 @@ import { Jobs } from './jobs.mjs';
import { now, text, record } from './validation.mjs';
import { officialUrl } from './validation.mjs';
+const channelIdLabel = /^视频号\s*ID/i;
+const channelNameLabel = /^(?:视频号(?:名称|昵称)|账号名称|帐号名称|账户名称)(?:\s*[::]|$)/;
+const pageHeadings = new Set(['视频号助手', '首页', '账号信息', '帐号信息', '账号设置', '帐号设置', '账号管理', '设置']);
+
+function identityField(entries, index, label) {
+ const inline = entries[index]?.value.replace(label, '').replace(/^\s*[::]\s*/, '').trim();
+ if (inline) return inline;
+ const next = entries[index + 1]?.value;
+ return /^[::]$/.test(next ?? '') ? entries[index + 2]?.value : next;
+}
+
export class Operations {
constructor({ store, dataDir, workspaceRoot }) {
this.store = store;
@@ -30,7 +41,8 @@ export class Operations {
return { account: this.store.put('account', account) };
}
connectAccount(input) {
- const prior = input.accountId ? record(this.store, 'account', input.accountId) : null;
+ const prior = input.accountId ? record(this.store, 'account', input.accountId)
+ : this.store.list('account', null, 50).find(item => item.autoNamed && !item.channelId);
if (!prior && this.store.count('account') >= 50) fail('最多管理 50 个账号');
const account = this.store.put('account', { ...prior, id: prior?.id || randomUUID(),
browserProfileId: prior?.browserProfileId || randomUUID(), name: prior?.name || '等待扫码连接',
@@ -42,6 +54,7 @@ export class Operations {
}
observeBrowserSession(input, context) {
const url = new URL(officialUrl(input.url));
+ if (url.origin !== 'https://channels.weixin.qq.com') return { connected: false };
const browserProfileId = text(input.browserProfileId, '浏览器环境', 36);
const account = this.store.list('account', null, 50).find(item => item.browserProfileId === browserProfileId);
if (!account) return { connected: false };
@@ -50,18 +63,24 @@ export class Operations {
verifiedSessionId: null, connectionError: '视频号登录已失效,请重新扫码登录', updatedAt: now() });
return { connected: false, accountId: account.id };
}
- if (!['/platform', '/platform/', '/platform/home'].includes(url.pathname)) return { connected: false };
+ if (!/^\/platform(?:\/home)?\/?$/.test(url.pathname)) return { connected: false };
const tree = text(input.tree, '页面内容', 100_000);
const entries = [...tree.matchAll(/\b(StaticText|heading)\s+("(?:[^"\\]|\\.)*")/g)].map(match => {
- try { return { role: match[1], value: JSON.parse(match[2]) }; } catch { return null; }
+ try { return { role: match[1], value: JSON.parse(match[2]).trim() }; } catch { return null; }
}).filter(Boolean);
- const marker = entries.findIndex(entry => /^视频号ID\s*[::]?\s*\S*$/.test(entry.value));
+ const marker = entries.findIndex(entry => channelIdLabel.test(entry.value));
if (marker < 0) return { connected: false, accountId: account.id };
- const inline = entries[marker].value.replace(/^视频号ID\s*[::]?\s*/, '');
- const actualChannelId = text(inline || entries[marker + 1]?.value, '页面视频号 ID', 100);
- if (/\s/.test(actualChannelId)) return { connected: false, accountId: account.id };
- const actualName = [...entries.slice(0, marker)].reverse().find(entry => entry.role === 'heading' && entry.value.trim())?.value;
- if (!actualName) return { connected: false, accountId: account.id };
+ const actualChannelId = identityField(entries, marker, channelIdLabel);
+ if (!actualChannelId || !/^\S{1,100}$/.test(actualChannelId)
+ || channelNameLabel.test(actualChannelId) || channelIdLabel.test(actualChannelId) || pageHeadings.has(actualChannelId))
+ return { connected: false, accountId: account.id };
+ const nameMarker = entries.findIndex((entry, index) => Math.abs(index - marker) <= 8 && channelNameLabel.test(entry.value));
+ const heading = [...entries.slice(0, marker)].reverse()
+ .find(entry => entry.role === 'heading' && entry.value && !pageHeadings.has(entry.value));
+ const actualName = (nameMarker >= 0 ? identityField(entries, nameMarker, channelNameLabel) : undefined) ?? heading?.value;
+ if (!actualName || actualName.length > 100 || pageHeadings.has(actualName)
+ || channelIdLabel.test(actualName) || channelNameLabel.test(actualName))
+ return { connected: false, accountId: account.id };
const duplicate = this.store.list('account', null, 50).find(item => item.id !== account.id && item.channelId === actualChannelId);
if (duplicate) {
this.store.put('account', { ...account, status: 'conflict', connectionError: '这个视频号已经添加过了', updatedAt: now() });
diff --git a/plugins/wechat-channels-ops/business/skills/wechat-channels-ops-worker/SKILL.md b/plugins/wechat-channels-ops/business/skills/wechat-channels-ops-worker/SKILL.md
index 2b017fc1f6..976d0f67a2 100644
--- a/plugins/wechat-channels-ops/business/skills/wechat-channels-ops-worker/SKILL.md
+++ b/plugins/wechat-channels-ops/business/skills/wechat-channels-ops-worker/SKILL.md
@@ -20,7 +20,7 @@ description: 在 iPolloWork 当前会话中管理微信视频号本地草稿、
## 账号连接
-1. 用户可直接在账号管理弹窗点击「扫码添加账号」。connect-account 会创建账号专属 browserProfileId,ui/open-link 打开 `https://channels.weixin.qq.com/login.html`;扫码进入 `/platform/home` 后,宿主调用 observe-browser-session,从可见昵称和「视频号ID」自动完成绑定。登录页、其他路径、缺少稳定 ID 或昵称都不会标记成功。
+1. 用户可直接在桌面工作台的账号管理弹窗点击「扫码添加账号」。connect-account 会预留账号专属 browserProfileId,桌面登录桥在该会话中打开官方扫码页;扫码进入视频号管理首页后,宿主调用 observe-browser-session,从可见名称和「视频号 ID」完成绑定。未完成扫码或缺少稳定 ID 和名称时保持等待核验。已有账号使用「继续登录」或「检查登录」复用会话。
2. list-accounts 选择用户指定账号。名称仅为本地标签,unverified/connecting 不是已登录。save-account 只用于编辑本地名称、定位、受众和风格,不得手工伪造已核验状态。
3. browser-target 直接返回已登录后台 `/platform/`、browserProfileId 和 profileId,避免从站点根路径误落到登录页。使用宿主 ipollowork_browser_open_url,传 **profileId 完整值**(wechat-channels-ops:UUID),后续一直使用该环境及返回的 tabId。ui/open-link 使用单独的 browserProfileId 字段,由宿主加前缀。
4. 用 ipollowork_browser_snapshot 检查视频号助手可见页面。若仍跳转到登录页,调用 observe-browser-session 记录会话失效;重试登录控件一次后仍需扫码时请用户完成。若页面持续显示「加载失败,点击重试」,说明视频号官方本地登录助手不可用,应提示用户先打开并登录桌面微信,再复用同一账号会话重试;不要换浏览器环境或重复建账号。不代替用户扫码,不读取 Cookie、Local Storage、隐藏接口或其他账号环境。登录后从页面读取实际账号名称和稳定视频号 ID,再调用 verify-account 回写;绑定后的 ID 不可替换。
diff --git a/plugins/wechat-channels-ops/business/ui/app.css b/plugins/wechat-channels-ops/business/ui/app.css
index 173da130ad..b55fbc4884 100644
--- a/plugins/wechat-channels-ops/business/ui/app.css
+++ b/plugins/wechat-channels-ops/business/ui/app.css
@@ -38,6 +38,11 @@
.table-scroll { overflow-x: auto; }
.dialog-content { max-width: 560px; }
.dialog-content .record { padding: 12px 0; }
+ .account-row { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 8px 12px; }
+ .account-row .record-head { align-items: center; justify-content: flex-start; margin: 0; min-width: 0; }
+ .account-row .caption { margin: 0; }
+ .account-row .caption:empty { display: none; }
+ .account-row .actions { margin: 0; }
.file-input { display: none; }
.long-copy { overflow-wrap: anywhere; }
.loading-icon { animation: spin 1s linear infinite; }
diff --git a/plugins/wechat-channels-ops/business/ui/app.js b/plugins/wechat-channels-ops/business/ui/app.js
index 9acfb5fed4..8d018d08d1 100644
--- a/plugins/wechat-channels-ops/business/ui/app.js
+++ b/plugins/wechat-channels-ops/business/ui/app.js
@@ -52,7 +52,7 @@ function hostRequest(method, params) {
timer = setTimeout(() => {
requests.delete(id);
reject(new Error("当前会话未响应,请重新打开运营台。"));
- }, 15000);
+ }, method === "ui/account-login" ? 310000 : 15000);
requests.set(id, { resolve, reject, timer });
parent.postMessage({ jsonrpc: "2.0", id, method, params }, "*");
});
@@ -402,20 +402,33 @@ async function openTarget(target) {
return result;
}
async function connect(id) {
- await getHost();
+ const host = await getHost();
+ if (window.ipolloPortedHost && !host.hostCapabilities?.experimental?.["ai.ipollo/desktop-account-login"])
+ throw new Error("请在支持账号登录的 iPolloWork 桌面版中打开运营台。");
const existing = model.data.accounts.find((item) => item.id === id);
- if (existing?.status === "verified") {
- await selectAccount(id);
- await openTarget(await action("browser-target", { accountId: id }));
+ const target = existing?.status === "verified"
+ ? await action("browser-target", { accountId: id })
+ : await action("connect-account", id ? { accountId: id } : {});
+ const accountId = target.account?.id ?? id;
+ if (model.accountId !== accountId) await selectAccount(accountId);
+ await refresh();
+ if (!window.ipolloPortedHost) {
+ await openTarget(target);
return;
}
- const target = await action("connect-account", id ? { accountId: id } : {});
- await selectAccount(target.account.id);
+ notify("请在登录窗口用微信扫码,完成后会自动连接。");
+ const { status } = await hostRequest("ui/account-login", {
+ browserProfileId: target.browserProfileId,
+ ...(!id && { startAtQr: true }),
+ });
await refresh();
- const result = await openTarget(target);
- notify(result?.browser === "external"
- ? "请在系统浏览器打开的视频号页面扫码。当前工作台无法自动确认该浏览器中的登录。"
- : "请在账号浏览器扫码登录,完成后会自动识别。");
+ if (status === "connected") notify("视频号账号已连接。");
+ else if (status === "closed") notify("登录窗口已关闭,可以重新扫码。");
+ else throw new Error({
+ duplicate: "这个视频号已添加,请切换账号后再试。",
+ mismatch: "登录账号与已绑定账号不同,请切换回原账号。",
+ expired: "暂未识别到登录,请重新扫码并停留在视频号助手首页。",
+ }[status] || "登录窗口暂不可用,请关闭其他登录窗口后重试。");
}
const dispatchKey = (job, reconcile = false) =>
reconcile ? `reconcile:${job.id}:${job.status}:${job.updatedAt}` : job.id;
@@ -502,9 +515,7 @@ function Accounts() {
h(
ui.DialogDescription,
null,
- window.ipolloPortedHost
- ? "在系统浏览器的视频号官方页面扫码,工作台会保留待核验的账号。"
- : "每个账号使用独立的浏览器环境,扫码后自动识别。",
+ "用微信扫码,账号会自动连接。",
),
),
model.notice &&
@@ -521,17 +532,15 @@ function Accounts() {
onClick: () => run("connect", () => connect()),
},
h(ui.Icon, { name: "Plus" }),
- pending.has("connect") ? "正在打开…" : "扫码添加账号",
+ pending.has("connect") ? "等待扫码…" : "扫码添加账号",
),
- window.ipolloPortedHost &&
- h("a", { href: "https://channels.weixin.qq.com/login.html", target: "_blank", rel: "noopener noreferrer" }, "手动打开视频号扫码页"),
h(
"div",
{ className: "stack compact" },
...model.data.accounts.map((item) =>
h(
"article",
- { key: item.id, className: "record" },
+ { key: item.id, className: "record account-row" },
h(
"div",
{ className: "record-head" },
@@ -542,7 +551,7 @@ function Accounts() {
h(
"p",
{ className: "caption" },
- item.channelId || "扫码后识别视频号 ID",
+ item.channelId || null,
),
),
h(
@@ -562,7 +571,7 @@ function Accounts() {
disabled: pending.size > 0,
onClick: () => run("connect", () => connect(item.id)),
},
- item.status === "verified" ? "打开账号" : "登录账号",
+ item.status === "verified" ? "检查登录" : "继续登录",
),
h(
ui.Button,
diff --git a/plugins/wechat-channels-ops/package.json b/plugins/wechat-channels-ops/package.json
index 77b173d70f..b5a7af17a4 100644
--- a/plugins/wechat-channels-ops/package.json
+++ b/plugins/wechat-channels-ops/package.json
@@ -1,6 +1,6 @@
{
"name": "@ipollo/dsh-wechat-channels-ops",
- "version": "0.1.7",
+ "version": "0.1.10",
"description": "管理视频号本地草稿、视频封面素材与运营任务,在原生会话中继续工作。",
"type": "module",
"license": "SEE LICENSE IN LICENSE",
@@ -44,7 +44,7 @@
},
"scripts": {
"build": "node ../../integrations/tooling/ported-plugins.mjs build wechat-channels-ops",
- "check": "node ../../integrations/tooling/ported-plugins.mjs check wechat-channels-ops",
+ "check": "node ../../integrations/tooling/ported-plugins.mjs check wechat-channels-ops && node --test tests/*.test.mjs",
"pack:check": "npm pack --dry-run"
},
"icon": "./icon.svg",
diff --git a/plugins/wechat-channels-ops/tests/login.test.mjs b/plugins/wechat-channels-ops/tests/login.test.mjs
new file mode 100644
index 0000000000..cc6bc6dbdb
--- /dev/null
+++ b/plugins/wechat-channels-ops/tests/login.test.mjs
@@ -0,0 +1,37 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { Operations } from '../business/service/operations.mjs';
+import { Store } from '../business/service/store.mjs';
+
+test('a connected WeChat session replaces the pending account with its visible identity', async () => {
+ const directory = await mkdtemp(join(tmpdir(), 'ipw-channels-login-'));
+ const store = new Store(directory);
+ try {
+ const operations = new Operations({ store, dataDir: directory, workspaceRoot: directory });
+ const { account } = await operations.action('connect-account');
+ const { browserProfileId } = account;
+ const context = { trusted: true, sessionId: 'fixture-session' };
+ const observe = (url, tree) => operations.action('observe-browser-session', { url, tree, browserProfileId }, context);
+ const identity = 'StaticText "视频号 ID"\nStaticText ":"\nStaticText "sph_fixture"\n'
+ + 'StaticText "帐号名称:"\nStaticText "样例视频号"';
+ const homepage = 'https://channels.weixin.qq.com/platform/home/';
+
+ assert.equal((await observe('https://weixin.qq.com/platform/home/', identity)).connected, false);
+ assert.equal((await observe('https://channels.weixin.qq.com/login.html', identity)).connected, false);
+ assert.equal((await observe(homepage, 'heading "视频号助手"\nStaticText "视频号 ID:sph_fixture"')).connected, false);
+ assert.equal(operations.state().accounts[0].status, 'connecting');
+ assert.deepEqual(await observe(homepage, identity), { connected: true, accountId: account.id });
+ assert.deepEqual(operations.state().accounts.map(item => [item.id, item.browserProfileId, item.name, item.channelId, item.status]), [
+ [account.id, browserProfileId, '样例视频号', 'sph_fixture', 'verified'],
+ ]);
+ assert.equal((await observe(homepage, 'heading "其他账号"\nStaticText "视频号ID:sph_other"')).reason, 'identity_mismatch');
+ assert.equal(operations.state().accounts[0].channelId, 'sph_fixture');
+ assert.equal((await observe(homepage, 'heading "样例视频号"\nStaticText "视频号ID:sph_fixture"')).connected, true);
+ } finally {
+ store.close();
+ await rm(directory, { recursive: true, force: true });
+ }
+});
diff --git a/plugins/wechat-official/business/ui/app.js b/plugins/wechat-official/business/ui/app.js
index 2c71d7b1fc..503fb580cd 100644
--- a/plugins/wechat-official/business/ui/app.js
+++ b/plugins/wechat-official/business/ui/app.js
@@ -169,8 +169,8 @@
const accountId = editing ? state.activeAccountId : '';
$('#account-dialog-title').textContent = editing ? '管理公众号' : '添加公众号';
$('#account-dialog-hint').textContent = editing
- ? 'AppID 或 AppSecret 留空会保留原值;保存前会先验证账号凭据。'
- : '每个账号的 AppID 和 AppSecret 会独立保存在 iPolloWork 加密授权仓库中。';
+ ? '留空的凭据会保留原值。'
+ : '填写公众号后台的开发凭据。';
$('#account-name').value = accountId; $('#account-name').readOnly = editing;
$('#account-appid').value = ''; $('#account-secret').value = '';
$('#account-appid').required = !editing; $('#account-secret').required = !editing;
diff --git a/plugins/wechat-official/business/ui/index.html b/plugins/wechat-official/business/ui/index.html
index ae8faff62c..75867c0b41 100644
--- a/plugins/wechat-official/business/ui/index.html
+++ b/plugins/wechat-official/business/ui/index.html
@@ -106,11 +106,11 @@
-