Prechádzať zdrojové kódy

fix(mobile): 移除前台任务完成提示 + 预览手势缩放与返回键

## 1. 移除前台提示(用户明确要求「不要任何前台提示」)

chat.ts 移除了任务完成时的 toast:
  任务已完成,用时 N 秒

两个问题:
  · 用户不要前台提示,任务完成看消息本身即可
  · durText() 在不足 1 秒时显示「0 秒」,看起来像 bug

系统通知保留 —— 它只在 App 不在前台时才看得见,属于离开时的提醒。

## 2. 预览返回键接管

BackButtonService 有完整的弹层登记机制,但**预览组件从未注册过**,
导致按返回键直接退回会话页、预览不关。

修复:预览打开时登记关闭回调(LIFO),返回键先关预览再退路由;
ngOnDestroy 兜底注销,避免残留回调导致「按返回没反应」。

## 3. 双指捏合缩放

检查发现**从未实现**,只有工具栏 +/- 和 PC 的 Ctrl+滚轮。

新增 touchstart/move/end 手势:按两指间距比例缩放,
复用 zoomBy 的边界逻辑。touchmove 必须 preventDefault,
否则浏览器会用自带页面缩放。

## 4. 预览打开时锁底层滚动

用户反馈「标签栏会上下滚动」。
根因:fp-backdrop 是 fixed 铺满,但没阻止底层 body 滚动,
触摸滑动穿透导致视觉错乱。

修复:预览(modal 形态)打开期间锁 body.overflow,关闭还原。

## 5. 登录页验证码冷却提示

倒计时中点击改为 toast 提示(自动消失),不再用行内持久红字。

单测 1861/1861 通过。

Co-Authored-By: Claude Code <noreply@anthropic.com>
Huccct 4 dní pred
rodič
commit
69a756695c

+ 4 - 0
src/app/app.config.ts

@@ -16,6 +16,8 @@ import { DeepLinkService } from './core/deep-link.service';
 import { SafeAreaService } from './core/safe-area.service';
 import { BackButtonService } from './core/back-button.service';
 import { AppNotificationService } from './core/app-notification.service';
+import { ShareReceiveService } from './core/share-receive.service';
+import { provideJPushLifecycle } from './core/jpush.lifecycle';
 import { routes } from './app.routes';
 
 export const appConfig: ApplicationConfig = {
@@ -65,5 +67,7 @@ export const appConfig: ApplicationConfig = {
      * 「App 没运行时点通知」永远不会跳到目标页。
      */
     provideAppInitializer(() => inject(AppNotificationService).init()),
+    provideAppInitializer(() => inject(ShareReceiveService).start()),
+    provideJPushLifecycle(),
   ],
 };

+ 19 - 1
src/app/app.ts

@@ -5,6 +5,8 @@ import { installDataApi } from './core/data-tools';
 import { UiMToast } from './ui/mobile/components/toast/toast';
 import { AlertHostComponent } from './components/feedback/alert-host/alert-host';
 import { AlertService } from './core/alert.service';
