自动保存并恢复助手模型连接设置

This commit is contained in:
tfarcraw 2026-11-13 16:22:15 +08:00
parent e580b74f15
commit 5c07df947e
4 changed files with 50 additions and 17 deletions

View File

@ -18,9 +18,9 @@
生成后逐步显示时间段、参考画面、名称、说明、区域键和提醒,可先修改。点击“将草稿添加到当前配方”才追加步骤,已有步骤和 ID 保留,同一份草稿不能重复添加。完成条件直接使用生成并编辑后的步骤说明;触发规则使用手在区域、离开区域或区域间移动。缺少区域时保留空值并提醒标定,不猜测坐标。到“步骤”页核对左右手、移动起终点及送检范围,最后点击“保存”写入配方文件。
成功分析后仅将地址和模型名记入工作区的 `workspace/sop-agent.json`;密钥只在当前编辑器内存中使用,不落盘。也可通过环境变量 `SOPHELPER_AGENT_ENDPOINT`、`SOPHELPER_AGENT_MODEL`、`SOPHELPER_AGENT_API_KEY` 提供设置。图片会发送到填写的接口。
地址、模型名和密钥修改时自动保存到工作区的 `workspace/sop-agent.json`,无须先成功分析或保存配方,下次启动自动恢复;清空密钥也会保存。该文件包含本地明文密钥,不应分享或提交,Linux 下文件权限限制为当前用户读写。也可通过环境变量 `SOPHELPER_AGENT_ENDPOINT`、`SOPHELPER_AGENT_MODEL`、`SOPHELPER_AGENT_API_KEY` 覆盖设置。图片会发送到填写的接口。
验证使用合成视频与模拟视觉服务,覆盖实际取帧、多图请求、时间/区域校验、草稿编辑、取消、追加和密钥不落盘;尚未连接用户实际视觉模型,不代表真实 SOP 拆解准确率已验证。
验证使用合成视频与模拟视觉服务,覆盖实际取帧、多图请求、时间/区域校验、草稿编辑、取消、追加、设置自动保存和重新打开后的恢复;尚未连接用户实际视觉模型,不代表真实 SOP 拆解准确率已验证。
## 配置接口

View File

@ -26,7 +26,7 @@ pwsh -File tools/Start-HandAiD3.ps1
SOP 流程视频可在配方编辑器中录制和播放,独立保存在该配方的 `sop_stand` 目录。配方选择和相机选择会记忆;恢复选择不会自动开始采集。
“Agent助手”可读取已录好的标准视频或选择本地视频,配置兼容 Chat Completions 的视觉模型完整接口地址、模型名和密钥后,抽取带时间戳的画面生成步骤草稿。草稿包含参考画面、步骤说明和手部触发规则,可修改后追加到当前配方,最后手动保存。地址和模型名会记住,密钥不写入文件。它与运行时 D3-lite 判定接口分开,需使用能生成文字的视觉模型;抽样分析可能漏掉短暂动作,必须核对草稿。详细限制与配置见 [HAND_AI.md](HAND_AI.md)。
“Agent助手”可读取已录好的标准视频或选择本地视频,配置兼容 Chat Completions 的视觉模型完整接口地址、模型名和密钥后,抽取带时间戳的画面生成步骤草稿。草稿包含参考画面、步骤说明和手部触发规则,可修改后追加到当前配方,最后手动保存。地址、模型名和密钥在修改时自动保存,下次启动恢复。它与运行时 D3-lite 判定接口分开,需使用能生成文字的视觉模型;抽样分析可能漏掉短暂动作,必须核对草稿。详细限制与配置见 [HAND_AI.md](HAND_AI.md)。
旧配方的 YOLO 模型绑定会被忽略,物体触发规则会提示已移除;需要手动改成手部/计时规则,并将物品要求写进步骤说明。不会根据旧类别名猜测或重写现场工艺。

View File

