harden(ai): AIRuntime 去掉冗余 weak self,prepare loading 路径加注释
按 code quality review 反馈(2×P0): - generate() 的 Task 闭包不再 [weak self];actor 单例 strong capture 没有循环引用风险,且避免 Swift 5.10+ weak-on-actor 警告 - prepare() 的 case .loading: return 加注释说明这是有意设计, 调用方需轮询或显示 loading UI(W3 引入 prepare 队列优化) Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -34,9 +34,15 @@ actor AIRuntime {
|
|||||||
/// 加载模型。首次调用会真正加载,后续幂等。
|
/// 加载模型。首次调用会真正加载,后续幂等。
|
||||||
func prepare() async throws {
|
func prepare() async throws {
|
||||||
switch status {
|
switch status {
|
||||||
case .ready: return
|
case .ready:
|
||||||
case .loading: return // 已经在加载
|
return
|
||||||
case .error, .notReady: break
|
case .loading:
|
||||||
|
// 已有其他调用方在加载;本次 prepare 直接返回,
|
||||||
|
// 调用方需稍后 await prepare() 再判 status,或自行轮询 / 显示加载 UI。
|
||||||
|
// W3 引入 prepare 队列时优化。
|
||||||
|
return
|
||||||
|
case .error, .notReady:
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
guard ModelStore.shared.isReady(.llm) else {
|
guard ModelStore.shared.isReady(.llm) else {
|
||||||
@@ -65,7 +71,7 @@ actor AIRuntime {
|
|||||||
let snapshotSession = llmSession
|
let snapshotSession = llmSession
|
||||||
|
|
||||||
return AsyncThrowingStream { continuation in
|
return AsyncThrowingStream { continuation in
|
||||||
Task { [weak self] in
|
Task {
|
||||||
guard snapshotStatus == .ready, let session = snapshotSession else {
|
guard snapshotStatus == .ready, let session = snapshotSession else {
|
||||||
continuation.finish(throwing: AIRuntimeError.notReady)
|
continuation.finish(throwing: AIRuntimeError.notReady)
|
||||||
return
|
return
|
||||||
@@ -74,7 +80,7 @@ actor AIRuntime {
|
|||||||
// session.generate 跨 actor 边界,需要 await
|
// session.generate 跨 actor 边界,需要 await
|
||||||
let stream = await session.generate(prompt: prompt, maxTokens: maxTokens)
|
let stream = await session.generate(prompt: prompt, maxTokens: maxTokens)
|
||||||
for try await chunk in stream {
|
for try await chunk in stream {
|
||||||
await self?.recordRate(chunk.decodeRate)
|
await self.recordRate(chunk.decodeRate)
|
||||||
continuation.yield(chunk)
|
continuation.yield(chunk)
|
||||||
}
|
}
|
||||||
continuation.finish()
|
continuation.finish()
|
||||||
|
|||||||
Reference in New Issue
Block a user