diff --git a/integrations/desktop/package.json b/integrations/desktop/package.json index d2670c671a..0fb9f59336 100644 --- a/integrations/desktop/package.json +++ b/integrations/desktop/package.json @@ -1,7 +1,7 @@ { "name": "@ipollo/desktop", "description": "Electron desktop shell for a bundled dsh runtime and external plugins", - "version": "1.0.22", + "version": "1.0.23", "private": true, "license": "SEE LICENSE IN LICENSE", "author": { diff --git a/integrations/desktop/renderer/social-login-loading.html b/integrations/desktop/renderer/social-login-loading.html new file mode 100644 index 0000000000..2098dff1f0 --- /dev/null +++ b/integrations/desktop/renderer/social-login-loading.html @@ -0,0 +1,95 @@ + + + + + + + + + +
+ +
+

平台账号登录

+

+
+ + + +
+
+
+ +

正在加载平台登录页…

+
+ + +
+
+
+ + + diff --git a/integrations/desktop/src/client/WelcomePage.tsx b/integrations/desktop/src/client/WelcomePage.tsx index 1f4adac4cc..6089b26796 100644 --- a/integrations/desktop/src/client/WelcomePage.tsx +++ b/integrations/desktop/src/client/WelcomePage.tsx @@ -148,6 +148,7 @@ export function Welcome({ api }: { api: WelcomeApi }) { 'invalid-credentials': m.welcomeInvalidCredentials, 'email-in-use': m.welcomeEmailInUse, 'session-rejected': m.welcomeAuthSessionRejected, + 'connection-interrupted': m.welcomeAuthConnectionInterrupted, 'service-unavailable': m.welcomeAuthServiceUnavailable, timeout: m.welcomeAuthTimeout, 'rate-limited': m.welcomeAuthRateLimited, diff --git a/integrations/desktop/src/enterprise-browser.ts b/integrations/desktop/src/enterprise-browser.ts index 4e5c82cd5e..29c5661bbe 100644 --- a/integrations/desktop/src/enterprise-browser.ts +++ b/integrations/desktop/src/enterprise-browser.ts @@ -35,7 +35,8 @@ export class EnterpriseDesktop { private readonly active = new Map() private readonly tracked = new Map void }>() - constructor(private readonly directory: string, private readonly localHost: () => string | undefined) {} + constructor(private readonly directory: string, private readonly localHost: () => string | undefined, + private readonly applicationIconPath: string) {} handle(message: EnterpriseDesktopMessage): Promise { return this.serialize(async () => { @@ -143,7 +144,7 @@ export class EnterpriseDesktop { }) profile.on('will-download', event => event.preventDefault()) const window = new BrowserWindow({ - title: input.label, width: 1060, height: 760, autoHideMenuBar: true, + title: input.label, width: 1060, height: 760, autoHideMenuBar: true, icon: this.applicationIconPath, webPreferences: { session: profile, sandbox: true, contextIsolation: true, nodeIntegration: false, webviewTag: false, devTools: false, navigateOnDragDrop: false, diff --git a/integrations/desktop/src/host-process.ts b/integrations/desktop/src/host-process.ts index 5e9fc81065..e2c684038f 100644 --- a/integrations/desktop/src/host-process.ts +++ b/integrations/desktop/src/host-process.ts @@ -8,6 +8,7 @@ import type { PlatformSession } from '@deepseek-ai/dsh-deepseek-account' import { desktopNodeEnvironment } from './node-environment.ts' import { enterpriseDesktopMessage, type EnterpriseDesktopMessage } from './enterprise-desktop-protocol.ts' import { parsePluginOperationRecord, type PluginOperationRecord, type PluginOperationRunId } from '@deepseek-ai/dsh-plugin-manager/diagnostic' +import type { SocialLoginObservation, SocialLoginObservationResult } from './social-login.ts' interface ReadyEvent { readonly type: 'ready' @@ -46,6 +47,11 @@ type DesktopHostEvent = ReadyEvent | FatalEvent | PlatformSessionEvent | { readonly activeTasks: boolean readonly scheduledTasks: boolean readonly error?: string +} | { + readonly type: 'ipollo-social-login' + readonly requestId: number + readonly result: SocialLoginObservationResult + readonly error?: string } /** Correlated answer to one shell control request. */ @@ -119,6 +125,10 @@ function isDesktopHostEvent(message: unknown): message is DesktopHostEvent { case 'quit-inspection': return Number.isSafeInteger(candidate.requestId) && typeof candidate.activeTasks === 'boolean' && typeof candidate.scheduledTasks === 'boolean' && (candidate.error === undefined || typeof candidate.error === 'string') + case 'ipollo-social-login': + return Number.isSafeInteger(candidate.requestId) && typeof candidate.result === 'string' + && ['waiting', 'connected', 'mismatch', 'duplicate'].includes(candidate.result) + && (candidate.error === undefined || typeof candidate.error === 'string') default: return false } @@ -348,9 +358,16 @@ export class DesktopHostProcess { return response.resource } + async observeSocialLogin(input: SocialLoginObservation, signal: AbortSignal): Promise { + const response = await this.control({ type: 'ipollo-social-login', input }, 8_000, 'Account recognition timed out', 'social login', signal) + if (response.type !== 'ipollo-social-login') throw new Error('Unexpected account recognition response') + return response.result + } + private async control( request: { readonly type: 'update-tasks'; readonly action: 'inspect' | 'lock' | 'unlock' } | { readonly type: 'quit-inspection' } - | { readonly type: 'file-drag-resource'; readonly address: string }, + | { readonly type: 'file-drag-resource'; readonly address: string } + | { readonly type: 'ipollo-social-login'; readonly input: SocialLoginObservation }, deadlineMs: number, deadlineMessage: string, operation: string, signal?: AbortSignal, ): Promise { const child = this.child diff --git a/integrations/desktop/src/ipc.ts b/integrations/desktop/src/ipc.ts index 42bec5ae12..3a725ff68a 100644 --- a/integrations/desktop/src/ipc.ts +++ b/integrations/desktop/src/ipc.ts @@ -7,6 +7,7 @@ import type { DesktopKeyboardApi, DesktopShortcutsApi } from '@deepseek-ai/dsh-c import type { IpcMainInvokeEvent } from 'electron' import type { DesktopBrowserBridge } from '@deepseek-ai/dsh-client-ui-sidebar-browser/types' import type { DesktopFileDrag } from '@deepseek-ai/dsh-util-file-drag' +import type { SocialLoginRequest, SocialLoginResult } from './social-login.ts' export const DESKTOP_VERSION_ARGUMENT = '--ipollo-app-version=' export const DESKTOP_FIXED_UPDATE_CHANNEL_ARGUMENT = '--ipollo-fixed-update-channel' @@ -29,6 +30,7 @@ export const DESKTOP_IPC = { browserAcquire: 'dsh-desktop:browser-acquire', browserRelease: 'dsh-desktop:browser-release', browserOpenRequested: 'dsh-desktop:browser-open-requested', + socialLogin: 'ipollo-desktop:social-login', directoryPick: 'dsh-desktop:directory-pick', fileDragPrepare: 'dsh-desktop:file-drag-prepare', fileDragCancel: 'dsh-desktop:file-drag-cancel', @@ -99,6 +101,8 @@ export interface DshDesktopProductApi { readonly version?: string readonly appVersion: () => Promise readonly browser: DesktopBrowserBridge + readonly socialLogin: (request: SocialLoginRequest) => Promise + readonly socialLoginQrEntry: true readonly organizationBrowser: true readonly organizationPackageSaveAs: true readonly fileDrag: DesktopFileDrag diff --git a/integrations/desktop/src/locale.ts b/integrations/desktop/src/locale.ts index bff0d7179b..f6641e5b72 100644 --- a/integrations/desktop/src/locale.ts +++ b/integrations/desktop/src/locale.ts @@ -87,6 +87,7 @@ export const en = { welcomeAuthExpiredDescription: 'Sign in again to continue', welcomeAuthFailed: 'Could not complete sign in. Please try again.', welcomeInvalidCredentials: 'Incorrect email or password. Please try again.', + welcomeAuthConnectionInterrupted: 'The connection was interrupted before we received a sign-in result. Please try again.', welcomeAuthServiceUnavailable: 'Cannot reach the sign-in service. Check your connection and try again.', welcomeAuthTimeout: 'The sign-in service timed out. Please try again.', welcomeAuthSessionRejected: 'The sign-in session could not be verified. Please try again.', @@ -135,6 +136,11 @@ export const en = { updateDownloadPermissionFailed: 'Cannot write the update files. Check the folder permissions and retry.', updateDownloadBusyFailed: 'An update file is in use. Close the program using it, then retry.', updateInstallFailed: 'Could not install the update. Please try again later.', + updateReadOnlyLocation: 'Move {app} to Applications to update it.', + updateMoveToApplicationsDetail: '{app} will move to Applications and reopen. You can then check for updates again.', + updateMoveToApplications: 'Move and Reopen', + updateOpenApplicationsDetail: "Quit this copy of {app}, then open it from Applications in Finder. If it isn't there yet, drag {bundle} from the disk image or Downloads into Applications.", + updateOpenApplications: 'Open Applications', updateCheckNetworkFailed: 'Could not check for updates. Check your connection and try again.', updateDownloadNetworkFailed: 'Could not download the update. Check your connection and try again.', updateInstallNetworkFailed: 'Could not install the update. Check your connection and try again.', @@ -296,6 +302,7 @@ export const zh = { welcomeAuthExpiredDescription: '请重新登录后继续操作', welcomeAuthFailed: '登录未完成,请重试。', welcomeInvalidCredentials: '邮箱或密码不正确,请重试。', + welcomeAuthConnectionInterrupted: '连接中断,未收到登录验证结果,请重试。', welcomeAuthServiceUnavailable: '无法连接登录服务,请检查网络后重试', welcomeAuthTimeout: '登录服务响应超时,请重试', welcomeAuthSessionRejected: '登录会话验证失败,请重试', @@ -344,6 +351,11 @@ export const zh = { updateDownloadPermissionFailed: '无法写入更新文件,请检查目录权限后重试。', updateDownloadBusyFailed: '更新文件正被占用,请关闭占用它的程序后重试。', updateInstallFailed: '安装更新失败,请稍后重试。', + updateReadOnlyLocation: '请将 {app} 移到「应用程序」后再更新。', + updateMoveToApplicationsDetail: '{app} 会移到「应用程序」并重新打开。打开后可以继续检查更新。', + updateMoveToApplications: '移动并重新打开', + updateOpenApplicationsDetail: '请退出当前的 {app},再从访达的「应用程序」中打开。如果还没有安装,请先从磁盘映像或「下载」文件夹将 {bundle} 拖入「应用程序」。', + updateOpenApplications: '打开「应用程序」', updateCheckNetworkFailed: '检查更新失败,请检查网络连接后重试。', updateDownloadNetworkFailed: '下载更新失败,请检查网络连接后重试。', updateInstallNetworkFailed: '安装更新失败,请检查网络连接后重试。', @@ -503,6 +515,7 @@ export const ja = { welcomeAuthExpiredDescription: '続行するには再度ログインしてください', welcomeAuthFailed: 'ログインを完了できませんでした。もう一度お試しください。', welcomeInvalidCredentials: 'メールアドレスまたはパスワードが正しくありません。もう一度お試しください。', + welcomeAuthConnectionInterrupted: '接続が中断され、ログイン結果を受信できませんでした。もう一度お試しください。', welcomeAuthServiceUnavailable: 'ログインサービスに接続できません。接続を確認して再試行してください。', welcomeAuthTimeout: 'ログインサービスがタイムアウトしました。再試行してください。', welcomeAuthSessionRejected: 'ログインセッションを確認できませんでした。再試行してください。', @@ -551,6 +564,11 @@ export const ja = { updateDownloadPermissionFailed: '更新ファイルを書き込めません。フォルダーのアクセス権を確認して再試行してください。', updateDownloadBusyFailed: '更新ファイルが使用中です。使用しているプログラムを閉じて再試行してください。', updateInstallFailed: 'アップデートをインストールできませんでした。後でもう一度お試しください。', + updateReadOnlyLocation: '{app} を「アプリケーション」に移動してからアップデートしてください。', + updateMoveToApplicationsDetail: '{app} を「アプリケーション」に移動して開き直します。その後、アップデートを再確認できます。', + updateMoveToApplications: '移動して開き直す', + updateOpenApplicationsDetail: 'いま開いている {app} を終了し、Finder の「アプリケーション」から開いてください。まだインストールされていない場合は、ディスクイメージまたは「ダウンロード」から {bundle} を「アプリケーション」にドラッグしてください。', + updateOpenApplications: '「アプリケーション」を開く', updateCheckNetworkFailed: 'アップデートを確認できませんでした。接続を確認してもう一度お試しください。', updateDownloadNetworkFailed: 'アップデートをダウンロードできませんでした。接続を確認してもう一度お試しください。', updateInstallNetworkFailed: 'アップデートをインストールできませんでした。接続を確認してもう一度お試しください。', @@ -710,6 +728,7 @@ export const es = { welcomeAuthExpiredDescription: 'Inicia sesión nuevamente para continuar', welcomeAuthFailed: 'No se pudo completar el inicio de sesión. Inténtelo de nuevo.', welcomeInvalidCredentials: 'El correo electrónico o la contraseña son incorrectos. Inténtalo de nuevo.', + welcomeAuthConnectionInterrupted: 'La conexión se interrumpió antes de recibir el resultado del inicio de sesión. Inténtalo de nuevo.', welcomeAuthServiceUnavailable: 'No se puede conectar con el servicio. Comprueba la conexión e inténtalo de nuevo.', welcomeAuthTimeout: 'El servicio de inicio de sesión tardó demasiado. Inténtalo de nuevo.', welcomeAuthSessionRejected: 'No se pudo verificar la sesión. Inténtalo de nuevo.', @@ -758,6 +777,11 @@ export const es = { updateDownloadPermissionFailed: 'No se pueden escribir los archivos de actualización. Revisa los permisos de la carpeta y vuelve a intentarlo.', updateDownloadBusyFailed: 'Un archivo de actualización está en uso. Cierra el programa que lo usa y vuelve a intentarlo.', updateInstallFailed: 'No se pudo instalar la actualización. Inténtelo de nuevo más tarde.', + updateReadOnlyLocation: 'Mueva {app} a Aplicaciones para actualizarlo.', + updateMoveToApplicationsDetail: '{app} se moverá a Aplicaciones y se volverá a abrir. Después podrá buscar actualizaciones de nuevo.', + updateMoveToApplications: 'Mover y volver a abrir', + updateOpenApplicationsDetail: 'Cierre esta copia de {app} y ábralo desde Aplicaciones en el Finder. Si aún no está allí, arrastre {bundle} desde la imagen de disco o Descargas a Aplicaciones.', + updateOpenApplications: 'Abrir Aplicaciones', updateCheckNetworkFailed: 'No se pudo buscar actualizaciones. Comprueba tu conexión y vuelve a intentarlo.', updateDownloadNetworkFailed: 'No se pudo descargar la actualización. Comprueba tu conexión y vuelve a intentarlo.', updateInstallNetworkFailed: 'No se pudo instalar la actualización. Comprueba tu conexión y vuelve a intentarlo.', @@ -917,6 +941,7 @@ export const fr = { welcomeAuthExpiredDescription: 'Connectez-vous à nouveau pour continuer', welcomeAuthFailed: 'Impossible de terminer la connexion. Veuillez réessayer.', welcomeInvalidCredentials: 'L’adresse e-mail ou le mot de passe est incorrect. Veuillez réessayer.', + welcomeAuthConnectionInterrupted: 'La connexion a été interrompue avant la réception du résultat. Veuillez réessayer.', welcomeAuthServiceUnavailable: 'Service de connexion inaccessible. Vérifiez votre connexion et réessayez.', welcomeAuthTimeout: 'Le service de connexion ne répond pas. Veuillez réessayer.', welcomeAuthSessionRejected: 'La session n’a pas pu être vérifiée. Veuillez réessayer.', @@ -965,6 +990,11 @@ export const fr = { updateDownloadPermissionFailed: 'Impossible d’écrire les fichiers de mise à jour. Vérifiez les autorisations du dossier, puis réessayez.', updateDownloadBusyFailed: 'Un fichier de mise à jour est utilisé. Fermez le programme qui l’utilise, puis réessayez.', updateInstallFailed: "Impossible d'installer la mise à jour. Veuillez réessayer plus tard.", + updateReadOnlyLocation: 'Déplacez {app} dans Applications pour le mettre à jour.', + updateMoveToApplicationsDetail: '{app} sera déplacé dans Applications, puis rouvert. Vous pourrez ensuite rechercher les mises à jour.', + updateMoveToApplications: 'Déplacer et rouvrir', + updateOpenApplicationsDetail: 'Quittez cette copie d’{app}, puis ouvrez l’application depuis Applications dans le Finder. Si elle ne s’y trouve pas encore, faites glisser {bundle} depuis l’image disque ou Téléchargements vers Applications.', + updateOpenApplications: 'Ouvrir Applications', updateCheckNetworkFailed: 'Impossible de vérifier les mises à jour. Vérifiez votre connexion et réessayez.', updateDownloadNetworkFailed: 'Impossible de télécharger la mise à jour. Vérifiez votre connexion et réessayez.', updateInstallNetworkFailed: "Impossible d'installer la mise à jour. Vérifiez votre connexion et réessayez.", @@ -1124,6 +1154,7 @@ export const de = { welcomeAuthExpiredDescription: 'Melden Sie sich erneut an, um fortzufahren', welcomeAuthFailed: 'Die Anmeldung konnte nicht abgeschlossen werden. Bitte versuchen Sie es erneut.', welcomeInvalidCredentials: 'E-Mail-Adresse oder Passwort ist falsch. Bitte versuchen Sie es erneut.', + welcomeAuthConnectionInterrupted: 'Die Verbindung wurde unterbrochen, bevor das Anmeldeergebnis vorlag. Bitte versuchen Sie es erneut.', welcomeAuthServiceUnavailable: 'Der Anmeldedienst ist nicht erreichbar. Prüfen Sie die Verbindung.', welcomeAuthTimeout: 'Zeitüberschreitung beim Anmelden. Bitte versuchen Sie es erneut.', welcomeAuthSessionRejected: 'Die Sitzung konnte nicht geprüft werden. Bitte erneut anmelden.', @@ -1172,6 +1203,11 @@ export const de = { updateDownloadPermissionFailed: 'Update-Dateien können nicht geschrieben werden. Prüfen Sie die Ordnerberechtigungen und versuchen Sie es erneut.', updateDownloadBusyFailed: 'Eine Update-Datei wird verwendet. Schließen Sie das verwendende Programm und versuchen Sie es erneut.', updateInstallFailed: 'Das Update konnte nicht installiert werden. Bitte versuchen Sie es später noch einmal.', + updateReadOnlyLocation: 'Verschieben Sie {app} in den Ordner „Programme“, um es zu aktualisieren.', + updateMoveToApplicationsDetail: '{app} wird in den Ordner „Programme“ verschoben und erneut geöffnet. Anschließend können Sie wieder nach Updates suchen.', + updateMoveToApplications: 'Verschieben und erneut öffnen', + updateOpenApplicationsDetail: 'Beenden Sie diese Kopie von {app} und öffnen Sie die App im Finder aus dem Ordner „Programme“. Falls sie dort noch fehlt, ziehen Sie {bundle} vom Image oder aus „Downloads“ in den Ordner „Programme“.', + updateOpenApplications: 'Ordner „Programme“ öffnen', updateCheckNetworkFailed: 'Es konnte nicht nach Updates gesucht werden. Überprüfen Sie Ihre Verbindung und versuchen Sie es erneut.', updateDownloadNetworkFailed: 'Das Update konnte nicht heruntergeladen werden. Überprüfen Sie Ihre Verbindung und versuchen Sie es erneut.', updateInstallNetworkFailed: 'Das Update konnte nicht installiert werden. Überprüfen Sie Ihre Verbindung und versuchen Sie es erneut.', @@ -1331,6 +1367,7 @@ export const ru = { welcomeAuthExpiredDescription: 'Войдите еще раз, чтобы продолжить', welcomeAuthFailed: 'Не удалось завершить вход. Повторите попытку.', welcomeInvalidCredentials: 'Неверный адрес электронной почты или пароль. Попробуйте ещё раз.', + welcomeAuthConnectionInterrupted: 'Соединение прервано до получения результата входа. Попробуйте ещё раз.', welcomeAuthServiceUnavailable: 'Сервис входа недоступен. Проверьте подключение и повторите попытку.', welcomeAuthTimeout: 'Истекло время ожидания входа. Повторите попытку.', welcomeAuthSessionRejected: 'Не удалось проверить сеанс. Повторите попытку.', @@ -1379,6 +1416,11 @@ export const ru = { updateDownloadPermissionFailed: 'Не удалось записать файлы обновления. Проверьте права доступа к папке и повторите попытку.', updateDownloadBusyFailed: 'Файл обновления занят. Закройте использующую его программу и повторите попытку.', updateInstallFailed: 'Не удалось установить обновление. Пожалуйста, повторите попытку позже.', + updateReadOnlyLocation: 'Переместите {app} в папку «Программы», чтобы обновить приложение.', + updateMoveToApplicationsDetail: '{app} переместится в папку «Программы» и снова откроется. Затем можно повторно проверить наличие обновлений.', + updateMoveToApplications: 'Переместить и открыть снова', + updateOpenApplicationsDetail: 'Закройте эту копию {app}, а затем откройте приложение из папки «Программы» в Finder. Если приложения там ещё нет, перетащите {bundle} из образа диска или папки «Загрузки» в папку «Программы».', + updateOpenApplications: 'Открыть папку «Программы»', updateCheckNetworkFailed: 'Не удалось проверить наличие обновлений. Проверьте подключение и повторите попытку.', updateDownloadNetworkFailed: 'Не удалось загрузить обновление. Проверьте подключение и повторите попытку.', updateInstallNetworkFailed: 'Не удалось установить обновление. Проверьте подключение и повторите попытку.', @@ -1538,6 +1580,7 @@ export const pt = { welcomeAuthExpiredDescription: 'Faça login novamente para continuar', welcomeAuthFailed: 'Não foi possível concluir o login. Tente novamente.', welcomeInvalidCredentials: 'E-mail ou senha incorretos. Tente novamente.', + welcomeAuthConnectionInterrupted: 'A conexão foi interrompida antes de recebermos o resultado do login. Tente novamente.', welcomeAuthServiceUnavailable: 'Não foi possível acessar o serviço. Verifique a conexão e tente novamente.', welcomeAuthTimeout: 'O serviço de login demorou demais. Tente novamente.', welcomeAuthSessionRejected: 'Não foi possível verificar a sessão. Tente novamente.', @@ -1586,6 +1629,11 @@ export const pt = { updateDownloadPermissionFailed: 'Não foi possível gravar os arquivos de atualização. Verifique as permissões da pasta e tente novamente.', updateDownloadBusyFailed: 'Um arquivo de atualização está em uso. Feche o programa que o utiliza e tente novamente.', updateInstallFailed: 'Não foi possível instalar a atualização. Por favor, tente novamente mais tarde.', + updateReadOnlyLocation: 'Mova o {app} para Aplicativos para atualizá-lo.', + updateMoveToApplicationsDetail: 'O {app} será movido para Aplicativos e será reaberto. Depois, você poderá verificar se há atualizações novamente.', + updateMoveToApplications: 'Mover e reabrir', + updateOpenApplicationsDetail: 'Encerre esta cópia do {app} e abra o app em Aplicativos no Finder. Se ele ainda não estiver lá, arraste {bundle} da imagem de disco ou de Downloads para Aplicativos.', + updateOpenApplications: 'Abrir Aplicativos', updateCheckNetworkFailed: 'Não foi possível verificar se há atualizações. Verifique sua conexão e tente novamente.', updateDownloadNetworkFailed: 'Não foi possível baixar a atualização. Verifique sua conexão e tente novamente.', updateInstallNetworkFailed: 'Não foi possível instalar a atualização. Verifique sua conexão e tente novamente.', diff --git a/integrations/desktop/src/macos-update-location.ts b/integrations/desktop/src/macos-update-location.ts new file mode 100644 index 0000000000..cb248b1a91 --- /dev/null +++ b/integrations/desktop/src/macos-update-location.ts @@ -0,0 +1,44 @@ +/** Detect the running Mac bundle rather than the folder where the update ZIP is cached. */ +import { constants } from 'node:fs' +import { access, lstat } from 'node:fs/promises' +import { posix } from 'node:path' + +export const macApplicationsDirectory = '/Applications' + +export function macApplicationBundle(executable: string): string | undefined { + const binaryDirectory = posix.dirname(executable) + const contents = posix.dirname(binaryDirectory) + const bundle = posix.dirname(contents) + if (posix.isAbsolute(executable) && posix.basename(binaryDirectory) === 'MacOS' + && posix.basename(contents) === 'Contents' && posix.extname(bundle) === '.app') return bundle +} + +export function isMacReadOnlyUpdateError(message: string | undefined): boolean { + return /\b(?:cannot update while running on|the application is on) a read[- ]only volume\b/iu.test(message ?? '') + || /\bSQRLUpdaterErrorDomain\s+Code=8\b/u.test(message ?? '') +} + +export async function macUpdateLocationIsReadOnly(bundle: string, check = access): Promise { + if (/\/T\/AppTranslocation\/[^/]+\/d\//u.test(bundle)) return true + try { await check(bundle, constants.W_OK); return false } + catch (error) { return errorCode(error) === 'EROFS' } +} + +/** + * Electron can enter its privileged replacement path before asking its conflict handler. + * Use the native move only for an empty destination the current user can install into. + */ +export async function canMoveMacApplication(bundle: string, check = access, inspect = lstat): Promise { + try { + await check(macApplicationsDirectory, constants.W_OK | constants.X_OK) + try { await inspect(posix.join(macApplicationsDirectory, posix.basename(bundle))) } + catch (error) { return errorCode(error) === 'ENOENT' } + return false + } catch { + return false + } +} + +function errorCode(error: unknown): unknown { + return error instanceof Error && 'code' in error ? error.code : undefined +} diff --git a/integrations/desktop/src/main.ts b/integrations/desktop/src/main.ts index 801e959aec..90572c97ec 100644 --- a/integrations/desktop/src/main.ts +++ b/integrations/desktop/src/main.ts @@ -9,10 +9,10 @@ import type { DesktopChannelState, DesktopChannelChangeResult } from '@deepseek- import { DesktopUpdateSettings, type DesktopUpdateSettingsResult } from './update-settings.ts' import { isDesktopUpdateChannel } from './settings-file.ts' import type { ProductEventMap, ProductEvent } from '@deepseek-ai/dsh-client-product-analytics/types' -import { WINDOWS_TITLEBAR_HEIGHT } from './windows-layout.ts' +import { WINDOWS_CAPTION_BACKGROUND, WINDOWS_TITLEBAR_HEIGHT } from './windows-layout.ts' import { access, readFile, writeFile } from 'node:fs/promises' import { mkdirSync, readFileSync } from 'node:fs' -import { join } from 'node:path' +import { basename, join } from 'node:path' import { fileURLToPath } from 'node:url' import { isDeepStrictEqual } from 'node:util' import { writeFileAtomic } from '@deepseek-ai/dsh-atomic-write' @@ -62,6 +62,7 @@ import { DesktopUpdateJournal } from './update-journal.ts' import { DesktopUpdatePreparationError } from './update-error.ts' import { DesktopUpdateSchedule, resolveDesktopUpdateScheduleConfig } from './update-schedule.ts' import { desktopUpdateErrorSummary, presentDesktopUpdate } from './update-presentation.ts' +import { canMoveMacApplication, isMacReadOnlyUpdateError, macApplicationBundle, macApplicationsDirectory, macUpdateLocationIsReadOnly } from './macos-update-location.ts' import { desktopErrorState } from './startup-error.ts' import { readDesktopLoginShellEnvironment, resolveDesktopLoginShellConfig } from './login-shell-environment.ts' import { DesktopMandatoryUpdatePolicy, resolveDesktopPolicyConfig, type DesktopPolicyState } from './mandatory-update-policy.ts' @@ -73,6 +74,7 @@ import { readDesktopLocaleCache, writeDesktopLocaleCache } from './locale-cache. import { DesktopUpdateDialog, type UpdateDialogOptions } from './update-dialog.ts' import { readDesktopRuntime } from './runtime-tree.ts' import { DesktopBrowserGuests } from './browser-guests.ts' +import { DesktopSocialLogin, socialLoginRequest, type SocialLoginObservation } from './social-login.ts' import { EnterpriseDesktop } from './enterprise-browser.ts' import { installDesktopShortcuts } from './keyboard.ts' import { DesktopUpdateOverlays } from './update-overlay.ts' @@ -261,8 +263,7 @@ function developmentHostInspectPort(enabled: boolean): number | undefined { /** * Opaque chrome fallback matching the built-in sidebar palette (the resolved * `--dsw-static-neutral-bluish-900` / `-50` tokens). An approximation for - * custom themes: Windows captions use the renderer's measured palette over - * windowsAppearance IPC. The Windows workspace base stays opaque and follows + * custom themes. The Windows workspace base stays opaque and follows * the effective light/dark theme; macOS uses it only while minimized or hidden. * @returns the sidebar fill hex for the effective application color scheme. */ @@ -295,7 +296,7 @@ function createWindow(preload: string, applicationIconPath: string, fixedUpdateC icon: applicationIconPath, backgroundColor: chromeFallbackFill(), titleBarStyle: 'hidden' as const, - titleBarOverlay: { height: WINDOWS_TITLEBAR_HEIGHT, color: chromeFallbackFill(), + titleBarOverlay: { height: WINDOWS_TITLEBAR_HEIGHT, color: WINDOWS_CAPTION_BACKGROUND, symbolColor: nativeTheme.shouldUseDarkColors ? '#f9fafb' : '#0f1115' }, } : {}), // hiddenInset places traffic lights inside the sidebar; sidebar vibrancy @@ -516,10 +517,13 @@ async function main(): Promise { }) const appPreload = fileURLToPath(new URL('./preload-app.cjs', import.meta.url)) const applicationUrl = `${SCHEME}://app/` + const applicationIconPath = development ? join(app.getAppPath(), 'resources', 'icon-windows.png') + : join(process.resourcesPath, desktopIdentity.dshApplicationIcon ?? 'icon.png') let hostUrl: string | undefined let hostCookie: string | undefined const browserGuests = new DesktopBrowserGuests(() => hostUrl) - const enterpriseDesktop = new EnterpriseDesktop(join(app.getPath('userData'), 'organization-browser'), () => hostUrl) + const socialLogin = new DesktopSocialLogin() + const enterpriseDesktop = new EnterpriseDesktop(join(app.getPath('userData'), 'organization-browser'), () => hostUrl, applicationIconPath) let injections: readonly unknown[] = [] let welcomeBackend: DesktopWelcomeBackend | undefined let reportedLaunch = false @@ -638,6 +642,7 @@ async function main(): Promise { updateTasks: (action: 'inspect' | 'lock' | 'unlock') => host.updateTasks(action), inspectQuit: () => host.inspectQuit(), resolveDragResource: (address: string, signal?: AbortSignal) => host.resolveDragResource(address, signal), + observeSocialLogin: (input: SocialLoginObservation, signal: AbortSignal) => host.observeSocialLogin(input, signal), } }, (state) => { if (state.phase === 'error') reportFatal(state.failure, 'host') @@ -645,6 +650,68 @@ async function main(): Promise { }) const updateErrors = new WeakMap>() + const macUpdateBundle = process.platform === 'darwin' && app.isPackaged ? macApplicationBundle(process.execPath) : undefined + let macUpdateRecovery: Promise | undefined + const showMacUpdateRecovery = (): Promise => { + if (macUpdateBundle === undefined || quitting || shuttingDown) return Promise.resolve() + if (macUpdateRecovery !== undefined) { updateDialog.focus(); return macUpdateRecovery } + const names = { app: app.name, bundle: basename(macUpdateBundle) } + const canMove = () => !app.isInApplicationsFolder() && canMoveMacApplication(macUpdateBundle) + const parent = () => mandatoryUI?.confirmationWindow ?? currentDialogWindow() + const showFinderRecovery = async (): Promise => { + const messages = locale.messages + const result = await ordinaryMessageBox({ + type: 'info', title: messages.updateTitle, message: formatDesktopMessage(messages.updateReadOnlyLocation, names), + detail: formatDesktopMessage(messages.updateOpenApplicationsDetail, names), + buttons: [messages.updateOpenApplications, messages.updateClose], cancelId: 1, + }, parent()) + if (result.response === 0) { + const error = await shell.openPath(macApplicationsDirectory) + if (error) console.warn('desktop update: could not open the Applications folder') + } + } + macUpdateRecovery = Promise.resolve().then(async () => { + await workspaceRecovery + if (quitting || shuttingDown) return + const host = backend.host + if (host === undefined || !await canMove()) return showFinderRecovery() + const messages = locale.messages + const result = await ordinaryMessageBox({ + type: 'info', title: messages.updateTitle, message: formatDesktopMessage(messages.updateReadOnlyLocation, names), + detail: formatDesktopMessage(messages.updateMoveToApplicationsDetail, names), + buttons: [messages.updateMoveToApplications, messages.updateClose], cancelId: 1, + }, parent()) + if (result.response !== 0 || quitting || shuttingDown) return + if (backend.host !== host) return showFinderRecovery() + let moved = false + try { + await host.updateTasks('lock') + if (!await quitConfirmation.confirm()) return + // Recheck the destination immediately before calling Electron. + if (await canMove()) { + if (quitting || shuttingDown || backend.host !== host) return + const previous = skipQuitConfirmation + try { + skipQuitConfirmation = true + moved = app.moveToApplicationsFolder({ conflictHandler: () => false }) + } finally { + if (!moved) skipQuitConfirmation = previous + } + } + } catch (error) { + console.warn('desktop update: could not move the Mac application', error instanceof Error ? error.name : 'UnknownError') + } finally { + if (!moved) await host.updateTasks('unlock').catch((error: unknown) => { console.error(error) }) + } + if (!moved && !quitting && !shuttingDown) await showFinderRecovery() + }).finally(() => { macUpdateRecovery = undefined }) + return macUpdateRecovery + } + const checkMacUpdateLocation = async (): Promise => { + if (macUpdateBundle === undefined || !await macUpdateLocationIsReadOnly(macUpdateBundle)) return true + await showMacUpdateRecovery() + return false + } const downloadProgress = (state: DesktopUpdateState) => { if (state.phase === 'verifying') return { label: locale.messages.updateVerifying } const percent = Math.min(100, Math.max(0, Math.floor(state.percent ?? 0))) @@ -657,10 +724,11 @@ async function main(): Promise { }).then(() => {}) const showUpdateFailure = (state: DesktopUpdateState): Promise => { if (state.phase !== 'error') return Promise.resolve() - if (isMandatory()) { mandatoryUI?.sync(); return Promise.resolve() } + const recoverLocation = macUpdateBundle !== undefined && isMacReadOnlyUpdateError(state.message) + if (!recoverLocation && isMandatory()) { mandatoryUI?.sync(); return Promise.resolve() } let shown = updateErrors.get(state) if (shown === undefined) { - shown = ordinaryMessageBox({ type: 'error', title: locale.messages.updateFailedTitle, + shown = recoverLocation ? showMacUpdateRecovery() : ordinaryMessageBox({ type: 'error', title: locale.messages.updateFailedTitle, message: desktopUpdateErrorSummary(state, locale.messages), technicalDetails: state.technicalDetails ?? state.message ?? '' }).then(() => {}) updateErrors.set(state, shown) @@ -798,6 +866,7 @@ async function main(): Promise { const updates = new DesktopUpdateCoordinator( publishUpdate, async () => { + if (!await checkMacUpdateLocation()) return false await commandManager.idle() await workspaceRecovery await startup?.catch(() => undefined) @@ -895,6 +964,7 @@ async function main(): Promise { const downloadUpdate = async (version: string, revision = updates.revision): Promise => { if (revision === updates.revision && updates.state.version === version) { + if (!await checkMacUpdateLocation()) return updates.state const plugins = inspectPlugins() if (plugins.blocked) { await showPluginWarning(currentDialogWindow(), plugins) @@ -972,6 +1042,12 @@ async function main(): Promise { assertProductSender(event) return browserGuests.release(event.sender, lease) }) + ipcMain.handle(DESKTOP_IPC.socialLogin, (event, request: unknown) => { + const owner = assertProductSender(event) + const host = backend.host + if (!host || quitting || shuttingDown || isMandatory()) return 'unavailable' + return socialLogin.open(owner, socialLoginRequest.parse(request), host.observeSocialLogin) + }) session.defaultSession.webRequest.onBeforeSendHeaders({ urls: ['ws://127.0.0.1/*', 'wss://127.0.0.1/*'] }, (details, callback) => { if (hostUrl === undefined || hostCookie === undefined || details.webContentsId !== mainWindow?.webContents.id) { @@ -1151,6 +1227,7 @@ async function main(): Promise { let policyAuthenticationQueued = false /** Present check results only while their captured channel revision remains current. */ const openUpdatePrompt = (manual = false): Promise => { + if (macUpdateRecovery !== undefined) { updateDialog.focus(); return macUpdateRecovery } if (channelState?.error !== undefined) { return showConfigurationError() } @@ -1174,6 +1251,7 @@ async function main(): Promise { if (manual) await Promise.all([checkPolicyManually(), updateSchedule.check(true)]) return } + if (!await checkMacUpdateLocation()) return let controller: AbortController | undefined let progress: Promise | undefined try { @@ -1292,8 +1370,6 @@ async function main(): Promise { updates.dispose() }) - const applicationIconPath = development ? join(app.getAppPath(), 'resources', 'icon-windows.png') - : join(process.resourcesPath, desktopIdentity.dshApplicationIcon ?? 'icon.png') app.setAboutPanelOptions({ applicationName: app.getName(), applicationVersion: app.getVersion(), @@ -1673,7 +1749,7 @@ async function main(): Promise { if (policyConfig !== undefined) { if (policyConfig.authentication === 'feishu-test') { policyAuth = new DesktopPolicyTestAuth(policyConfig.origin, policyConfig.allowedAuthOrigins, locale, - () => mandatoryUI?.confirmationWindow ?? currentDialogWindow(), + () => mandatoryUI?.confirmationWindow ?? currentDialogWindow(), applicationIconPath, (event) => { console.info(`desktop policy authentication: ${event}`); updateJournal?.action(`policy-login-${event}`) }) } if (!['win32', 'darwin'].includes(process.platform) || !['x64', 'arm64'].includes(process.arch)) throw new Error('desktop policy: unsupported platform') diff --git a/integrations/desktop/src/policy-test-auth.ts b/integrations/desktop/src/policy-test-auth.ts index e7597a5e57..1fb20950ed 100644 --- a/integrations/desktop/src/policy-test-auth.ts +++ b/integrations/desktop/src/policy-test-auth.ts @@ -28,11 +28,13 @@ export class DesktopPolicyTestAuth { * @param allowedAuthOrigins Validated HTTPS origins for login document navigation. * @param locale Shell-owned login title. * @param parent Current application or mandatory-update window. + * @param applicationIconPath Packaged product artwork for the native login window. * @param record Fixed, nonsecret login outcomes for diagnostic evidence. */ constructor(private readonly origin: string, private readonly allowedAuthOrigins: readonly string[], private readonly locale: DesktopLocale, private readonly parent: () => BrowserWindow | undefined, + private readonly applicationIconPath: string, private readonly record: (event: 'opened' | DesktopPolicyLoginResult) => void) { this.browserSession.setPermissionRequestHandler((_contents, _permission, callback) => { callback(false) }) this.browserSession.setPermissionCheckHandler(() => false) @@ -71,7 +73,7 @@ export class DesktopPolicyTestAuth { const result = Promise.withResolvers() const parent = this.parent() const window = new BrowserWindow({ width: 720, height: 760, ...(parent === undefined ? {} : { parent }), - title: this.locale.messages.policyLoginTitle, autoHideMenuBar: true, + title: this.locale.messages.policyLoginTitle, autoHideMenuBar: true, icon: this.applicationIconPath, webPreferences: { session: this.browserSession, nodeIntegration: false, contextIsolation: true, sandbox: true, webSecurity: true, webviewTag: false, devTools: true, spellcheck: false } }) this.pending = result.promise diff --git a/integrations/desktop/src/preload-app.ts b/integrations/desktop/src/preload-app.ts index 7114d78fc0..0d18a6b253 100644 --- a/integrations/desktop/src/preload-app.ts +++ b/integrations/desktop/src/preload-app.ts @@ -37,6 +37,8 @@ function createProductApi(): DshDesktopProductApi { Promise<{ bytes: Uint8Array; mediaType: string }>, }, browser: createDesktopBrowserBridge(), + socialLogin: request => ipcRenderer.invoke(DESKTOP_IPC.socialLogin, request) as ReturnType, + socialLoginQrEntry: true, organizationBrowser: true, organizationPackageSaveAs: true, fileDrag: { diff --git a/integrations/desktop/src/preload-windows.ts b/integrations/desktop/src/preload-windows.ts index 0534ed16d9..9e38838601 100644 --- a/integrations/desktop/src/preload-windows.ts +++ b/integrations/desktop/src/preload-windows.ts @@ -1,7 +1,7 @@ -import { WINDOWS_TITLEBAR_HEIGHT } from './windows-layout.ts' -/** Synchronizes Windows caption colors with the application document. */ +/** Synchronizes Windows caption symbols with the application document. */ import { ipcRenderer } from 'electron' import { DESKTOP_IPC } from './ipc.ts' +import { WINDOWS_CAPTION_BACKGROUND, WINDOWS_TITLEBAR_HEIGHT } from './windows-layout.ts' /** Install the Windows-only titlebar marker and observe application language and palette changes. */ export function syncWindowsAppearance(): void { @@ -17,39 +17,36 @@ export function syncWindowsAppearance(): void { mark() const root = document.documentElement const probe = document.createElement('span') - probe.style.cssText = 'position:fixed;visibility:hidden;pointer-events:none;background-color:var(--dsw-specific-sidebar-fill);color:var(--dsw-alias-label-primary)' + probe.style.cssText = 'position:fixed;visibility:hidden;pointer-events:none;color-scheme:light dark;color:var(--dsw-alias-label-primary,CanvasText)' document.body.append(probe) const canvas = document.createElement('canvas') canvas.width = canvas.height = 1 const context = canvas.getContext('2d', { willReadFrequently: true }) if (context === null) throw new Error('Desktop caption requires a 2D canvas context') - const nativeColor = (color: string): string => { + const systemPalette = window.matchMedia('(prefers-color-scheme: dark)') + let previous = '' + const send = (): void => { context.clearRect(0, 0, 1, 1) - context.fillStyle = color + context.fillStyle = getComputedStyle(probe).color context.fillRect(0, 0, 1, 1) const [red, green, blue, alpha] = context.getImageData(0, 0, 1, 1).data - return `rgba(${red}, ${green}, ${blue}, ${Number(alpha) / 255})` - } - let previous = '' - const send = (): void => { - const style = getComputedStyle(probe) - const color = nativeColor(style.backgroundColor) - const symbolColor = nativeColor(style.color) - const values = [root.lang, color, symbolColor] - const current = JSON.stringify(values) + const symbolColor = `rgba(${red}, ${green}, ${blue}, ${Number(alpha) / 255})` + const current = root.lang + symbolColor if (current === previous) return previous = current - ipcRenderer.send(DESKTOP_IPC.windowsAppearance, ...values) + ipcRenderer.send(DESKTOP_IPC.windowsAppearance, root.lang, WINDOWS_CAPTION_BACKGROUND, symbolColor) } const observer = new MutationObserver(send) observer.observe(root, { attributes: true, attributeFilter: ['lang'] }) observer.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme', 'style'] }) observer.observe(document.head, { childList: true, subtree: true, characterData: true }) document.head.addEventListener('load', send, true) + systemPalette.addEventListener('change', send) window.addEventListener('pagehide', () => { observer.disconnect() probe.remove() document.head.removeEventListener('load', send, true) + systemPalette.removeEventListener('change', send) }, { once: true }) send() } diff --git a/integrations/desktop/src/social-login-feedback.ts b/integrations/desktop/src/social-login-feedback.ts new file mode 100644 index 0000000000..28346391af --- /dev/null +++ b/integrations/desktop/src/social-login-feedback.ts @@ -0,0 +1,125 @@ +import { WebContentsView, type BrowserWindow, type Input, type Rectangle } from 'electron' +import { WINDOWS_TITLEBAR_HEIGHT } from './windows-layout.ts' + +const toolbarHeight = 52 +const asset = 'renderer/social-login-loading.html' + +interface ChromeState { + label: string + hostname: string + authorization: boolean + notice: string | undefined + message: string | undefined + retry: boolean + directRetry: boolean +} + +export function isSocialLoginReload(input: Input): boolean { + const modifier = process.platform === 'darwin' ? input.meta : input.control + return input.type === 'keyDown' && modifier && !input.alt && !input.shift + && !input.isAutoRepeat && input.key.toLowerCase() === 'r' +} + +/** Keep trusted navigation and feedback above the isolated platform view. */ +export function mountSocialLoginChrome( + owner: BrowserWindow, platform: { label: string; hostname: string }, initialPage: WebContentsView, + actions: { leave(): void; retry(): void; directRetry(): void; back(): void; failed(): void }, +) { + const chrome = new WebContentsView({ webPreferences: { + sandbox: true, contextIsolation: true, nodeIntegration: false, devTools: false, webSecurity: true, + } }) + const contents = chrome.webContents + const state: ChromeState = { ...platform, authorization: false, notice: undefined, message: undefined, retry: false, directRetry: false } + let page = initialPage + let ready = false + let disposed = false + const resize = (): void => { + if (disposed || owner.isDestroyed()) return + const { width, height } = owner.getContentBounds() + const titlebar = process.platform === 'win32' ? WINDOWS_TITLEBAR_HEIGHT : process.platform === 'darwin' ? 42 : 0 + const top = owner.isFullScreen() ? 0 : titlebar + const body: Rectangle = { x: 0, y: top + toolbarHeight, width, height: Math.max(0, height - top - toolbarHeight) } + page.setBounds(body) + chrome.setBounds({ x: 0, y: top, width, height: state.message ? Math.max(toolbarHeight, height - top) : toolbarHeight }) + } + const focus = (): void => { + if (disposed || owner.isDestroyed() || !owner.isFocused()) return + const target = state.message ? contents : page.webContents + if (target && !target.isDestroyed()) target.focus() + } + const render = (): void => { + resize() + if (ready && !contents.isDestroyed()) { + void contents.executeJavaScript(`globalThis.renderSocialLogin(${JSON.stringify(state)})`).catch(() => {}) + } + } + const retry = (): void => { + if (state.authorization) actions.back() + else actions.retry() + } + contents.setWindowOpenHandler(() => ({ action: 'deny' })) + contents.on('will-navigate', event => event.preventDefault()) + contents.on('did-navigate-in-page', (_event, url, mainFrame) => { + const target = URL.parse(url) + if (!mainFrame || target?.protocol !== 'file:' || !target.pathname.endsWith('/' + asset)) return + if (target.hash === '#leave') actions.leave() + if (target.hash === '#back' && state.authorization) actions.back() + if (target.hash === '#retry' && !state.authorization && (!state.message || state.retry)) actions.retry() + if (target.hash === '#direct' && !state.authorization && state.directRetry && (!state.message || state.retry)) actions.directRetry() + }) + contents.on('before-input-event', (event, input) => { + if (!isSocialLoginReload(input)) return + event.preventDefault() + retry() + }) + contents.on('render-process-gone', actions.failed) + contents.once('destroyed', () => { if (!disposed) actions.failed() }) + owner.contentView.addChildView(chrome) + owner.on('resize', resize) + owner.on('enter-full-screen', resize) + owner.on('leave-full-screen', resize) + void contents.loadFile(asset).then(() => { + if (disposed) return + ready = true + render() + focus() + }, () => { if (!disposed) actions.failed() }) + + return { + focus, + show(message: string, canRetry: boolean): void { + state.message = message + state.retry = canRetry + render() + focus() + }, + clear(): void { + const hadFeedback = state.message !== undefined + state.message = undefined + state.retry = false + render() + if (hadFeedback) focus() + }, + directRetry(enabled: boolean): void { state.directRetry = enabled; render() }, + notice(message?: string): void { state.notice = message; render() }, + hostname(hostname: string): void { state.hostname = hostname; render() }, + select(view: WebContentsView, hostname: string, authorization: boolean): void { + if (page.webContents && !page.webContents.isDestroyed()) page.setVisible(false) + page = view + page.setVisible(true) + state.hostname = hostname + state.authorization = authorization + owner.contentView.addChildView(chrome) + render() + focus() + }, + dispose(): void { + disposed = true + owner.off('resize', resize) + owner.off('enter-full-screen', resize) + owner.off('leave-full-screen', resize) + if (!owner.isDestroyed()) owner.contentView.removeChildView(chrome) + if (!contents.isDestroyed()) contents.close({ waitForBeforeUnload: false }) + }, + } +} diff --git a/integrations/desktop/src/social-login.ts b/integrations/desktop/src/social-login.ts new file mode 100644 index 0000000000..44e0f6990b --- /dev/null +++ b/integrations/desktop/src/social-login.ts @@ -0,0 +1,454 @@ +/** Account-specific browser views for the social workbenches. */ +import { createHash } from 'node:crypto' +import { WebContentsView, session, type BrowserWindow, type WebContents, type WebPreferences } from 'electron' +import { z } from 'zod' +import { isSocialLoginReload, mountSocialLoginChrome } from './social-login-feedback.ts' + +// A full-window feedback view can cover the renderer, so Chromium may delay paint timing until it is removed. +const WAIT_FOR_PLATFORM_CONTENT = `new Promise(resolve => { + const hasContent = () => document.body.innerText.trim().length > 0 + || Array.from(document.body.querySelectorAll('img, svg, canvas, iframe, video')).some(element => { + const box = element.getBoundingClientRect() + return box.width > 0 && box.height > 0 && getComputedStyle(element).visibility === 'visible' + && (!(element instanceof HTMLImageElement) || element.naturalWidth > 0) + }) + if (hasContent()) { resolve(true); return } + const check = () => { + if (!hasContent()) return + observer.disconnect() + document.removeEventListener('load', check, true) + resolve(true) + } + const observer = new MutationObserver(check) + observer.observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true }) + document.addEventListener('load', check, true) +})` + +const wechatAssets = 'https://res.wx.qq.com' +const localHttpProxy = /^PROXY ((?:127\.0\.0\.1|localhost|\[::1\]):\d{1,5})$/i + +const platforms = { + 'douyin-ops': { + label: '抖音账号登录', + url: 'https://www.douyin.com/user/self', + origins: ['https://www.douyin.com', 'https://sso.douyin.com', 'https://login.douyin.com'], + page: /^\/user\/[\w-]+\/?$/, + }, + 'wechat-channels-ops': { + label: '视频号账号登录', + url: 'https://channels.weixin.qq.com/platform/', + loginEntry: 'https://channels.weixin.qq.com/login.html', + origins: ['https://channels.weixin.qq.com', 'https://open.weixin.qq.com'], + page: /^\/platform(?:\/home)?\/?$/, + }, + 'xiaohongshu-ops': { + label: '小红书账号登录', + url: 'https://creator.xiaohongshu.com/new/home', + loginEntry: 'https://creator.xiaohongshu.com/login', + origins: ['https://creator.xiaohongshu.com'], + page: /^\/new\/home\/?$/, + }, +} + +export const socialLoginRequest = z.object({ + plugin: z.enum(['douyin-ops', 'wechat-channels-ops', 'xiaohongshu-ops']), + browserProfileId: z.uuid(), + workspace: z.string().min(1).max(4096), + sessionId: z.string().min(1).max(200), + startAtQr: z.literal(true).optional(), +}).strict() +export type SocialLoginRequest = z.infer +export type SocialLoginObservation = Omit & { readonly url: string; readonly tree: string } +export type SocialLoginObservationResult = 'waiting' | 'connected' | 'mismatch' | 'duplicate' +export type SocialLoginResult = Exclude | 'closed' | 'expired' | 'unavailable' + +interface AXNode { + nodeId?: string + childIds?: string[] + ignored?: boolean + role?: { value?: unknown } + name?: { value?: unknown } + properties?: { name: string; value?: { value?: unknown } }[] +} + +/** Keep the rendered identity and account-owner controls in the format the business observers expect. */ +export function socialLoginTree(nodes: readonly AXNode[], plugin?: SocialLoginRequest['plugin']): string { + const byId = new Map(nodes.map(node => [node.nodeId, node])) + const children = new Set(nodes.flatMap(node => node.childIds ?? [])) + const pending = nodes.filter(node => node.nodeId === undefined || !children.has(node.nodeId)).reverse() + const seen = new Set() + const entries: { role: string; text: string; level: unknown }[] = [] + while (pending.length > 0) { + const node = pending.pop()! + if (seen.has(node)) continue + seen.add(node) + const { ignored, role, name, properties, childIds } = node + for (const id of [...(childIds ?? [])].reverse()) { + const child = byId.get(id) + if (child) pending.push(child) + } + if (ignored || typeof name?.value !== 'string' || !name.value.trim() + || !['heading', 'StaticText', 'tab', 'button'].includes(String(role?.value))) continue + entries.push({ + role: String(role?.value), text: name.value.trim().slice(0, 300), + level: properties?.find(property => property.name === 'level')?.value?.value, + }) + } + // Forward the public account labels and their neighbors, not the full page. + const wechat = plugin === 'wechat-channels-ops' + const wechatId = /^视频号\s*ID/i + const wechatName = /^(?:视频号(?:名称|昵称)|账号名称|帐号名称|账户名称)(?:\s*[::]|$)/ + const isText = (role: string): boolean => role === 'StaticText' || role === 'heading' + const marker = entries.findIndex(entry => wechat + ? isText(entry.role) && wechatId.test(entry.text) + : /^(?:抖音号\s*[::]|视频号\s*ID|小红书(?:账号|号)\s*[::])/i.test(entry.text)) + if (marker < 0) return '' + const relevant = new Set([marker]) + if (wechat) { + const addField = (index: number, pattern: RegExp): void => { + const field = entries[index] + if (!field) return + relevant.add(index) + if (field.text.replace(pattern, '').replace(/^[\s::]+/, '')) return + const next = entries[index + 1] + if (next && isText(next.role)) { + relevant.add(index + 1) + if (/^[::]$/.test(next.text) && entries[index + 2] && isText(entries[index + 2]!.role)) relevant.add(index + 2) + } + } + addField(marker, wechatId) + const label = entries.findIndex((entry, index) => Math.abs(index - marker) <= 8 + && isText(entry.role) && wechatName.test(entry.text)) + addField(label, wechatName) + } else relevant.add(marker + 1) + const brand = entries.findIndex(entry => entry.text === '创作服务平台') + if (brand >= 0) { relevant.add(brand); relevant.add(brand + 1) } + const heading = entries.findLastIndex((entry, index) => entry.role === 'heading' && index < marker) + if (heading >= 0) relevant.add(heading) + const topHeading = entries.findLastIndex((entry, index) => entry.role === 'heading' && entry.level === 1 && index < marker) + if (topHeading >= 0) relevant.add(topHeading) + return entries.flatMap(({ role, text, level }, index) => + relevant.has(index) || (['button', 'tab'].includes(role) && ['编辑资料', '批量管理', '私密作品', '观看历史'].includes(text)) + ? [`${role} ${JSON.stringify(text)}${typeof level === 'number' ? ' level=' + String(level) : ''}`] + : []).join('\n') +} + +export class DesktopSocialLogin { + private active: { focus(): void; key: string; result: Promise } | undefined + private readonly configured = new WeakSet() + + open( + owner: BrowserWindow, { startAtQr, ...input }: SocialLoginRequest, + observe: (sample: SocialLoginObservation, signal: AbortSignal) => Promise, + ): Promise { + const key = `${input.plugin}:${input.browserProfileId}` + if (this.active?.key === key) { + this.active.focus() + return this.active.result + } + if (this.active || owner.isDestroyed()) return Promise.resolve('unavailable') + const ownerContents = owner.webContents + const platform = platforms[input.plugin] + const approved = (address: string): boolean => { + const url = URL.parse(address) + return url !== null && platform.origins.includes(url.origin) && !url.username && !url.password + } + const partition = 'persist:ipollo-social-' + createHash('sha256').update(key).digest('hex') + const browserSession = session.fromPartition(partition) + if (!this.configured.has(browserSession)) { + this.configured.add(browserSession) + browserSession.setPermissionCheckHandler(() => false) + browserSession.setPermissionRequestHandler((_contents, _permission, done) => done(false)) + browserSession.setDevicePermissionHandler(() => false) + browserSession.setDisplayMediaRequestHandler((_request, done) => done({})) + browserSession.on('will-download', event => event.preventDefault()) + browserSession.webRequest.onBeforeRequest(({ url, resourceType }, done) => { + const address = new URL(url) + const network = ['https:', 'wss:'].includes(address.protocol) + const remoteName = /[a-z]/i.test(address.hostname) && !address.hostname.includes(':') + && address.hostname.includes('.') && !/\.(localhost|local|internal)\.?$/i.test(address.hostname) + done({ cancel: resourceType === 'mainFrame' ? !approved(url) + : network ? !remoteName || Boolean(address.username || address.password) + : !['about:', 'data:', 'blob:'].includes(address.protocol) }) + }) + } + const webPreferences = { + session: browserSession, sandbox: true, contextIsolation: true, nodeIntegration: false, + webSecurity: true, webviewTag: false, devTools: false, navigateOnDragDrop: false, disableDialogs: true, + } satisfies WebPreferences + const browser = new WebContentsView({ webPreferences }) + owner.contentView.addChildView(browser) + const contents = browser.webContents + const identityOrigin = new URL(platform.url).origin + const identityHostname = new URL(platform.url).hostname + const wechat = input.plugin === 'wechat-channels-ops' + let popup: WebContentsView | undefined + const result = Promise.withResolvers() + const lifetime = new AbortController() + const remove = (view: WebContentsView): void => { + if (!owner.isDestroyed()) owner.contentView.removeChildView(view) + const page = view.webContents + if (page && !page.isDestroyed()) page.close({ waitForBeforeUnload: false }) + } + const finish = (phase: SocialLoginResult): void => { + if (lifetime.signal.aborted) return + lifetime.abort() + clearTimeout(expiration) + clearInterval(poll) + clearTimeout(feedbackTimer) + owner.off('closed', ownerClosed) + ownerContents.off('did-start-navigation', ownerNavigating) + ownerContents.off('render-process-gone', ownerClosed) + chrome.dispose() + if (popup) remove(popup) + remove(browser) + if (!owner.isDestroyed() && owner.isFocused() && !ownerContents.isDestroyed()) ownerContents.focus() + const settle = (): void => { this.active = undefined; result.resolve(phase) } + if (routing) { + void routing.then(async () => { + if (!routingChanged) return + await browserSession.setProxy({ mode: 'system' }) + await browserSession.closeAllConnections() + }).then(settle, settle) + } else settle() + } + let recognition: Promise | undefined + const lastObserved = new WeakMap() + const recognitionFailures = new WeakMap() + let issue: 'mismatch' | 'duplicate' | undefined + let navigation = 0 + const blockedNotice = '此授权页无法在软件内打开,请使用平台扫码登录' + const fallbackEntry = 'loginEntry' in platform ? platform.loginEntry : undefined + let entry = platform.url + let loadFailed = false + let awaitingContent = false + let attempt = 0 + let feedbackTimer: NodeJS.Timeout | undefined + let proxyAddress: string | undefined + let routing: Promise | undefined + let routingChanged = false + let routingPending = false + const ownerClosed = (): void => { finish(issue ?? 'closed') } + const ownerNavigating = (event: { isMainFrame: boolean; isSameDocument: boolean }): void => { + if (event.isMainFrame && !event.isSameDocument) ownerClosed() + } + const retry = (): void => { + if (!routingPending) loadEntry(fallbackEntry && (awaitingContent || loadFailed) ? fallbackEntry : entry) + } + const directRetry = (): void => { + if (!proxyAddress || !fallbackEntry || routing) return + const proxyRules = `http://${proxyAddress}` + attempt++ + awaitingContent = false + routingPending = true + clearTimeout(feedbackTimer) + chrome.directRetry(false) + chrome.show('正在直连视频号登录页…', false) + routing = (async () => { + await browserSession.setProxy({ + mode: 'fixed_servers', proxyRules, + proxyBypassRules: [...platform.origins, wechatAssets].map(origin => origin + ':443').join(','), + }) + routingChanged = true + await browserSession.closeAllConnections() + })().catch(() => { + // The same session can still retry through its current route. + }).then(() => { + routingPending = false + if (!lifetime.signal.aborted) loadEntry(fallbackEntry) + }) + } + const returnToLogin = (notice?: string): void => { + const child = popup + if (!child || lifetime.signal.aborted) return + popup = undefined + navigation++ + clearTimeout(feedbackTimer) + chrome.select(browser, URL.parse(contents.getURL())?.hostname || identityHostname, false) + chrome.clear() + chrome.notice(notice) + remove(child) + } + const chrome = mountSocialLoginChrome(owner, { label: platform.label, hostname: identityHostname }, browser, { + leave: () => { void inspect().then(ownerClosed, ownerClosed) }, retry, directRetry, + back: () => returnToLogin(), failed: () => finish('unavailable'), + }) + if (wechat) { + void Promise.all([browserSession.resolveProxy(platform.url), browserSession.resolveProxy(wechatAssets)]) + .then(([pageProxy, assetsProxy]) => { + if (pageProxy !== assetsProxy || lifetime.signal.aborted) return + proxyAddress = localHttpProxy.exec(pageProxy)?.[1] + if (proxyAddress) chrome.directRetry(true) + }).catch(() => {}) + } + const offerRetry = (message: string): void => { + const canDirectRetry = Boolean(proxyAddress && !routing) + chrome.show(canDirectRetry ? message + '本机正在使用代理,也可以选择直连微信重试。' : message, true) + } + const reportLoadFailure = (): void => { + if (routingPending) return + if (wechat && fallbackEntry && entry === platform.url) { loadEntry(fallbackEntry); return } + loadFailed = true + awaitingContent = false + clearTimeout(feedbackTimer) + offerRetry('暂时无法加载平台登录页,请检查网络后重试。') + } + const preparePage = (page: WebContents, rejected: () => void): void => { + page.on('did-start-navigation', event => { if (event.isMainFrame) navigation++ }) + page.on('will-frame-navigate', event => { + if (event.isMainFrame && !approved(event.url)) { event.preventDefault(); rejected() } + }) + page.on('will-redirect', event => { + if (event.isMainFrame && !approved(event.url)) { event.preventDefault(); rejected() } + }) + page.on('did-navigate', (_event, address) => { + if (page === (popup ?? browser).webContents && approved(address)) chrome.hostname(new URL(address).hostname) + }) + page.on('will-attach-webview', event => event.preventDefault()) + page.on('login', (event, _details, _auth, done) => { event.preventDefault(); done() }) + } + preparePage(contents, () => chrome.notice(blockedNotice)) + const loadEntry = (url: string): void => { + const current = ++attempt + entry = url + loadFailed = false + awaitingContent = true + clearTimeout(feedbackTimer) + chrome.notice() + chrome.show('正在加载' + platform.label + '页面…', false) + feedbackTimer = setTimeout(() => { + const address = URL.parse(contents.getURL()) + // WeChat can keep loading subresources while its management page stays blank. + const stillOnHome = wechat + ? !address || address.protocol === 'about:' || (address.origin === identityOrigin && platform.page.test(address.pathname)) + : contents.getURL() === url && !contents.isLoadingMainFrame() + if (fallbackEntry && url === platform.url && stillOnHome) { + loadEntry(fallbackEntry) + return + } + offerRetry('平台登录页加载较慢。可以继续等待,或点击重试。') + }, 12_000) + void contents.loadURL(url).catch((error: unknown) => { + if (current === attempt && !lifetime.signal.aborted && !popup + && !(error instanceof Error && 'code' in error && error.code === 'ERR_ABORTED')) + reportLoadFailure() + }) + } + contents.on('did-navigate', (_event, url) => { if (approved(url)) loadFailed = false }) + contents.on('dom-ready', () => { + if (popup || !awaitingContent || loadFailed || !approved(contents.getURL())) return + const revision = navigation + const current = attempt + void contents.mainFrame.executeJavaScript(WAIT_FOR_PLATFORM_CONTENT).then((ready: unknown) => { + if (ready !== true || lifetime.signal.aborted || popup || loadFailed || navigation !== revision || attempt !== current) return + awaitingContent = false + clearTimeout(feedbackTimer) + chrome.clear() + }).catch(() => {}) + }) + contents.on('did-fail-load', (_event, code, _description, url, mainFrame) => { + if (wechat && url === platform.url && entry !== platform.url) return + if (!popup && mainFrame && code !== -3) reportLoadFailure() + }) + contents.on('before-input-event', (event, input) => { + if (!isSocialLoginReload(input)) return + event.preventDefault() + retry() + }) + contents.setWindowOpenHandler(({ url }) => { + if (lifetime.signal.aborted || !approved(contents.getURL())) return { action: 'deny' } + if (url !== 'about:blank' && !approved(url)) { + chrome.notice(blockedNotice) + return { action: 'deny' } + } + if (popup) { chrome.focus(); return { action: 'deny' } } + // Adopt Chromium's child contents to keep the opener, referrer and form POST. + return { + action: 'allow', overrideBrowserWindowOptions: { webPreferences }, + createWindow: (options) => { + const child = new WebContentsView({ ...options, webPreferences }) + const page = child.webContents + popup = child + awaitingContent = false + clearTimeout(feedbackTimer) + owner.contentView.addChildView(child) + chrome.notice() + chrome.show('正在加载授权页…', false) + chrome.select(child, URL.parse(url)?.hostname || identityHostname, true) + feedbackTimer = setTimeout(() => { + chrome.show('授权页加载较慢。可以继续等待,或返回登录页重试。', false) + }, 12_000) + const failed = (): void => { + if (popup === child) returnToLogin('无法打开授权页,请重新点击登录或使用扫码登录') + } + preparePage(page, failed) + page.setWindowOpenHandler(() => ({ action: 'deny' })) + page.on('dom-ready', () => { + if (popup !== child || !approved(page.getURL())) return + clearTimeout(feedbackTimer) + chrome.clear() + }) + page.on('did-fail-load', (_event, code, _description, _url, mainFrame) => { + if (mainFrame && code !== -3) failed() + }) + page.on('before-input-event', (event, input) => { + if (!isSocialLoginReload(input)) return + event.preventDefault() + if (popup === child) returnToLogin() + }) + page.once('render-process-gone', failed) + page.once('destroyed', () => { if (popup === child) returnToLogin() }) + return page + }, + } + }) + const addressFor = (page: WebContents | undefined): URL | undefined => { + if (page === undefined || page.isDestroyed() || page.isLoadingMainFrame()) return + const address = URL.parse(page.getURL()) + if (address?.origin === identityOrigin && platform.page.test(address.pathname)) return address + } + const inspectPages = async (): Promise => { + if (lifetime.signal.aborted) return + for (const page of [contents, popup?.webContents]) { + if (lifetime.signal.aborted || page === undefined) return + const address = addressFor(page) + if (!address) continue + const revision = navigation + try { + if (!page.debugger.isAttached()) page.debugger.attach() + const { nodes } = await page.debugger.sendCommand('Accessibility.getFullAXTree') as { nodes: AXNode[] } + if (lifetime.signal.aborted || navigation !== revision) return + const tree = socialLoginTree(nodes, input.plugin) + const url = address.origin + address.pathname + if (!tree || lastObserved.get(page) === url + tree) continue + const observed = await observe({ ...input, url, tree }, lifetime.signal) + if (lifetime.signal.aborted) return + if (recognitionFailures.delete(page) && issue === undefined) chrome.notice() + lastObserved.set(page, url + tree) + if (observed === 'connected') { finish(observed); return } + if (observed === 'mismatch' || observed === 'duplicate') { + issue = observed + chrome.notice(observed === 'duplicate' ? '账号已添加,请切换账号' : '账号不匹配,请切换账号') + } + } catch { + if (lifetime.signal.aborted || navigation !== revision || page.isDestroyed() || page.isLoadingMainFrame()) continue + const failures = (recognitionFailures.get(page) ?? 0) + 1 + if (failures === 3) { finish('unavailable'); return } + recognitionFailures.set(page, failures) + if (issue === undefined) chrome.notice('正在重试账号核验') + } + } + } + const inspect = (): Promise => recognition ??= inspectPages().finally(() => { recognition = undefined }) + const expiration = setTimeout(() => finish(issue ?? 'expired'), 5 * 60_000) + const poll = setInterval(() => { void inspect() }, 1500) + owner.once('closed', ownerClosed) + ownerContents.on('did-start-navigation', ownerNavigating) + ownerContents.once('render-process-gone', ownerClosed) + contents.once('render-process-gone', () => finish('unavailable')) + contents.once('destroyed', () => finish('unavailable')) + this.active = { focus: chrome.focus, key, result: result.promise } + loadEntry(wechat && startAtQr && fallbackEntry ? fallbackEntry : platform.url) + return result.promise + } +} diff --git a/integrations/desktop/src/welcome-api.ts b/integrations/desktop/src/welcome-api.ts index d4a9079003..63b0d315ca 100644 --- a/integrations/desktop/src/welcome-api.ts +++ b/integrations/desktop/src/welcome-api.ts @@ -25,7 +25,7 @@ export type WelcomeSaveResult = { readonly ok: true } | { readonly ok: false } /** Only recognized account rejections cross into the welcome renderer. */ export type WelcomeAccountResult = { readonly ok: true } | { readonly ok: false - readonly reason?: 'invalid-credentials' | 'email-in-use' | 'session-rejected' | 'service-unavailable' | 'timeout' | 'rate-limited' + readonly reason?: 'invalid-credentials' | 'email-in-use' | 'session-rejected' | 'connection-interrupted' | 'service-unavailable' | 'timeout' | 'rate-limited' } /** One-time notification retained by the main process until Welcome receives it. */ diff --git a/integrations/desktop/src/welcome-backend.ts b/integrations/desktop/src/welcome-backend.ts index 92e21b4057..95c6910cf6 100644 --- a/integrations/desktop/src/welcome-backend.ts +++ b/integrations/desktop/src/welcome-backend.ts @@ -98,6 +98,7 @@ export function connectDesktopWelcome( } if (response.status === 429) return { ok: false, reason: 'rate-limited' } if (response.status === 504 || code === 'IPW_ACCOUNT_TIMEOUT') return { ok: false, reason: 'timeout' } + if (response.status === 502 && code === 'IPW_ACCOUNT_CONNECTION_FAILED') return { ok: false, reason: 'connection-interrupted' } if (response.status >= 500) return { ok: false, reason: 'service-unavailable' } return { ok: false } } diff --git a/integrations/desktop/src/windows-layout.ts b/integrations/desktop/src/windows-layout.ts index 0ba4ad5c7e..b6aad7f12f 100644 --- a/integrations/desktop/src/windows-layout.ts +++ b/integrations/desktop/src/windows-layout.ts @@ -2,3 +2,6 @@ /** Windows application titlebar height in device-independent pixels. */ export const WINDOWS_TITLEBAR_HEIGHT = 40 + +/** Let the renderer's current surface paint behind the native caption buttons. */ +export const WINDOWS_CAPTION_BACKGROUND = '#00000000' diff --git a/integrations/desktop/tests/macos-update-location.spec.ts b/integrations/desktop/tests/macos-update-location.spec.ts new file mode 100644 index 0000000000..bbd1370ae1 --- /dev/null +++ b/integrations/desktop/tests/macos-update-location.spec.ts @@ -0,0 +1,61 @@ +import { constants } from 'node:fs' +import { describe, expect, it, vi } from 'vitest' +import { + canMoveMacApplication, + isMacReadOnlyUpdateError, + macApplicationBundle, + macUpdateLocationIsReadOnly, +} from '../src/macos-update-location.ts' + +const installed = '/Applications/iPolloWork.app' +const diskImage = '/Volumes/iPolloWork/iPolloWork.app' +const translocated = '/private/var/folders/ab/cd/T/AppTranslocation/A1B2/d/iPolloWork.app' +const fsError = (code: string) => Object.assign(new Error(code), { code }) + +describe('macOS update location', () => { + it.each([installed, diskImage, translocated])('finds the containing bundle at %s', (bundle) => { + expect(macApplicationBundle(bundle + '/Contents/MacOS/iPolloWork')).toBe(bundle) + expect(macApplicationBundle('/opt/ipollowork')).toBeUndefined() + }) + + it('recognizes translocation regardless of reported access permissions', async () => { + const check = vi.fn().mockResolvedValue(undefined) + await expect(macUpdateLocationIsReadOnly(translocated, check)).resolves.toBe(true) + expect(check).not.toHaveBeenCalled() + }) + + it('distinguishes a read-only disk image from a writable location or a permissions error', async () => { + const check = vi.fn().mockRejectedValueOnce(fsError('EROFS')).mockResolvedValueOnce(undefined).mockRejectedValueOnce(fsError('EACCES')) + await expect(macUpdateLocationIsReadOnly(diskImage, check)).resolves.toBe(true) + expect(check).toHaveBeenCalledWith(diskImage, constants.W_OK) + await expect(macUpdateLocationIsReadOnly(installed, check)).resolves.toBe(false) + await expect(macUpdateLocationIsReadOnly(installed, check)).resolves.toBe(false) + }) + + it.each([ + 'Cannot update while running on a read-only volume. The application is on a read-only volume.', + 'The application is on a read only volume.', + 'Error Domain=SQRLUpdaterErrorDomain Code=8', + ])('recognizes the native error %s', (message) => { + expect(isMacReadOnlyUpdateError(message)).toBe(true) + }) + + it.each(['EROFS: read-only file system, mkdir ~/Library/Caches/ipollo-updater', 'SQRLUpdaterErrorDomain Code=80', undefined])( + 'preserves the original error handling for %s', (message) => { + expect(isMacReadOnlyUpdateError(message)).toBe(false) + }, + ) + + it('allows a move only when Applications is writable and the destination is absent', async () => { + const check = vi.fn().mockResolvedValue(undefined) + const inspect = vi.fn().mockRejectedValueOnce(fsError('ENOENT')).mockResolvedValueOnce({}).mockRejectedValueOnce(fsError('EACCES')) + await expect(canMoveMacApplication(diskImage, check, inspect)).resolves.toBe(true) + expect(check).toHaveBeenCalledWith('/Applications', constants.W_OK | constants.X_OK) + expect(inspect).toHaveBeenCalledWith(installed) + await expect(canMoveMacApplication(diskImage, check, inspect)).resolves.toBe(false) + await expect(canMoveMacApplication(diskImage, check, inspect)).resolves.toBe(false) + check.mockRejectedValueOnce(fsError('EACCES')) + await expect(canMoveMacApplication(diskImage, check, inspect)).resolves.toBe(false) + expect(inspect).toHaveBeenCalledTimes(3) + }) +}) diff --git a/integrations/desktop/tests/policy-test-auth.spec.ts b/integrations/desktop/tests/policy-test-auth.spec.ts index d830dd1d22..4a6884a3c9 100644 --- a/integrations/desktop/tests/policy-test-auth.spec.ts +++ b/integrations/desktop/tests/policy-test-auth.spec.ts @@ -35,7 +35,8 @@ beforeEach(() => { vi.clearAllMocks() browserSession = makeSession(); window = makeWindow() native.partition.mockReturnValue(browserSession); native.create.mockReturnValue(window) - auth = new DesktopPolicyTestAuth('https://policy.example.com', ['https://login.example.com'], resolveDesktopLocale('zh'), () => undefined, record) + auth = new DesktopPolicyTestAuth('https://policy.example.com', ['https://login.example.com'], + resolveDesktopLocale('zh'), () => undefined, 'ipollo-icon.png', record) }) afterEach(async () => { await auth.dispose() }) @@ -55,7 +56,7 @@ it('opens a sandboxed window on explicit action and coalesces logins without aut const pending = auth.login() expect(auth.login()).toBe(pending) expect(native.create).toHaveBeenCalledTimes(1) - expect(native.create.mock.calls[0]![0]).toMatchObject({ title: '登录测试环境', webPreferences: { + expect(native.create.mock.calls[0]![0]).toMatchObject({ title: '登录测试环境', icon: 'ipollo-icon.png', webPreferences: { session: browserSession, nodeIntegration: false, contextIsolation: true, sandbox: true, webSecurity: true, webviewTag: false, devTools: true } }) expect(native.create.mock.calls[0]![0].webPreferences?.preload).toBeUndefined() diff --git a/integrations/desktop/tests/social-login.spec.ts b/integrations/desktop/tests/social-login.spec.ts new file mode 100644 index 0000000000..d59c5c1dcb --- /dev/null +++ b/integrations/desktop/tests/social-login.spec.ts @@ -0,0 +1,334 @@ +import { EventEmitter } from 'node:events' +import type { BrowserWindow, HandlerDetails, WebContentsViewConstructorOptions, WindowOpenHandlerResponse } from 'electron' +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import { DesktopSocialLogin, type SocialLoginRequest } from '../src/social-login.ts' + +const native = vi.hoisted(() => ({ + window: vi.fn(), + partition: vi.fn(), + view: vi.fn<(options: WebContentsViewConstructorOptions) => object>(), +})) +vi.mock('electron', () => ({ + BrowserWindow: function () { return native.window() }, + WebContentsView: function (options: WebContentsViewConstructorOptions) { return native.view(options) }, + session: { fromPartition: native.partition }, +})) + +function makeContents() { + let url = 'about:blank' + let destroyed = false + const contents = Object.assign(new EventEmitter(), { + setWindowOpenHandler: vi.fn<(handler: (details: HandlerDetails) => WindowOpenHandlerResponse) => void>(), + isDestroyed: () => destroyed, + isLoadingMainFrame: () => false, + getURL: () => url, + loadURL: vi.fn(async (next: string) => { url = next }), + loadFile: vi.fn(async (_path: string) => {}), + executeJavaScript: vi.fn(async (_code: string) => {}), + mainFrame: { executeJavaScript: vi.fn().mockResolvedValue(true) }, + debugger: { isAttached: () => true, sendCommand: vi.fn().mockResolvedValue({ nodes: [] }) }, + focus: vi.fn(), + close: vi.fn(() => { + if (destroyed) return + destroyed = true + contents.emit('destroyed') + }), + }) + return contents +} + +function makeView() { + return { webContents: makeContents(), setBounds: vi.fn(), setVisible: vi.fn() } +} + +function makeOwner() { + return Object.assign(new EventEmitter(), { + webContents: makeContents(), contentView: { addChildView: vi.fn(), removeChildView: vi.fn() }, + getContentBounds: () => ({ width: 980, height: 740 }), isFullScreen: () => false, + isDestroyed: () => false, isFocused: () => true, + }) +} + +function openDetails(url: string, withForm = false): HandlerDetails { + return { + url, frameName: '_blank', features: '', disposition: 'foreground-tab', + referrer: { url: 'https://www.douyin.com/user/self', policy: 'strict-origin-when-cross-origin' }, + ...(withForm ? { postBody: { data: [], contentType: 'application/x-www-form-urlencoded' } } : {}), + } +} + +const source = { browserProfileId: '11111111-1111-4111-8111-111111111111', workspace: 'workspace', sessionId: 'session' } +let owner: ReturnType +let browser: ReturnType +let toolbar: ReturnType +let social: DesktopSocialLogin + +beforeEach(() => { + vi.clearAllMocks() + vi.useFakeTimers() + native.partition.mockReturnValue(Object.assign(new EventEmitter(), { + setPermissionCheckHandler: vi.fn(), setPermissionRequestHandler: vi.fn(), setDevicePermissionHandler: vi.fn(), + setDisplayMediaRequestHandler: vi.fn(), webRequest: { onBeforeRequest: vi.fn() }, + resolveProxy: vi.fn().mockResolvedValue('DIRECT'), setProxy: vi.fn().mockResolvedValue(undefined), + closeAllConnections: vi.fn().mockResolvedValue(undefined), + })) + owner = makeOwner() + browser = makeView() + toolbar = makeView() + native.view.mockReset() + native.view.mockReturnValueOnce(browser).mockReturnValueOnce(toolbar) + social = new DesktopSocialLogin() +}) +afterEach(() => { owner.emit('closed'); vi.useRealTimers() }) + +const start = (plugin: SocialLoginRequest['plugin']) => + social.open(owner as unknown as BrowserWindow, { ...source, plugin }, async () => 'waiting') + +function action(name: 'retry' | 'direct' | 'back' | 'leave') { + toolbar.webContents.emit('did-navigate-in-page', {}, 'file:///test/renderer/social-login-loading.html#' + name, true) +} + +function openAuthorization(url: string, withForm = false) { + const handler = browser.webContents.setWindowOpenHandler.mock.calls[0]![0] + return handler(openDetails(url, withForm)) +} + +function createAuthorization(url: string) { + const options = openAuthorization(url, true) + const child = makeView() + native.view.mockReturnValueOnce(child) + expect(options.createWindow?.({})).toBe(child.webContents) + return child +} + +function chromeUpdate() { return toolbar.webContents.executeJavaScript.mock.lastCall?.[0] } + +const platforms: ReadonlyArray<[SocialLoginRequest['plugin'], string, string]> = [ + ['douyin-ops', 'https://www.douyin.com/user/self', 'https://login.douyin.com/authorize'], + ['wechat-channels-ops', 'https://channels.weixin.qq.com/platform/', 'https://open.weixin.qq.com/authorize'], + ['xiaohongshu-ops', 'https://creator.xiaohongshu.com/new/home', 'https://creator.xiaohongshu.com/login'], +] + +it.each(platforms)('opens %s and its authorization inside the owner with one account partition', async (plugin, entry, authorization) => { + const pending = start(plugin) + const options = native.view.mock.calls[0]![0] + expect(options.webPreferences).toMatchObject({ + sandbox: true, contextIsolation: true, nodeIntegration: false, webSecurity: true, webviewTag: false, + }) + expect(openAuthorization('about:blank').action).toBe('allow') + expect(openAuthorization('https://example.com/authorize').action).toBe('deny') + const child = createAuthorization(authorization) + expect(native.view.mock.calls[2]![0].webPreferences?.session).toBe(options.webPreferences?.session) + expect(owner.contentView.addChildView).toHaveBeenCalledWith(child) + expect(native.window).not.toHaveBeenCalled() + expect(browser.webContents.loadURL.mock.calls).toEqual([[entry]]) + action('leave') + expect(await pending).toBe('closed') + expect(owner.contentView.removeChildView).toHaveBeenCalledWith(child) +}) + +it('reuses the active authorization and restores the login page after a blocked redirect', async () => { + const pending = start('douyin-ops') + const child = createAuthorization('https://login.douyin.com/authorize') + await child.webContents.loadURL('https://login.douyin.com/authorize') + child.webContents.emit('dom-ready') + await Promise.resolve() + const nested = child.webContents.setWindowOpenHandler.mock.calls[0]![0] + expect(nested(openDetails('https://login.douyin.com/authorize')).action).toBe('deny') + expect(start('douyin-ops')).toBe(pending) + expect(native.view).toHaveBeenCalledTimes(3) + const preventDefault = vi.fn() + child.webContents.emit('will-redirect', { isMainFrame: true, url: 'https://example.com/', preventDefault }) + expect(preventDefault).toHaveBeenCalledOnce() + expect(child.webContents.isDestroyed()).toBe(true) + expect(browser.setVisible).toHaveBeenLastCalledWith(true) + expect(chromeUpdate()).toContain('重新点击登录') + action('leave') + expect(await pending).toBe('closed') +}) + +it('restores the same login page when the user returns from platform authorization', async () => { + const pending = start('douyin-ops') + const child = createAuthorization('https://login.douyin.com/authorize') + action('back') + expect(child.webContents.isDestroyed()).toBe(true) + expect(browser.setVisible).toHaveBeenLastCalledWith(true) + expect(browser.webContents.loadURL).toHaveBeenCalledOnce() + action('leave') + expect(await pending).toBe('closed') +}) + +it('checks completed authorization even while the opener has no identity', async () => { + const observe = vi.fn().mockResolvedValue('connected') + const pending = social.open(owner as unknown as BrowserWindow, { ...source, plugin: 'douyin-ops' }, observe) + const child = createAuthorization('https://login.douyin.com/authorize') + await child.webContents.loadURL('https://www.douyin.com/user/test?discarded=1') + child.webContents.debugger.sendCommand.mockResolvedValue({ nodes: [ + { role: { value: 'StaticText' }, name: { value: '抖音号:fixture' } }, + ] }) + await vi.advanceTimersByTimeAsync(1500) + expect(observe).toHaveBeenCalledWith(expect.objectContaining({ url: 'https://www.douyin.com/user/test' }), expect.any(AbortSignal)) + expect(await pending).toBe('connected') + expect(child.webContents.isDestroyed()).toBe(true) + expect(browser.webContents.isDestroyed()).toBe(true) + expect(owner.webContents.focus).toHaveBeenCalled() +}) + +it('reports a document failure and retries in the same login view', async () => { + const pending = start('douyin-ops') + browser.webContents.emit('did-fail-load', {}, -105, '', 'https://www.douyin.com/user/self', true) + await Promise.resolve() + expect(chromeUpdate()).toContain('暂时无法加载') + expect(chromeUpdate()).toContain('"retry":true') + const preventDefault = vi.fn() + browser.webContents.emit('before-input-event', { preventDefault }, { type: 'keyDown', key: 'r', control: true, meta: true }) + expect(preventDefault).toHaveBeenCalledOnce() + expect(browser.webContents.loadURL).toHaveBeenCalledTimes(2) + expect(native.view).toHaveBeenCalledTimes(2) + action('leave') + expect(await pending).toBe('closed') +}) + +it('preserves the authorized page when the first account confirmation fails', async () => { + const observe = vi.fn().mockRejectedValueOnce(new Error('Host timed out')).mockResolvedValueOnce('connected') + const pending = social.open(owner as unknown as BrowserWindow, { ...source, plugin: 'douyin-ops' }, observe) + await browser.webContents.loadURL('https://www.douyin.com/user/test/') + browser.webContents.debugger.sendCommand.mockResolvedValue({ nodes: [ + { role: { value: 'StaticText' }, name: { value: '抖音号:fixture' } }, + ] }) + await vi.advanceTimersByTimeAsync(1500) + expect(browser.webContents.isDestroyed()).toBe(false) + expect(chromeUpdate()).toContain('重试账号核验') + await vi.advanceTimersByTimeAsync(1500) + expect(observe).toHaveBeenCalledTimes(2) + expect(browser.webContents.loadURL).toHaveBeenCalledTimes(2) + expect(await pending).toBe('connected') +}) + +it('shows retry after twelve seconds and keeps the toolbar when platform content arrives', async () => { + const paint = Promise.withResolvers() + browser.webContents.mainFrame.executeJavaScript.mockReturnValue(paint.promise) + const pending = start('douyin-ops') + browser.webContents.emit('dom-ready') + await Promise.resolve() + expect(chromeUpdate()).toContain('正在加载抖音账号登录页面') + await vi.advanceTimersByTimeAsync(12_000) + expect(chromeUpdate()).toContain('加载较慢') + action('retry') + expect(browser.webContents.loadURL).toHaveBeenCalledTimes(2) + paint.resolve(true) + await Promise.resolve() + expect(chromeUpdate()).toContain('正在加载抖音账号登录页面') + browser.webContents.mainFrame.executeJavaScript.mockResolvedValue(true) + browser.webContents.emit('dom-ready') + await Promise.resolve() + expect(toolbar.setBounds).toHaveBeenLastCalledWith(expect.objectContaining({ height: 52 })) + expect(owner.contentView.removeChildView).not.toHaveBeenCalled() + action('leave') + expect(await pending).toBe('closed') +}) + +it('tries the official Xiaohongshu login route if the creator home stays blank', async () => { + browser.webContents.mainFrame.executeJavaScript.mockReturnValue(new Promise(() => {})) + const pending = start('xiaohongshu-ops') + browser.webContents.emit('dom-ready') + await vi.advanceTimersByTimeAsync(12_000) + expect(browser.webContents.loadURL.mock.calls).toEqual([ + ['https://creator.xiaohongshu.com/new/home'], ['https://creator.xiaohongshu.com/login'], + ]) + expect(native.view).toHaveBeenCalledTimes(2) + action('leave') + expect(await pending).toBe('closed') +}) + +it('recovers a pending WeChat account from its existing session before returning to the workbench', async () => { + const observe = vi.fn().mockResolvedValue('connected') + const pending = social.open(owner as unknown as BrowserWindow, { ...source, plugin: 'wechat-channels-ops' }, observe) + expect(browser.webContents.loadURL).toHaveBeenCalledExactlyOnceWith('https://channels.weixin.qq.com/platform/') + await browser.webContents.loadURL('https://channels.weixin.qq.com/platform/home/?ignored=1') + browser.webContents.debugger.sendCommand.mockResolvedValue({ nodes: [ + { role: { value: 'button' }, name: { value: '视频号 ID' } }, + ...['视频号 ID', ':', 'sph_test', '帐号名称:', '样例视频号', '不相关内容'].map(value => ({ + role: { value: 'StaticText' }, name: { value }, + })), + ] }) + action('leave') + expect(await pending).toBe('connected') + expect(observe).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + url: 'https://channels.weixin.qq.com/platform/home/', + tree: 'StaticText "视频号 ID"\nStaticText ":"\nStaticText "sph_test"\nStaticText "帐号名称:"\nStaticText "样例视频号"', + }), expect.any(AbortSignal)) +}) + +it('starts at the official QR page when the user adds a WeChat account', async () => { + const pending = social.open(owner as unknown as BrowserWindow, { + ...source, plugin: 'wechat-channels-ops', startAtQr: true, + }, async () => 'waiting') + expect(browser.webContents.loadURL).toHaveBeenCalledExactlyOnceWith('https://channels.weixin.qq.com/login.html') + action('leave') + expect(await pending).toBe('closed') +}) + +it('opens the WeChat QR login even if the blank management page is still loading', async () => { + browser.webContents.mainFrame.executeJavaScript.mockReturnValue(new Promise(() => {})) + vi.spyOn(browser.webContents, 'isLoadingMainFrame').mockReturnValue(true) + const pending = start('wechat-channels-ops') + browser.webContents.emit('dom-ready') + await vi.advanceTimersByTimeAsync(12_000) + expect(browser.webContents.loadURL.mock.calls).toEqual([ + ['https://channels.weixin.qq.com/platform/'], ['https://channels.weixin.qq.com/login.html'], + ]) + action('leave') + expect(await pending).toBe('closed') +}) + +it('falls back once to the WeChat QR page if opening the management page fails', async () => { + const pending = start('wechat-channels-ops') + const failed = (address: string) => browser.webContents.emit('did-fail-load', {}, -100, '', address, true) + failed('https://channels.weixin.qq.com/platform/') + failed('https://channels.weixin.qq.com/platform/') + expect(browser.webContents.loadURL.mock.calls).toEqual([ + ['https://channels.weixin.qq.com/platform/'], ['https://channels.weixin.qq.com/login.html'], + ]) + failed('https://channels.weixin.qq.com/login.html') + await Promise.resolve() + expect(chromeUpdate()).toContain('暂时无法加载') + expect(chromeUpdate()).toContain('"directRetry":false') + action('leave') + expect(await pending).toBe('closed') +}) + +it('offers an explicit WeChat-only direct retry and restores the proxy when the login ends', async () => { + const profile = native.partition.getMockImplementation()!() + profile.resolveProxy.mockResolvedValue('PROXY 127.0.0.1:7890') + const pending = start('wechat-channels-ops') + action('direct') + expect(profile.setProxy).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(24_000) + expect(chromeUpdate()).toContain('"directRetry":true') + action('direct') + await vi.advanceTimersByTimeAsync(0) + expect(profile.setProxy).toHaveBeenCalledExactlyOnceWith({ + mode: 'fixed_servers', proxyRules: 'http://127.0.0.1:7890', + proxyBypassRules: 'https://channels.weixin.qq.com:443,https://open.weixin.qq.com:443,https://res.wx.qq.com:443', + }) + expect(profile.closeAllConnections).toHaveBeenCalledOnce() + expect(browser.webContents.loadURL).toHaveBeenCalledTimes(3) + expect(browser.webContents.loadURL).toHaveBeenLastCalledWith('https://channels.weixin.qq.com/login.html') + expect(native.view).toHaveBeenCalledTimes(2) + action('leave') + expect(await pending).toBe('closed') + expect(profile.setProxy).toHaveBeenLastCalledWith({ mode: 'system' }) + expect(profile.closeAllConnections).toHaveBeenCalledTimes(2) +}) + +it('releases the embedded views when the application reloads', async () => { + const pending = start('douyin-ops') + owner.webContents.emit('did-start-navigation', { isMainFrame: true, isSameDocument: true }) + expect(browser.webContents.isDestroyed()).toBe(false) + owner.webContents.emit('did-start-navigation', { isMainFrame: true, isSameDocument: false }) + expect(await pending).toBe('closed') + expect(toolbar.webContents.isDestroyed()).toBe(true) + expect(browser.webContents.isDestroyed()).toBe(true) + expect(vi.getTimerCount()).toBe(0) +}) diff --git a/integrations/desktop/tests/welcome-host.spec.ts b/integrations/desktop/tests/welcome-host.spec.ts index 41074c6ee8..6f2015012b 100644 --- a/integrations/desktop/tests/welcome-host.spec.ts +++ b/integrations/desktop/tests/welcome-host.spec.ts @@ -160,9 +160,11 @@ it('uses the iPolloWork account service without returning the session grant', as it.each([ [401, 'IPW_SIGN_IN_REQUIRED', { ok: false, reason: 'session-rejected' }], + [401, 'IPW_INVALID_LOGIN', { ok: false, reason: 'invalid-credentials' }], [400, 'IPW_INVALID_LOGIN', { ok: false, reason: 'invalid-credentials' }], [401, 'UNRELATED_ERROR', { ok: false }], [502, 'IPW_ACCOUNT_UNAVAILABLE', { ok: false, reason: 'service-unavailable' }], + [502, 'IPW_ACCOUNT_CONNECTION_FAILED', { ok: false, reason: 'connection-interrupted' }], [504, 'IPW_ACCOUNT_TIMEOUT', { ok: false, reason: 'timeout' }], [429, 'IPW_ACCOUNT_UNAVAILABLE', { ok: false, reason: 'rate-limited' }], ] as const)('returns a safe sign-in result for HTTP %s with %s', async (status, error, expected) => { diff --git a/integrations/desktop/tests/welcome-renderer.client.spec.tsx b/integrations/desktop/tests/welcome-renderer.client.spec.tsx index de9d40e917..194078ab07 100644 --- a/integrations/desktop/tests/welcome-renderer.client.spec.tsx +++ b/integrations/desktop/tests/welcome-renderer.client.spec.tsx @@ -346,6 +346,7 @@ it('reports each return to the welcome entry once, including account cancellatio it.each([ [{ ok: false, reason: 'invalid-credentials' }, '邮箱或密码不正确,请重试。'], [{ ok: false, reason: 'session-rejected' }, '登录会话验证失败,请重试'], + [{ ok: false, reason: 'connection-interrupted' }, '连接中断,未收到登录验证结果,请重试。'], [{ ok: false, reason: 'service-unavailable' }, '无法连接登录服务,请检查网络后重试'], [{ ok: false, reason: 'timeout' }, '登录服务响应超时,请重试'], [{ ok: false, reason: 'rate-limited' }, '登录尝试次数过多,请稍后重试'], diff --git a/integrations/desktop/vitest.config.ts b/integrations/desktop/vitest.config.ts index adb0ae46a2..baa8946e51 100644 --- a/integrations/desktop/vitest.config.ts +++ b/integrations/desktop/vitest.config.ts @@ -14,6 +14,8 @@ export default defineConfig({ 'integrations/desktop/tests/account-origin.spec.ts', 'integrations/desktop/tests/development-project.spec.ts', 'integrations/desktop/tests/plugin-update.spec.ts', + 'integrations/desktop/tests/macos-update-location.spec.ts', + 'integrations/desktop/tests/social-login.spec.ts', 'integrations/desktop/tests/smoke-runtime.spec.ts', 'integrations/desktop/tests/welcome-renderer.client.spec.tsx'], setupFiles: ['./scripts/test-proxy-environment.ts'], diff --git a/integrations/runtime/compatibility.md b/integrations/runtime/compatibility.md index 845c513c68..2ab0eb8af1 100644 --- a/integrations/runtime/compatibility.md +++ b/integrations/runtime/compatibility.md @@ -40,7 +40,7 @@ The optional nine-step beginner tour uses native `configForms`, `settings.sectio Service schema 22 is an existing product migration, not a new DSH schema. Build copies every migration through the exported service schema constant. Deployment reads the target version from the built image instead of assuming schema 21; verify backups, forward migration and post-cutover readiness against the actual server before declaring deployment complete. -The first-run and restart loading branches share `plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.tsx`. The existing `shell.overlay` entry uses the public `IconLoadingOutlineRegular` and the DSH theme label color. On the next pin, hold the settings or account read pending during desktop startup and verify the centered indicator, titlebar clearance, light and dark themes, reduced motion and disappearance when the read settles. +The first-run and restart loading branches share `plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.tsx`. The existing `shell.overlay` entry uses the public `IconLoadingOutlineRegular` and the DSH theme tokens, with critical loading styles available before the Suite stylesheet arrives. On Windows, the desktop shell keeps native caption backgrounds transparent and the preload reads `--dsw-alias-label-primary` for their symbols. On the next pin, delay both the Suite stylesheet and settings or account reads during desktop startup. Verify the connected caption background from boot through workspace, legible symbols, the centered settings indicator at narrow width, light and dark themes, reduced motion, and the transition after reads settle. Enterprise Desktop packages add selected archives to the existing signed package set through `integrations/desktop/scripts/pack-enterprise-plugins.ts`. Their additive Cordis entries join the private Host application under the native install anchor. On the next pin, package both registry and local bundles, verify relative entry resolution and duplicate-ID rejection, then open the installed application with a disposable profile and repeat an upgrade after changing a plugin preference. @@ -72,7 +72,7 @@ The [organization usage observer](../../plugins/ipollowork-suite/src/host/enterp Suite `0.1.46` adds the 24-identity multi-engine migration inventory and checked independent native bundles to the existing format-1 market. `src/ported/host.ts` uses `ctx.tools.register`, `ctx.skills.register`, `workspaceRegistry`, owner admission, sandbox policy, native credential records and lifetime-bound `mcpManager.register`; `src/ported/client.tsx` uses `main`, `sidebar.panellist`, `plugins.bundle.config`, `uiWorkspace.connectWorkspace` and unsent conversation drafts. The owned iframe bridge reuses native UI primitives and never includes the former host or Agent runtime. `ServiceCenter.capability` exposes the existing account-authorized capability transport without provider keys. Verify all archive installations, schema drafts, enable/disable/uninstall, credential redaction, read-only and workspace rejection, MCP authorization, iframe operations, light/dark themes and narrow layout on the next pin. Advanced legacy media modes without a matching service contract remain explicitly unavailable; see the [migration inventory](../../docs/multi-engine-plugin-migration.zh.md). -The frame theme adapter reads computed --dsw-/--dsh- tokens from the native body and clones only style[data-plugin="@deepseek-ai/dsh-client-ui-primitives"] sheets; verify these DOM conventions on upgrade. Local redirects, dynamic Onto extension imports and EventSource URLs retain the authenticated proxy prefix. Per-account browser profiles, automatic observation and the old ui/open-link bridge have no equivalent at this pin and remain explicitly unavailable. +The frame theme adapter reads computed --dsw-/--dsh- tokens from the native body and clones only style[data-plugin="@deepseek-ai/dsh-client-ui-primitives"] sheets; verify these DOM conventions on upgrade. Local redirects, dynamic Onto extension imports and EventSource URLs retain the authenticated proxy prefix. Desktop `1.0.10` reconciles existing profiles through `initProfile`/`readProfileManifest` and the native `dsh.profile.bundles` selection. The private Host is required even for an already initialized profile; competing public product bundles and direct product dependencies are backed up before removal. `desktop-runtime.json.sharedPackages` identifies installation-owned Suite/Stage/Host copies, including matching versions. The last native Include overlay enables only the owned application entries; Suite enforces the distribution's account/theme/origin using the verified install-anchor package identity. Other plugin configuration and credential files remain unchanged. Recheck legacy web-only profiles, stale/same-version Suite copies, disabled entries, actual cloud login, incorrect-password classification, and a returning signed-in session in the installed Mac app. Welcome checks `/ipollowork-suite/info` before entering the workspace and distinguishes rejected credentials, sessions, outages, timeouts and throttling. See [the upgrade diagnosis](../../docs/diagnostics/2026-11-20-mac-login-and-upgrade.md). @@ -86,6 +86,7 @@ The [MCP connection controls](../../plugins/ipollowork-suite/src/host/mcp-connec | --- | --- | --- | | [Desktop update compatibility](../desktop/src/plugin-update.ts) and [mandatory update recovery](../desktop/src/mandatory-update-window.ts) | The updater checks native profile bundle selection, `resolveBundleDir`, `evaluatePluginCompatibility` and existing exact-version permissions from `readProfileVersionExemptions`. Only bundled, reviewed market archives enter the migration plan. | Install a user-authored linked workbench in the old desktop app. After a compatible update, open its UI and tools and verify its source, settings, data and activation. An incompatible link blocks a mandatory update. Open its source from the update page, verify a compatible change, then retry and confirm the same plugin is still enabled. | | [Organization website links](../../plugins/ipollowork-suite/src/client/organization-websites.tsx) | The existing organization settings surface uses the Suite Host bridge under the current DSH connection owner. The Work account service owns visibility and resolves a link when opened. | Sign in as a manager and add a department- and role-scoped link. Sign in as an allowed member and open it in the browser. Change that member’s access and verify a previously displayed link can no longer be opened. Check both themes and a narrow window. | +| [Resource recipients](../../plugins/ipollowork-suite/src/client/organization-recipients.tsx) | The Suite uses the native Modal, Button and shared field popover. The Work account service searches the full authorized organization directory before pagination. | Open Publish resource, search for a member absent from the first page using partial name or employee number, and select two departments. Verify keyboard dismissal keeps the dialog open, both choices remain selected, and the request includes both departments. Check both themes and a narrow window. | | [Background plugin installation](../../plugins/ipollowork-suite/src/client/market-installation.ts) and the [native Add Plugin entry](../../plugins/ipollowork-suite/src/client/add-plugin.ts) | Plugin Manager request IDs, `plugin-manager/install-state`, `plugin-manager/changed`, connection reset, `shell.overlay` and `plugins.tab`. The toolbar also depends on the native DOM, including `data-plugin-toolbar`, menu roles and localized labels. | Start from the toolbar button, dropdown and marketplace. Dismiss the dialog and navigate away. Confirm installation continues, reopening shows progress, and completion refreshes the action. Remove DOM interception when DSH offers a replaceable install action. | | [Plugin toggle limit in the client](../../plugins/ipollowork-suite/src/client/plugin-toggle-limit.ts) and [Host](../../plugins/ipollowork-suite/src/host/plugin-toggle-limit.ts) | `pluginChanges.bundle(name)` tracks bundle and component writes. The native switches are identified by the plugin panel, card, detail header and row DOM attributes, the Switch role and the bundle progress status sibling. The authenticated `connection/request` waterfall admits one POST at a time across `/api/pluginManager/setBundleEnabled` and `/api/pluginManager/setPluginEnabled`. | Delay one enable or disable, then try another card and a component row with mouse and keyboard. Verify the switches unlock after success or failure, other controls still work and a concurrent authenticated request receives HTTP 409. Retire the client interception when DSH exposes a shared toggle state. | | [Curated market updates](../../plugins/ipollowork-suite/src/host/market.ts) | `listBundles` supplies version, source, availability, selection and read-only state. Matching pinned Git sources use the native `plugins.tab.update` callback. Archive updates use `installBundle` with exact expected name/version and `enabled: false`, which retains existing selection when the same dependency is replaced. | With an older enabled and an older disabled archive install, confirm an update from the market and check the result, configuration, work files and selection after restart. Reject a changed current version and a corrupt archive. Check compatibility, offline fallback, a same-origin Git update, light and dark themes and a narrow window. The [desktop smoke](../desktop/scripts/smoke-runtime.ts) checks the offered source and verifies both fallback archive hashes against the packaged runtime inventory. Verify that an online entry replaces a bundled entry of the same name in place and that changing its pinned source selects the curated install target. | @@ -104,12 +105,13 @@ The [MCP connection controls](../../plugins/ipollowork-suite/src/host/mcp-connec | [Branding and the Windows title bar](../../plugins/ipollowork-suite/src/client/brand.css) | Suite theme, native slots and some DSH DOM and CSS tokens. The extra Windows mark above the workspace was removed by dropping a `body::before` override. | Check the title bar, collapsed sidebar, full screen, and both themes. Branding and native window controls should render correctly. | | [macOS window dragging](../../plugins/ipollowork-suite/src/client/suite.module.css) | DSH `dsh-v0.2.2-rc.3` marks the main flex column with `data-global-panel`, native drag rows with `data-window-drag`, and the portalled settings panel with `data-shortcut-modal="settings"`. The suite uses `--dsh-frame-top-clearance` for its top strip and leaves the native drag controls in place. | In macOS Electron, drag from the top of Home, a conversation, Plugins, Organization, Data, Agents and Settings. Repeat with the sidebar collapsed and at narrow width. Check scroll, buttons, dialogs and fullscreen. | | [Sign-in, profiles and desktop integration](../desktop-host) and [official launcher integration](../tooling/start.mjs) | `profile-boot`, `app-boot`, Connection and authentication exports, DSH profile configuration and desktop bridges. Compare exports from the source build and public npm packages separately, even for the same version label. | Launch real Electron with a disposable home and a test copy of an existing profile. Check sign-in, registration, models and agent modes, workspaces and sessions, browser and file operations. | -| [Desktop welcome account forms](../desktop/src/client/WelcomePage.tsx) | The desktop uses authenticated local Host account routes. The preload passes allowlisted sign-in and registration errors. | Check a wrong password and a duplicate email. Verify that login omits the password recovery control and successful sign-in enters the workspace. | +| [Desktop welcome account forms](../desktop/src/client/WelcomePage.tsx) | The desktop uses authenticated local Host account routes. The preload passes allowlisted sign-in and registration errors. The [account adapter](../../plugins/ipollowork-suite/src/host/account.ts) retries sign-in once for Node's explicit pre-TLS disconnect. | Check a wrong password, an interrupted connection, and a duplicate email. Verify that a pre-TLS disconnect can recover, an ambiguous reset sends no second request, and successful sign-in enters the workspace. | | [Desktop conversation sharing](../desktop/src/web-document.ts) and [relay](../../services/ipollowork/src/liveshare.ts) | LiveShare binds owner authorization to the web origin on `ownerLoginStart` and `ownerLoginRedeem`; desktop forwards its authenticated Host's HTTP origin. The DSH v1 relay re-registers the same share ID when permissions change. The service checks the existing owner, source session, instance and gateway token before updating the share. | Open a link as another account, then change the publisher's permissions and department scope. Reopen the original link and verify it stays online, and verify a removed recipient or revoked link remains denied. | | [Desktop download destination](../desktop/src/file-actions.ts) | Both `dshDesktop.fileActions.save` modes open the native Save As dialog. The main application window also applies it to browser downloads such as native plugin links and Blob exports. The allowlisted Suite project artifact, memory version and organization package routes stream the authenticated Host response or fetch a signed HTTPS object without forwarding Host credentials. | Choose a different directory and filename for chat attachments, a plugin Blob export, an organization package download and a project deliverable. Verify original bytes, cancellation, a failed overwrite, both storage modes and both bridge modes. Verify browser guest restrictions and native Web downloads. | | [General Settings version row](../../plugins/ipollowork-suite/src/client/desktop-version.tsx) and [desktop preload](../desktop/src/preload-app.ts) | DSH `dsh-v0.2.2-rc.3` exposes `settings.general.item` with the `current-version` entry and `general.currentVersion` locale key. The product replaces that entry using the Electron package version. | Compare General Settings and About with an installer version that differs from the DSH pin. Check that the web client still shows the DSH version and that the desktop with an older preload still resolves its version through IPC. | | [Release packaging](../../.github/workflows/ipollo-release-packages.yml) and [public update feeds](../tooling/release-publication.mjs) | The package target runs DSH `build:official` and checks the pinned build record. Intel macOS batches the same DSH package family through pnpm recursive pack with one worker, then applies the upstream payload and manifest validators. The public Windows installer and blockmap share one filename stem. | Check the Intel archive list and packaged runtime with cold and restored dependency stores. Verify both Mac ZIP entries, the Windows installer and blockmap, and the four direct downloads before promoting a draft. | | [Desktop update channel](../desktop/src/update-channel.ts) | The public iPolloWork release directory publishes stable manifests. The desktop preload omits the optional `dshDesktop.updates.channels` bridge for this source, so DSH General Settings does not offer the nightly selector. | Start a packaged client with a saved nightly preference and confirm the official feed uses stable and the manual update check remains available. Verify that another feed can still use the channel selector. | +| [macOS update location](../desktop/src/macos-update-location.ts) | The shell checks the running bundle before manual updates and recognizes Squirrel.Mac's read-only volume error. Electron moves and reopens the app after consent when the current user has a writable, vacant destination in Applications. The other cases offer to open Applications in Finder. The move reuses the Host task lock and quit confirmation. | With a signed candidate, open it from a mounted DMG and from a translocated Downloads copy. Verify cancel, active-task confirmation, reopen from Applications with the same profile, and a successful in-app update to the next version. Repeat with a same-name app already installed and verify Finder opens with the existing bundle intact. | | [Plugin composition](../../plugins/ipollowork-suite/cordis.patch.yml), the [Studio catalog](../../plugins/ipollowork-suite/catalog/index.json), and [desktop resource packaging](../desktop/scripts/prepare-dsh.ts) | Cordis insertion points and dependencies, native plugin loader, DSH ASAR layout, Host/CLI entry points and Computer Use resource paths. Website installers and Office fallback live in product packaging. | In packaged clients on affected platforms, verify startup, on-demand marketplace installation, existing Design/Video projects, Office opening and Computer Use helpers. | | [Design template generation and result opening](https://github.com/Devin-AXIS/deepseek-design) | On the `dsh-v0.2.2-rc.3` baseline, Design uses session-scoped `resources.source`, the right-sidebar file association, `conversation.chat.turnTail`, and the native `present` tool and delivery card. `design-actions.tsx` opens the editor, and `surface.tsx` inserts the file reference in the composer while keeping the editor open. | Apply a template and give the model a brief unrelated to the sample. Switch conversations while it saves, return and check the current preview. Close the preview and open the final HTML from the response. For a native slide deck, ask for a PPT, then use Edit in Design to change a slide and verify that the same HTML file saves with its page count preserved. | | Stage desktop plugin (retired in PR #582) | Formerly used `main`, `sidebar.panellist`, `plugins.bundle.config`, Host connection admission, `workspaceRegistry`, `tools` and `sandboxPolicy`. | Product composition checks verify that the Stage Bundle is absent. | @@ -270,4 +272,18 @@ The Suite Host retries one transient account GET within the original deadline, i On the next pin, start the real Desktop with a disposable profile. Open a configured site from Business websites with no conversation, cold-start with the same profile, and verify that a permitted HTTPS cookie is restored. Change account, revoke organization membership, and sign out to verify the appropriate restrictions. Verify the Host plugin capability and that the credential provider serializes only the encrypted desktop account grant. ### Ported workbench routes and model tasks -The [ported Host](../../plugins/ipollowork-suite/src/ported/host.ts) passes the authorized `workspaceRegistry` ID to business actions and scopes pending requests to the owner connection. The [ported client](../../plugins/ipollowork-suite/src/ported/client.tsx) validates workbench message origins and lets the Desktop shell open each supported social platform in the system browser. System-browser login does not provide per-account observation. On the next DSH pin, test the allowlisted login link, a rejected cross-platform link, a WeChat Channels upload and media preview through the workbench proxy, and a pending image generation task that completes through the existing service receipt without a second submission. Verify the Xiaohongshu archive includes the matching platform's native dependency and starts from a fresh profile. +The [ported Host](../../plugins/ipollowork-suite/src/ported/host.ts) checks workspace and session membership through `workspaceRegistry`. The [ported client](../../plugins/ipollowork-suite/src/ported/client.tsx) validates workbench message origins and resolves the session with `uiWorkspace.connectWorkspace`. For Douyin, WeChat Channels and Xiaohongshu, the optional product [desktop login bridge](../desktop/src/social-login.ts) embeds a sandboxed, account-specific Chromium view in the existing application window. The Electron parent passes a bounded set of visible identity labels over the private Host channel. The business service keeps ownership of identity verification and persisted state. Public site links use the system browser. The DSH Sidebar browser exposes a URL-only opening API and uses workspace storage. The account view uses its existing persistent per-account partition and provides no model browser tools. + +On the next pin, use the three installed archives in real Electron. Check QR display, scan completion, automatic refresh, different accounts in isolated sessions, retry after close, and a mismatched identity. Check an earlier Xiaohongshu binding without a browser profile and an older shell without the optional bridge. Verify public site links, WeChat Channels media upload and preview, and image generation receipt recovery through the existing workbench proxy. Check that Xiaohongshu includes its platform dependency and starts from a fresh profile. + +Approved platform authorization popups use Electron's `setWindowOpenHandler` and `createWindow` callback to adopt the child `WebContentsView` within the existing application window. Chromium retains the opener and form submission. The child shares the account's sandboxed session and the platform allowlist governs top-level navigation. Recheck a blank popup followed by an approved origin, form POST and opener callback, off-platform redirect denial, one native application window, and return from authorization to the login page or workbench. + +The embedded login [toolbar and feedback](../desktop/src/social-login-feedback.ts) load independently of the platform page. A read-only check for rendered text or visible media collapses the loading feedback to the toolbar. A slow or failed attempt offers retry in the same account session. Recheck a delayed response, a blank document, a visible page with a slow subresource, a failed connection, keyboard and button retry, and cleanup when the application reloads or closes. + +The WeChat Channels workbench requests the official QR entry for Add Account when the desktop preload advertises `socialLoginQrEntry`. The existing account action tries the management page first and falls back to the login page if the home page fails or remains blank while loading. For a matching local HTTP proxy, the toolbar offers a user-initiated retry that routes only the official WeChat login and static-content origins directly in that account partition. Recheck old workbench and desktop combinations, adding and continuing an account, QR rendering behind a slow proxy, and restoration of proxy routing when the account view closes. + +Account recognition allows two retries after a failed check on a stable platform page. Verify that one failed Host observation can recover within the same window, using the same authorized page, on the next runtime. + +WeChat Channels checks the existing account session at `/platform/` before opening the QR sign-in page. The desktop passes the visible ID and name fields, and Returning to workbench completes one observation before closing. Recheck a pending account with a valid session, a spaced ID label and a non-heading account name, plus rejection of a different account. + +If Xiaohongshu's creator home loads without rendering, the embedded view tries the platform's direct sign-in page in the same account session. Recheck first-time sign-in on a blank creator home and that an existing signed-in creator home bypasses the fallback. diff --git a/integrations/runtime/compatibility.zh.md b/integrations/runtime/compatibility.zh.md index 4783ac29d3..d33dc84ff4 100644 --- a/integrations/runtime/compatibility.zh.md +++ b/integrations/runtime/compatibility.zh.md @@ -40,7 +40,7 @@ Windows 安装核验准确的 Git commit 和 tree,无需文件符号链接权 服务 schema 22 是已有产品迁移,并非 DSH 新增 schema。构建按导出的服务 schema 常量复制全部迁移;部署从构建镜像读取目标版本,避免继续固定为 21。实际服务器完成备份、向前迁移和切换后就绪验证前,不能宣称部署已完成。 -首次启动与重启等待设置时共用 `plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.tsx`。原有 `shell.overlay` 入口使用公开的 `IconLoadingOutlineRegular` 和 DSH 主题文字色。下次更换固定版本时,在桌面启动期间延迟设置或账号读取,检查加载指示居中、标题栏留空、明暗主题、减少动态效果,以及读取结束后提示退出。 +首次启动与重启等待设置时共用 `plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.tsx`。原有 `shell.overlay` 入口使用公开的 `IconLoadingOutlineRegular` 和 DSH 主题变量,加载布局在套件样式表到达前即可使用。Windows 桌面外壳为原生窗口按钮使用透明背景,预加载脚本读取 `--dsw-alias-label-primary` 设置按钮符号颜色。更新运行时固定版本时,启动期间同时延迟套件样式表和设置或账号读取,检查启动页到工作区的窗口按钮背景、图标辨识度、窄窗口加载指示居中、明暗主题、减少动态效果和读取完成后的切换。 企业桌面包通过 `integrations/desktop/scripts/pack-enterprise-plugins.ts` 将选择的归档加入现有签名包集合。归档新增的 Cordis 条目随私有 Host 应用从原生 install anchor 加载。下次更换固定版本时,验证 npm 与本地归档、相对入口解析和重复 ID 拒绝,再用独立 profile 启动已安装客户端,修改一项插件偏好后复测覆盖安装。 @@ -72,7 +72,7 @@ Suite `0.1.47` 携带 22 个迁移原生包的显示元数据修复。各包导 Suite `0.1.46` 将多引擎分支 24 个身份的对应清单和经校验的独立原生包加入既有 format-1 市场。`src/ported/host.ts` 使用 `ctx.tools.register`、`ctx.skills.register`、`workspaceRegistry`、所有者准入、沙箱策略、原生凭据记录和生命周期内的 `mcpManager.register`;`src/ported/client.tsx` 使用 `main`、`sidebar.panellist`、`plugins.bundle.config`、`uiWorkspace.connectWorkspace` 及未发送的会话草稿。自有 iframe 桥接复用原生组件,不包含旧宿主或 Agent 运行时。`ServiceCenter.capability` 通过既有账号授权能力接口接通模型,不向插件传递供应商密钥。下次升级复测实际安装包、schema 方言、启停卸载、凭据脱敏、只读和工作区拒绝、MCP 授权、iframe 操作、明暗主题与窄布局。没有对应服务契约的旧版高级媒体操作明确不可用;见[迁移清单](../../docs/multi-engine-plugin-migration.zh.md)。 -工作台主题桥接从原生 body 读取 --dsw-/--dsh- 计算 token,只复制 style[data-plugin="@deepseek-ai/dsh-client-ui-primitives"] 样式;升级时复核这些 DOM 约定。本地重定向、Onto 动态扩展导入和 EventSource 地址保留所有者代理前缀。当前 pin 没有旧宿主按账号浏览器资料、自动观察和 ui/open-link 桥接的对应接口,这些流程明确不可用。 +工作台主题桥接从原生 body 读取 --dsw-/--dsh- 计算 token,只复制 style[data-plugin="@deepseek-ai/dsh-client-ui-primitives"] 样式。升级时复核这些 DOM 约定。本地重定向、Onto 动态扩展导入和 EventSource 地址保留所有者代理前缀。 Desktop `1.0.10` 沿用 `initProfile`/`readProfileManifest` 和原生 `dsh.profile.bundles`,补齐已初始化配置缺失的私有 Host;备份原清单后移除重复的公开产品 Bundle 和产品直接依赖。`desktop-runtime.json.sharedPackages` 限定安装包拥有的 Suite/Stage/Host 副本,即使版本相同也恢复为安装包提供。最终原生 Include overlay 仅启用产品入口;Suite 根据 install-anchor 包身份固定该发行版的账号、主题及服务地址,保留其他插件配置和凭据。升级时复测旧 web-only profile、旧及相同版本 Suite、停用条目、已安装 Mac 的真实云端登录、错误密码分类和保持登录后再次进入。欢迎页进入工作区前核验 `/ipollowork-suite/info`,区分凭据错误、会话拒绝、服务异常、超时和限流。详见[升级诊断](../../docs/diagnostics/2026-11-20-mac-login-and-upgrade.md)。 @@ -88,6 +88,7 @@ Suite `0.1.39` 携带 Design `1.0.0-beta.37`,使用原生 `ctx.skills.register | --- | --- | --- | | [桌面更新兼容检查](../desktop/src/plugin-update.ts)和[强更恢复](../desktop/src/mandatory-update-window.ts) | 更新使用原生 profile 启用列表、`resolveBundleDir`、`evaluatePluginCompatibility` 和 `readProfileVersionExemptions` 已有的精确版本许可。迁移计划只收录安装包内已审核的市场归档。 | 在旧客户端安装用户自制的本地链接工作台。兼容更新后打开界面和调用工具,检查源码、设置、数据与启用状态。不兼容链接须能拦截强更。由强更页打开源目录,验证适配后重试,确认同一插件仍启用。 | | [组织网页入口](../../plugins/ipollowork-suite/src/client/organization-websites.tsx) | 复用组织设置页面和当前 DSH 连接身份下的套件 Host 接口,由 Work 账号服务判定可见性,并在打开时解析网址。 | 用管理员账号添加按部门和角色授权的链接,用有权限的成员账号打开。修改成员权限后,确认此前显示的入口也无法继续打开。检查深浅主题和窄窗口。 | +| [资源下发对象](../../plugins/ipollowork-suite/src/client/organization-recipients.tsx) | 套件复用原生 Modal、Button 和表单浮层。Work 账号服务在完整的已授权组织成员目录中搜索,再对结果分页。 | 打开下发资源弹窗,用部分姓名或工号查找不在首屏的成员,并勾选两个部门。确认按 Esc 只关闭下拉框、已选部门保留且提交包含两个部门。检查深浅主题和窄窗口。 | | [插件后台安装](../../plugins/ipollowork-suite/src/client/market-installation.ts)与[原生添加插件入口](../../plugins/ipollowork-suite/src/client/add-plugin.ts) | DSH Plugin Manager 的安装请求 ID、`plugin-manager/install-state`、`plugin-manager/changed`、连接重置、`shell.overlay`、`plugins.tab`。原生工具栏的 DOM 是额外依赖,涉及 `data-plugin-toolbar`、菜单角色和本地化标签。 | 分别从工具栏主按钮、下拉菜单和市场开始安装。关闭弹窗并切换页面,确认安装继续、重新打开可见进度、安装结束按钮自动刷新。上游提供可替换的安装入口后移除 DOM 拦截。 | | [插件启停客户端限制](../../plugins/ipollowork-suite/src/client/plugin-toggle-limit.ts)与 [Host 限制](../../plugins/ipollowork-suite/src/host/plugin-toggle-limit.ts) | `pluginChanges.bundle(name)` 提供插件包及组件的写入状态。通过原生面板、卡片、详情头部和组件行的 DOM 属性、开关角色及插件包进度状态元素识别开关。已验证连接的 `connection/request` 在 `/api/pluginManager/setBundleEnabled` 和 `/api/pluginManager/setPluginEnabled` 间共用一个 POST 请求名额。 | 延迟一次启用或停用,在列表卡片和组件行用鼠标和键盘尝试下一次操作。确认成功或失败后恢复操作,其他控件仍可使用,并发的已验证请求收到 HTTP 409。上游提供共享的开关禁用状态后移除客户端拦截。 | | [精选市场更新](../../plugins/ipollowork-suite/src/host/market.ts) | `listBundles` 提供版本、来源、归属、选中及只读状态。同来源的固定 Git 提交使用 `plugins.tab.update`。归档更新以预期包名、版本和 `enabled: false` 调用原生 `installBundle`,替换同一个依赖时沿用现有选中状态。 | 分别更新已启用、已停用的旧归档,重启核对版本、配置、工程文件和启用状态。验证当前版本变化、归档损坏时拒绝更新,并复验兼容性、离线目录、同来源 Git 更新、明暗主题与窄窗口。[桌面自检](../desktop/scripts/smoke-runtime.ts) 核对市场安装来源,并根据安装包内的运行时清单验证两个离线归档的哈希。 | @@ -106,7 +107,7 @@ Suite `0.1.39` 携带 Design `1.0.0-beta.37`,使用原生 `ctx.skills.register | [品牌和 Windows 标题栏](../../plugins/ipollowork-suite/src/client/brand.css) | 使用套件 theme、原生 slot 及部分 DSH DOM 和 CSS token。工作区顶部的额外 Windows 标志通过移除 `body::before` 覆盖处理。 | 检查标题栏、折叠侧栏、全屏、浅色和暗色。品牌标志和原生窗口控制应各自正确显示。 | | [macOS 窗口拖拽](../../plugins/ipollowork-suite/src/client/suite.module.css) | DSH `dsh-v0.2.2-rc.3` 用 `data-global-panel` 标记主内容列,用 `data-window-drag` 标记原生拖拽栏,用 `data-shortcut-modal="settings"` 标记挂在页面根节点外的设置面板。套件按 `--dsh-frame-top-clearance` 设置顶部拖拽区,保留原生窗口控件。 | 在 macOS Electron 中从首页、会话、插件、组织空间、数据、机器人和设置顶部拖动窗口。收起侧栏和缩窄窗口后重试,检查滚动、按钮、弹窗和全屏。 | | [登录、profile 和桌面集成](../desktop-host)、[官方启动器接入](../tooling/start.mjs) | `profile-boot`、`app-boot`、Connection 与认证导出,以及 DSH profile 配置和桌面桥接。源码构建和公开 npm 包需要分别核对导出,即使版本号一致。 | 在隔离 home 中启动真实 Electron,打开已有 profile 的测试副本,验证登录注册、模型和 agent 模式、工作区与会话、浏览器和文件操作。 | -| [桌面首页账号表单](../desktop/src/client/WelcomePage.tsx) | 桌面使用经过认证的本地 Host 账号路由,原生 preload 向表单传递明确允许的登录和注册错误。 | 验证错误密码、邮箱已注册,检查登录页没有忘记密码控件,确认成功登录后进入工作区。 | +| [桌面首页账号表单](../desktop/src/client/WelcomePage.tsx) | 桌面使用经过认证的本地 Host 账号路由,原生 preload 向表单传递明确允许的登录和注册错误。[账号适配器](../../plugins/ipollowork-suite/src/host/account.ts)在 Node 明确报告 TLS 建立前断线时重试一次登录。 | 验证密码错误、连接中断及邮箱已注册。检查 TLS 建立前断线可以恢复,无法确定请求状态时只发送一次,成功登录后进入工作区。 | | [桌面会话分享](../desktop/src/web-document.ts)与[中继](../../services/ipollowork/src/liveshare.ts) | LiveShare 在 `ownerLoginStart` 和 `ownerLoginRedeem` 校验 Web 来源,桌面转发已认证的宿主 HTTP 来源。DSH v1 中继在修改权限时用原 ID 重新注册;服务端核对所有者、来源会话、运行实例和网关令牌后更新分享。 | 用另一账号打开分享,再由所有者修改权限和部门范围。确认原链接保持在线,移除的成员和作废链接仍不能访问。 | | [桌面下载位置](../desktop/src/file-actions.ts) | `dshDesktop.fileActions.save` 的两种模式都打开系统另存为窗口,主应用窗口里的插件下载链接和 Blob 导出也使用同一个窗口。套件的项目制品、记忆版本和组织文件包仅允许从已授权路由下载。桌面流式读取经过鉴权的 Host 响应,下载签名 HTTPS 对象时不转发 Host 凭据。 | 从对话附件、插件 Blob 导出、组织文件包和项目交付物选择其他目录并改名保存,核对原始字节。复验取消、覆盖中断、两种存储方式和两种桥接模式,并检查访客窗口下载限制及 Web 端下载。 | | [通用设置版本行](../../plugins/ipollowork-suite/src/client/desktop-version.tsx)与[桌面 preload](../desktop/src/preload-app.ts) | DSH `dsh-v0.2.2-rc.3` 提供 `settings.general.item` 插槽、`current-version` 条目和 `general.currentVersion` 翻译。产品用 Electron 包版本覆盖该条目。 | 使用版本号与 DSH 固定版本不同的安装包,核对通用设置和关于界面。检查浏览器仍显示 DSH 版本,使用旧 preload 的桌面客户端仍能通过 IPC 取得版本。 | @@ -114,6 +115,7 @@ Suite `0.1.39` 携带 Design `1.0.0-beta.37`,使用原生 `ctx.skills.register | [插件组合](../../plugins/ipollowork-suite/cordis.patch.yml)、[Studio 市场](../../plugins/ipollowork-suite/catalog/index.json)与[桌面资源打包](../desktop/scripts/prepare-dsh.ts) | Cordis 插入项和依赖、原生插件加载器、DSH ASAR 布局、Host/CLI 启动入口和电脑操作资源路径。官网安装包和 Office 回退在产品打包层。 | 用各平台打包客户端验证启动、市场按需安装、打开已有 Design/Video 项目、Office 打开和电脑操作辅助程序。 | | [Design 模板生成和结果打开](https://github.com/Devin-AXIS/deepseek-design) | 基于 `dsh-v0.2.2-rc.3`,Design 使用会话范围的 `resources.source`、右侧栏文件关联、`conversation.chat.turnTail`、原生 `present` 工具和交付卡片。`design-actions.tsx` 打开编辑器,`surface.tsx` 向输入框插入文件引用时保持编辑器打开。 | 套用模板并给出与示例主题明显不同的提示词。保存期间切换会话,再返回检查预览。关闭预览后,从对话结果打开最终 HTML。用原生幻灯片模板发出做 PPT 的请求,点击「在 Design 中编辑」修改一页,核对修改已保存到同一份 HTML 且页数一致。 | | [桌面更新频道](../desktop/src/update-channel.ts) | iPolloWork 正式发布源提供稳定版更新清单。桌面预加载对该来源省略可选的 `dshDesktop.updates.channels` 接口,DSH 通用设置不会显示开发版频道选项。 | 用保存过开发版偏好的设置启动正式安装包,确认它使用稳定版且仍可手动检查更新。换用其他更新源,确认频道选择仍可用。 | +| [macOS 更新运行位置](../desktop/src/macos-update-location.ts) | 桌面端在手动更新前检查运行中的应用包,并识别 Squirrel.Mac 的只读卷错误。当前用户可写入「应用程序」且目标未被占用时,用户确认后由 Electron 移动并重新打开应用。其余情况可打开访达的「应用程序」。移动流程复用 Host 任务锁定和退出确认。 | 用签名候选包从挂载的 DMG 和「下载」中触发 App Translocation 的副本分别启动。检查取消、运行中任务确认、从「应用程序」用原有 profile 重开,以及应用内更新到下一版。再验证已有同名应用时可打开访达,原应用包保持完整。 | | Stage 桌面插件(在 PR #582 中移除) | 曾使用 `main`、`sidebar.panellist`、`plugins.bundle.config`、Host 连接准入、`workspaceRegistry`、`tools` 和 `sandboxPolicy`。 | 检查产品组合是否已移除 Stage Bundle。 | | [iPolloWork 共用控件](../../plugins/_shared/ui/controls.tsx) | 套件客户端、项目看板与通知中心在构建时打入同一份产品源码。共用控件使用固定 DSH 的公开 `Button`、`Input`、`Menu`、`MenuSurface`、`Tag`、`Switch` 与主题语义变量。`FieldPopover` 在套件的智能体编辑和看板详情中使用浏览器顶层锚定弹层。看板和通知中心各自随客户端生命周期加载与撤销样式。 | 安装套件,在明暗主题与窄屏用鼠标和键盘检查智能体编辑与看板的下拉。分别停用和启用两个子插件,确认另一个入口的样式仍然可用。单独安装两个归档并验证它们可在没有套件时打开控件。 | | [项目文件](../../plugins/project-files) | 使用原生 `sidebarRightTabs` 和 `sidebar.right.pane.tab` 接入对话右侧,用 `keepMounted` 在资源预览时保留文件浏览位置。Host 通过 `workspaceRegistry` 确认项目,使用 `sessionQuery.readSession` 读取历史、原生附件和工作区变更摘要,通过 `sessionFileAddress` 打开预览,使用 `fileMediaUrl` 和 `ImageLightbox` 支持项目图片和上传图片预览,按会话头的 `cwd` 解析记录中的相对路径。条目复用对话附件使用的原生 `FileTypeIcon`、`classifyFileType`、`fileExtension` 和 `fileSizeText`。从 `deliverables/presented` 的可选 `description` 取得显示标题。插件自己的文件操作要求所有者身份、文件系统一致及工作区路径校验。 | 分别独立安装和随套件安装。在两个项目打开右栏,核对本次对话和整个项目范围的输入输出、交付标题和文件名以及网格和列表排列、等大条目、原生文件图标、附件原件下载、小缩略图和直接预览交付网页及目录首页、复制、拖放、改名、废纸篓和恢复,验证跨项目与非所有者访问失败,并检查明暗主题和 390 px。 | @@ -270,4 +272,18 @@ Suite `src/host/service-models.ts` 保持原生模型的 `retryPolicy.maxRetries 升级 DSH 固定版本时,使用独立桌面 profile,在没有会话的情况下从「业务网页」打开已配置的站点。以相同 profile 冷启动,验证获准的 HTTPS Cookie 恢复。切换账号、取消组织成员资格和主动退出,验证权限和隔离。检查插件 Host 的组织接口,以及凭据库中账号授权记录的加密状态。 ### 移植工作台路由与模型任务 -[移植 Host](../../plugins/ipollowork-suite/src/ported/host.ts) 将 `workspaceRegistry` 校验后的工作区 ID 传给业务操作,并按所有者连接的生命周期管理请求。[移植客户端](../../plugins/ipollowork-suite/src/ported/client.tsx) 校验工作台消息来源,由桌面壳在系统浏览器打开对应的官方平台;系统浏览器登录无法提供独立账号环境与自动核验。升级 DSH 时复测官方登录链接可打开、跨平台链接会被拒绝、视频号封面通过工作台代理上传与预览,以及图片任务按原任务回执查询成功且只有一次提交。检查小红书安装包是否包含目标平台的本地依赖,并用全新配置验证冷启动。 +[移植 Host](../../plugins/ipollowork-suite/src/ported/host.ts) 通过 `workspaceRegistry` 验证工作区及会话归属。[移植客户端](../../plugins/ipollowork-suite/src/ported/client.tsx) 校验工作台消息来源,并用 `uiWorkspace.connectWorkspace` 解析当前会话。抖音、视频号及小红书使用可选的[产品桌面登录桥](../desktop/src/social-login.ts),在现有主窗口嵌入按账号隔离的 Chromium 页面。Electron 主进程通过私有 Host 通道发送有限的可见身份信息,由业务服务核验并保存账号状态。公开网页链接仍使用系统浏览器。DSH 侧栏浏览器的公开打开接口仅接受网址,会话存储按工作区设置。授权页沿用原有的账号隔离存储,登录桥不向模型提供浏览器工具。 + +升级 pin 后在真实 Electron 中安装三个归档,复验显示二维码、扫码后回写、多个账号隔离、关闭后重试与拒绝错号。用缺少浏览器配置的旧小红书账号和缺少登录桥的旧桌面壳各检查一次。复测公开网页链接、视频号封面上传与预览和图片任务回执恢复。确认小红书归档包含对应平台依赖并能从新配置冷启动。 + +平台授权页通过 Electron 的 `setWindowOpenHandler` 和 `createWindow` 将子 `WebContentsView` 接入同一个主窗口,保留原网页回调和表单提交。子页面使用当前账号的沙盒会话,顶层导航遵守平台域名名单。更新运行时后复验空白子页面跳转、表单 POST、原网页回调、阻止平台外跳转、只有一个主窗口,以及授权页返回登录页和运营台。 + +授权页的[工具栏和反馈](../desktop/src/social-login-feedback.ts)独立于平台网页加载。只读检查发现已渲染文字或可见媒体后收起加载提示并保留工具栏。加载过慢或失败时,用户可在同一账号会话内重试。更新运行时后复验主文档延迟、空白页、可见内容与慢资源并存、连接失败、按钮和键盘重试,以及主窗口重载或关闭后的清理。 + +桌面 preload 提供 `socialLoginQrEntry` 时,视频号工作台的「扫码添加账号」直接打开官方扫码入口。已有账号优先恢复管理页,管理页失败或加载中持续空白时切换到登录入口。检测到微信页面和静态资源使用同一个本机 HTTP 代理时,工具栏提供「直连重试」,仅在该账号浏览器分区内临时直连官方微信登录及静态资源域名。复验新旧工作台与桌面版本的组合、添加账号、继续登录、代理较慢时的二维码加载,以及关闭页面后恢复代理。 + +平台页面稳定后,账号核验失败最多自动重试两次。更新运行时后复验 Host 首次核验失败时,可以在同一窗口和已授权页面恢复核验。 + +视频号优先从 `/platform/` 核验已有账号会话,再打开扫码入口。桌面桥读取页面上可见的视频号 ID 和名称,返回运营台前会完成一次核验。复验已有会话的待绑定账号、带空格的 ID 标签、非标题元素中的账号名称及错号拒绝。 + +小红书创作首页加载完成后仍为空白时,内嵌页面会在同一账号会话里尝试平台的登录入口。更新运行时后复验首次登录的空白页恢复,以及已有登录的创作首页正常开启。 diff --git a/integrations/tooling/native-package.mjs b/integrations/tooling/native-package.mjs index d43f0e9b32..abc25fad85 100644 --- a/integrations/tooling/native-package.mjs +++ b/integrations/tooling/native-package.mjs @@ -14,6 +14,9 @@ export async function packNativeArchive(directory,output,npm){ const binary = `sharp-${process.platform}-${process.arch}` const required = `business/runtime/vendor/@img/${binary}/lib/${binary}.node` if (!packed.files.some(file => file.path === required)) throw new Error(`Xiaohongshu plugin archive is missing ${required}`) + if (packed.files.some(file => file.path.startsWith('business/skills/xhs-ops-worker/app/data/'))) { + throw new Error('Xiaohongshu plugin archive contains local account or test data') + } } return packed }finally{await rm(staging,{recursive:true,force:true})} diff --git a/package.json b/package.json index f5b921676c..c5d0f1dcac 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@ipollo/work", - "version": "1.0.22", + "version": "1.0.23", "private": true, "type": "module", "packageManager": "pnpm@11.28.5", diff --git a/plugins/douyin-ops/README.md b/plugins/douyin-ops/README.md index 290d608f07..c05452abb2 100644 --- a/plugins/douyin-ops/README.md +++ b/plugins/douyin-ops/README.md @@ -2,4 +2,6 @@ Native DSH bundle migrated from `douyin-ops` 0.2.22. 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. After scanning, the workbench checks the Douyin ID on the signed-in profile page and refreshes the account status. Use Check login to verify an existing account. + +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/douyin-ops/README.zh.md b/plugins/douyin-ops/README.zh.md index 81b9a27da0..8fa731aa47 100644 --- a/plugins/douyin-ops/README.zh.md +++ b/plugins/douyin-ops/README.zh.md @@ -2,4 +2,6 @@ 从多引擎分支 `douyin-ops` 0.2.22 移植的 DSH 原生插件。通过 iPolloWork 市场或原生插件管理器安装 .tgz,选择已有工作区后打开工作台。凭据由原生 Host 凭据提供方保存,保留旧版本地业务数据。停用或卸载释放工具、Skill、路由和子服务,保留用户文件。 +在支持账号登录的 iPolloWork 桌面版中,点击「扫码添加账号」。在打开的抖音窗口扫码后,工作台会从本人的主页核对抖音号并刷新状态。已有账号可用「检查登录」重新核对。 + 运行 `npm run build`、`npm run check`、`npm run pack:check`。各能力的验收与限制见仓库迁移清单。 diff --git a/plugins/douyin-ops/business/service/browser.mjs b/plugins/douyin-ops/business/service/browser.mjs index dd9a295ecf..9ae66a0215 100644 --- a/plugins/douyin-ops/business/service/browser.mjs +++ b/plugins/douyin-ops/business/service/browser.mjs @@ -42,24 +42,26 @@ export class BrowserOperations { const account = this.store.list('account', null, 50).find(item => item.browserProfileId === input.browserProfileId); if (!account) return { connected: false, reason: 'profile_required' }; const url = new URL(required(input.url, '当前页面地址')); - if (url.origin !== 'https://www.douyin.com' || url.pathname !== '/user/self' || url.username || url.password) return { connected: false, reason: 'own_page_required' }; + if (url.origin !== 'https://www.douyin.com' || !/^\/user\/[\w-]+\/?$/.test(url.pathname) || url.username || url.password) return { connected: false, reason: 'own_page_required' }; const tree = required(input.tree, '可见页面', 100000); const entries = tree.split('\n').flatMap(line => { const match = line.match(/^\s*(?:\[@[^\]]+\]\s*)?(heading|StaticText|tab|button) ("(?:[^"\\]|\\.)*")(.*)$/); if (!match) return []; try { return [{ role: match[1], text: JSON.parse(match[2]), detail: match[3] }]; } catch { return []; } }); - const nickname = entries.find(item => item.role === 'heading' && /\blevel=1\b/.test(item.detail))?.text; - const identityIndex = entries.findIndex(item => item.role === 'StaticText' && /^抖音号[::]/.test(item.text)); - const identityLabel = entries[identityIndex]?.text.replace(/^抖音号[::]\s*/, ''); + const identityIndex = entries.findIndex(item => item.role === 'StaticText' && /^抖音号\s*[::]/.test(item.text)); + const nickname = [...entries.slice(0, Math.max(0, identityIndex))].reverse() + .find(item => item.role === 'heading' && /\blevel=1\b/.test(item.detail))?.text; + const identityLabel = entries[identityIndex]?.text.replace(/^抖音号\s*[::]\s*/, ''); const webIdentity = identityLabel || (entries[identityIndex + 1]?.role === 'StaticText' ? entries[identityIndex + 1].text : ''); const ownsPage = entries.some(item => item.role === 'button' && ['编辑资料', '批量管理'].includes(item.text)) && entries.some(item => item.role === 'tab' && ['私密作品', '观看历史'].includes(item.text)); if (identityIndex < 0 || !nickname || !/^[\w.-]{1,200}$/.test(webIdentity) || !ownsPage) return { connected: false, reason: 'identity_not_visible' }; if (account.webIdentity && account.webIdentity !== webIdentity) return { connected: false, reason: 'account_mismatch' }; + if (this.store.list('account', null, 50).some(item => item.id !== account.id && item.webIdentity === webIdentity)) return { connected: false, reason: 'duplicate' }; return this.verify({ accountId: account.id, actualProfileId: `douyin-ops:${account.browserProfileId}`, - actualAccount: webIdentity, nickname, profileUrl: account.profileUrl || url.href, - evidence: `宿主可见的本人主页 /user/self 显示昵称 ${nickname}、抖音号 ${webIdentity},并存在个人管理与私密作品或观看历史入口。` }); + actualAccount: webIdentity, nickname, profileUrl: account.profileUrl || url.origin + url.pathname.replace(/\/$/, ''), + evidence: `本人主页显示昵称 ${nickname}、抖音号 ${webIdentity},并存在个人管理与私密作品或观看历史入口。` }); } verify(input) { const account = this.ops.account(input.accountId); diff --git a/plugins/douyin-ops/business/ui/app.css b/plugins/douyin-ops/business/ui/app.css index 173da130ad..b55fbc4884 100644 --- a/plugins/douyin-ops/business/ui/app.css +++ b/plugins/douyin-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/douyin-ops/business/ui/app.js b/plugins/douyin-ops/business/ui/app.js index df328b4087..0a994c193d 100644 --- a/plugins/douyin-ops/business/ui/app.js +++ b/plugins/douyin-ops/business/ui/app.js @@ -53,7 +53,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 }, "*"); }); @@ -500,14 +500,26 @@ async function openTarget(target) { }); } 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 target = await action("connect-browser", id ? { accountId: id } : {}); - await selectAccount(target.account.id); + if (model.accountId !== target.account.id) await selectAccount(target.account.id); + await refresh(); + if (!window.ipolloPortedHost) { + await openTarget(target); + return; + } + notify("请在登录窗口扫码,完成后会自动连接。"); + const { status } = await hostRequest("ui/account-login", { browserProfileId: target.browserProfileId }); 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 @@ -682,9 +694,7 @@ function Accounts() { h( ui.DialogDescription, null, - window.ipolloPortedHost - ? "在系统浏览器的抖音官方页面扫码,工作台会保留待核验的账号。" - : "每个账号使用独立的浏览器环境,登录后自动识别。", + "扫码登录后,账号会自动连接。", ), ), model.notice && @@ -701,17 +711,15 @@ function Accounts() { onClick: () => run("connect", () => connect()), }, h(ui.Icon, { name: "Plus" }), - pending.has("connect") ? "正在打开…" : "扫码添加账号", + pending.has("connect") ? "等待扫码…" : "扫码添加账号", ), - window.ipolloPortedHost && - h("a", { href: "https://www.douyin.com/user/self", 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" }, @@ -722,7 +730,7 @@ function Accounts() { h( "p", { className: "caption" }, - item.webIdentity || item.openId || "登录后识别抖音号", + item.webIdentity || item.openId || null, ), ), h( @@ -749,9 +757,9 @@ function Accounts() { disabled: pending.size > 0, onClick: () => run("connect", () => connect(item.id)), }, - "打开账号", + item.webIdentity ? "检查登录" : "继续登录", ), - item.connection === "browser" && + !window.ipolloPortedHost && item.connection === "browser" && h( ui.Button, { diff --git a/plugins/douyin-ops/package.json b/plugins/douyin-ops/package.json index 5291e7536d..6e870dadc9 100644 --- a/plugins/douyin-ops/package.json +++ b/plugins/douyin-ops/package.json @@ -1,6 +1,6 @@ { "name": "@ipollo/dsh-douyin-ops", - "version": "0.1.7", + "version": "0.1.8", "description": "管理抖音本地草稿、素材、作品及评论记录,通过平台 API 和原生会话继续运营。", "type": "module", "license": "SEE LICENSE IN LICENSE", diff --git a/plugins/ipollowork-suite/catalog/bundled-releases.json b/plugins/ipollowork-suite/catalog/bundled-releases.json index eb36d03d66..f4b3673fd8 100644 --- a/plugins/ipollowork-suite/catalog/bundled-releases.json +++ b/plugins/ipollowork-suite/catalog/bundled-releases.json @@ -139,46 +139,46 @@ "tag": "v1.0.20" }, { - "name": "@ipollo/dsh-wechat-official", - "version": "0.1.8", - "file": "ipollo-dsh-wechat-official-0.1.8-0c05b558efbf.tgz", - "sha256": "0c05b558efbfa0e44207343b628dfc590929b30e1fde276562b5941fc584cd5a", - "tag": "v1.0.20" + "name": "@ipollo/dsh-media-studio", + "version": "0.1.9", + "file": "ipollo-dsh-media-studio-0.1.9-322ebd259f48.tgz", + "sha256": "322ebd259f48cad8c2efd0b5681dc451eaefbf88a21f9d2f3f73e33e11a6c6a1", + "tag": "v1.0.22" }, { - "name": "@ipollo/dsh-douyin-ops", - "version": "0.1.7", - "file": "ipollo-dsh-douyin-ops-0.1.7-eee19e6a3609.tgz", - "sha256": "eee19e6a3609bd49cf2d81110e1456dd388203ec4e875ab66114fca5be273b53", + "name": "@ipollo/dsh-decision-intelligence", + "version": "1.0.4", + "file": "ipollo-dsh-decision-intelligence-1.0.4-7a5edde4f883.tgz", + "sha256": "7a5edde4f88354ac9823607945d2f5124014687004e4f76a81afb99312e22bd2", "tag": "v1.0.22" }, { - "name": "@ipollo/dsh-media-studio", + "name": "@ipollo/dsh-wechat-official", "version": "0.1.9", - "file": "ipollo-dsh-media-studio-0.1.9-322ebd259f48.tgz", - "sha256": "322ebd259f48cad8c2efd0b5681dc451eaefbf88a21f9d2f3f73e33e11a6c6a1", + "file": "ipollo-dsh-wechat-official-0.1.9-9decd162096e.tgz", + "sha256": "9decd162096e31390cda9d80ec344d8629707202a217960d456a3324c7bbcfc8", "tag": "v1.0.22" }, { - "name": "@ipollo/dsh-wechat-channels-ops", - "version": "0.1.7", - "file": "ipollo-dsh-wechat-channels-ops-0.1.7-654599bf34be.tgz", - "sha256": "654599bf34be8aa91baef1a3979ada95f88e70f3cd7afcc4ddc6d099a80770ac", + "name": "@ipollo/dsh-douyin-ops", + "version": "0.1.8", + "file": "ipollo-dsh-douyin-ops-0.1.8-3398b55edc04.tgz", + "sha256": "3398b55edc04891778e2830e3640b5fed510e0e301f3af67cf7277cc3572900d", "tag": "v1.0.22" }, { "name": "@ipollo/dsh-xiaohongshu-ops", - "version": "0.1.9", - "file": "ipollo-dsh-xiaohongshu-ops-0.1.9-a2af2ee4f07b.tgz", - "sha256": "a2af2ee4f07b6d97241da6c4405071194181b375b7fbca554a33704c08cca82b", + "version": "0.1.10", + "file": "ipollo-dsh-xiaohongshu-ops-0.1.10-3632c6762b5d.tgz", + "sha256": "3632c6762b5d956d58a5a16f44c553b9b73f13d72431100dcd15e98ba5290323", "tag": "v1.0.22" }, { - "name": "@ipollo/dsh-decision-intelligence", - "version": "1.0.4", - "file": "ipollo-dsh-decision-intelligence-1.0.4-7a5edde4f883.tgz", - "sha256": "7a5edde4f88354ac9823607945d2f5124014687004e4f76a81afb99312e22bd2", - "tag": "v1.0.22" + "name": "@ipollo/dsh-wechat-channels-ops", + "version": "0.1.10", + "file": "ipollo-dsh-wechat-channels-ops-0.1.10-d4310ab44ac8.tgz", + "sha256": "d4310ab44ac836802564f410686167bad50fe58296dad219e514949cb7a18851", + "tag": "v1.0.23" } ] } diff --git a/plugins/ipollowork-suite/catalog/index.json b/plugins/ipollowork-suite/catalog/index.json index 3d5c28eb17..7bff500683 100644 --- a/plugins/ipollowork-suite/catalog/index.json +++ b/plugins/ipollowork-suite/catalog/index.json @@ -191,7 +191,7 @@ }, "versions": [ { - "version": "0.1.7", + "version": "0.1.8", "publishTimestamp": 1795382400, "source": { "type": "npm" @@ -633,7 +633,7 @@ }, "versions": [ { - "version": "0.1.7", + "version": "0.1.10", "publishTimestamp": 1795382400, "source": { "type": "npm" @@ -667,7 +667,7 @@ }, "versions": [ { - "version": "0.1.8", + "version": "0.1.9", "publishTimestamp": 1795382400, "source": { "type": "npm" @@ -701,7 +701,7 @@ }, "versions": [ { - "version": "0.1.9", + "version": "0.1.10", "publishTimestamp": 1795382400, "source": { "type": "npm" diff --git a/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-douyin-ops-0.1.8-3398b55edc04.tgz b/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-douyin-ops-0.1.8-3398b55edc04.tgz new file mode 100644 index 0000000000..aa9d4ea84c Binary files /dev/null and b/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-douyin-ops-0.1.8-3398b55edc04.tgz differ diff --git a/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-wechat-channels-ops-0.1.10-d4310ab44ac8.tgz b/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-wechat-channels-ops-0.1.10-d4310ab44ac8.tgz new file mode 100644 index 0000000000..18697b8565 Binary files /dev/null and b/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-wechat-channels-ops-0.1.10-d4310ab44ac8.tgz differ diff --git a/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-wechat-official-0.1.9-9decd162096e.tgz b/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-wechat-official-0.1.9-9decd162096e.tgz new file mode 100644 index 0000000000..79f8cad997 Binary files /dev/null and b/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-wechat-official-0.1.9-9decd162096e.tgz differ diff --git a/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-xiaohongshu-ops-0.1.10-3632c6762b5d.tgz b/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-xiaohongshu-ops-0.1.10-3632c6762b5d.tgz new file mode 100644 index 0000000000..d14b068506 Binary files /dev/null and b/plugins/ipollowork-suite/catalog/packages/ipollo-dsh-xiaohongshu-ops-0.1.10-3632c6762b5d.tgz differ diff --git a/plugins/ipollowork-suite/package.json b/plugins/ipollowork-suite/package.json index ae801f2316..4646797bf4 100644 --- a/plugins/ipollowork-suite/package.json +++ b/plugins/ipollowork-suite/package.json @@ -82,12 +82,12 @@ "catalog/packages/ipollo-dsh-sentry-0.1.6-b7d854eb6ab8.tgz", "catalog/packages/ipollo-dsh-short-video-studio-0.1.7-28d2f77d3a95.tgz", "catalog/packages/ipollo-dsh-stripe-0.1.6-eb1248952096.tgz", - "catalog/packages/ipollo-dsh-wechat-official-0.1.8-0c05b558efbf.tgz", - "catalog/packages/ipollo-dsh-douyin-ops-0.1.7-eee19e6a3609.tgz", "catalog/packages/ipollo-dsh-media-studio-0.1.9-322ebd259f48.tgz", - "catalog/packages/ipollo-dsh-wechat-channels-ops-0.1.7-654599bf34be.tgz", - "catalog/packages/ipollo-dsh-xiaohongshu-ops-0.1.9-a2af2ee4f07b.tgz", - "catalog/packages/ipollo-dsh-decision-intelligence-1.0.4-7a5edde4f883.tgz" + "catalog/packages/ipollo-dsh-decision-intelligence-1.0.4-7a5edde4f883.tgz", + "catalog/packages/ipollo-dsh-wechat-official-0.1.9-9decd162096e.tgz", + "catalog/packages/ipollo-dsh-douyin-ops-0.1.8-3398b55edc04.tgz", + "catalog/packages/ipollo-dsh-xiaohongshu-ops-0.1.10-3632c6762b5d.tgz", + "catalog/packages/ipollo-dsh-wechat-channels-ops-0.1.10-d4310ab44ac8.tgz" ], "dsh": { "bundle": { diff --git a/plugins/ipollowork-suite/src/client/enterprise-assets.tsx b/plugins/ipollowork-suite/src/client/enterprise-assets.tsx index 9f32874977..c67d0a4f44 100644 --- a/plugins/ipollowork-suite/src/client/enterprise-assets.tsx +++ b/plugins/ipollowork-suite/src/client/enterprise-assets.tsx @@ -56,7 +56,7 @@ import { type Call, } from "./enterprise-ui.tsx"; import { KeyGlyph, Monogram } from "./glyphs.tsx"; -import { EmployeeRecipients } from "./organization-recipients.tsx"; +import { DepartmentRecipients, EmployeeRecipients } from "./organization-recipients.tsx"; import css from "./suite.module.css"; type Kind = "skill" | "service" | "mcp" | "package"; @@ -207,21 +207,9 @@ export function AudienceFields({ selected={audience.members} change={members => change({ scope, audience: { ...audience, members } })} disabled={disabled} managersHaveAccess={managersHaveAccess} excludeUserId={excludeUserId}/>} {!legacy && (scope === "departments" || scope === "mixed") && -
- {detail.departments.length ?
- {detail.departments.map(department => { - const checked = audience.departments.includes(department.id); - return ; - })} -
:

{t.noDepartments}

} +
+ change({ scope, audience: { ...audience, departments } })}/> {includeDepartmentTree && !!audience.departments.length && }
} diff --git a/plugins/ipollowork-suite/src/client/enterprise-locale.ts b/plugins/ipollowork-suite/src/client/enterprise-locale.ts index b62f4e3386..43c08b00b1 100644 --- a/plugins/ipollowork-suite/src/client/enterprise-locale.ts +++ b/plugins/ipollowork-suite/src/client/enterprise-locale.ts @@ -472,7 +472,10 @@ const en = { peopleLabel: "People", employeeRecipients: "Selected employees", departmentRecipients: "Selected departments", - searchEmployeeRecipients: "Search by name or employee number", + searchEmployeeRecipients: "Search by name, employee number, or email", + managerAlreadyHasAccess: "Already has access", + chooseDepartments: "Select departments", + departmentSelectionCount: "{count} departments selected", publishResource: "Publish resource", resourcePublished: "Resource published", searchPeople: "Search people", @@ -980,7 +983,10 @@ const zh: typeof en = { peopleLabel: "成员", employeeRecipients: "选定员工", departmentRecipients: "选定部门", - searchEmployeeRecipients: "按姓名或工号搜索", + searchEmployeeRecipients: "按姓名、工号或邮箱搜索", + managerAlreadyHasAccess: "已有访问权限", + chooseDepartments: "请选择部门", + departmentSelectionCount: "已选 {count} 个部门", publishResource: "下发资源", resourcePublished: "资源已下发", searchPeople: "搜索成员", diff --git a/plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.module.css b/plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.module.css index 8626032901..377b40d388 100644 --- a/plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.module.css +++ b/plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.module.css @@ -43,32 +43,6 @@ overflow: auto; } -.loading { - display: flex; - flex-direction: column; - align-self: center; - align-items: center; - gap: 8px; - min-width: 0; - padding: 16px; - color: var(--dsw-alias-label-secondary); - font-size: 13px; - line-height: 20px; - text-align: center; -} - -.spinner { - animation: loadingSpin 1s linear infinite; -} - -@keyframes loadingSpin { - to { transform: rotate(360deg); } -} - -@media (prefers-reduced-motion: reduce) { - .spinner { animation: none; } -} - .onboardingOverlay[inert] .dragBand { -webkit-app-region: no-drag; } diff --git a/plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.tsx b/plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.tsx index cf4bfd2823..d2907f1e85 100644 --- a/plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.tsx +++ b/plugins/ipollowork-suite/src/client/onboarding/OnboardingSurface.tsx @@ -6,15 +6,64 @@ import type { ReactNode } from 'react' import { createPortal } from 'react-dom' import css from './OnboardingSurface.module.css' +// This overlay can mount before the asynchronously linked Suite stylesheet. +const loadingStyles = ` + [data-ipw-onboarding-loading] { + position: fixed; + inset: 0; + z-index: 900; + display: flex; + flex-direction: column; + color-scheme: light dark; + background: var(--dsw-alias-bg-base, Canvas); + user-select: none; + } + html[data-platform="darwin"] [data-ipw-onboarding-loading] { + background: transparent; + } + [data-ipw-onboarding-loading] > [data-window-drag-controls] { + display: grid; + flex: 1; + min-height: 0; + grid-template-columns: minmax(0, 1fr); + place-items: safe center; + padding: var(--dsh-windows-titlebar-height, 32px) 24px; + overflow: auto; + } + [data-ipw-onboarding-loading] [role="status"] { + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; + min-width: 0; + color: var(--dsw-alias-label-secondary, CanvasText); + font-size: 14px; + line-height: 22px; + text-align: center; + overflow-wrap: anywhere; + } + [data-ipw-onboarding-loading] [role="status"] > svg { + flex: none; + color: var(--dsw-alias-label-primary, CanvasText); + animation: ipw-onboarding-spin 900ms linear infinite; + } + @keyframes ipw-onboarding-spin { to { transform: rotate(360deg); } } + @media (prefers-reduced-motion: reduce) { + [data-ipw-onboarding-loading] [role="status"] > svg { animation: none; } + } +` + /** * Render a body-portaled onboarding stage and keep the application root inert * while mounted. Completion reveals the root beneath a fading stage; * native titlebar controls, dialogs, and account pages remain above the stage. * @param props.children - the step's page content, centered on the stage. * @param props.exiting - reveal the application while the owner retains the stage for its 180ms exit. + * @param props.loading - apply the startup layout before the Suite stylesheet loads. * @returns the body-portaled overlay tree. */ -export function OnboardingSurface({ children, exiting = false }: { children: ReactNode; exiting?: boolean }) { +export function OnboardingSurface({ children, exiting = false, loading = false }: + { children: ReactNode; exiting?: boolean; loading?: boolean }) { const rootState = useRef<{ element: HTMLElement; opacity: string } | null>(null) useLayoutEffect(() => { const appRoot = document.getElementById('root') @@ -35,7 +84,9 @@ export function OnboardingSurface({ children, exiting = false }: { children: Rea }, [exiting]) return createPortal(( -
+
+ {loading && } @@ -43,9 +94,9 @@ export function OnboardingSurface({ children, exiting = false }: { children: Rea } export function OnboardingLoading({ label }: { label: string }) { - return -
- + return +
+
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 @@
-