+import { ShareReceiveService } from './core/share-receive.service';
+import { MShareReceiveComponent } from './mobile/components/m-share-receive/m-share-receive';
 /**
  * 应用根组件
  *
@@ -13,7 +15,7 @@ import { AlertService } from './core/alert.service';
  */
 @Component({
   selector: 'app-root',
-  imports: [RouterOutlet, UiMToast, AlertHostComponent],
+  imports: [RouterOutlet, UiMToast, AlertHostComponent, MShareReceiveComponent],
   changeDetection: ChangeDetectionStrategy.OnPush,
   template: `
     <router-outlet />
@@ -24,9 +26,25 @@ import { AlertService } from './core/alert.service';
       必须让人看见、知道「这条没被处理」的情况。
     -->
     <app-alert-host />
+    @if (shares.visible()) {
+      @defer (on immediate) {
+        <app-m-share-receive />
+      }
+    } @else if (shares.current() && !shares.transfer()) {
+      <button class="pending-share" type="button" (click)="shares.resume()">继续接收分享({{ shares.pending().length }})</button>
+    }
+    @if (shares.transfer()) {
+      <div class="share-progress" role="status">{{ shares.busy() ? '正在导入分享文件…' : '正在打开接收会话…' }} <button type="button" (click)="shares.cancelTransfer()">取消</button></div>
+    }
   `,
+  styles: [`
+    .pending-share, .share-progress { position: fixed; left: 50%; transform: translateX(-50%); z-index: var(--z-toast); background: var(--surface); color: var(--ink); border: 1px solid var(--edge); border-radius: var(--r-md); padding: var(--sp-3) var(--sp-4); box-shadow: var(--shadow-soft); }
+    .pending-share { bottom: calc(80px + env(safe-area-inset-bottom, 0px)); min-height: 44px; white-space: nowrap; }
+    .share-progress { top: calc(var(--mob-safe-top, 24px) + 12px); }
+  `],
 })
 export class App {
+  protected readonly shares = inject(ShareReceiveService);
   private readonly palette = inject(PaletteService);
   private readonly alert = inject(AlertService);
 

+ 148 - 3
src/app/components/preview/file-preview/file-preview.ts

@@ -15,7 +15,7 @@ import { PdfPreviewComponent } from '../pdf-preview/pdf-preview';
 import { OfficePreviewComponent } from '../office-preview/office-preview';
 import { PreviewKind, extOf, previewKindOf } from '../file-kind';
 import { UiTooltip } from '../../../ui';
-import { inject } from '@angular/core';
+import { inject, OnDestroy } from '@angular/core';
 import { MatrixClientService } from '../../../core/matrix-client.service';
 import { FmodeApi } from '../../../core/api/fmode-api';
 import { isCloudUrl } from '../../../core/s3-link';
@@ -23,6 +23,7 @@ import { downloadAs, needsBlobPreview, toBlobUrl } from '../../../core/attachmen
 import { copyLink, openInNewTab } from '../../../core/open-link';
 import { isNativeApp } from '../../../core/api/platform-proxy.service';
 import { detectUiMode } from '../../../core/device.service';
+import { BackButtonService } from '../../../core/back-button.service';
 import { FileShareService } from '../../../core/file-share.service';
 
 /**
@@ -982,9 +983,29 @@ export type PreviewPresentation = 'rail' | 'full' | 'modal';
     `,
   ],
 })
-export class FilePreviewComponent {
+export class FilePreviewComponent implements OnDestroy {
   /** Matrix 客户端(「新标签打开」需要带 access_token 的直链) */
-  private readonly mx = inject(MatrixClientService);  /** 云盘文件走服务端代理(云盘没配 CORS,见 fetchText 注释) */
+  private readonly mx = inject(MatrixClientService);
+  /**
+   * 物理返回键接管(2026-11-18 用户要求)。
+   *
+   * ## 问题
+   *
+   * 预览打开时按手机返回键 / 手势返回 → **直接退回会话页**,预览不关。
+   * 用户预期是「先关预览,再退会话」。
+   *
+   * ## 机制
+   *
+   * `BackButtonService` 支持弹层登记关闭回调(LIFO,后进先出)——
+   * 预览打开时登记,关闭时注销。返回键会**先**消费到预览、
+   * 只关预览不碰路由。
+   *
+   * 注意 `unregister` 必须与 `register` 成对,否则会出现
+   * 「按一次返回没反应」(回调还在但弹层已关)。
+   */
+  private readonly backButton = inject(BackButtonService);
+  /** 返回键登记 id(每个实例唯一,避免多实例互相覆盖) */
+  private readonly backHandlerId = `file-preview-${Math.random().toString(36).slice(2, 9)}`;  /** 云盘文件走服务端代理(云盘没配 CORS,见 fetchText 注释) */
   private readonly api = inject(FmodeApi);
 
   /** 是否打开 */
@@ -1148,6 +1169,62 @@ export class FilePreviewComponent {
     this.zoomBy(e.deltaY < 0 ? 0.1 : -0.1);
   };
 
+  /* ---------------- 双指捏合缩放(2026-11-18) ---------------- */
+
+  /** 上一次捏合时的两指间距(0 = 当前没有捏合) */
+  private pinchStartDist = 0;
+  /** 捏合开始时的缩放值 */
+  private pinchStartZoom = 1;
+
+  private static touchDistance(t1: Touch, t2: Touch): number {
+    return Math.hypot(t1.clientX - t2.clientX, t1.clientY - t2.clientY);
+  }
+
+  /**
+   * 双指捏合缩放(移动端手势)。
+   *
+   * ## 为什么需要
+   *
+   * 用户反馈「预览组件的 mobile 端手势缩放功能失效」——
+   * 检查发现**从未实现过**:只有工具栏的 +/- 按钮和 PC 的 Ctrl+滚轮。
+   * 移动端用户习惯双指缩放,没有这个手势体验上等于「不能缩放」。
+   *
+   * ## 实现
+   *
+   * 用 `touchstart/touchmove/touchend` 监听两指操作:
+   *   · 两指按下 → 记录初始间距与当前缩放
+   *   · 两指移动 → 按「当前间距 / 初始间距」比例算新缩放
+   *   · 离开一指 → 结束本次捏合
+   *
+   * 必须 `preventDefault`,否则浏览器会用自己的页面缩放,视图错乱。
+   *
+   * ## 与 iframe 的关系
+   *
+   * HTML 预览是 iframe,手指事件落在 iframe 内部、不冒泡到宿主。
+   * 模板里 `frameStop()` 在加载完成后把 iframe 标成 `pointer-events: none`,
+   * 由外层 `.fp-html-shield` 接管 —— 手势监听挂在这个外层容器上即可。
+   */
+  private readonly onTouchStart = (e: TouchEvent): void => {
+    if (!this.touchUi || e.touches.length !== 2) return;
+    this.pinchStartDist = FilePreviewComponent.touchDistance(e.touches[0], e.touches[1]);
+    this.pinchStartZoom = this.zoom();
+  };
+
+  private readonly onTouchMove = (e: TouchEvent): void => {
+    if (!this.touchUi || e.touches.length !== 2 || this.pinchStartDist <= 0) return;
+    e.preventDefault();
+    const dist = FilePreviewComponent.touchDistance(e.touches[0], e.touches[1]);
+    if (dist <= 0) return;
+    const next = this.pinchStartZoom * (dist / this.pinchStartDist);
+    /* 复用 zoomBy 的边界与取整逻辑:按差值估算步数 */
+    const steps = next - this.zoom();
+    if (Math.abs(steps) >= 0.01) this.zoomBy(steps);
+  };
+
+  private readonly onTouchEnd = (e: TouchEvent): void => {
+    if (e.touches.length < 2) this.pinchStartDist = 0;
+  };
+
   constructor() {
     effect(() => {
       const isOpen = this.open();
@@ -1177,21 +1254,89 @@ export class FilePreviewComponent {
       });
     });
 
+    /*
+     * 🔴 预览打开时**锁住底层页面滚动**(2026-11-18 用户实测「标签栏会上下滚动」)。
+     *
+     * ## 现象
+     *
+     * 移动端预览打开后,手指在内容上滑动,**顶部标题栏也跟着上下移动**。
+     *
+     * ## 根因
+     *
+     * `fp-backdrop` 是 `position: fixed; inset: 0`,遮住了整个视口,
+     * 但**没有阻止底层页面滚动**。移动端触摸滑动会穿透到 body,
+     * body 一滚,fixed 定位的视觉参照就变了 —— 看起来像标签栏在动。
+     *
+     * ## 修法
+     *
+     * 打开期间给 body 加 `overflow: hidden`,关闭时还原。
+     * 只锁 `modal` 形态(移动端全屏)—— `rail` 是桌面右栏内联,不该锁页面。
+     */
+    effect((onCleanup) => {
+      const isOpen = this.open();
+      const isModal = this.presentation() === 'modal';
+      if (!isOpen || !isModal || typeof document === 'undefined') return;
+      const body = document.body;
+      const prev = body.style.overflow;
+      body.style.overflow = 'hidden';
+      onCleanup(() => {
+        body.style.overflow = prev;
+      });
+    });
+
     // 面板挂载/卸载时绑定原生 wheel(capture)+ 全局 Ctrl 按键状态
     effect((onCleanup) => {
       const el = this.panelEl()?.nativeElement;
       if (!el) return;
       el.addEventListener('wheel', this.onPanelWheel, { passive: false, capture: true });
+      /* 双指捏合缩放(2026-11-18):挂面板上,覆盖所有预览类型 */
+      el.addEventListener('touchstart', this.onTouchStart, { passive: true });
+      el.addEventListener('touchmove', this.onTouchMove, { passive: false });
+      el.addEventListener('touchend', this.onTouchEnd, { passive: true });
+      el.addEventListener('touchcancel', this.onTouchEnd, { passive: true });
       window.addEventListener('keydown', this.onKeyDown, true);
       window.addEventListener('keyup', this.onKeyUp, true);
       window.addEventListener('blur', this.onBlur);
       onCleanup(() => {
         el.removeEventListener('wheel', this.onPanelWheel, { capture: true });
+        el.removeEventListener('touchstart', this.onTouchStart);
+        el.removeEventListener('touchmove', this.onTouchMove);
+        el.removeEventListener('touchend', this.onTouchEnd);
+        el.removeEventListener('touchcancel', this.onTouchEnd);
         window.removeEventListener('keydown', this.onKeyDown, true);
         window.removeEventListener('keyup', this.onKeyUp, true);
         window.removeEventListener('blur', this.onBlur);
       });
     });
+
+    /*
+     * 物理返回键:预览打开时登记关闭回调(2026-11-18)。
+     *
+     * 返回 true = 「我消费了这次返回」,BackButtonService 就不会再退路由。
+     * 预览关闭后立即注销,把返回键交还给页面。
+     */
+    effect((onCleanup) => {
+      const isOpen = this.open();
+      if (!isOpen) return;
+      this.backButton.register(this.backHandlerId, () => {
+        this.closed.emit();
+        return true;
+      });
+      onCleanup(() => this.backButton.unregister(this.backHandlerId));
+    });
+  }
+
+  /**
+   * 组件销毁时注销返回键回调(2026-11-18)。
+   *
+   * 🔴 必须成对:`effect` 的 onCleanup 只在 effect 重跑/销毁时触发,
+   *    组件被整体销毁时可能来不及 —— 这里再兜一次,避免残留回调导致
+   *    「按返回没反应」。
+   */
+  ngOnDestroy(): void {
+    this.backButton.unregister(this.backHandlerId);
+    this.clearFrameTimer();
+    this.releaseBlob();
   }
 
   setPresentation(p: 'rail' | 'full'): void {

+ 13 - 0
src/app/components/preview/image-lightbox/image-lightbox.ts

@@ -3,11 +3,13 @@ import {
   Component,
   ElementRef,
   effect,
+  inject,
   input,
   output,
   viewChild,
 } from '@angular/core';
 import { downloadAs } from '../../../core/attachment-fetch';
+import { FileShareService } from '../../../core/file-share.service';
 
 /**
  * 图片灯箱 —— 附件图片的**唯一**放大查看方式。
@@ -53,6 +55,12 @@ import { downloadAs } from '../../../core/attachment-fetch';
               }
             </span>
             <span class="lb-actions">
+              @if (fileShare.available) {
+                <button type="button" class="lb-act" aria-label="分享图片" [disabled]="fileShare.busy()" (click)="shareFile()">
+                  <i class="fa-solid fa-share-nodes" aria-hidden="true"></i>
+                  <span>{{ fileShare.busy() ? '准备中' : '分享' }}</span>
+                </button>
+              }
               <button type="button" class="lb-act" (click)="download()">
                 <i class="fa-solid fa-download" aria-hidden="true"></i>
                 <span>下载</span>
@@ -206,6 +214,7 @@ import { downloadAs } from '../../../core/attachment-fetch';
   ],
 })
 export class ImageLightboxComponent {
+  protected readonly fileShare = inject(FileShareService);
   readonly open = input(false);
   readonly url = input('');
   readonly name = input('');
@@ -264,6 +273,10 @@ export class ImageLightboxComponent {
     await downloadAs(this.url(), this.name() || 'image');
   }
 
+  async shareFile(): Promise<void> {
+    await this.fileShare.share({ url: this.url(), name: this.name() || 'image' });
+  }
+
   close(): void {
     this.closed.emit();
   }

+ 58 - 0
src/app/core/file-share.service.spec.ts

@@ -0,0 +1,58 @@
+import { TestBed } from '@angular/core/testing';
+import { FileShareService, SYSTEM_FILE_SHARE } from './file-share.service';
+import { NATIVE_SHARE, NATIVE_SHARING_AVAILABLE } from './native-share';
+import { UiMToastService } from '../ui/mobile/components/toast/toast';
+
+describe('FileShareService', () => {
+  let service: FileShareService;
+  let prepare: jasmine.Spy;
+  let share: jasmine.Spy;
+  let toast: jasmine.SpyObj<UiMToastService>;
+
+  beforeEach(() => {
+    prepare = jasmine.createSpy('prepareOutgoing').and.resolveTo({ path: 'file:///cache/shared-outgoing/report.pdf' });
+    toast = jasmine.createSpyObj('Toast', ['error']);
+    share = jasmine.createSpy('share').and.resolveTo({});
+    TestBed.configureTestingModule({ providers: [
+      { provide: NATIVE_SHARE, useValue: { prepareOutgoing: prepare } },
+      { provide: NATIVE_SHARING_AVAILABLE, useValue: true },
+      { provide: SYSTEM_FILE_SHARE, useValue: { share } },
+      { provide: UiMToastService, useValue: toast },
+    ] });
+    service = TestBed.inject(FileShareService);
+  });
+
+  it('以本地文件调系统分享,不把远程URL当文字链接发送', async () => {
+    await service.share({ name: 'report.pdf', url: 'https://s3.fmode.cn/report.pdf' });
+    expect(prepare).toHaveBeenCalledWith({ url: 'https://s3.fmode.cn/report.pdf', name: 'report.pdf' });
+    expect(share.calls.mostRecent().args[0].files).toEqual(['file:///cache/shared-outgoing/report.pdf']);
+    expect(share.calls.mostRecent().args[0].url).toBeUndefined();
+    expect(service.busy()).toBeFalse();
+  });
+
+  it('用户取消不弹错误', async () => {
+    share.and.rejectWith(new Error('Share canceled'));
+    await service.share({ name: 'report.pdf', url: 'https://s3.fmode.cn/report.pdf' });
+    expect(toast.error).not.toHaveBeenCalled();
+    expect(service.busy()).toBeFalse();
+  });
+
+  it('下载失败给出可见错误并恢复按钮', async () => {
+    prepare.and.rejectWith(new Error('下载失败(HTTP 404)'));
+    await service.share({ name: 'report.pdf', url: 'https://s3.fmode.cn/report.pdf' });
+    expect(share).not.toHaveBeenCalled();
+    expect(toast.error).toHaveBeenCalledWith('下载失败(HTTP 404)');
+    expect(service.busy()).toBeFalse();
+  });
+
+  it('准备文件期间防止连点重复发起', async () => {
+    let finish!: (value: { path: string }) => void;
+    prepare.and.returnValue(new Promise((resolve) => { finish = resolve; }));
+    const first = service.share({ name: 'report.pdf', url: 'https://s3.fmode.cn/report.pdf' });
+    await service.share({ name: 'report.pdf', url: 'https://s3.fmode.cn/report.pdf' });
+    expect(prepare).toHaveBeenCalledTimes(1);
+    finish({ path: 'file:///cache/shared-outgoing/report.pdf' });
+    await first;
+    expect(share).toHaveBeenCalledTimes(1);
+  });
+});

+ 35 - 0
src/app/core/file-share.service.ts

@@ -0,0 +1,35 @@
+import { inject, Injectable, InjectionToken, signal } from '@angular/core';
+import { Share } from '@capacitor/share';
+import { NATIVE_SHARE, NATIVE_SHARING_AVAILABLE } from './native-share';
+import { OpenableFile } from './file-open';
+import { UiMToastService } from '../ui/mobile/components/toast/toast';
+
+export const SYSTEM_FILE_SHARE = new InjectionToken<Pick<typeof Share, 'share'>>('SystemFileShare', {
+  providedIn: 'root',
+  factory: () => Share,
+});
+
+@Injectable({ providedIn: 'root' })
+export class FileShareService {
+  private readonly native = inject(NATIVE_SHARE);
+  private readonly systemShare = inject(SYSTEM_FILE_SHARE);
+  private readonly toast = inject(UiMToastService);
+  readonly available = inject(NATIVE_SHARING_AVAILABLE);
+  readonly busy = signal(false);
+
+  async share(file: OpenableFile): Promise<void> {
+    if (!this.available || this.busy()) return;
+    this.busy.set(true);
+    try {
+      const { path } = await this.native.prepareOutgoing({ url: file.url, name: file.name });
+      await this.systemShare.share({ files: [path], title: file.name || '分享文件', dialogTitle: '发送到微信、企业微信或其他应用' });
+    } catch (error) {
+      const message = error instanceof Error ? error.message : String(error ?? '');
+      if (!/cancel|canceled|cancelled|取消|未选择/i.test(message)) {
+        this.toast.error(message || '分享失败,请稍后重试');
+      }
+    } finally {
+      this.busy.set(false);
+    }
+  }
+}

+ 72 - 0
src/app/core/jpush.lifecycle.spec.ts

@@ -0,0 +1,72 @@
+import { ApplicationInitStatus, signal } from '@angular/core';
+import { TestBed } from '@angular/core/testing';
+import { JPushLifecycleService, provideJPushLifecycle } from './jpush.lifecycle';
+import { JPushService } from './jpush.service';
+import { SessionService } from './session.service';
+
+describe('JPush lifecycle integration', () => {
+  let push: jasmine.SpyObj<JPushService>;
+  const loggedIn = signal(false);
+  const me = signal<{ id: string; companyId?: string } | null>(null);
+
+  beforeEach(() => {
+    loggedIn.set(false);
+    me.set(null);
+    push = jasmine.createSpyObj<JPushService>('push', ['start', 'unbindAccount']);
+    push.start.and.resolveTo(false);
+    push.unbindAccount.and.resolveTo(true);
+    TestBed.configureTestingModule({ providers: [
+      provideJPushLifecycle(),
+      { provide: JPushService, useValue: push },
+      { provide: SessionService, useValue: { isLoggedIn: loggedIn, me } },
+    ] });
+  });
+
+  it('calls start without manufacturing privacy consent in AppInitializer', async () => {
+    const initialization = TestBed.inject(ApplicationInitStatus);
+    await initialization.donePromise;
+    expect(push.start).toHaveBeenCalledOnceWith();
+  });
+
+  it('does not bind an account just because a session exists', () => {
+    loggedIn.set(true);
+    me.set({ id: 'account-test' });
+    TestBed.inject(JPushLifecycleService);
+    TestBed.flushEffects();
+    expect(push.unbindAccount).not.toHaveBeenCalled();
+    expect(push.start).toHaveBeenCalledOnceWith();
+  });
+
+  it('automatically requests alias deletion on logout', () => {
+    loggedIn.set(true);
+    me.set({ id: 'account-test' });
+    TestBed.inject(JPushLifecycleService);
+    TestBed.flushEffects();
+    loggedIn.set(false);
+    me.set(null);
+    TestBed.flushEffects();
+    expect(push.unbindAccount).toHaveBeenCalledTimes(1);
+  });
+
+  it('automatically unbinds on account or tenant changes', () => {
+    loggedIn.set(true);
+    me.set({ id: 'account-one', companyId: 'tenant-one' });
+    TestBed.inject(JPushLifecycleService);
+    TestBed.flushEffects();
+    me.set({ id: 'account-two', companyId: 'tenant-one' });
+    TestBed.flushEffects();
+    me.set({ id: 'account-two', companyId: 'tenant-two' });
+    TestBed.flushEffects();
+    expect(push.unbindAccount).toHaveBeenCalledTimes(2);
+  });
+
+  it('does not delete alias for an unchanged identity refresh', () => {
+    loggedIn.set(true);
+    me.set({ id: 'account-one', companyId: 'tenant-one' });
+    TestBed.inject(JPushLifecycleService);
+    TestBed.flushEffects();
+    me.set({ id: 'account-one', companyId: 'tenant-one' });
+    TestBed.flushEffects();
+    expect(push.unbindAccount).not.toHaveBeenCalled();
+  });
+});

+ 34 - 0
src/app/core/jpush.lifecycle.ts

@@ -0,0 +1,34 @@
+import { Injectable, effect, inject, provideAppInitializer } from '@angular/core';
+import { SessionService } from './session.service';
+import { JPushService } from './jpush.service';
+
+@Injectable({ providedIn: 'root' })
+export class JPushLifecycleService {
+  private readonly session = inject(SessionService);
+  private readonly push = inject(JPushService);
+  private previousAccount = this.currentAccount();
+
+  constructor() {
+    effect(() => {
+      const account = this.currentAccount();
+      if (this.previousAccount && this.previousAccount !== account) {
+        void this.push.unbindAccount();
+      }
+      this.previousAccount = account;
+    });
+  }
+
+  start(): Promise<boolean> {
+    return this.push.start();
+  }
+
+  private currentAccount(): string | null {
+    if (!this.session.isLoggedIn()) return null;
+    const account = this.session.me();
+    return account ? JSON.stringify([account.companyId ?? '', account.id]) : null;
+  }
+}
+
+export function provideJPushLifecycle() {
+  return provideAppInitializer(() => inject(JPushLifecycleService).start());
+}

+ 50 - 0
src/app/core/jpush.plugin.ts

@@ -0,0 +1,50 @@
+import { InjectionToken } from '@angular/core';
+import { Capacitor, PluginListenerHandle, registerPlugin } from '@capacitor/core';
+
+export interface JPushStatus {
+  available: boolean;
+  started: boolean;
+  reason?: string;
+}
+
+export interface JPushNotice {
+  kind: 'notification' | 'message';
+  messageId: string;
+  businessKey?: string;
+  title?: string;
+  body?: string;
+  deepLink?: string;
+}
+
+export interface JPushPlugin {
+  getStatus(): Promise<JPushStatus>;
+  start(options: { privacyConsent: boolean }): Promise<JPushStatus>;
+  stop(): Promise<void>;
+  getRegistrationId(): Promise<{ registrationId: string | null }>;
+  setAlias(options: { alias: string }): Promise<void>;
+  deleteAlias(): Promise<void>;
+  addListener(
+    event: 'registration',
+    listener: (data: { registrationId: string }) => void,
+  ): Promise<PluginListenerHandle>;
+  addListener(
+    event: 'notificationReceived' | 'notificationOpened',
+    listener: (data: JPushNotice) => void,
+  ): Promise<PluginListenerHandle>;
+}
+
+export const JPUSH_OPTIONS = new InjectionToken<{ enabled: boolean }>('JPUSH_OPTIONS', {
+  providedIn: 'root',
+  factory: () => ({ enabled: false }),
+});
+
+export const JPUSH_PLUGIN = new InjectionToken<JPushPlugin>('JPUSH_PLUGIN', {
+  providedIn: 'root',
+  factory: () => registerPlugin<JPushPlugin>('FmodeJPush'),
+});
+
+export const JPUSH_SUPPORTED = new InjectionToken<() => boolean>('JPUSH_SUPPORTED', {
+  providedIn: 'root',
+  factory: () => () =>
+    Capacitor.getPlatform() === 'android' && Capacitor.isPluginAvailable('FmodeJPush'),
+});

+ 235 - 0
src/app/core/jpush.service.spec.ts

@@ -0,0 +1,235 @@
+import { TestBed } from '@angular/core/testing';
+import { Router } from '@angular/router';
+import { AppNotificationService } from './app-notification.service';
+import { DeepLinkService } from './deep-link.service';
+import { JPUSH_OPTIONS, JPUSH_PLUGIN, JPUSH_SUPPORTED, JPushNotice, JPushPlugin } from './jpush.plugin';
+import { JPushService } from './jpush.service';
+
+describe('JPushService', () => {
+  let service: JPushService;
+  let plugin: jasmine.SpyObj<JPushPlugin>;
+  let notifications: jasmine.SpyObj<AppNotificationService>;
+  let router: jasmine.SpyObj<Router>;
+  let options: { enabled: boolean };
+  let supported: boolean;
+  let listeners: Map<string, (data: never) => void>;
+  let removed: jasmine.Spy;
+
+  beforeEach(() => {
+    options = { enabled: true };
+    supported = true;
+    listeners = new Map();
+    removed = jasmine.createSpy('remove').and.resolveTo();
+    plugin = jasmine.createSpyObj<JPushPlugin>('FmodeJPush', [
+      'getStatus', 'start', 'stop', 'getRegistrationId', 'setAlias', 'deleteAlias', 'addListener',
+    ]);
+    plugin.getStatus.and.resolveTo({ available: true, started: false });
+    plugin.start.and.resolveTo({ available: true, started: true });
+    plugin.stop.and.resolveTo();
+    plugin.getRegistrationId.and.resolveTo({ registrationId: null });
+    plugin.setAlias.and.resolveTo();
+    plugin.deleteAlias.and.resolveTo();
+    plugin.addListener.and.callFake(async (event, callback) => {
+      listeners.set(event, callback);
+      return { remove: removed };
+    });
+    notifications = jasmine.createSpyObj<AppNotificationService>('notifications', ['notify', 'request']);
+    notifications.notify.and.resolveTo();
+    notifications.request.and.resolveTo(true);
+    router = jasmine.createSpyObj<Router>('router', ['navigateByUrl']);
+    router.navigateByUrl.and.resolveTo(true);
+    TestBed.configureTestingModule({ providers: [
+      JPushService, DeepLinkService,
+      { provide: JPUSH_OPTIONS, useValue: options },
+      { provide: JPUSH_SUPPORTED, useValue: () => supported },
+      { provide: JPUSH_PLUGIN, useValue: plugin },
+      { provide: AppNotificationService, useValue: notifications },
+      { provide: Router, useValue: router },
+    ] });
+    service = TestBed.inject(JPushService);
+  });
+
+  function emit(event: string, data: unknown): void {
+    listeners.get(event)?.(data as never);
+  }
+
+  function notice(overrides: Partial<JPushNotice> = {}): JPushNotice {
+    return { kind: 'message', messageId: 'event-one', title: '任务完成', body: '完成', ...overrides };
+  }
+
+  it('defaults to disabled without touching the bridge', async () => {
+    options.enabled = false;
+    expect(await service.start(true)).toBeFalse();
+    expect(service.phase()).toBe('disabled');
+    expect(plugin.getStatus).not.toHaveBeenCalled();
+    expect(plugin.start).not.toHaveBeenCalled();
+    expect(notifications.request).not.toHaveBeenCalled();
+  });
+
+  it('requires explicit privacy consent', async () => {
+    expect(await service.start()).toBeFalse();
+    expect(service.reason()).toBe('privacy-consent-required');
+    expect(plugin.getStatus).not.toHaveBeenCalled();
+  });
+
+  it('does not start on web or without native registration', async () => {
+    supported = false;
+    expect(await service.start(true)).toBeFalse();
+    expect(service.reason()).toBe('native-plugin-unavailable');
+    expect(plugin.start).not.toHaveBeenCalled();
+  });
+
+  it('reports missing AppKey without starting SDK or listeners', async () => {
+    plugin.getStatus.and.resolveTo({ available: false, started: false, reason: 'missing-or-invalid-appkey' });
+    expect(await service.start(true)).toBeFalse();
+    expect(service.reason()).toBe('missing-or-invalid-appkey');
+    expect(plugin.start).not.toHaveBeenCalled();
+    expect(plugin.addListener).not.toHaveBeenCalled();
+  });
+
+  it('starts once, clears stale alias and never treats an empty registration as registered', async () => {
+    const first = service.start(true);
+    expect(service.start(true)).toBe(first);
+    expect(await first).toBeTrue();
+    expect(await service.start(true)).toBeTrue();
+    expect(plugin.start).toHaveBeenCalledOnceWith({ privacyConsent: true });
+    expect(plugin.deleteAlias).toHaveBeenCalledTimes(1);
+    expect(service.registrationId()).toBeNull();
+    emit('registration', { registrationId: 'registration-test-only' });
+    expect(service.registrationId()).toBe('registration-test-only');
+    expect(notifications.request).not.toHaveBeenCalled();
+  });
+
+  it('cleans partial listeners and can retry startup', async () => {
+    plugin.addListener.and.rejectWith(new Error('listener-unavailable'));
+    expect(await service.start(true)).toBeFalse();
+    expect(service.phase()).toBe('error');
+    expect(service.reason()).toBe('native-start-failed');
+    plugin.addListener.and.callFake(async (event, callback) => {
+      listeners.set(event, callback);
+      return { remove: removed };
+    });
+    expect(await service.start(true)).toBeTrue();
+  });
+
+  it('stops if stale alias cannot be cleared', async () => {
+    plugin.deleteAlias.and.rejectWith(new Error('offline'));
+    expect(await service.start(true)).toBeFalse();
+    expect(plugin.stop).toHaveBeenCalled();
+    expect(removed).toHaveBeenCalledTimes(3);
+    expect(service.registrationId()).toBeNull();
+  });
+
+  it('does not redisplay SDK-rendered notification and suppresses a paired data message', async () => {
+    await service.start(true);
+    emit('notificationReceived', notice({ kind: 'notification', businessKey: 'business-one' }));
+    emit('notificationReceived', notice({ messageId: 'data-one', businessKey: 'business-one' }));
+    expect(notifications.notify).not.toHaveBeenCalled();
+  });
+
+  it('reuses local notifications once per event and never navigates on arrival', async () => {
+    await service.start(true);
+    const data = notice({ deepLink: 'fmode://chat/agent/session' });
+    emit('notificationReceived', data);
+    emit('notificationReceived', data);
+    expect(notifications.notify).toHaveBeenCalledOnceWith({
+      title: '任务完成', body: '完成', deepLink: data.deepLink, key: 'jpush:event-one',
+    });
+    expect(router.navigateByUrl).not.toHaveBeenCalled();
+  });
+
+  it('deduplicates migrated local producers and remote messages using an explicit business event key', async () => {
+    await service.start(true);
+    await service.notifyLocal({ title: '任务完成', body: '完成', key: 'task-group' }, 'task-event-one');
+    emit('notificationReceived', notice({ businessKey: 'task-event-one' }));
+    expect(notifications.notify).toHaveBeenCalledTimes(1);
+    await service.notifyLocal({ title: '任务完成', body: '另一任务完成', key: 'task-group' }, 'task-event-two');
+    expect(notifications.notify).toHaveBeenCalledTimes(2);
+  });
+
+  it('does not confuse notification replacement keys with event deduplication keys', async () => {
+    const data = { title: '任务完成', body: '完成', key: 'same-session' };
+    await service.notifyLocal(data);
+    await service.notifyLocal(data);
+    expect(notifications.notify).toHaveBeenCalledTimes(2);
+  });
+
+  it('deduplicates clicks separately from receipt and uses existing DeepLinkService', async () => {
+    await service.start(true);
+    const data = notice({ kind: 'notification', deepLink: 'fmode://chat/agent/session' });
+    emit('notificationReceived', data);
+    emit('notificationOpened', data);
+    emit('notificationOpened', data);
+    expect(router.navigateByUrl).toHaveBeenCalledOnceWith('/mobile/chat/agent/session');
+  });
+
+  it('rejects external URLs and malformed percent-encoded deep links', async () => {
+    await service.start(true);
+    emit('notificationOpened', notice({ deepLink: 'https://example.invalid' }));
+    emit('notificationOpened', notice({ deepLink: 'fmode://chat/%ZZ' }));
+    emit('notificationOpened', notice({ deepLink: 'javascript:alert(1)' }));
+    expect(router.navigateByUrl).not.toHaveBeenCalled();
+  });
+
+  it('serializes account switches and waits for native acknowledgment', async () => {
+    await service.start(true);
+    const firstAlias = `fm_${'a'.repeat(32)}`;
+    const secondAlias = `fm_${'b'.repeat(32)}`;
+    let acknowledge: (() => void) | undefined;
+    plugin.setAlias.and.callFake(() => new Promise<void>((resolve) => { acknowledge = resolve; }));
+    const first = service.bindAccount(firstAlias);
+    const second = service.bindAccount(secondAlias);
+    await Promise.resolve();
+    await Promise.resolve();
+    expect(service.binding()).toBe('binding');
+    expect(plugin.setAlias).toHaveBeenCalledOnceWith({ alias: firstAlias });
+    acknowledge!();
+    expect(await first).toBeTrue();
+    await Promise.resolve();
+    await Promise.resolve();
+    expect(plugin.setAlias).toHaveBeenCalledWith({ alias: secondAlias });
+    acknowledge!();
+    expect(await second).toBeTrue();
+    expect(service.binding()).toBe('bound');
+    expect(plugin.deleteAlias).toHaveBeenCalledTimes(3);
+  });
+
+  it('rejects non-opaque aliases without forwarding user identifiers', async () => {
+    await service.start(true);
+    expect(await service.bindAccount('user-name')).toBeFalse();
+    expect(await service.bindAccount('session-token')).toBeFalse();
+    expect(plugin.setAlias).not.toHaveBeenCalled();
+  });
+
+  it('clears account binding on logout and stops if unbinding fails', async () => {
+    await service.start(true);
+    expect(await service.bindAccount(`fm_${'a'.repeat(32)}`)).toBeTrue();
+    plugin.deleteAlias.and.rejectWith(new Error('offline'));
+    expect(await service.unbindAccount()).toBeFalse();
+    expect(service.binding()).toBe('error');
+    expect(service.phase()).toBe('error');
+    expect(service.reason()).toBe('alias-operation-failed');
+    expect(plugin.stop).toHaveBeenCalled();
+  });
+
+  it('unbinds and removes listeners when stopped', async () => {
+    await service.start(true);
+    await service.stop();
+    expect(plugin.deleteAlias).toHaveBeenCalledTimes(2);
+    expect(plugin.stop).toHaveBeenCalled();
+    expect(removed).toHaveBeenCalledTimes(3);
+    expect(service.registrationId()).toBeNull();
+    expect(service.phase()).toBe('disabled');
+  });
+
+  it('reuses the existing permission request only when explicitly requested', async () => {
+    expect(await service.requestPermission()).toBeTrue();
+    expect(notifications.request).toHaveBeenCalledTimes(1);
+  });
+});
+
+describe('JPush default configuration', () => {
+  it('is disabled without an application-level override', () => {
+    expect(TestBed.inject(JPUSH_OPTIONS)).toEqual({ enabled: false });
+  });
+});

+ 196 - 0
src/app/core/jpush.service.ts

@@ -0,0 +1,196 @@
+import { Injectable, NgZone, inject, signal } from '@angular/core';
+import { PluginListenerHandle } from '@capacitor/core';
+import { AppNotice, AppNotificationService } from './app-notification.service';
+import { DeepLinkService } from './deep-link.service';
+import { JPUSH_OPTIONS, JPUSH_PLUGIN, JPUSH_SUPPORTED, JPushNotice } from './jpush.plugin';
+
+@Injectable({ providedIn: 'root' })
+export class JPushService {
+  private readonly options = inject(JPUSH_OPTIONS);
+  private readonly plugin = inject(JPUSH_PLUGIN);
+  private readonly supported = inject(JPUSH_SUPPORTED);
+  private readonly notifications = inject(AppNotificationService);
+  private readonly deepLink = inject(DeepLinkService);
+  private readonly zone = inject(NgZone);
+  private readonly phaseValue = signal<'disabled' | 'blocked' | 'starting' | 'started' | 'error'>('disabled');
+  private readonly reasonValue = signal<string | null>(null);
+  private readonly registrationValue = signal<string | null>(null);
+  private readonly bindingValue = signal<'unbound' | 'binding' | 'bound' | 'error'>('unbound');
+  readonly phase = this.phaseValue.asReadonly();
+  readonly reason = this.reasonValue.asReadonly();
+  readonly registrationId = this.registrationValue.asReadonly();
+  readonly binding = this.bindingValue.asReadonly();
+  private handles: PluginListenerHandle[] = [];
+  private startPromise: Promise<boolean> | null = null;
+  private accountQueue: Promise<void> = Promise.resolve();
+  private readonly seen = new Map<string, number>();
+  private readonly clicked = new Map<string, number>();
+
+  start(privacyConsent = false): Promise<boolean> {
+    if (!this.options.enabled) {
+      this.phaseValue.set('disabled');
+      this.reasonValue.set('disabled-by-config');
+      return Promise.resolve(false);
+    }
+    if (!privacyConsent || !this.supported()) {
+      this.phaseValue.set('blocked');
+      this.reasonValue.set(!privacyConsent ? 'privacy-consent-required' : 'native-plugin-unavailable');
+      return Promise.resolve(false);
+    }
+    if (this.phase() === 'started') return Promise.resolve(true);
+    if (this.startPromise) return this.startPromise;
+    this.startPromise = this.initialize().finally(() => { this.startPromise = null; });
+    return this.startPromise;
+  }
+
+  private async initialize(): Promise<boolean> {
+    this.phaseValue.set('starting');
+    this.reasonValue.set(null);
+    try {
+      const status = await this.plugin.getStatus();
+      if (!status.available) {
+        this.phaseValue.set('blocked');
+        this.reasonValue.set(status.reason ?? 'native-configuration-required');
+        return false;
+      }
+      await this.removeListeners();
+      this.handles.push(await this.plugin.addListener('registration', (data) => {
+        this.zone.run(() => this.registrationValue.set(data.registrationId || null));
+      }));
+      this.handles.push(await this.plugin.addListener('notificationReceived', (data) => {
+        void this.zone.run(() => this.receive(data)).catch(() => undefined);
+      }));
+      this.handles.push(await this.plugin.addListener('notificationOpened', (data) => {
+        void this.zone.run(() => this.open(data)).catch(() => undefined);
+      }));
+      const result = await this.plugin.start({ privacyConsent: true });
+      if (!result.started) throw new Error('start-rejected');
+      await this.plugin.deleteAlias();
+      this.bindingValue.set('unbound');
+      const registrationId = (await this.plugin.getRegistrationId()).registrationId;
+      if (registrationId) this.registrationValue.set(registrationId);
+      this.phaseValue.set('started');
+      return true;
+    } catch {
+      await this.plugin.stop().catch(() => undefined);
+      await this.removeListeners();
+      this.registrationValue.set(null);
+      this.phaseValue.set('error');
+      this.reasonValue.set('native-start-failed');
+      return false;
+    }
+  }
+
+  async requestPermission(): Promise<boolean> {
+    return this.notifications.request();
+  }
+
+  bindAccount(opaqueAlias: string): Promise<boolean> {
+    if (!/^fm_[a-f0-9]{32,60}$/.test(opaqueAlias)) return Promise.resolve(false);
+    return this.enqueueAccount(async () => {
+      if (this.phase() !== 'started') return false;
+      this.bindingValue.set('binding');
+      try {
+        await this.plugin.deleteAlias();
+        await this.plugin.setAlias({ alias: opaqueAlias });
+        this.bindingValue.set('bound');
+        return true;
+      } catch {
+        await this.failBinding();
+        return false;
+      }
+    });
+  }
+
+  unbindAccount(): Promise<boolean> {
+    return this.enqueueAccount(async () => {
+      if (this.phase() !== 'started') return this.binding() === 'unbound';
+      try {
+        await this.plugin.deleteAlias();
+        this.bindingValue.set('unbound');
+        this.seen.clear();
+        this.clicked.clear();
+        return true;
+      } catch {
+        await this.failBinding();
+        return false;
+      }
+    });
+  }
+
+  async stop(): Promise<void> {
+    if (this.startPromise) await this.startPromise;
+    await this.unbindAccount();
+    if (this.supported() && this.phase() !== 'disabled') {
+      await this.plugin.stop().catch(() => undefined);
+    }
+    await this.removeListeners();
+    this.registrationValue.set(null);
+    this.phaseValue.set('disabled');
+    this.reasonValue.set('stopped');
+  }
+
+  async notifyLocal(notice: AppNotice, businessKey?: string): Promise<void> {
+    if (businessKey && !this.claim(this.seen, businessKey)) return;
+    await this.notifications.notify(notice);
+  }
+
+  private async receive(notice: JPushNotice): Promise<void> {
+    if (this.phase() !== 'started') return;
+    if (!notice?.messageId || !['notification', 'message'].includes(notice.kind)) return;
+    const key = notice.businessKey || `jpush:${notice.messageId}`;
+    if (notice.kind === 'notification') {
+      this.claim(this.seen, key);
+      return;
+    }
+    if (!this.claim(this.seen, key)) return;
+    await this.notifications.notify({
+      title: notice.title || '新消息',
+      body: notice.body || '',
+      deepLink: this.safeRoute(notice.deepLink) ? notice.deepLink : undefined,
+      key,
+    });
+  }
+
+  private async open(notice: JPushNotice): Promise<void> {
+    if (!notice?.messageId) return;
+    const route = this.safeRoute(notice.deepLink);
+    if (!route || !this.claim(this.clicked, notice.messageId)) return;
+    await this.deepLink.navigate(route);
+  }
+
+  private safeRoute(raw?: string): string | null {
+    if (!raw) return null;
+    try { return this.deepLink.toRoute(raw); } catch { return null; }
+  }
+
+  private claim(cache: Map<string, number>, key: string): boolean {
+    const now = Date.now();
+    for (const [entry, expires] of cache) {
+      if (expires <= now) cache.delete(entry);
+    }
+    if (cache.has(key)) return false;
+    if (cache.size >= 256) cache.delete(cache.keys().next().value!);
+    cache.set(key, now + 5 * 60_000);
+    return true;
+  }
+
+  private enqueueAccount(operation: () => Promise<boolean>): Promise<boolean> {
+    const result = this.accountQueue.then(operation);
+    this.accountQueue = result.then(() => undefined, () => undefined);
+    return result;
+  }
+
+  private async failBinding(): Promise<void> {
+    this.bindingValue.set('error');
+    this.reasonValue.set('alias-operation-failed');
+    this.phaseValue.set('error');
+    this.registrationValue.set(null);
+    await this.plugin.stop().catch(() => undefined);
+  }
+
+  private async removeListeners(): Promise<void> {
+    const handles = this.handles.splice(0);
+    await Promise.all(handles.map((handle) => handle.remove().catch(() => undefined)));
+  }
+}

+ 37 - 0
src/app/core/native-share.ts

@@ -0,0 +1,37 @@
+import { InjectionToken } from '@angular/core';
+import { Capacitor, PluginListenerHandle, registerPlugin } from '@capacitor/core';
+
+export interface IncomingSharedFile {
+  path: string;
+  name: string;
+  mimeType: string;
+  size: number;
+}
+
+export interface IncomingShare {
+  id: string;
+  text?: string;
+  title?: string;
+  files: IncomingSharedFile[];
+  errors?: string[];
+}
+
+export interface NativeSharePlugin {
+  getPendingShares(): Promise<{ shares: IncomingShare[] }>;
+  acknowledgeShare(options: { id: string }): Promise<void>;
+  prepareOutgoing(options: { url: string; name?: string }): Promise<{ path: string }>;
+  addListener(
+    event: 'shareReceived',
+    listener: (event: { share: IncomingShare }) => void,
+  ): Promise<PluginListenerHandle>;
+}
+
+export const NATIVE_SHARE = new InjectionToken<NativeSharePlugin>('NativeShare', {
+  providedIn: 'root',
+  factory: () => registerPlugin<NativeSharePlugin>('NativeShare'),
+});
+
+export const NATIVE_SHARING_AVAILABLE = new InjectionToken<boolean>('NativeSharingAvailable', {
+  providedIn: 'root',
+  factory: () => Capacitor.getPlatform() === 'android',
+});

+ 229 - 0
src/app/core/share-receive.service.spec.ts

@@ -0,0 +1,229 @@
+import { signal } from '@angular/core';
+import { TestBed } from '@angular/core/testing';
+import { Router } from '@angular/router';
+import { ChatService } from './chat.service';
+import { ChatSession } from './chat-session';
+import { IncomingShare, NATIVE_SHARE, NATIVE_SHARING_AVAILABLE } from './native-share';
+import { SessionService } from './session.service';
+import { ShareReceiveService } from './share-receive.service';
+import { CLOUD_LIMIT_BYTES } from './upload-limits';
+
+describe('ShareReceiveService', () => {
+  let service: ShareReceiveService;
+  let auth: SessionService;
+  let native: jasmine.SpyObj<{
+    getPendingShares(): Promise<{ shares: IncomingShare[] }>;
+    acknowledgeShare(options: { id: string }): Promise<void>;
+    addListener(event: string, listener: (event: { share: IncomingShare }) => void): Promise<{ remove(): Promise<void> }>;
+  }>;
+  let receive: (event: { share: IncomingShare }) => void;
+  let router: { navigate: jasmine.Spy; isActive: jasmine.Spy; createUrlTree: jasmine.Spy; url: string };
+  const session: ChatSession = {
+    id: 'session-a', agentId: 'agent-a', roomId: '!room-a', title: '测试会话', createdAt: 1, updatedAt: 1,
+  };
+  const incoming: IncomingShare = {
+    id: 'share-a', text: '来自外部的文字',
+    files: [{ path: 'file:///cache/shared-incoming/a/report.txt', name: 'report.txt', mimeType: 'text/plain', size: 5 }],
+  };
+
+  function chat() {
+    return {
+      state: signal('ready'), agentId: signal('agent-a'), sessionId: signal('session-a'),
+      draft: signal('原草稿'), stageFiles: jasmine.createSpy('stageFiles'),
+      setDraft: jasmine.createSpy('setDraft'), sendText: jasmine.createSpy('sendText'),
+    };
+  }
+
+  beforeEach(async () => {
+    localStorage.removeItem('fmode_session_token');
+    localStorage.removeItem('fmode_me');
+    localStorage.removeItem('fmode_session_expires_at');
+    native = jasmine.createSpyObj('NativeShare', ['getPendingShares', 'acknowledgeShare', 'addListener']);
+    native.getPendingShares.and.resolveTo({ shares: [incoming] });
+    native.acknowledgeShare.and.resolveTo();
+    native.addListener.and.callFake(async (_event, listener) => {
+      receive = listener;
+      return { remove: async () => undefined };
+    });
+    router = {
+      navigate: jasmine.createSpy('navigate').and.resolveTo(true),
+      isActive: jasmine.createSpy('isActive').and.returnValue(false),
+      createUrlTree: jasmine.createSpy('createUrlTree').and.returnValue({}),
+      url: '/mobile/messages',
+    };
+    TestBed.configureTestingModule({ providers: [
+      { provide: NATIVE_SHARE, useValue: native },
+      { provide: NATIVE_SHARING_AVAILABLE, useValue: true },
+      { provide: Router, useValue: router },
+    ] });
+    auth = TestBed.inject(SessionService);
+    auth.setSession('test-session', { id: 'user-a', name: '测试用户', roles: [] });
+    service = TestBed.inject(ShareReceiveService);
+    await service.start();
+  });
+
+  afterEach(() => auth.logout());
+
+  it('冷启动读取待处理分享,热启动重复事件不重复入队', async () => {
+    receive({ share: incoming });
+    await service.start();
+    expect(service.pending().length).toBe(1);
+    expect(native.addListener).toHaveBeenCalledTimes(1);
+    expect(service.visible()).toBeTrue();
+  });
+
+  it('热启动新分享按顺序排队', () => {
+    receive({ share: { ...incoming, id: 'share-b' } });
+    expect(service.pending().map((share) => share.id)).toEqual(['share-a', 'share-b']);
+  });
+
+  it('稍后处理不会删除文件,重新打开可继续', () => {
+    service.defer();
+    expect(service.visible()).toBeFalse();
+    expect(native.acknowledgeShare).not.toHaveBeenCalled();
+    service.resume();
+    expect(service.visible()).toBeTrue();
+  });
+
+  it('选择会话只导航,不自动发消息', async () => {
+    await service.select(session);
+    expect(router.navigate).toHaveBeenCalledWith(['/mobile/chat', 'agent-a', 'session-a']);
+    expect(service.transfer()?.sessionId).toBe('session-a');
+    expect(native.acknowledgeShare).not.toHaveBeenCalled();
+  });
+
+  it('未登录不允许选择接收会话', async () => {
+    auth.logout();
+    await service.select(session);
+    expect(router.navigate).not.toHaveBeenCalled();
+    expect(service.pending().length).toBe(1);
+  });
+
+  it('不允许分享到归档会话或已关闭的群聊', async () => {
+    await service.select({ ...session, archived: true });
+    await service.select({ ...session, kind: 'group' });
+    expect(router.navigate).not.toHaveBeenCalled();
+    expect(service.error()).toContain('单聊');
+  });
+
+  it('导航失败保留分享并允许重试', async () => {
+    router.navigate.and.resolveTo(false);
+    await service.select(session);
+    expect(service.transfer()).toBeNull();
+    expect(service.error()).toContain('无法打开');
+    expect(service.pending().length).toBe(1);
+  });
+
+  it('添加文件并合并草稿后确认消费,但不发送', async () => {
+    spyOn(window, 'fetch').and.resolveTo(new Response(new Blob(['hello'])));
+    const target = chat();
+    await service.select(session);
+    await service.stageInto(target as unknown as ChatService);
+    const files = target.stageFiles.calls.mostRecent().args[0] as File[];
+    expect(files.length).toBe(1);
+    expect(files[0].name).toBe('report.txt');
+    expect(await files[0].text()).toBe('hello');
+    expect(target.setDraft).toHaveBeenCalledWith('原草稿\n来自外部的文字');
+    expect(target.sendText).not.toHaveBeenCalled();
+    expect(native.acknowledgeShare).toHaveBeenCalledWith({ id: 'share-a' });
+    expect(service.pending()).toEqual([]);
+  });
+
+  it('纯文本分享同样进入草稿,不生成空附件', async () => {
+    await service.discard();
+    receive({ share: { id: 'text-share', text: 'hello', files: [] } });
+    const target = chat();
+    await service.select(session);
+    await service.stageInto(target as unknown as ChatService);
+    expect(target.stageFiles).toHaveBeenCalledWith([]);
+    expect(target.setDraft).toHaveBeenCalledWith('原草稿\nhello');
+  });
+
+  it('文件读取失败不丢弃分享、不篡改草稿', async () => {
+    spyOn(window, 'fetch').and.resolveTo(new Response('', { status: 404 }));
+    const target = chat();
+    await service.select(session);
+    await service.stageInto(target as unknown as ChatService);
+    expect(target.stageFiles).not.toHaveBeenCalled();
+    expect(target.setDraft).not.toHaveBeenCalled();
+    expect(native.acknowledgeShare).not.toHaveBeenCalled();
+    expect(service.error()).toContain('无法读取');
+  });
+
+  it('不向错误会话添加附件', async () => {
+    const target = chat();
+    target.sessionId.set('session-b');
+    await service.select(session);
+    await service.stageInto(target as unknown as ChatService);
+    expect(target.stageFiles).not.toHaveBeenCalled();
+    expect(service.pending().length).toBe(1);
+  });
+
+  it('读取期间切换会话会中止导入,保持可重试', async () => {
+    const target = chat();
+    spyOn(window, 'fetch').and.callFake(async () => {
+      target.sessionId.set('session-b');
+      return new Response(new Blob(['hello']));
+    });
+    await service.select(session);
+    await service.stageInto(target as unknown as ChatService);
+    expect(target.stageFiles).not.toHaveBeenCalled();
+    expect(native.acknowledgeShare).not.toHaveBeenCalled();
+    expect(service.error()).toContain('切换');
+  });
+
+  it('读取期间取消导入不会添加文件或删除原生队列', async () => {
+    const target = chat();
+    spyOn(window, 'fetch').and.callFake(async () => {
+      service.cancelTransfer();
+      return new Response(new Blob(['hello']));
+    });
+    await service.select(session);
+    await service.stageInto(target as unknown as ChatService);
+    expect(target.stageFiles).not.toHaveBeenCalled();
+    expect(native.acknowledgeShare).not.toHaveBeenCalled();
+  });
+
+  it('超限文件在读入内存前拦截', async () => {
+    await service.discard();
+    receive({ share: { ...incoming, files: [{ ...incoming.files[0], size: CLOUD_LIMIT_BYTES + 1 }] } });
+    const fetcher = spyOn(window, 'fetch');
+    await service.select(session);
+    await service.stageInto(chat() as unknown as ChatService);
+    expect(fetcher).not.toHaveBeenCalled();
+    expect(service.error()).toContain('800MB');
+    expect(service.pending().length).toBe(1);
+  });
+
+  it('原生确认失败重试不重复添加附件且不能改投另一会话', async () => {
+    spyOn(window, 'fetch').and.resolveTo(new Response(new Blob(['hello'])));
+    native.acknowledgeShare.and.rejectWith(new Error('disk error'));
+    const target = chat();
+    await service.select(session);
+    await service.stageInto(target as unknown as ChatService);
+    expect(target.stageFiles).toHaveBeenCalledTimes(1);
+    await service.select({ ...session, id: 'session-b' });
+    expect(service.transfer()).toBeNull();
+    native.acknowledgeShare.and.resolveTo();
+    await service.select(session);
+    await service.stageInto(target as unknown as ChatService);
+    expect(target.stageFiles).toHaveBeenCalledTimes(1);
+    expect(service.pending()).toEqual([]);
+  });
+
+  it('取消失败保留待处理项', async () => {
+    native.acknowledgeShare.and.rejectWith(new Error('disk error'));
+    await service.discard();
+    expect(service.pending().length).toBe(1);
+    expect(service.error()).toContain('取消');
+  });
+
+  it('账号切换清除待投递目标,不能自动跨账号导入', async () => {
+    await service.select(session);
+    TestBed.flushEffects();
+    auth.logout();
+    TestBed.flushEffects();
+    expect(service.transfer()).toBeNull();
+    expect(service.pending().length).toBe(1);
+  });
+});

+ 178 - 0
src/app/core/share-receive.service.ts

@@ -0,0 +1,178 @@
+import { computed, effect, inject, Injectable, signal } from '@angular/core';
+import { Capacitor } from '@capacitor/core';
+import { Router } from '@angular/router';
+import { ChatService } from './chat.service';
+import { ChatSession } from './chat-session';
+import { SessionService } from './session.service';
+import { IncomingShare, NATIVE_SHARE, NATIVE_SHARING_AVAILABLE } from './native-share';
+import { CLOUD_LIMIT_BYTES } from './upload-limits';
+
+export interface ShareTransfer {
+  shareId: string;
+  agentId: string;
+  sessionId: string;
+  userId: string;
+}
+
+@Injectable({ providedIn: 'root' })
+export class ShareReceiveService {
+  private readonly native = inject(NATIVE_SHARE);
+  private readonly available = inject(NATIVE_SHARING_AVAILABLE);
+  private readonly auth = inject(SessionService);
+  private readonly router = inject(Router);
+  private readonly queue = signal<IncomingShare[]>([]);
+  private readonly selection = signal<ShareTransfer | null>(null);
+  private readonly deferred = signal(false);
+  private started = false;
+  private attaching = false;
+  private readonly staged = new Map<string, ShareTransfer>();
+
+  readonly pending = this.queue.asReadonly();
+  readonly current = computed(() => this.queue()[0] ?? null);
+  readonly transfer = this.selection.asReadonly();
+  readonly busy = signal(false);
+  readonly error = signal('');
+  readonly visible = computed(() => !!this.current() && !this.selection() && !this.deferred());
+
+  constructor() {
+    effect(() => {
+      const transfer = this.selection();
+      if (transfer && this.auth.me()?.id !== transfer.userId) {
+        this.selection.set(null);
+        this.error.set('登录账号已变化,请重新选择会话');
+      }
+    });
+  }
+
+  async start(): Promise<void> {
+    if (!this.available || this.started) return;
+    this.started = true;
+    try {
+      await this.native.addListener('shareReceived', ({ share }) => this.enqueue(share));
+      await this.refresh();
+    } catch {
+      this.started = false;
+      this.error.set('无法读取外部分享,请重新打开 App 后重试');
+    }
+  }
+
+  async refresh(): Promise<void> {
+    const { shares } = await this.native.getPendingShares();
+    for (const share of shares) this.enqueue(share);
+  }
+
+  private enqueue(share: IncomingShare): void {
+    if (!share?.id || this.queue().some((item) => item.id === share.id)) return;
+    this.queue.update((items) => [...items, share]);
+    this.deferred.set(false);
+  }
+
+  defer(): void {
+    if (!this.busy()) this.deferred.set(true);
+  }
+
+  resume(): void {
+    this.deferred.set(false);
+  }
+
+  cancelTransfer(reason = ''): void {
+    this.selection.set(null);
+    this.error.set(reason);
+  }
+
+  async discard(): Promise<void> {
+    const share = this.current();
+    if (!share || this.busy()) return;
+    this.busy.set(true);
+    try {
+      await this.native.acknowledgeShare({ id: share.id });
+      this.remove(share.id);
+    } catch {
+      this.error.set('取消分享失败,请重试');
+    } finally {
+      this.busy.set(false);
+    }
+  }
+
+  async select(session: ChatSession): Promise<void> {
+    const share = this.current();
+    const userId = this.auth.me()?.id;
+    if (!share || !userId || !this.auth.isLoggedIn() || this.busy()) return;
+    if (session.archived || session.kind === 'group') {
+      this.error.set('请选择可用的单聊会话');
+      return;
+    }
+    const staged = this.staged.get(share.id);
+    if (staged && (staged.sessionId !== session.id || staged.userId !== userId)) {
+      this.error.set('附件已添加到原会话,请返回原会话完成导入');
+      return;
+    }
+    if (!share.files.length && !share.text?.trim()) {
+      this.error.set(share.errors?.join(';') || '没有可导入的文件或文字,请取消后重新分享');
+      return;
+    }
+    this.error.set('');
+    this.selection.set({ shareId: share.id, agentId: session.agentId, sessionId: session.id, userId });
+    try {
+      const navigated = await this.router.navigate(['/mobile/chat', session.agentId, session.id]);
+      if (!navigated && !this.router.isActive(
+        this.router.createUrlTree(['/mobile/chat', session.agentId, session.id]),
+        { paths: 'exact', queryParams: 'ignored', matrixParams: 'ignored', fragment: 'ignored' },
+      )) {
+        this.selection.set(null);
+        this.error.set('无法打开目标会话,请重试');
+      }
+    } catch {
+      this.selection.set(null);
+      this.error.set('无法打开目标会话,请重试');
+    }
+  }
+
+  async stageInto(chat: ChatService): Promise<void> {
+    const transfer = this.selection();
+    if (!transfer || this.attaching || !['ready', 'empty'].includes(chat.state())) return;
+    if (chat.agentId() !== transfer.agentId || chat.sessionId() !== transfer.sessionId) return;
+    const share = this.queue().find((item) => item.id === transfer.shareId);
+    if (!share) return;
+    this.attaching = true;
+    this.busy.set(true);
+    try {
+      if (!this.staged.has(share.id)) {
+        const files: File[] = [];
+        for (const file of share.files) {
+          if (file.size > CLOUD_LIMIT_BYTES) throw new Error(`${file.name} 超过 800MB,无法导入`);
+          const response = await fetch(Capacitor.convertFileSrc(file.path));
+          if (!response.ok) throw new Error(`无法读取 ${file.name},请重新分享`);
+          const blob = await response.blob();
+          if (blob.size > CLOUD_LIMIT_BYTES) throw new Error(`${file.name} 超过 800MB,无法导入`);
+          files.push(new File([blob], file.name, { type: file.mimeType || blob.type }));
+        }
+        if (
+          this.auth.me()?.id !== transfer.userId || !this.auth.isLoggedIn() ||
+          this.selection()?.shareId !== transfer.shareId ||
+          chat.agentId() !== transfer.agentId || chat.sessionId() !== transfer.sessionId
+        ) throw new Error('会话或账号已切换,请重新选择接收会话');
+        chat.stageFiles(files);
+        if (share.text?.trim()) {
+          chat.setDraft([chat.draft(), share.text.trim()].filter(Boolean).join('\n'));
+        }
+        this.staged.set(share.id, transfer);
+      }
+      await this.native.acknowledgeShare({ id: share.id });
+      this.staged.delete(share.id);
+      this.remove(share.id);
+    } catch (error) {
+      this.selection.set(null);
+      this.error.set(error instanceof Error ? error.message : '文件导入失败,请重新选择会话');
+    } finally {
+      this.attaching = false;
+      this.busy.set(false);
+    }
+  }
+
+  private remove(id: string): void {
+    this.queue.update((items) => items.filter((item) => item.id !== id));
+    this.selection.set(null);
+    this.error.set('');
+  }
+}

+ 124 - 0
src/app/mobile/components/m-share-receive/m-share-receive.ts

@@ -0,0 +1,124 @@
+import { ChangeDetectionStrategy, Component, computed, DestroyRef, inject, signal } from '@angular/core';
+import { Router } from '@angular/router';
+import { ShareReceiveService } from '../../../core/share-receive.service';
+import { SessionService } from '../../../core/session.service';
+import { LiveService } from '../../../core/live.service';
+import { ChatSessionService } from '../../../core/chat-session.service';
+import { BackButtonService } from '../../../core/back-button.service';
+import { formatBytes } from '../../../core/upload-limits';
+
+@Component({
+  selector: 'app-m-share-receive',
+  changeDetection: ChangeDetectionStrategy.OnPush,
+  template: `
+    <div class="share-mask" role="presentation">
+      <section class="share-panel" role="dialog" aria-modal="true" aria-labelledby="share-title">
+        <header><h2 id="share-title">选择接收会话</h2>
+          <button type="button" aria-label="稍后处理分享" (click)="shares.defer()" [disabled]="shares.busy()">稍后</button>
+        </header>
+        <p class="share-hint">文件将添加到会话输入区,确认后再发送。</p>
+        @if (shares.current(); as share) {
+          <div class="share-files">
+            @for (file of share.files; track file.path) {
+              <p><i class="fa-solid fa-file" aria-hidden="true"></i> {{ file.name }} <small>{{ size(file.size) }}</small></p>
+            }
+            @if (share.text) { <p class="share-text">{{ share.text }}</p> }
+            @for (error of share.errors ?? []; track $index) { <p class="share-error" role="alert">{{ error }}</p> }
+          </div>
+        }
+        @if (shares.error()) { <p class="share-error" role="alert">{{ shares.error() }}</p> }
+        @if (!auth.isLoggedIn()) {
+          <p>请先登录,分享内容会保留。</p>
+          <button type="button" class="share-primary" (click)="login()">前往登录</button>
+        } @else if (loading()) {
+          <p role="status">正在加载会话…</p>
+        } @else if (loadError()) {
+          <p class="share-error" role="alert">{{ loadError() }}</p>
+          <button type="button" (click)="reload()">重新加载会话</button>
+        } @else {
+          <input type="search" placeholder="搜索会话或数字生命" aria-label="搜索接收会话" [value]="keyword()" (input)="keyword.set($any($event.target).value)" />
+          <div class="share-sessions">
+            @for (session of choices(); track session.id) {
+              <button type="button" class="share-session" [disabled]="shares.busy()" (click)="shares.select(session)">
+                <strong>{{ session.title || '未命名会话' }}</strong><small>{{ agentName(session.agentId) }}</small>
+              </button>
+            } @empty { <p>没有可接收的会话,请先在 App 中创建会话后再分享。</p> }
+          </div>
+        }
+        <footer><button type="button" (click)="shares.discard()" [disabled]="shares.busy()">取消本次分享</button></footer>
+      </section>
+    </div>
+  `,
+  styles: [`
+    :host { display: contents; }
+    .share-mask { position: fixed; inset: 0; z-index: var(--z-preview); background: var(--overlay); display: flex; align-items: flex-end; padding-top: calc(var(--mob-safe-top, 24px) + 16px); }
+    .share-panel { width: 100%; max-height: 90dvh; display: flex; flex-direction: column; background: var(--surface); color: var(--ink); border-radius: var(--r-lg) var(--r-lg) 0 0; padding: var(--sp-4); padding-bottom: calc(var(--sp-4) + env(safe-area-inset-bottom, 0px)); gap: var(--sp-3); }
+    header, footer { display: flex; align-items: center; justify-content: space-between; flex-shrink: 0; }
+    h2, p { margin: 0; }
+    h2 { font-size: 18px; }
+    button, input { font: inherit; min-height: 44px; border: 1px solid var(--edge); border-radius: var(--r-md); background: var(--surface); color: inherit; padding: var(--sp-2) var(--sp-3); }
+    button:disabled { opacity: .5; }
+    button:focus-visible, input:focus-visible { outline: 2px solid var(--primary); }
+    .share-hint, small { color: var(--muted); font-size: var(--fs-13); }
+    .share-files { max-height: 20dvh; overflow: auto; overflow-wrap: anywhere; flex-shrink: 0; }
+    .share-files p + p { margin-top: var(--sp-2); }
+    .share-text { white-space: pre-wrap; }
+    .share-error { color: var(--danger); overflow-wrap: anywhere; }
+    .share-sessions { overflow-y: auto; min-height: 0; }
+    .share-session { width: 100%; display: flex; flex-direction: column; align-items: flex-start; text-align: left; gap: var(--sp-1); margin-bottom: var(--sp-2); overflow-wrap: anywhere; }
+    .share-primary { color: var(--primary); }
+    footer { justify-content: center; }
+  `],
+})
+export class MShareReceiveComponent {
+  protected readonly shares = inject(ShareReceiveService);
+  protected readonly auth = inject(SessionService);
+  private readonly live = inject(LiveService);
+  private readonly sessions = inject(ChatSessionService);
+  private readonly router = inject(Router);
+  private readonly back = inject(BackButtonService);
+  protected readonly keyword = signal('');
+  protected readonly loading = signal(false);
+  protected readonly loadError = signal('');
+  protected readonly size = formatBytes;
+  protected readonly choices = computed(() => {
+    const keyword = this.keyword().trim().toLowerCase();
+    return this.sessions.all()
+      .filter((session) => !session.archived && session.kind !== 'group' && !!this.live.agentById(session.agentId))
+      .filter((session) => !keyword || `${session.title} ${this.agentName(session.agentId)}`.toLowerCase().includes(keyword))
+      .sort((left, right) => right.updatedAt - left.updatedAt);
+  });
+
+  constructor() {
+    this.back.register('incoming-share', () => {
+      if (this.shares.visible()) { this.shares.defer(); return true; }
+      return false;
+    });
+    inject(DestroyRef).onDestroy(() => this.back.unregister('incoming-share'));
+    if (this.auth.isLoggedIn()) void this.reload();
+  }
+
+  protected agentName(agentId: string): string {
+    return this.live.agentById(agentId)?.name ?? '数字生命';
+  }
+
+  protected login(): void {
+    this.shares.defer();
+    void this.router.navigate(['/login']);
+  }
+
+  protected async reload(): Promise<void> {
+    this.loading.set(true);
+    this.loadError.set('');
+    try {
+      await this.live.ensureLoaded();
+      if (this.live.state() === 'error') throw new Error(this.live.error() || '加载失败');
+      await this.sessions.reloadAll(this.live.agents().map((agent) => agent.id));
+      if (!this.sessions.ready()) throw new Error(this.sessions.error() || '会话目录加载失败');
+    } catch (error) {
+      this.loadError.set(error instanceof Error ? error.message : '会话目录加载失败');
+    } finally {
+      this.loading.set(false);
+    }
+  }
+}

+ 12 - 3
src/app/mobile/pages/chat/chat.ts

@@ -41,7 +41,6 @@ import {
 import { Message } from '../../../core/api/models';
 import { sessionPresence } from '../../../core/agent-liveness';
 import { TaskPulseService } from '../../../core/task-pulse.service';
-import { UiMToastService } from '../../../ui/mobile/components/toast/toast';
 import { AppNotificationService } from '../../../core/app-notification.service';
 import { BackButtonService } from '../../../core/back-button.service';
 import { fileIdentity } from '../../../core/s3-link';
@@ -1064,7 +1063,6 @@ export class MbChatPage implements OnDestroy {
    * alert.service 注释里划给它的那一类(不该用常驻的告警条,那会一直杵在屏上)。
    * 容器已由 `app.ts` 全局挂载 `UiMToast`,直接注入即可。
    */
-  private readonly toast = inject(UiMToastService);
   /** 系统通知(2026-11-15):App 在后台时也能在通知栏留痕 */
   private readonly notify = inject(AppNotificationService);
   /** Android 返回键接管(2026-11-15):弹层开着时返回键只关弹层 */
@@ -1489,7 +1487,18 @@ export class MbChatPage implements OnDestroy {
       seenPulseAt = latest.at;
       const spent = latest.durationMs ? `,用时 ${MbChatPage.durText(latest.durationMs)}` : '';
       const text = `${latest.task ? latest.task + ' 已完成' : '任务已完成'}${spent}`;
-      this.toast.success(text);
+      /*
+       * 🔴 前台 toast 已移除(2026-11-18 用户明确要求「不要任何前台提示」)。
+       *
+       * 原实现会弹一条「xxx 已完成,用时 N 秒」的 toast。
+       *
+       * 两个问题:
+       *   ① 用户明确不要前台提示 —— 任务完成看消息本身即可,弹层纯属打断
+       *   ② `durText()` 在不足 1 秒时显示「0 秒」,看起来像 bug
+       *
+       * **系统通知保留**:它只在 App 不在前台时才看得见,属于「离开时的提醒」,
+       * 不是前台打断。浏览器里 `notify()` 内部直接返回,不影响 Web 端。
+       */
       /*
        * 同时发一条系统通知(2026-11-15)。
        *

+ 21 - 3
src/app/mobile/pages/login/login.ts

@@ -15,6 +15,7 @@ import { DeviceService } from '../../../core/device.service';
 import { PaletteService } from '../../../core/palette.service';
 import { SessionService } from '../../../core/session.service';
 import { queryHasOrg } from '../../../core/org.guard';
+import { UiMToastService } from '../../../ui/mobile/components/toast/toast';
 
 type Stage = 'phone' | 'code' | 'token' | 'password';
 
@@ -330,6 +331,14 @@ export class MbLoginPage implements OnDestroy {
   private readonly palette = inject(PaletteService);
   private readonly router = inject(Router);
   private readonly route = inject(ActivatedRoute);
+  /**
+   * 全局提示(2026-11-18 用户要求「需要给出全局提示词,让用户知道为什么点击没有效果」)。
+   *
+   * 行内 `error()` 只贴在按钮下方,倒计时冷却时用户可能根本没注意到;
+   * toast 浮在屏幕中央/上方,一次性闪现,明确告知「为什么点了没反应」。
+   * 两处同时保留:行内是持久提示,toast 是即时反馈。
+   */
+  private readonly toast = inject(UiMToastService);
 
   protected readonly stage = signal<Stage>('phone');
   protected readonly phone = signal('');
@@ -425,14 +434,23 @@ export class MbLoginPage implements OnDestroy {
   /** 发送验证码:真实接口 + 60s 倒计时(Demo 无倒计时,此处按规范补齐防刷) */
   protected async sendCode(): Promise<void> {
     /*
-     * 🔴 倒计时未结束时给出**明确提示**,不再静默返回(2026-11-18 用户实测)。
+     * 🔴 倒计时未结束时给出**全局提示**,不再静默返回(2026-11-18 用户实测)。
+     *
+     * ## 第一版的问题
      *
      * 原来这里直接 `return` —— 用户点了按钮什么都没发生,
      * 分不清「是没点中」「是坏了」还是「在等冷却」。
-     * 现在告诉他还剩几秒。
+     *
+     * 第一版修复写成 `this.error.set(...)` → 行内红字,**一直挂在那里不走**,
+     * 用户反馈「提示需要自动消失而不是一直显示状态」。
+     *
+     * ## 现在
+     *
+     * 改用 toast:浮层提示,2 秒后自动消失,不占用页面空间、不留下持久红字。
+     * 同时按钮本身会显示 `55s` 倒计时,用户随时能看到还剩多久。
      */
     if (this.countdown() > 0) {
-      this.error.set(`请等待 ${this.countdown()} 秒后再试`);
+      this.toast.warning(`请等待 ${this.countdown()} 秒后再试`);
       return;
     }
     if (this.sending() || this.busy()) return;