@ -20,13 +20,14 @@ public partial class RecipeEditorViewModel
private Task? _agentTask;
private SopVideoSample? _agentSample;
private bool _isAgentBusy, _draftApplied;
private bool _agentSettingsLoaded;
private string _agentEndpoint = "", _agentModel = "", _agentApiKey = "", _agentVideoPath = "", _agentInstructions = "";
private string _agentStatus = "", _agentSummary = "";
private int _agentMaxFrames = 40;
public ObservableCollection<AgentDraftRow> AgentDraftSteps { get; } = [];
public string AgentEndpoint { get => _agentEndpoint; set => SetProperty(ref _agentEndpoint, value); }
public string AgentModel { get => _agentModel; set => SetProperty(ref _agentModel, value); }
public string AgentApiKey { get => _agentApiKey; set => SetProperty(ref _agentApiKey, value); }
public string AgentEndpoint { get => _agentEndpoint; set { if (SetProperty(ref _agentEndpoint, value)) SaveAgentSettings(); } }
public string AgentModel { get => _agentModel; set { if (SetProperty(ref _agentModel, value)) SaveAgentSettings(); } }
public string AgentApiKey { get => _agentApiKey; set { if (SetProperty(ref _agentApiKey, value)) SaveAgentSettings(); } }
public string AgentInstructions { get => _agentInstructions; set => SetProperty(ref _agentInstructions, value); }
public int AgentMaxFrames { get => _agentMaxFrames; set => SetProperty(ref _agentMaxFrames, value); }
public string AgentVideoPath
@ -71,6 +72,7 @@ public partial class RecipeEditorViewModel
private void LoadAgentSettings()
{
_agentSettingsLoaded = false;
try
{
if (File.Exists(AgentSettingsPath))
@ -78,14 +80,38 @@ public partial class RecipeEditorViewModel
using var document = JsonDocument.Parse(File.ReadAllText(AgentSettingsPath));
AgentEndpoint = document.RootElement.GetProperty("endpoint").GetString() ?? "";
AgentModel = document.RootElement.GetProperty("model").GetString() ?? "";
AgentApiKey = document.RootElement.TryGetProperty("apiKey", out var key) ? key.GetString() ?? "" : "";
}
}
catch (Exception) { AgentStatus = "模型连接设置无法读取,请重新填写地址和模型名。"; }
AgentEndpoint = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_ENDPOINT") ?? AgentEndpoint;
AgentModel = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_MODEL") ?? AgentModel;
AgentApiKey = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_API_KEY") ?? "";
AgentApiKey = Environment.GetEnvironmentVariable("SOPHELPER_AGENT_API_KEY") ?? AgentApiKey;
_agentSettingsLoaded = true;
UpdateAgentDefaultVideo();
}
private void SaveAgentSettings()
{
if (!_agentSettingsLoaded) return;
var temporary = AgentSettingsPath + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
Directory.CreateDirectory(Path.GetDirectoryName(AgentSettingsPath)!);
var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write };
if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
using (var stream = new FileStream(temporary, options))
JsonSerializer.Serialize(stream, new { endpoint = AgentEndpoint, model = AgentModel, apiKey = AgentApiKey });
File.Move(temporary, AgentSettingsPath, overwrite: true);
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{ AgentStatus = "模型设置保存失败。"; }
finally
{
try { File.Delete(temporary); }
catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
}
}
private void UpdateAgentDefaultVideo()
{
if (string.IsNullOrWhiteSpace(AgentVideoPath) && SopRecording is not null) AgentVideoPath = SopRecording.StandardVideoPath;
@ -120,13 +146,6 @@ public partial class RecipeEditorViewModel
AgentSummary = draft.Summary + (draft.Warnings.Count == 0 ? "" : "\n需核对:" + string.Join(";", draft.Warnings));
_draftApplied = false;
AgentStatus = $"已生成 {draft.Steps.Count} 步,抽取 {sample.Frames.Count} 帧。";
try
{
Directory.CreateDirectory(Path.GetDirectoryName(AgentSettingsPath)!);
File.WriteAllText(AgentSettingsPath, JsonSerializer.Serialize(new { endpoint = connection.Endpoint, model = connection.Model }));
}
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{ AgentStatus += " 连接设置未能记住。"; }
}
catch (OperationCanceledException) { AgentStatus = "分析已取消或超时,当前配方未修改。"; }
catch (Exception error) when (error is ArgumentException or InvalidDataException or FileNotFoundException or FormatException)

View File

@ -724,7 +724,22 @@ internal static class Smoke
}
var client=new UiSopAgent();model.AgentClient=client;
model.AgentVideoPath=video;model.AgentEndpoint="https://custom.invalid/v1/chat/completions";
model.AgentModel="custom-vision";model.AgentApiKey="not-to-be-saved";model.AgentMaxFrames=4;
model.AgentModel="custom-vision";model.AgentApiKey="remember-test-key";model.AgentMaxFrames=4;
var settingsPath=Path.Combine(store.Root,"workspace","sop-agent.json");
Check(File.ReadAllText(settingsPath).Contains("custom-vision"),"Model settings are saved before any analysis request");
async Task<RecipeEditorViewModel> ReopenAgent()
{
var restored=new RecipeEditorViewModel();
restored.OnDialogOpened(new DialogParameters{{"directory",store.RecipesDirectory},{"new",true}});
await restored.ShutdownAsync();
return restored;
}
var reopened=await ReopenAgent();
Check(reopened.AgentEndpoint==model.AgentEndpoint&&reopened.AgentModel==model.AgentModel&&reopened.AgentApiKey==model.AgentApiKey,
"A fresh editor restores endpoint, model and key without requiring successful analysis");
model.AgentApiKey="";
Check((await ReopenAgent()).AgentApiKey=="","Clearing the key persists across editor restarts");
model.AgentApiKey="remember-test-key";
var originalCount=model.Recipe.Steps.Count;
var configPath=store.ConfigPath("手部AI验证");var before=File.ReadAllBytes(configPath);
var tabs=editor.GetVisualDescendants().OfType<TabControl>().First();tabs.SelectedIndex=4;await Task.Delay(30);
@ -734,8 +749,7 @@ internal static class Smoke
Check(!model.IsAgentBusy&&model.AgentDraftSteps.Count==2,"Assistant samples video and presents model-generated draft steps");
Check(client.Connection?.Endpoint==model.AgentEndpoint&&client.Connection.Model==model.AgentModel&&client.Request?.Video.Frames.Count==3,"Assistant uses current connection and real sampled frames");
Check(model.Recipe.Steps.Count==originalCount&&File.ReadAllBytes(configPath).SequenceEqual(before),"Generating a draft does not replace steps or write the recipe");
var settings=File.ReadAllText(Path.Combine(store.Root,"workspace","sop-agent.json"));
Check(settings.Contains("custom-vision")&&!settings.Contains(model.AgentApiKey)&&!settings.Contains("apiKey"),"Only endpoint/model are remembered; key is not persisted");
Check((await ReopenAgent()).AgentApiKey==model.AgentApiKey,"Successful analysis preserves the saved key");
model.AgentDraftSteps[0].Description="把连接器放入盒子,盒内可见连接器";
Save(dialog,"sop-video-agent-draft");
client.Hold=true;