nolo-cli 0.1.13 → 0.1.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -2
- package/agent-runtime/hostAdapter.ts +53 -0
- package/agent-runtime/index.ts +28 -0
- package/agent-runtime/localLoop.ts +62 -0
- package/agent-runtime/runtimeDecision.ts +70 -0
- package/agent-runtime/types.ts +87 -0
- package/agentRunCommand.ts +104 -0
- package/agentRuntimeCommands.ts +139 -22
- package/agentRuntimeLocal.ts +7 -0
- package/ai/agent/_executeModel.ts +118 -0
- package/ai/agent/agentSlice.ts +544 -1
- package/ai/agent/appWorkingMemory.ts +126 -0
- package/ai/agent/avatarUtils.ts +24 -0
- package/ai/agent/buildEditingContext.ts +373 -0
- package/ai/agent/buildSystemPrompt.ts +532 -0
- package/ai/agent/cleanAgentMessages.ts +140 -0
- package/ai/agent/cliChatClient.ts +119 -0
- package/ai/agent/contextCompiler.ts +107 -0
- package/ai/agent/contextLayerContract.ts +44 -0
- package/ai/agent/createAgentSchema.ts +234 -0
- package/ai/agent/executeToolCall.ts +58 -0
- package/ai/agent/fetchAgentContexts.ts +42 -0
- package/ai/agent/generatePrompt.ts +3 -0
- package/ai/agent/getFullChatContextKeys.ts +168 -0
- package/ai/agent/hooks/fetchPublicAgents.ts +133 -0
- package/ai/agent/hooks/useAgentConfig.ts +61 -0
- package/ai/agent/hooks/useAgentDialog.ts +35 -0
- package/ai/agent/hooks/useAgentFormValidation.ts +202 -0
- package/ai/agent/hooks/usePublicAgents.ts +473 -0
- package/ai/agent/persistMessageWithFixedId.ts +37 -0
- package/ai/agent/planSlice.ts +259 -0
- package/ai/agent/referenceUtils.ts +229 -0
- package/ai/agent/runAgentBackground.ts +238 -0
- package/ai/agent/runAgentClientLoop.ts +138 -0
- package/ai/agent/runtimeGuidance.ts +97 -0
- package/ai/agent/runtimeServerBase.ts +37 -0
- package/ai/agent/server/fetchPublicAgents.ts +128 -0
- package/ai/agent/startParallelAgentStreams.ts +424 -0
- package/ai/agent/startupProtocol.ts +53 -0
- package/ai/agent/streamAgentChatTurn.ts +1299 -0
- package/ai/agent/streamAgentChatTurnUtils.ts +738 -0
- package/ai/agent/types.ts +71 -0
- package/ai/agent/utils/imageOutput.ts +39 -0
- package/ai/agent/utils/publicImageAgentMode.ts +26 -0
- package/ai/agent/utils/sortUtils.ts +250 -0
- package/ai/agent/web/referencePickerUtils.ts +146 -0
- package/ai/ai.locale.ts +1083 -0
- package/ai/chat/accumulateToolCallChunks.ts +95 -0
- package/ai/chat/fetchUtils.native.ts +276 -0
- package/ai/chat/fetchUtils.ts +153 -0
- package/ai/chat/inlineImageUrlsForCustomProvider.ts +117 -0
- package/ai/chat/parseApiError.ts +64 -0
- package/ai/chat/parseMultilineSSE.ts +95 -0
- package/ai/chat/sendOpenAICompletionsRequest.native.ts +682 -0
- package/ai/chat/sendOpenAICompletionsRequest.ts +712 -0
- package/ai/chat/sendOpenAIResponseRequest.ts +512 -0
- package/ai/chat/shouldUseServerProxy.ts +18 -0
- package/ai/chat/sseClient.native.ts +91 -0
- package/ai/chat/sseClient.ts +67 -0
- package/ai/chat/streamReader.native.ts +31 -0
- package/ai/chat/streamReader.ts +62 -0
- package/ai/chat/updateTotalUsage.ts +72 -0
- package/ai/context/buildReferenceContext.ts +437 -0
- package/ai/context/calculateContextUsage.ts +133 -0
- package/ai/context/retention.ts +165 -0
- package/ai/context/tokenUtils.ts +78 -0
- package/ai/index.ts +1 -1
- package/ai/llm/agentCapabilities.ts +74 -0
- package/ai/llm/calculateGeminiImageTokens.ts +57 -0
- package/ai/llm/deepinfra.ts +28 -0
- package/ai/llm/fireworks.ts +68 -0
- package/ai/llm/generateRequestBody.ts +165 -0
- package/ai/llm/getModelContextWindow.ts +84 -0
- package/ai/llm/getNoloKey.ts +37 -0
- package/ai/llm/getPricing.ts +232 -0
- package/ai/llm/hooks/useModelPricing.ts +75 -0
- package/ai/llm/imagePricing.ts +66 -0
- package/ai/llm/isResponseAPIModel.ts +13 -0
- package/ai/llm/kimi.ts +18 -0
- package/ai/llm/mimo.ts +71 -0
- package/ai/llm/mistral.ts +22 -0
- package/ai/llm/modelAvatar.ts +427 -0
- package/ai/llm/models.ts +45 -0
- package/ai/llm/openrouterModels.ts +141 -0
- package/ai/llm/providers.ts +307 -0
- package/ai/llm/reasoningModels.ts +28 -0
- package/ai/llm/types.ts +59 -0
- package/ai/llm/usageRequestOptions.ts +59 -0
- package/ai/memory/capture.ts +148 -0
- package/ai/memory/consolidate.ts +104 -0
- package/ai/memory/delete.ts +147 -0
- package/ai/memory/overlay.ts +84 -0
- package/ai/memory/query.ts +38 -0
- package/ai/memory/queryShared.ts +160 -0
- package/ai/memory/rank.ts +105 -0
- package/ai/memory/recentRelationshipRecap.ts +247 -0
- package/ai/memory/remember.ts +167 -0
- package/ai/memory/runtime.ts +76 -0
- package/ai/memory/store.ts +20 -0
- package/ai/memory/storeShared.ts +76 -0
- package/ai/memory/types.ts +46 -0
- package/ai/memory/understanding.ts +349 -0
- package/ai/memory/understandingGreeting.ts +264 -0
- package/ai/messages/type.ts +20 -0
- package/ai/policy/personalizationDialog.ts +333 -0
- package/ai/policy/runtimePolicy.ts +440 -0
- package/ai/policy/selfUpdateFields.ts +48 -0
- package/ai/policy/types.ts +64 -0
- package/ai/skills/referenceRuntime.ts +274 -0
- package/ai/skills/skillDiagnostics.ts +251 -0
- package/ai/skills/skillDocBuilder.ts +139 -0
- package/ai/skills/skillDocProtocol.ts +434 -0
- package/ai/skills/skillReferenceSummary.ts +63 -0
- package/ai/skills/skillSummaryMarker.ts +26 -0
- package/ai/token/calculatePrice.ts +546 -0
- package/ai/token/db.ts +98 -0
- package/ai/token/externalToolCost.ts +321 -0
- package/ai/token/hooks/useRecords.ts +65 -0
- package/ai/token/missingUsageEstimate.ts +42 -0
- package/ai/token/modelUsageQuery.ts +252 -0
- package/ai/token/normalizeUsage.ts +84 -0
- package/ai/token/openaiImageGenerationUsage.ts +56 -0
- package/ai/token/prepareTokenUsageData.ts +88 -0
- package/ai/token/query.ts +88 -0
- package/ai/token/queryUserTokens.ts +59 -0
- package/ai/token/resolveBillingTarget.ts +52 -0
- package/ai/token/saveTokenRecord.ts +53 -0
- package/ai/token/serverDialogProjection.ts +78 -0
- package/ai/token/serverTokenWriter.ts +143 -0
- package/ai/token/stats.ts +21 -0
- package/ai/token/tokenThunks.ts +24 -0
- package/ai/token/types.ts +93 -0
- package/ai/tools/agent/agentTools.ts +176 -0
- package/ai/tools/agent/agentUpdateShared.ts +311 -0
- package/ai/tools/agent/callAgentTool.ts +139 -0
- package/ai/tools/agent/createAgentTool.ts +512 -0
- package/ai/tools/agent/createDialogTool.ts +69 -0
- package/ai/tools/agent/createSkillAgentTool.ts +62 -0
- package/ai/tools/agent/parallelBudget.ts +221 -0
- package/ai/tools/agent/presets/appBuilderPreset.ts +147 -0
- package/ai/tools/agent/runLlmTool.ts +96 -0
- package/ai/tools/agent/runStreamingAgentTool.ts +73 -0
- package/ai/tools/agent/skillAgentArgs.ts +106 -0
- package/ai/tools/agent/skillAgentPreset.ts +89 -0
- package/ai/tools/agent/streamParallelAgentsTool.ts +122 -0
- package/ai/tools/agent/updateAgentTool.ts +96 -0
- package/ai/tools/agent/updateSelfTool.ts +113 -0
- package/ai/tools/amazonProductScraperTool.ts +86 -0
- package/ai/tools/apifyActorClient.ts +45 -0
- package/ai/tools/appEditGuard.ts +372 -0
- package/ai/tools/appReadSnapshot.ts +153 -0
- package/ai/tools/appTools.ts +1549 -0
- package/ai/tools/applyEditTool.ts +256 -0
- package/ai/tools/applyLineEditsTool.ts +312 -0
- package/ai/tools/browserTools/click.ts +33 -0
- package/ai/tools/browserTools/closeSession.ts +29 -0
- package/ai/tools/browserTools/common.ts +27 -0
- package/ai/tools/browserTools/openSession.ts +48 -0
- package/ai/tools/browserTools/readContent.ts +38 -0
- package/ai/tools/browserTools/selectOption.ts +46 -0
- package/ai/tools/browserTools/typeText.ts +42 -0
- package/ai/tools/category/createCategoryTool.ts +66 -0
- package/ai/tools/category/queryContentsByCategoryTool.ts +69 -0
- package/ai/tools/category/updateContentCategoryTool.ts +75 -0
- package/ai/tools/cfBrowserTools.ts +319 -0
- package/ai/tools/cfSpeechToTextTool.ts +49 -0
- package/ai/tools/checkEnvTool.ts +65 -0
- package/ai/tools/cloudflareCrawlTool.ts +289 -0
- package/ai/tools/codeSearchTool.ts +111 -0
- package/ai/tools/codeTools.ts +101 -0
- package/ai/tools/createDocTool.ts +132 -0
- package/ai/tools/createPlanTool.ts +999 -0
- package/ai/tools/createSkillDocTool.ts +155 -0
- package/ai/tools/createWorkflowTool.ts +154 -0
- package/ai/tools/deepseekOcrTool.ts +34 -0
- package/ai/tools/delayTool.ts +31 -0
- package/ai/tools/deleteSpacesTool.ts +325 -0
- package/ai/tools/deleteSpacesToolModel.ts +159 -0
- package/ai/tools/devReloadUtils.ts +29 -0
- package/ai/tools/dialogMessageSearch.ts +137 -0
- package/ai/tools/doctorSkillTool.ts +72 -0
- package/ai/tools/ecommerceScraperTool.ts +86 -0
- package/ai/tools/emailTools.ts +549 -0
- package/ai/tools/evalSkillTool.ts +92 -0
- package/ai/tools/exaSearchTool.ts +64 -0
- package/ai/tools/execBashTool.ts +379 -0
- package/ai/tools/executeSqlTool.ts +192 -0
- package/ai/tools/fetchWebpageSupport.ts +309 -0
- package/ai/tools/fetchWebpageTool.ts +84 -0
- package/ai/tools/geminiImagePreviewTool.ts +361 -0
- package/ai/tools/generateDocxTool.ts +215 -0
- package/ai/tools/googleSearchScraperTool.ts +106 -0
- package/ai/tools/importDataTool.ts +133 -0
- package/ai/tools/importSkillTool.ts +162 -0
- package/ai/tools/index.ts +1927 -0
- package/ai/tools/listFilesTool.ts +82 -0
- package/ai/tools/listUserSpacesTool.ts +113 -0
- package/ai/tools/modelUsageTools.ts +199 -0
- package/ai/tools/olmOcrTool.ts +34 -0
- package/ai/tools/openaiImageTool.ts +267 -0
- package/ai/tools/prepareTools.ts +23 -0
- package/ai/tools/readDocTool.ts +84 -0
- package/ai/tools/readFileTool.ts +211 -0
- package/ai/tools/readTool.ts +163 -0
- package/ai/tools/readXPostTool.ts +233 -0
- package/ai/tools/rememberMemoryTool.ts +84 -0
- package/ai/tools/remotionVideoTool.ts +151 -0
- package/ai/tools/searchDialogMessagesTool.ts +222 -0
- package/ai/tools/searchRepoTool.ts +115 -0
- package/ai/tools/searchWorkspaceTool.ts +259 -0
- package/ai/tools/skillFollowup.ts +86 -0
- package/ai/tools/surfWeatherTool.ts +169 -0
- package/ai/tools/table/addTableRowTool.ts +217 -0
- package/ai/tools/table/createTableTool.ts +315 -0
- package/ai/tools/table/rowTools.ts +366 -0
- package/ai/tools/table/schemaTools.ts +244 -0
- package/ai/tools/table/shareTableTool.ts +148 -0
- package/ai/tools/table/toolShared.ts +129 -0
- package/ai/tools/toolApiClient.ts +198 -0
- package/ai/tools/toolNameAliases.ts +57 -0
- package/ai/tools/toolResultError.ts +42 -0
- package/ai/tools/toolRunSlice.ts +303 -0
- package/ai/tools/toolSchemaCompatibility.ts +53 -0
- package/ai/tools/toolVisibility.ts +4 -0
- package/ai/tools/types.ts +20 -0
- package/ai/tools/uiAskChoiceTool.ts +104 -0
- package/ai/tools/updateContentTitleTool.ts +84 -0
- package/ai/tools/updateDocTool.ts +105 -0
- package/ai/tools/updateUserPreferenceProfileTool.ts +145 -0
- package/ai/tools/whisperTool.ts +77 -0
- package/ai/tools/writeFileTool.ts +210 -0
- package/ai/tools/youtubeScraperTool.ts +116 -0
- package/ai/tools/ziweiChartTool.ts +678 -0
- package/ai/types.ts +55 -0
- package/ai/workflow/workflowExecutor.ts +323 -0
- package/ai/workflow/workflowSlice.ts +73 -0
- package/ai/workflow/workflowTypes.ts +106 -0
- package/client/agentRun.test.ts +240 -0
- package/client/agentRun.ts +182 -19
- package/client/compactDialog.test.ts +238 -0
- package/client/localRuntimeAdapter.test.ts +135 -0
- package/client/localRuntimeAdapter.ts +244 -0
- package/client/profileConfig.test.ts +40 -0
- package/client/streamingOutput.test.ts +22 -0
- package/client/streamingOutput.ts +38 -0
- package/commandRegistry.ts +11 -2
- package/connector-experimental/index.ts +5 -0
- package/database/actions/cacheMergedUserData.ts +64 -0
- package/database/actions/common.ts +242 -0
- package/database/actions/deleteFile.ts +40 -0
- package/database/actions/fetchUserData.ts +16 -0
- package/database/actions/fileContent.ts +125 -0
- package/database/actions/patch.ts +155 -0
- package/database/actions/read.ts +337 -0
- package/database/actions/readAndWait.ts +224 -0
- package/database/actions/readRequestManager.ts +120 -0
- package/database/actions/remove.ts +94 -0
- package/database/actions/replication.ts +366 -0
- package/database/actions/upload.ts +174 -0
- package/database/actions/upsert.ts +56 -0
- package/database/actions/write.ts +126 -0
- package/database/client/db.native.ts +73 -0
- package/database/client/db.ts +51 -0
- package/database/client/fetchUserData.ts +61 -0
- package/database/client/handleError.ts +19 -0
- package/database/client/queryRequest.ts +21 -0
- package/database/config.ts +21 -0
- package/database/dbActionThunks.ts +1 -0
- package/database/dbSlice.ts +149 -0
- package/database/email.ts +42 -0
- package/database/fileRing.ts +51 -0
- package/database/fileSharding.ts +70 -0
- package/database/fileStorage.native.ts +92 -0
- package/database/fileStorage.ts +232 -0
- package/database/fileUrl.ts +34 -0
- package/database/hooks/useUserData.ts +489 -0
- package/database/index.ts +1 -0
- package/database/keys.ts +765 -0
- package/database/queryPrefixes.ts +14 -0
- package/database/requests.ts +443 -0
- package/database/runtimeServerContext.ts +35 -0
- package/database/server/MemoryDB.ts +76 -0
- package/database/server/actorAccess.ts +76 -0
- package/database/server/agentDelegation.ts +124 -0
- package/database/server/coreDataOwnership.ts +13 -0
- package/database/server/coreDataProxy.ts +76 -0
- package/database/server/cybotReadonly.ts +18 -0
- package/database/server/dataHandlers.ts +111 -0
- package/database/server/db.ts +118 -0
- package/database/server/dbPath.ts +20 -0
- package/database/server/delete.ts +499 -0
- package/database/server/emailRepository.ts +1480 -0
- package/database/server/ensureDbOpen.ts +12 -0
- package/database/server/fileRead.ts +337 -0
- package/database/server/fileService.ts +436 -0
- package/database/server/handleTransaction.ts +86 -0
- package/database/server/patch.ts +282 -0
- package/database/server/query.ts +138 -0
- package/database/server/read.ts +325 -0
- package/database/server/resourceAccess.ts +211 -0
- package/database/server/routes.ts +110 -0
- package/database/server/spaceMemberAuthority.ts +67 -0
- package/database/server/upload.ts +159 -0
- package/database/server/write.ts +494 -0
- package/database/server/writeAuthority.ts +133 -0
- package/database/sqliteDb.ts +46 -0
- package/database/table/deleteTable.ts +120 -0
- package/database/tenantPlacement.ts +57 -0
- package/database/tombstones.ts +52 -0
- package/database/userDataLoadDecision.ts +17 -0
- package/database/userDataMerge.ts +95 -0
- package/database/userPreferenceRegister.ts +108 -0
- package/database/utils/dbPath.ts +47 -0
- package/database/utils/ulid.native.ts +6 -0
- package/database/utils/ulid.ts +1 -0
- package/index.ts +37 -19
- package/localRuntimeDb.ts +28 -0
- package/package.json +17 -4
- package/runtimeModeArgs.ts +33 -0
- package/tui/readlineWorkspace.ts +1 -0
- package/tui/session.ts +22 -0
|
@@ -0,0 +1,489 @@
|
|
|
1
|
+
// database/hooks/useUserData.ts
|
|
2
|
+
import { useEffect, useState, useCallback, useRef, useMemo } from "react";
|
|
3
|
+
import {
|
|
4
|
+
selectRuntimeRemoteServers,
|
|
5
|
+
selectRuntimeSnapshot,
|
|
6
|
+
} from "app/stateViews/runtime";
|
|
7
|
+
import { toast } from "app/utils/toast";
|
|
8
|
+
|
|
9
|
+
import { DataType } from "create/types";
|
|
10
|
+
import { useAppDispatch, useAppSelector } from "app/store";
|
|
11
|
+
import {
|
|
12
|
+
getUserDataItemTimestamp,
|
|
13
|
+
mergeAndDedupUserData,
|
|
14
|
+
} from "../userDataMerge";
|
|
15
|
+
import { isTombstoneRecord } from "../tombstones";
|
|
16
|
+
import { getUserDataLoadDecision } from "../userDataLoadDecision";
|
|
17
|
+
|
|
18
|
+
import { fetchUserDataThunk } from "../actions/fetchUserData";
|
|
19
|
+
import { cacheMergedUserDataThunk } from "../actions/cacheMergedUserData";
|
|
20
|
+
import { noloQueryRequest } from "../client/queryRequest";
|
|
21
|
+
|
|
22
|
+
interface BaseItem {
|
|
23
|
+
id: string;
|
|
24
|
+
type: DataType;
|
|
25
|
+
updatedAt?: string | number;
|
|
26
|
+
created?: string | number;
|
|
27
|
+
userId: string;
|
|
28
|
+
[key: string]: any;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
interface FetchState {
|
|
32
|
+
loading: boolean;
|
|
33
|
+
error: Error | null;
|
|
34
|
+
data: BaseItem[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface UseUserDataReturn extends FetchState {
|
|
38
|
+
reload: () => Promise<void>;
|
|
39
|
+
clearCache: () => void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
interface UseUserDataOptions {
|
|
43
|
+
allowPartialData?: boolean;
|
|
44
|
+
partialDataStrategy?: PartialDataStrategy;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type PartialDataStrategy = "always" | "never" | "hydrated-cache";
|
|
48
|
+
|
|
49
|
+
const shouldDebugUserData =
|
|
50
|
+
typeof window !== "undefined" &&
|
|
51
|
+
!!window.location &&
|
|
52
|
+
typeof window.location.hostname === "string" &&
|
|
53
|
+
/^(localhost|127\.0\.0\.1)$/.test(window.location.hostname);
|
|
54
|
+
|
|
55
|
+
const summarizeItemsByType = (items: BaseItem[]): Record<string, number> => {
|
|
56
|
+
return items.reduce<Record<string, number>>((acc, item) => {
|
|
57
|
+
const key =
|
|
58
|
+
(typeof item.type === "string" && item.type.trim()) ||
|
|
59
|
+
(typeof item.appKey === "string" && item.appKey.startsWith("app-") ? DataType.APP : "unknown");
|
|
60
|
+
acc[key] = (acc[key] ?? 0) + 1;
|
|
61
|
+
return acc;
|
|
62
|
+
}, {});
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const summarizeAppKeys = (items: BaseItem[]): string[] => {
|
|
66
|
+
return items
|
|
67
|
+
.filter((item) => {
|
|
68
|
+
const candidates = [item.dbKey, item.contentKey, item.appKey];
|
|
69
|
+
return candidates.some(
|
|
70
|
+
(candidate) => typeof candidate === "string" && candidate.startsWith("app-")
|
|
71
|
+
);
|
|
72
|
+
})
|
|
73
|
+
.slice(0, 12)
|
|
74
|
+
.map(
|
|
75
|
+
(item) =>
|
|
76
|
+
item.dbKey ??
|
|
77
|
+
item.contentKey ??
|
|
78
|
+
item.appKey ??
|
|
79
|
+
item.appId ??
|
|
80
|
+
item.id
|
|
81
|
+
)
|
|
82
|
+
.filter((candidate): candidate is string => typeof candidate === "string");
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const debugUserData = (
|
|
86
|
+
phase: string,
|
|
87
|
+
payload: Record<string, unknown>
|
|
88
|
+
) => {
|
|
89
|
+
if (!shouldDebugUserData) return;
|
|
90
|
+
console.debug(`[useUserData] ${phase}`, payload);
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
export const buildUserDataHydrationKey = ({
|
|
94
|
+
userId,
|
|
95
|
+
typesKey,
|
|
96
|
+
serverKey,
|
|
97
|
+
}: {
|
|
98
|
+
userId: string;
|
|
99
|
+
typesKey: string;
|
|
100
|
+
serverKey: string;
|
|
101
|
+
}): string => `nolo-user-data-hydrated:${userId}:${typesKey}:${serverKey}`;
|
|
102
|
+
|
|
103
|
+
const readHydratedUserDataCacheFlag = (hydrationKey: string): boolean => {
|
|
104
|
+
if (typeof window === "undefined" || !hydrationKey) return false;
|
|
105
|
+
try {
|
|
106
|
+
return window.localStorage.getItem(hydrationKey) === "1";
|
|
107
|
+
} catch {
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const markHydratedUserDataCacheFlag = (hydrationKey: string) => {
|
|
113
|
+
if (typeof window === "undefined" || !hydrationKey) return;
|
|
114
|
+
try {
|
|
115
|
+
window.localStorage.setItem(hydrationKey, "1");
|
|
116
|
+
} catch {
|
|
117
|
+
// Best-effort local UI optimization only.
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
export const shouldUsePartialLocalData = ({
|
|
122
|
+
strategy,
|
|
123
|
+
hasHydratedCache,
|
|
124
|
+
localItemCount,
|
|
125
|
+
}: {
|
|
126
|
+
strategy: PartialDataStrategy;
|
|
127
|
+
hasHydratedCache: boolean;
|
|
128
|
+
localItemCount: number;
|
|
129
|
+
}): boolean => {
|
|
130
|
+
if (strategy === "never") return false;
|
|
131
|
+
if (strategy === "hydrated-cache") {
|
|
132
|
+
return hasHydratedCache && localItemCount > 0;
|
|
133
|
+
}
|
|
134
|
+
return true;
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
const withServerOrigin = (items: BaseItem[], serverOrigin: string) =>
|
|
138
|
+
items.map((item) => ({
|
|
139
|
+
...item,
|
|
140
|
+
serverOrigin,
|
|
141
|
+
}));
|
|
142
|
+
|
|
143
|
+
const extractRemoteItems = async (
|
|
144
|
+
response: Response,
|
|
145
|
+
serverOrigin: string
|
|
146
|
+
): Promise<BaseItem[]> => {
|
|
147
|
+
const data = await response.json();
|
|
148
|
+
const items = Array.isArray(data?.data?.data) ? data.data.data : [];
|
|
149
|
+
return withServerOrigin(items as BaseItem[], serverOrigin);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
export const getItemTimestamp = (dataItem: BaseItem): number =>
|
|
153
|
+
getUserDataItemTimestamp(dataItem);
|
|
154
|
+
|
|
155
|
+
export const mergeAndDedupData = (
|
|
156
|
+
localData: BaseItem[],
|
|
157
|
+
remoteResults: any[],
|
|
158
|
+
options: { includeDeleted?: boolean } = {}
|
|
159
|
+
): BaseItem[] =>
|
|
160
|
+
mergeAndDedupUserData(localData, remoteResults, options) as BaseItem[];
|
|
161
|
+
|
|
162
|
+
const loadRemoteUserData = async ({
|
|
163
|
+
serverOrigin,
|
|
164
|
+
queryUserId,
|
|
165
|
+
types,
|
|
166
|
+
limit,
|
|
167
|
+
}: {
|
|
168
|
+
serverOrigin: string;
|
|
169
|
+
queryUserId: string;
|
|
170
|
+
types: DataType[];
|
|
171
|
+
limit: number;
|
|
172
|
+
}) => {
|
|
173
|
+
try {
|
|
174
|
+
const batchResponse = await noloQueryRequest({
|
|
175
|
+
server: serverOrigin,
|
|
176
|
+
queryUserId,
|
|
177
|
+
options: {
|
|
178
|
+
limit,
|
|
179
|
+
condition: { type: types, includeDeleted: true },
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
if (batchResponse.ok) {
|
|
184
|
+
return { data: { data: await extractRemoteItems(batchResponse, serverOrigin) } };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// 多服务器环境里远端可能还是旧版本,只接受单个 type。
|
|
188
|
+
// 这里回退到 legacy per-type 查询,保证正确性优先于省请求。
|
|
189
|
+
if (![400, 404].includes(batchResponse.status)) {
|
|
190
|
+
return { data: { data: [] } };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const legacyResponses = await Promise.all(
|
|
194
|
+
types.map(async (type) => {
|
|
195
|
+
try {
|
|
196
|
+
const response = await noloQueryRequest({
|
|
197
|
+
server: serverOrigin,
|
|
198
|
+
queryUserId,
|
|
199
|
+
options: {
|
|
200
|
+
limit,
|
|
201
|
+
condition: { type, includeDeleted: true },
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
if (!response.ok) return [];
|
|
205
|
+
return extractRemoteItems(response, serverOrigin);
|
|
206
|
+
} catch {
|
|
207
|
+
return [];
|
|
208
|
+
}
|
|
209
|
+
})
|
|
210
|
+
);
|
|
211
|
+
|
|
212
|
+
return { data: { data: legacyResponses.flat() } };
|
|
213
|
+
} catch {
|
|
214
|
+
return { data: { data: [] } };
|
|
215
|
+
}
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
export function useUserData(
|
|
219
|
+
types: DataType | DataType[],
|
|
220
|
+
userId: string,
|
|
221
|
+
limit: number,
|
|
222
|
+
options: UseUserDataOptions = {}
|
|
223
|
+
): UseUserDataReturn {
|
|
224
|
+
const dispatch = useAppDispatch();
|
|
225
|
+
const { currentUserId, currentToken } = useAppSelector(selectRuntimeSnapshot);
|
|
226
|
+
const partialDataStrategy = useMemo<PartialDataStrategy>(() => {
|
|
227
|
+
if (options.partialDataStrategy) return options.partialDataStrategy;
|
|
228
|
+
return options.allowPartialData ?? true ? "always" : "never";
|
|
229
|
+
}, [options.allowPartialData, options.partialDataStrategy]);
|
|
230
|
+
|
|
231
|
+
const [{ loading, error, data }, setState] = useState<FetchState>({
|
|
232
|
+
loading: true,
|
|
233
|
+
error: null,
|
|
234
|
+
data: [],
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
const typeArray = useMemo(
|
|
238
|
+
() => (Array.isArray(types) ? types : [types]),
|
|
239
|
+
[types]
|
|
240
|
+
);
|
|
241
|
+
const typesKey = useMemo(() => typeArray.join(","), [typeArray]);
|
|
242
|
+
|
|
243
|
+
const loadingRef = useRef(false);
|
|
244
|
+
const pendingRefreshRef = useRef(false);
|
|
245
|
+
const previousParamsRef = useRef<{
|
|
246
|
+
typesKey: string;
|
|
247
|
+
userId: string;
|
|
248
|
+
serverKey: string;
|
|
249
|
+
}>({
|
|
250
|
+
typesKey: "",
|
|
251
|
+
userId: "",
|
|
252
|
+
serverKey: "",
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
const effectiveUserId = useMemo(() => {
|
|
256
|
+
if (userId === "local" && currentToken && currentUserId) {
|
|
257
|
+
return currentUserId;
|
|
258
|
+
}
|
|
259
|
+
return userId;
|
|
260
|
+
}, [userId, currentToken, currentUserId]);
|
|
261
|
+
const allServers = useAppSelector(selectRuntimeRemoteServers);
|
|
262
|
+
const serverKey = useMemo(() => allServers.join(","), [allServers]);
|
|
263
|
+
const hydrationKey = useMemo(() => {
|
|
264
|
+
if (!effectiveUserId || effectiveUserId === "undefined") return "";
|
|
265
|
+
return buildUserDataHydrationKey({
|
|
266
|
+
userId: effectiveUserId,
|
|
267
|
+
typesKey,
|
|
268
|
+
serverKey,
|
|
269
|
+
});
|
|
270
|
+
}, [effectiveUserId, serverKey, typesKey]);
|
|
271
|
+
|
|
272
|
+
const clearCache = useCallback(() => {
|
|
273
|
+
previousParamsRef.current = { typesKey: "", userId: "", serverKey: "" };
|
|
274
|
+
}, []);
|
|
275
|
+
|
|
276
|
+
const loadData = useCallback(async (options?: { forceRefresh?: boolean }) => {
|
|
277
|
+
if (!effectiveUserId || effectiveUserId === "undefined") {
|
|
278
|
+
previousParamsRef.current = { typesKey: "", userId: "", serverKey: "" };
|
|
279
|
+
setState({
|
|
280
|
+
loading: false,
|
|
281
|
+
error: null,
|
|
282
|
+
data: [],
|
|
283
|
+
});
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const currentParams = {
|
|
288
|
+
typesKey,
|
|
289
|
+
userId: effectiveUserId,
|
|
290
|
+
serverKey,
|
|
291
|
+
};
|
|
292
|
+
const hydratedCacheReady = readHydratedUserDataCacheFlag(hydrationKey);
|
|
293
|
+
const sameParams =
|
|
294
|
+
JSON.stringify(previousParamsRef.current) ===
|
|
295
|
+
JSON.stringify(currentParams);
|
|
296
|
+
const decision = getUserDataLoadDecision({
|
|
297
|
+
loading: loadingRef.current,
|
|
298
|
+
sameParams,
|
|
299
|
+
forceRefresh: options?.forceRefresh,
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
if (decision === "queue") {
|
|
303
|
+
pendingRefreshRef.current = true;
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
if (decision === "skip") {
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
loadingRef.current = true;
|
|
312
|
+
previousParamsRef.current = currentParams;
|
|
313
|
+
setState((prev) => ({ ...prev, loading: true, error: null }));
|
|
314
|
+
|
|
315
|
+
try {
|
|
316
|
+
const localResults = await dispatch(
|
|
317
|
+
fetchUserDataThunk({
|
|
318
|
+
types: typeArray,
|
|
319
|
+
userId: effectiveUserId,
|
|
320
|
+
includeDeleted: true,
|
|
321
|
+
})
|
|
322
|
+
).unwrap();
|
|
323
|
+
const localData: BaseItem[] = (Object.values(localResults).flat() as any[]).map(
|
|
324
|
+
(item) => item as BaseItem
|
|
325
|
+
);
|
|
326
|
+
debugUserData("local-loaded", {
|
|
327
|
+
userId: effectiveUserId,
|
|
328
|
+
types: typeArray,
|
|
329
|
+
localCount: localData.length,
|
|
330
|
+
localByType: summarizeItemsByType(localData),
|
|
331
|
+
localAppKeys: summarizeAppKeys(localData),
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
if (userId === "local" && !currentToken) {
|
|
335
|
+
const sortedLocalData = [...localData]
|
|
336
|
+
.filter((item) => !isTombstoneRecord(item))
|
|
337
|
+
.sort((a, b) => {
|
|
338
|
+
return getItemTimestamp(b) - getItemTimestamp(a);
|
|
339
|
+
});
|
|
340
|
+
const limitedLocalData = sortedLocalData.slice(0, limit);
|
|
341
|
+
|
|
342
|
+
setState({
|
|
343
|
+
loading: false,
|
|
344
|
+
error: null,
|
|
345
|
+
data: limitedLocalData,
|
|
346
|
+
});
|
|
347
|
+
loadingRef.current = false;
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const sortedInitialLocalData = [...localData]
|
|
352
|
+
.filter((item) => !isTombstoneRecord(item))
|
|
353
|
+
.sort((a, b) => {
|
|
354
|
+
return getItemTimestamp(b) - getItemTimestamp(a);
|
|
355
|
+
});
|
|
356
|
+
const limitedInitialLocalData = sortedInitialLocalData.slice(0, limit);
|
|
357
|
+
|
|
358
|
+
if (
|
|
359
|
+
shouldUsePartialLocalData({
|
|
360
|
+
strategy: partialDataStrategy,
|
|
361
|
+
hasHydratedCache: hydratedCacheReady,
|
|
362
|
+
localItemCount: limitedInitialLocalData.length,
|
|
363
|
+
})
|
|
364
|
+
) {
|
|
365
|
+
setState((prev) => ({
|
|
366
|
+
...prev,
|
|
367
|
+
data: limitedInitialLocalData,
|
|
368
|
+
loading: true,
|
|
369
|
+
}));
|
|
370
|
+
} else {
|
|
371
|
+
// 对于冷缓存或明确禁用 partial data 的场景,继续等完整 merge 后再替换,
|
|
372
|
+
// 避免首次进入时空列表/错位列表带来的明显闪烁。
|
|
373
|
+
setState((prev) => ({
|
|
374
|
+
...prev,
|
|
375
|
+
loading: true,
|
|
376
|
+
}));
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const remoteResults = await Promise.all(
|
|
380
|
+
allServers.map((serverOrigin) =>
|
|
381
|
+
loadRemoteUserData({
|
|
382
|
+
serverOrigin,
|
|
383
|
+
queryUserId: effectiveUserId,
|
|
384
|
+
types: typeArray,
|
|
385
|
+
limit,
|
|
386
|
+
})
|
|
387
|
+
)
|
|
388
|
+
);
|
|
389
|
+
debugUserData("remote-loaded", {
|
|
390
|
+
userId: effectiveUserId,
|
|
391
|
+
servers: allServers,
|
|
392
|
+
remoteCounts: remoteResults.map((result, index) => ({
|
|
393
|
+
index,
|
|
394
|
+
count: Array.isArray(result?.data?.data) ? result.data.data.length : 0,
|
|
395
|
+
byType: summarizeItemsByType(Array.isArray(result?.data?.data) ? result.data.data : []),
|
|
396
|
+
appKeys: summarizeAppKeys(Array.isArray(result?.data?.data) ? result.data.data : []),
|
|
397
|
+
})),
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
const mergedDataWithDeleted = mergeAndDedupData(localData, remoteResults, {
|
|
401
|
+
includeDeleted: true,
|
|
402
|
+
});
|
|
403
|
+
const mergedData = mergedDataWithDeleted.filter((item) => !isTombstoneRecord(item));
|
|
404
|
+
const sortedData = [...mergedData].sort((a, b) => {
|
|
405
|
+
return getItemTimestamp(b) - getItemTimestamp(a);
|
|
406
|
+
});
|
|
407
|
+
const limitedData = sortedData.slice(0, limit);
|
|
408
|
+
debugUserData("merged", {
|
|
409
|
+
userId: effectiveUserId,
|
|
410
|
+
mergedCount: mergedData.length,
|
|
411
|
+
mergedByType: summarizeItemsByType(mergedData),
|
|
412
|
+
mergedAppKeys: summarizeAppKeys(mergedData),
|
|
413
|
+
limitedCount: limitedData.length,
|
|
414
|
+
limitedByType: summarizeItemsByType(limitedData),
|
|
415
|
+
limitedAppKeys: summarizeAppKeys(limitedData),
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
if (mergedDataWithDeleted.length > 0) {
|
|
419
|
+
try {
|
|
420
|
+
await dispatch(cacheMergedUserDataThunk({ records: mergedDataWithDeleted })).unwrap();
|
|
421
|
+
} catch (cacheError) {
|
|
422
|
+
console.warn("[useUserData] Failed to persist merged user data cache", cacheError);
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
if (partialDataStrategy === "hydrated-cache" && hydrationKey) {
|
|
427
|
+
markHydratedUserDataCacheFlag(hydrationKey);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
setState({
|
|
431
|
+
loading: false,
|
|
432
|
+
error: null,
|
|
433
|
+
data: limitedData,
|
|
434
|
+
});
|
|
435
|
+
} catch (err) {
|
|
436
|
+
const error =
|
|
437
|
+
err instanceof Error
|
|
438
|
+
? err
|
|
439
|
+
: new Error(String(err) || "Unknown error occurred");
|
|
440
|
+
toast.error("加载数据失败,请检查网络或稍后重试");
|
|
441
|
+
|
|
442
|
+
setState((prev) => ({
|
|
443
|
+
...prev,
|
|
444
|
+
loading: false,
|
|
445
|
+
error,
|
|
446
|
+
}));
|
|
447
|
+
} finally {
|
|
448
|
+
loadingRef.current = false;
|
|
449
|
+
if (pendingRefreshRef.current) {
|
|
450
|
+
pendingRefreshRef.current = false;
|
|
451
|
+
void loadData({ forceRefresh: true });
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
}, [
|
|
455
|
+
typesKey,
|
|
456
|
+
effectiveUserId,
|
|
457
|
+
serverKey,
|
|
458
|
+
hydrationKey,
|
|
459
|
+
limit,
|
|
460
|
+
dispatch,
|
|
461
|
+
currentToken,
|
|
462
|
+
userId,
|
|
463
|
+
typeArray,
|
|
464
|
+
partialDataStrategy,
|
|
465
|
+
allServers,
|
|
466
|
+
]);
|
|
467
|
+
|
|
468
|
+
useEffect(() => {
|
|
469
|
+
loadData();
|
|
470
|
+
}, [loadData]);
|
|
471
|
+
|
|
472
|
+
useEffect(() => {
|
|
473
|
+
if (typeof window === "undefined") {
|
|
474
|
+
return;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
const refresh = () => {
|
|
478
|
+
clearCache();
|
|
479
|
+
void loadData({ forceRefresh: true });
|
|
480
|
+
};
|
|
481
|
+
|
|
482
|
+
window.addEventListener("nolo-user-data-updated", refresh);
|
|
483
|
+
return () => {
|
|
484
|
+
window.removeEventListener("nolo-user-data-updated", refresh);
|
|
485
|
+
};
|
|
486
|
+
}, [clearCache, loadData]);
|
|
487
|
+
|
|
488
|
+
return { loading, error, data, reload: loadData, clearCache };
|
|
489
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
console.log('Hello via Bun!');
|