An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Defer boot sync until the UI is ready https://github.com/siyuan-note/siyuan/issues/20819
Daniel10934f1735c2
diff --git a/app/src/index.ts b/app/src/index.tsindex 0b0cd55b4c..8da2584141 100644--- a/app/src/index.ts+++ b/app/src/index.ts@@ -352,7 +352,6 @@ export class App {Constants.SIYUAN_VERSION,);window.siyuan.menus = new Menus(this);- bootSync();fetchPost("/api/setting/getCloudUser", {cached: true}, async userResponse => {window.siyuan.user = userResponse.data && "userId" in userResponse.data ? userResponse.data : null;await ensureOnboarding();@@ -370,6 +369,7 @@ export class App {/// #endifwindow.siyuan.isReady = true;mainWs.flushMainMessages();+ bootSync();exitAfterSettingsReset();fetchPost("/api/setting/getCloudUser", {});});diff --git a/app/src/layout/Model.ts b/app/src/layout/Model.tsindex 4e5fc00ca0..d92a476b1b 100644--- a/app/src/layout/Model.ts+++ b/app/src/layout/Model.ts@@ -60,6 +60,7 @@ export class Model {}});if (!this.socketDisposed && window.siyuan.isReady) {+ this.send("ready", {});const {refreshSettingConfig}: typeof import("../config/setting/sync") = require("../config/setting/sync");void refreshSettingConfig();const {reconcileSyncCheckout}: typeof import("../sync/checkoutProgress") = require("../sync/checkoutProgress");@@ -71,7 +72,7 @@ export class Model {if (this.socketDisposed) return;clearTimeout(this.reconnectTimer);const websocketURL = `${window.location.protocol === "https:" ? "wss" : "ws"}://${window.location.host}/ws`;- const ws = new WebSocket(`${websocketURL}?app=${Constants.SIYUAN_APPID}&id=${options.id}${options.type ? "&type=" + options.type : ""}`);+ const ws = new WebSocket(`${websocketURL}?app=${Constants.SIYUAN_APPID}&id=${options.id}${options.type === "main" ? "&ready=false" : ""}${options.type ? "&type=" + options.type : ""}`);ws.onopen = () => {if (this.socketDisposed || this.ws !== ws) return;if (options.type === "main") {@@ -79,6 +80,7 @@ export class Model {markKernelConnectionAlive();}if (options.type === "main" && window.siyuan.isReady) {+ this.send("ready", {});const {reconcileSyncCheckout}: typeof import("../sync/checkoutProgress") = require("../sync/checkoutProgress");void reconcileSyncCheckout(options.id, true);const {reloadSettingsResetOnReconnect}: typeof import("../config/setting/reset") = require("../config/setting/reset");@@ -149,6 +151,7 @@ export class Model {public send(cmd: string, param: Record<string, unknown>, process = false) {if (this.socketDisposed || !this.ws ||+ this.ws.readyState === WebSocket.CONNECTING ||this.ws.readyState === WebSocket.CLOSING ||this.ws.readyState === WebSocket.CLOSED) { // Inbox 无 WebSocket,关闭中的连接不能继续发送return;diff --git a/app/src/layout/ModelLifecycle.test.ts b/app/src/layout/ModelLifecycle.test.tsindex f124fd5a0e..b75f164a9a 100644--- a/app/src/layout/ModelLifecycle.test.ts+++ b/app/src/layout/ModelLifecycle.test.ts@@ -103,7 +103,9 @@ test("main socket recovery is recorded and obsolete sockets cannot finish a faultest("main windows query their own checkout preparation on startup and reconnect", () => {const sockets: Socket[] = [];const queries: {id: string, reconnect?: boolean}[] = [];+ const messages: string[] = [];class Socket {+ static CONNECTING = 0;onopen: () => void;onclose: unknown;onmessage: unknown;@@ -111,6 +113,7 @@ test("main windows query their own checkout preparation on startup and reconnectreadyState = 1;constructor(public url: string) { sockets.push(this); }close() {}+ send(message: string) { messages.push(message); }}const api = {} as {Model: new (options: unknown) => {connect: (options: unknown) => void, flushMainMessages: () => void, destroy: () => void,@@ -134,9 +137,22 @@ test("main windows query their own checkout preparation on startup and reconnect});const model = new api.Model({app: {}});model.connect({id: "detached-window", type: "main"});+ assert.equal(new URL(sockets[0].url).searchParams.get("ready"), "false");+ sockets[0].onopen();+ assert.equal(messages.length, 0, "a connected window must not report readiness during initialization");window.siyuan.isReady = true;+ sockets[0].readyState = Socket.CONNECTING;+ model.flushMainMessages();+ assert.equal(messages.length, 0, "readiness must wait for the socket to open");+ sockets[0].readyState = 1;model.flushMainMessages();sockets[0].onopen();- assert.deepEqual(queries, [{id: "detached-window", reconnect: undefined}, {id: "detached-window", reconnect: true}]);+ assert.deepEqual(messages.map(message => JSON.parse(message).cmd), ["ready", "ready"]);+ assert.deepEqual(queries, [{id: "detached-window", reconnect: undefined},+ {id: "detached-window", reconnect: undefined}, {id: "detached-window", reconnect: true}]);+ model.connect({id: "detached-window", type: "main"});+ assert.equal(new URL(sockets[1].url).searchParams.get("ready"), "false");+ sockets[1].onopen();+ assert.equal(JSON.parse(messages.at(-1)).cmd, "ready");model.destroy();});diff --git a/app/src/mobile/index.ts b/app/src/mobile/index.tsindex 9f4ab5a1ff..8903bf3b30 100644--- a/app/src/mobile/index.ts+++ b/app/src/mobile/index.ts@@ -241,7 +241,6 @@ class App {window.siyuan.menus = new Menus(this);initMobileSelect();document.title = window.siyuan.languages.siyuanNote;- bootSync();void Promise.resolve(appearanceConfigApi.apply(window.siyuan.config.appearance)).catch(reportStartupError);initMessage();initAssets(true);@@ -270,6 +269,7 @@ class App {window.siyuan.isReady = true;finishMobileSystemUris(this);mainWs.flushMainMessages();+ bootSync();completeStartup();fetchPost("/api/setting/getCloudUser", {});}), undefined, startupRequestFailed);diff --git a/kernel/cmd/cmd.go b/kernel/cmd/cmd.goindex 5d974486dc..940bc2aa5e 100644--- a/kernel/cmd/cmd.go+++ b/kernel/cmd/cmd.go@@ -56,6 +56,8 @@ func NewCommand(cmdStr string, cmdId float64, param map[string]any, session *melret = &closews{baseCmd}case "ping":ret = &ping{baseCmd}+ case "ready":+ ret = &ready{baseCmd}}if nil == ret {diff --git a/kernel/cmd/ready.go b/kernel/cmd/ready.gonew file mode 100644index 0000000000..991cb9606f--- /dev/null+++ b/kernel/cmd/ready.go@@ -0,0 +1,16 @@+package cmd++// ready 只更新当前连接,刷新和重连后的窗口必须重新报告界面就绪。+type ready struct {+ *BaseCmd+}++func (cmd *ready) Exec() {+ if typ, _ := cmd.session.Get("type"); typ == "main" {+ cmd.session.Set("uiReady", true)+ }+}++func (cmd *ready) Name() string { return "ready" }++func (cmd *ready) IsRead() bool { return true }diff --git a/kernel/cmd/ready_test.go b/kernel/cmd/ready_test.gonew file mode 100644index 0000000000..9da529ff38--- /dev/null+++ b/kernel/cmd/ready_test.go@@ -0,0 +1,43 @@+package cmd++import (+ "net/http/httptest"+ "testing"++ "github.com/olahol/melody"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestReadyIsScopedToCurrentMainConnection(t *testing.T) {+ connect := func(query string) *melody.Session {+ session := &melody.Session{Request: httptest.NewRequest("GET", "/ws?app=ready-test&"+query, nil)}+ util.AddPushChan(session)+ t.Cleanup(func() { util.RemovePushChan(session) })+ return session+ }+ first := connect("id=first&type=main&ready=false")+ second := connect("id=second&type=main&ready=false")+ legacy := connect("id=legacy&type=main")+ if util.IsSessionReady(first) || util.IsSessionReady(second) || !util.IsSessionReady(legacy) {+ t.Fatal("new and legacy readiness defaults are incorrect")+ }+ command := NewCommand("ready", 1, map[string]any{}, first)+ if command == nil || !command.IsRead() {+ t.Fatal("readiness must be available to every main window")+ }+ command.Exec()+ command.Exec()+ if !util.IsSessionReady(first) || util.IsSessionReady(second) {+ t.Fatal("readiness was not idempotent or leaked across windows")+ }+ util.RemovePushChan(first)+ reloaded := connect("id=first&type=main&ready=false")+ if util.IsSessionReady(reloaded) {+ t.Fatal("reload reused the previous connection's readiness")+ }+ dock := connect("id=dock&type=filetree")+ NewCommand("ready", 1, map[string]any{}, dock).Exec()+ if _, exists := dock.Get("uiReady"); exists {+ t.Fatal("a non-main connection changed UI readiness")+ }+}diff --git a/kernel/model/boot_sync.go b/kernel/model/boot_sync.gonew file mode 100644index 0000000000..fe340bfe86--- /dev/null+++ b/kernel/model/boot_sync.go@@ -0,0 +1,67 @@+package model++import (+ "context"+ "sync/atomic"+ "time"++ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/util"+)++var bootSyncScheduled atomic.Bool++func syncUIReady(requireMain bool) bool {+ sessions := util.SessionsByType("main")+ if requireMain && len(sessions) == 0 {+ return false+ }+ for _, session := range sessions {+ if !util.IsSessionReady(session) {+ return false+ }+ }+ return true+}++// waitForSyncUI 界面加载不计入编辑保存确认的超时,取消或退出时终止等待。+func waitForSyncUI(ctx context.Context, requireMain, waitBoot bool) error {+ ticker := time.NewTicker(100 * time.Millisecond)+ defer ticker.Stop()+ for {+ if err := ctx.Err(); err != nil {+ return err+ }+ if util.IsExiting.Load() {+ return context.Canceled+ }+ if (!waitBoot || util.IsBooted()) && syncUIReady(requireMain) {+ return nil+ }+ select {+ case <-ctx.Done():+ return ctx.Err()+ case <-ticker.C:+ }+ }+}++// scheduleBootSync 原生界面先从本地数据启动,再执行完整同步;重复启动请求合并为一个任务。+func scheduleBootSync() bool {+ if bootSyncScheduled.Load() {+ return true+ }+ if !(util.AttachUI || util.IsMobileContainer()) || (util.IsBooted() && syncUIReady(true)) {+ return false+ }+ if bootSyncScheduled.CompareAndSwap(false, true) {+ go func() {+ defer logging.Recover()+ defer bootSyncScheduled.Store(false)+ if waitForSyncUI(context.Background(), true, true) == nil {+ bootSyncData()+ }+ }()+ }+ return true+}diff --git a/kernel/model/boot_sync_attribute_view_fts5_test.go b/kernel/model/boot_sync_attribute_view_fts5_test.goindex e2c1fb4273..cbfdcd2c1c 100644--- a/kernel/model/boot_sync_attribute_view_fts5_test.go+++ b/kernel/model/boot_sync_attribute_view_fts5_test.go@@ -52,7 +52,7 @@ func TestBootSyncAttributeViewIndex(t *testing.T) {tree.Root.AppendChild(&ast.Node{Type: ast.NodeAttributeView, ID: "20260909170002-db00001", AttributeViewID: avID})writeAssetDownloadDocumentTest(t, tree)- // 启动同步标志只能在后处理返回后清除;超时解除等待,使回归失败能够正常报告。+ // 预取期间的索引处理不能等待自身的存储标志;超时解除等待,使回归失败能够正常报告。originalBootSyncing := isBootSyncing.Swap(true)var timedOut atomic.BoolwatchdogDone := make(chan struct{})diff --git a/kernel/model/boot_sync_test.go b/kernel/model/boot_sync_test.goindex 32341fcfdb..8795345bdc 100644--- a/kernel/model/boot_sync_test.go+++ b/kernel/model/boot_sync_test.go@@ -1,6 +1,10 @@package modelimport (+ "context"+ "encoding/json"+ "errors"+ "fmt""net/http""net/http/httptest""os"@@ -8,12 +12,194 @@ import ("path/filepath""strings""testing"+ "testing/synctest""time""github.com/gorilla/websocket"+ "github.com/olahol/melody"+ "github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/conf""github.com/siyuan-note/siyuan/kernel/util")+func addBootSyncSession(t *testing.T, id string) *melody.Session {+ t.Helper()+ session := &melody.Session{Request: httptest.NewRequest("GET", "/ws?app=boot-sync-test&id="+id+"&type=main&ready=false", nil)}+ util.AddPushChan(session)+ t.Cleanup(func() { util.RemovePushChan(session) })+ return session+}++func TestBootSyncUIWaitSurvivesSlowStartupAndRefresh(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ first := addBootSyncSession(t, "first")+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ done := make(chan error, 1)+ go func() { done <- waitForSyncUI(ctx, true, false) }()+ time.Sleep(20 * time.Second)+ synctest.Wait()+ select {+ case err := <-done:+ t.Fatalf("slow initialization ended the readiness wait: %v", err)+ default:+ }+ for _, id := range []string{"refresh-1", "refresh-2", "refresh-3"} {+ util.RemovePushChan(first)+ first = addBootSyncSession(t, id)+ time.Sleep(time.Second)+ }+ first.Set("uiReady", true)+ time.Sleep(time.Second)+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ })+}++func TestBootSyncUIWaitHeadlessAndCancellation(t *testing.T) {+ if err := waitForSyncUI(context.Background(), false, false); err != nil {+ t.Fatal(err)+ }+ synctest.Test(t, func(t *testing.T) {+ addBootSyncSession(t, "loading")+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan error, 1)+ go func() { done <- waitForSyncUI(ctx, false, false) }()+ synctest.Wait()+ cancel()+ if err := <-done; !errors.Is(err, context.Canceled) {+ t.Fatalf("cancellation did not interrupt initialization wait: %v", err)+ }+ })+}++func acknowledgeBootSyncClient(t *testing.T, id string) {+ t.Helper()+ connection := connectSyncCheckoutClient(t, id)+ done := make(chan struct{})+ go func() {+ defer close(done)+ for {+ var event struct {+ Cmd string+ Data json.RawMessage+ }+ if connection.ReadJSON(&event) != nil {+ return+ }+ if event.Cmd == "syncProgress" {+ var state apicontract.SyncCheckoutState+ if json.Unmarshal(event.Data, &state) == nil && state.Phase == "preparing" {+ ConfirmSyncCheckout(state.TaskID, state.Token, true)+ }+ }+ }+ }()+ t.Cleanup(func() { connection.Close(); <-done })+}++func TestBootSyncStartupLifecycle(t *testing.T) {+ const childEnv = "SIYUAN_TEST_BOOT_SYNC_STARTUP"+ mode := os.Getenv(childEnv)+ if mode == "" {+ for _, mode := range []string{"desktop", "android", "ios", "harmony", "headless", "disabled", "source-changed", "reopen-failed"} {+ t.Run(mode, func(t *testing.T) {+ cmd := exec.Command(os.Args[0], "-test.run=^TestBootSyncStartupLifecycle$", "-test.timeout=30s")+ cmd.Env = append(os.Environ(), childEnv+"="+mode)+ if output, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("boot sync subprocess failed: %v\n%s", err, output)+ }+ })+ }+ return+ }+ full, _, fullData := prepareAssetDownloadRepoTest(t)+ Conf.NotebookCrypto = conf.NewNotebookCrypto()+ Conf.Sync.Load().Perception = false+ lastAutoPurgeRepo = time.Now()+ getPetals()+ if err := os.MkdirAll(filepath.Join(fullData, "storage"), 0755); err != nil {+ t.Fatal(err)+ }+ for _, name := range []string{"remote.txt", "storage/boot-test.json"} {+ if err := os.WriteFile(filepath.Join(fullData, filepath.FromSlash(name)), []byte(`{"synced":true}`), 0644); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := full.Index("remote startup changes", true, nil); err != nil {+ t.Fatal(err)+ }+ if _, _, err := full.Sync(nil); err != nil {+ t.Fatal(err)+ }+ native := mode == "desktop" || mode == "android" || mode == "ios" || mode == "harmony"+ util.AttachUI = mode == "desktop"+ if native && mode != "desktop" {+ util.Container = mode+ }+ var loading *melody.Session+ if native {+ loading = addBootSyncSession(t, "loading")+ }+ BootSyncData()+ if native {+ BootSyncData()+ if !bootSyncScheduled.Load() || checkSync(false, false, false) {+ t.Fatal("startup was not deferred or automatic sync bypassed readiness")+ }+ }+ if BootSyncSucc.Load() != -1 || isSyncingStorages() {+ t.Fatal("pending startup reported success or blocked storage initialization")+ }+ if _, err := os.Stat(filepath.Join(util.DataDir, "remote.txt")); !os.IsNotExist(err) {+ t.Fatalf("cloud changes applied before local boot: %v", err)+ }+ if mode == "disabled" {+ Conf.Sync.Load().Enabled = false+ } else if mode == "source-changed" {+ Conf.Sync.Load().CloudName = "different"+ } else if mode == "reopen-failed" {+ // 保留同步源身份,只破坏仓库目录,覆盖重开失败后的任务收尾。+ if err := os.RemoveAll(util.RepoDir); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(util.RepoDir, []byte("not a directory"), 0644); err != nil {+ t.Fatal(err)+ }+ }+ util.SetBooted()+ if native {+ for i := range 3 {+ util.RemovePushChan(loading)+ loading = addBootSyncSession(t, fmt.Sprintf("refresh-%d", i))+ time.Sleep(120 * time.Millisecond)+ if BootSyncSucc.Load() != -1 || isSyncingStorages() {+ t.Fatal("loading-page refresh started sync or blocked storage reads")+ }+ }+ acknowledgeBootSyncClient(t, "ready")+ util.RemovePushChan(loading)+ }+ deadline := time.Now().Add(10 * time.Second)+ for (BootSyncSucc.Load() == -1 || bootSyncScheduled.Load()) && time.Now().Before(deadline) {+ time.Sleep(20 * time.Millisecond)+ }+ want := int32(0)+ if mode == "disabled" || mode == "source-changed" || mode == "reopen-failed" {+ want = 1+ }+ if BootSyncSucc.Load() != want || bootSyncScheduled.Load() || isSyncingStorages() {+ t.Fatalf("startup did not finish cleanly: result=%d scheduled=%t storage=%t", BootSyncSucc.Load(), bootSyncScheduled.Load(), isSyncingStorages())+ }+ if want == 0 {+ data, err := os.ReadFile(filepath.Join(util.DataDir, "remote.txt"))+ if err != nil || string(data) != `{"synced":true}` {+ t.Fatalf("ready startup failed to apply cloud changes: %q %v", data, err)+ }+ }+}+func TestIOSBootSyncPerception(t *testing.T) {// 启动状态和同步后的后台任务属于进程状态,使用子进程隔离其他测试。const childEnv = "SIYUAN_TEST_IOS_BOOT_SYNC"@@ -30,6 +216,7 @@ func TestIOSBootSyncPerception(t *testing.T) {util.Container = util.ContainerIOSutil.SetBooted()util.IsUILoaded.Store(true)+ acknowledgeBootSyncClient(t, "ios-ready")lastAutoPurgeRepo = time.Now()Conf.Sync.Load().Perception = truegetPetals()diff --git a/kernel/model/import_data_test.go b/kernel/model/import_data_test.goindex b3f842acb8..ff04fc57f9 100644--- a/kernel/model/import_data_test.go+++ b/kernel/model/import_data_test.go@@ -796,7 +796,8 @@ func TestDataImportFailedRollbackQuarantinesWritesUntilRecovery(t *testing.T) {t.Fatal("allowed a snapshot of a partially installed batch")}for _, syncAttempt := range []func() error{- func() error { return syncDataLocked(false, false) }, syncRepoDownload, syncRepoUpload, bootSyncRepo,+ func() error { return syncDataLocked(false, false) }, syncRepoDownload, syncRepoUpload,+ func() error { _, err := bootSyncRepo(func(error) {}); return err },func() error { _, err := syncRepo(false, false); return err },} {if err = syncAttempt(); err == nil {diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 05bbdbd1b6..46c3535157 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -1970,7 +1970,6 @@ func SetRepoSnapshotMemo(id, memo string) error {}var syncingFiles = sync.Map{}-var syncingStorages = atomic.Bool{}func waitForSyncingStorages() {for isSyncingStorages() {@@ -1979,7 +1978,7 @@ func waitForSyncingStorages() {}func isSyncingStorages() bool {- return syncingStorages.Load() || isBootSyncing.Load()+ return isBootSyncing.Load()}func IsSyncingFile(rootID string) (ret bool) {@@ -2178,7 +2177,7 @@ func syncRepoUpload() (err error) {var isBootSyncing = atomic.Bool{}-func bootSyncRepo() (err error) {+func bootSyncRepo(complete func(error)) (scheduled bool, err error) {if err = checkDataImportRecovery(); err != nil {return}@@ -2213,6 +2212,7 @@ func bootSyncRepo() (err error) {preparedSourceScope := assetDownloadScope(Conf.Sync.Load().Provider, preparedSourceConf, Conf.Repo.Load().Key)isBootSyncing.Store(true)+ defer isBootSyncing.Store(false)waitGroup := sync.WaitGroup{}var indexErr error@@ -2263,36 +2263,31 @@ func bootSyncRepo() (err error) {pushSyncStatusBar(msg)util.PushErrMsg(msg, 0)BootSyncSucc.Store(1)- isBootSyncing.Store(false)return}- syncingFiles = sync.Map{}- syncingStorages.Store(false)if 1 > len(fetchedFiles) {cleanupSyncedBoxResiduals(nil)}- for _, fetchedFile := range fetchedFiles {- name := path.Base(fetchedFile.Path)- if strings.HasSuffix(name, ".sy") {- id := name[:len(name)-3]- syncingFiles.Store(id, true)- continue- }- if strings.HasPrefix(fetchedFile.Path, "/storage/") {- syncingStorages.Store(true)- }- }if 0 < len(fetchedFiles) {+ scheduled = truego func() {- confSyncSnapshot := Conf.LoadSync()-defer logging.Recover()- defer isBootSyncing.Store(false)+ // 预取结束后不再用文件标记阻塞初始化,实际应用由 checkout 的保存确认和写保护负责。+ if waitErr := waitForSyncUI(context.Background(), false, true); waitErr != nil {+ complete(waitErr)+ return+ }lockSync()defer unlockSync()+ syncErr := errSyncRemoteRequestSkipped+ defer func() { complete(syncErr) }()+ if !checkSync(true, false, false) {+ return+ }+ confSyncSnapshot := Conf.LoadSync()currentSourceConf, sourceErr := buildCloudConf()if sourceErr != nil || preparedSourceScope != assetDownloadScope(confSyncSnapshot.Provider, currentSourceConf, Conf.Repo.Load().Key) {logging.LogInfof("skip prepared boot sync after repository source changed")@@ -2300,6 +2295,7 @@ func bootSyncRepo() (err error) {}repo, repoErr := newSyncRepository()if repoErr != nil {+ syncErr = repoErrlogging.LogErrorf("reopen prepared boot repository failed: %s", repoErr)return}@@ -2307,7 +2303,7 @@ func bootSyncRepo() (err error) {logging.LogInfof("syncing prepared boot data repo [device=%s, kernel=%s, provider=%d]", Conf.System.Load().ID, KernelID, confSyncSnapshot.Provider)syncStart := time.Now()indexStart := time.Now()- _, _, syncErr := indexRepoBeforeCloudSync(repo)+ _, _, syncErr = indexRepoBeforeCloudSync(repo)indexElapsed := time.Since(indexStart)if nil == syncErr {syncErr = syncIndexedRepoAfterBootWithDNSRetry(repo, syncStart, indexElapsed, prefetchTraffic)@@ -2317,8 +2313,6 @@ func bootSyncRepo() (err error) {return}}()- } else {- isBootSyncing.Store(false)}return}@@ -2786,7 +2780,6 @@ func processSyncMergeResult(exit, byHand bool, mergeResult *dejavu.MergeResult,removeEmptyPackageDirs(filepath.Join(util.DataDir, "widgets"), removeWidgetDirSet)syncingFiles = sync.Map{}- syncingStorages.Store(false)if needReloadInlineStyles && !exit {invalidateWorkspaceAVPaletteCache()util.BroadcastByType("main", "reloadInlineStyles", 0, "", nil)diff --git a/kernel/model/sync.go b/kernel/model/sync.goindex 278deee086..b5c7fa81f7 100644--- a/kernel/model/sync.go+++ b/kernel/model/sync.go@@ -17,6 +17,7 @@package modelimport (+ "context""errors""fmt""net/http"@@ -178,6 +179,13 @@ func SyncDataJob() {func BootSyncData() {defer logging.Recover()+ if scheduleBootSync() {+ return+ }+ bootSyncData()+}++func bootSyncData() {refreshLANSyncManager()if Conf.Sync.Load().Perception {@@ -191,12 +199,12 @@ func BootSyncData() {lockSync()defer unlockSync()- iosAfterBoot := util.ContainerIOS == util.Container && util.IsBooted()- if !iosAfterBoot {+ afterBoot := util.IsBooted()+ if !afterBoot {util.IncBootProgress(3, Conf.Language(307))}BootSyncSucc.Store(-1)- if iosAfterBoot {+ if afterBoot {logging.LogInfof("sync after boot")} else {logging.LogInfof("sync before boot")@@ -205,23 +213,33 @@ func BootSyncData() {now := util.CurrentTimeMillis()UpdateSyncConf(func(s *conf.Sync) { s.Synced = now })revision := pendingSync.begin()- if iosAfterBoot {+ if afterBoot {// 本地界面已可编辑,保持同步入口可见直到云端合并成功。notifySyncPending(true)}util.BroadcastByType("main", "syncing", 0, Conf.Language(81), nil)var cloudPublished boolvar err error- if iosAfterBoot {+ if afterBoot {cloudPublished, err = syncRepoWithDNSRetry(false, false)} else {- err = bootSyncRepoWithDNSRetry()+ var scheduled bool+ scheduled, err = bootSyncRepoWithDNSRetry(func(err error) {+ finishBootSync(revision, false, err)+ })+ if scheduled {+ return+ }}+ finishBootSync(revision, cloudPublished, err)+}++func finishBootSync(revision uint64, cloudPublished bool, err error) {code := 1if err != nil {code = 2BootSyncSucc.Store(1)- if iosAfterBoot {+ if util.IsBooted() && !errors.Is(err, context.Canceled) && !errors.Is(err, errSyncRemoteRequestSkipped) {msg := formatSyncRepoErrorMsg(err)UpdateSyncConf(func(s *conf.Sync) { s.Stat = msg })pushSyncStatusBar(msg)@@ -236,7 +254,7 @@ func BootSyncData() {// 启动同步成功后消费本地速记临时文件,避免移动端开启云同步时需手动触发同步才能刷新闪念速记consumeShorthands()}- if iosAfterBoot {+ if util.IsBooted() {completeSyncPerception(cloudPublished, err)}}@@ -382,6 +400,9 @@ func completeSyncPerception(cloudPublished bool, err error) {}func checkSync(boot, exit, byHand bool) bool {+ if !boot && !exit && !byHand && bootSyncScheduled.Load() {+ return false+ }confSyncReadSnapshot := Conf.LoadSync()if 2 == confSyncReadSnapshot.Mode && !boot && !exit && !byHand { // 手动模式下只有启动和退出进行同步@@ -1027,10 +1048,10 @@ func syncRepoUploadWithDNSRetry() (err error) {return}-func bootSyncRepoWithDNSRetry() (err error) {- err = bootSyncRepo()+func bootSyncRepoWithDNSRetry(complete func(error)) (scheduled bool, err error) {+ scheduled, err = bootSyncRepo(complete)if nil != err && flushAndRetryOnDNSError(err) {- err = bootSyncRepo()+ scheduled, err = bootSyncRepo(complete)}return}diff --git a/kernel/model/sync_checkout_state.go b/kernel/model/sync_checkout_state.goindex 0bc0f4a964..e1f1b25a4b 100644--- a/kernel/model/sync_checkout_state.go+++ b/kernel/model/sync_checkout_state.go@@ -127,7 +127,23 @@ func (task *syncCheckoutTask) prepareApply() error {task.Unlock()return nil}- sessions := util.SessionsByType("main")+ task.Unlock()+ var sessions []*melody.Session+ for {+ if err := waitForSyncUI(task.ctx, false, false); err != nil {+ return err+ }+ // 就绪检查后仍可能接入新窗口,确认超时只约束这次取得的已就绪会话。+ sessions = util.SessionsByType("main")+ ready := true+ for _, session := range sessions {+ ready = ready && util.IsSessionReady(session)+ }+ if ready {+ break+ }+ }+ task.Lock()task.phase, task.revision = "preparing", syncCheckoutRevision.Add(1)task.clients = map[*melody.Session]*syncCheckoutClient{}task.confirmations = make(chan bool, len(sessions))diff --git a/kernel/model/sync_checkout_state_test.go b/kernel/model/sync_checkout_state_test.goindex 1775f4bdba..ae851cdf71 100644--- a/kernel/model/sync_checkout_state_test.go+++ b/kernel/model/sync_checkout_state_test.go@@ -8,6 +8,7 @@ import ("slices""strings""testing"+ "testing/synctest""time""github.com/gin-gonic/gin"@@ -19,6 +20,51 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+func TestSyncCheckoutPreparationStartsTimeoutOnlyAfterUIReady(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ task := prepareSyncCheckoutStateTest(t)+ client := addBootSyncSession(t, "loading")+ done := make(chan error, 1)+ go func() { done <- task.prepareApply() }()+ time.Sleep(20 * time.Second)+ synctest.Wait()+ if state := GetSyncCheckout("boot-sync-test", "loading").Task; state.Phase != "background" || state.Token != "" {+ t.Fatalf("save confirmation started during initialization: %+v", state)+ }+ if !dataImportAccess.TryLock() {+ t.Fatal("initialization wait holds a write lease")+ }+ dataImportAccess.Unlock()+ client.Set("uiReady", true)+ time.Sleep(time.Second)+ synctest.Wait()+ state := GetSyncCheckout("boot-sync-test", "loading").Task+ if state.Phase != "preparing" || state.Token == "" {+ t.Fatalf("ready window did not receive its own save confirmation: %+v", state)+ }+ ConfirmSyncCheckout(task.id, state.Token, true)+ if err := <-done; err != nil {+ t.Fatal(err)+ }+ })+}++func TestSyncCheckoutPreparationCanCancelWhileLoading(t *testing.T) {+ synctest.Test(t, func(t *testing.T) {+ task := prepareSyncCheckoutStateTest(t)+ addBootSyncSession(t, "loading")+ done := make(chan error, 1)+ go func() { done <- task.prepareApply() }()+ synctest.Wait()+ if !CancelSyncCheckout(task.id) {+ t.Fatal("loading task could not be canceled")+ }+ if err := <-done; !errors.Is(err, context.Canceled) || task.releaseWrites != nil {+ t.Fatalf("canceled initialization entered application: %v", err)+ }+ })+}+func prepareSyncCheckoutStateTest(t *testing.T) *syncCheckoutTask {t.Helper()prepareSyncDirectoryTest(t)diff --git a/kernel/util/websocket.go b/kernel/util/websocket.goindex 96f443f0a1..dade19dbfb 100644--- a/kernel/util/websocket.go+++ b/kernel/util/websocket.go@@ -122,6 +122,12 @@ func SessionsByType(typ string) (ret []*melody.Session) {return sessionsByType(typ, false)}+// IsSessionReady 未声明就绪协议的旧客户端沿用连接后即可接收控制消息的行为。+func IsSessionReady(session *melody.Session) bool {+ ready, exists := session.Get("uiReady")+ return !exists || ready == true+}+func publishSessionsByType(typ string) (ret []*melody.Session) {return sessionsByType(typ, true)}@@ -172,6 +178,9 @@ func AddPushChan(session *melody.Session) {return}session.Set("type", typ)+ if typ == "main" && session.Request.URL.Query().Get("ready") == "false" {+ session.Set("uiReady", false)+ }if IsAuthSession(session) {if appSessions, ok := authSessions.Load(appID); !ok {