From a4f4f03b5efbcb261b69d46c44bec8d473a8172c Mon Sep 17 00:00:00 2001 From: nick Date: Thu, 5 Nov 2026 20:31:55 +0000 Subject: [PATCH] Recover ClickOnce upgrades and start the registered matching agent --- .../2026-11-05-usability-recovery.md | 18 ++++++++ .../DeveloperVersion.props | 2 +- .../Vsto/AgentProcess.cs | 34 ++++++++++++-- .../Vsto/CompanionSettingsWindow.cs | 9 +++- .../Vsto/Properties/AssemblyInfo.cs | 4 +- .../Vsto/WordAdapter.cs | 8 ++-- .../Install-WordCompanion.ps1 | 45 ++++++++++++++++++- .../Update-WordCompanion.ps1 | 4 +- 8 files changed, 110 insertions(+), 14 deletions(-) diff --git a/Docs/WordCompanion/2026-11-05-usability-recovery.md b/Docs/WordCompanion/2026-11-05-usability-recovery.md index e67c2508..663b2d47 100644 --- a/Docs/WordCompanion/2026-11-05-usability-recovery.md +++ b/Docs/WordCompanion/2026-11-05-usability-recovery.md @@ -38,3 +38,21 @@ The Windows managed Release solution and signed VSTO host compile with the exist The author's Word UI checks remain distinct from automation. In particular, real book persistence across save/reopen, modeless focus/DPI, historic COM error reproduction and 155k/190k/250k responsiveness require actual Word interaction. A successful build is not desktop acceptance. Automated Windows results for recovery source: managed Release build and VSTO compile passed with zero warnings/errors; 192 native assertions passed; native pairing, actual HTTP pairing/auth/AI gates and saved-workspace/import-preview checks passed. The full application harness reproduced the previously observed Windows CoreImportWizardOrdersScenesBeforeCharacters assertion, “Saving chapter review should validate only structure before scene import.” That importer path was not changed. PowerShell parsing and ribbon XML parsing passed. + +## Windows installation finding + +The first Word launch exposed a VSTO runtime conflict that a registry-only staging script could not detect: “The customization cannot be installed because another version is currently installed and cannot be upgraded from this location.” The account had a ClickOnce 1.0.0.6 subscription in HKCU uninstall records, while the new per-user developer registration pointed at another signed package folder. + +Install-WordCompanion.ps1 now detects only the exact PlotDirector.WordAddIn ClickOnce product, validates its local deployment URI, records the original URI/version in previous-clickonce.json and invokes the existing VSTOInstaller /Uninstall for that product before developer registration. The original 1.0.0.6 signed package is retained. Rollback supports restoring its ClickOnce deployment with VSTOInstaller /Install, as well as restoring prior per-user Word registry values. It never runs arbitrary uninstall strings or touches unrelated PlotDirector PWA registrations. + +The account's 1.0.0.6 VSTO uninstall succeeded. The 1.0.0.7 registration was reapplied, and Word reached the normal local-certificate trust prompt. Accepting this prompt is an author action. No certificate or machine trust setting was altered. + +## Final recovery build 1.0.0.8 + +Live Word checks with the interim 1.0.0.7 build confirmed the new ribbon, searchable authorised book list, explicit Remember selection, selected book title and enabled workspace action. The blank synthetic document was saved as PlotDirector-Recovery-Test.docx in Downloads. Its DOCX package contains the single association property with all three identity/book/site fields. No author manuscript was edited for this test. + +Two further Windows defects were found during this qualification. AgentProcess.Start originally searched only beside Assembly.Location. VSTO can shadow-copy that DLL without the Agent directory; manual launch of the matching agent restored connection. The startup resolver now falls back to a per-user registered local package only when its add-in DLL hash exactly matches the loaded DLL, then launches its adjacent agent on the existing worker. No executable path search or Word-thread network work was added. + +The established Update script's Office Clean target also invokes UnregisterOfficeAddin and RemoveOfficeAddInSecurity. Running Clean during the recovery build removed the test registration. The corrected update procedure uses Build;VisualStudioForApplicationsBuild with PrepareForRunDependsOn=CopyFilesToOutputDirectory and omits Clean. The installation is reapplied after building. This prevents future preparation from unregistering the tested add-in. The update remote is read from the shared branch's configured tracking remote. + +The final build also labels the book-title search explicitly and ensures remembered books without a server project identifier never generate an invalid half-populated ProjectId/BookId descriptor. Native book authorisation remains in the existing workspace flow. ClickOnce/registry rollback records are archived before replacement so earlier recovery steps remain recoverable. diff --git a/PlotDirector.NativeCompanion/DeveloperVersion.props b/PlotDirector.NativeCompanion/DeveloperVersion.props index 0c8a70c6..ada6f0a4 100644 --- a/PlotDirector.NativeCompanion/DeveloperVersion.props +++ b/PlotDirector.NativeCompanion/DeveloperVersion.props @@ -1 +1 @@ -1.0.0.7 +1.0.0.8 diff --git a/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs b/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs index 1abd0386..33edc708 100644 --- a/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs +++ b/PlotDirector.NativeCompanion/Vsto/AgentProcess.cs @@ -7,11 +7,14 @@ using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Principal; using System.Text; +using System.Linq; +using Microsoft.Win32; namespace PlotDirector.WordAddIn { internal static class AgentProcess { + internal static string LaunchStatus {get;private set;}="Not requested"; internal static string PipeName() { var value = WindowsIdentity.GetCurrent().User.Value + ":" + Process.GetCurrentProcess().SessionId; @@ -20,11 +23,36 @@ namespace PlotDirector.WordAddIn // Called only on the IPC worker. No Word objects, UI calls or shell search paths. internal static void Start() { - var root = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - var executable = Path.Combine(root,"Agent","PlotDirector.Companion.Agent.exe"); - if (!File.Exists(executable)) return; + var assembly=Assembly.GetExecutingAssembly().Location; + var executable=Path.Combine(Path.GetDirectoryName(assembly),"Agent","PlotDirector.Companion.Agent.exe"); + if(!File.Exists(executable))executable=FindRegisteredAgent(assembly); + if(string.IsNullOrEmpty(executable)){LaunchStatus="Matching agent missing from the registered package. Reinstall the complete package.";return;} + LaunchStatus="Starting the matching local agent"; using (Process.Start(new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = Path.GetDirectoryName(executable) })) { } } + private static string FindRegisteredAgent(string loadedAssembly) + { + // VSTO can shadow-copy the DLL without its adjacent Agent directory. + // Resolve only a registered local package containing the exact DLL bytes. + using(var registrations=Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Office\Word\Addins")) + using(var hash=SHA256.Create()) + { + if(registrations==null||!File.Exists(loadedAssembly))return null; + byte[] expected;using(var stream=File.OpenRead(loadedAssembly))expected=hash.ComputeHash(stream); + foreach(var key in registrations.GetSubKeyNames().Take(64)) + using(var entry=registrations.OpenSubKey(key)) + { + var manifest=(entry?.GetValue("Manifest") as string??"").Split('|')[0]; + if(!Uri.TryCreate(manifest,UriKind.Absolute,out var uri)||!uri.IsFile||Path.GetFileName(uri.LocalPath)!="PlotDirector.WordAddIn.vsto")continue; + var root=Path.GetDirectoryName(uri.LocalPath); + var candidate=Path.Combine(root,"PlotDirector.WordAddIn.dll"); + var agent=Path.Combine(root,"Agent","PlotDirector.Companion.Agent.exe"); + if(!File.Exists(candidate)||!File.Exists(agent))continue; + using(var stream=File.OpenRead(candidate))if(hash.ComputeHash(stream).SequenceEqual(expected))return agent; + } + } + return null; + } internal static bool VerifyOwner(NamedPipeClientStream pipe) { uint processId; diff --git a/PlotDirector.NativeCompanion/Vsto/CompanionSettingsWindow.cs b/PlotDirector.NativeCompanion/Vsto/CompanionSettingsWindow.cs index 313754ac..34ab1f1c 100644 --- a/PlotDirector.NativeCompanion/Vsto/CompanionSettingsWindow.cs +++ b/PlotDirector.NativeCompanion/Vsto/CompanionSettingsWindow.cs @@ -29,7 +29,12 @@ namespace PlotDirector.WordAddIn for(var i=0;i<7;i++)layout.RowStyles.Add(new RowStyle(i==3?SizeType.Percent:SizeType.AutoSize,i==3?100:0)); layout.Controls.Add(new Label{Text="Choose the PlotDirector book for "+adapter.DocumentName,AutoSize=true},0,0); layout.Controls.Add(status,0,1); - search.Margin=new Padding(0,10,0,6);layout.Controls.Add(search,0,2); + var searchLayout=new TableLayoutPanel{Dock=DockStyle.Fill,AutoSize=true,ColumnCount=1,RowCount=2,Margin=new Padding(0,10,0,6)}; + searchLayout.ColumnStyles.Add(new ColumnStyle(SizeType.Percent,100)); + searchLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize));searchLayout.RowStyles.Add(new RowStyle(SizeType.AutoSize)); + search.AccessibleName="Search books by title"; + searchLayout.Controls.Add(new Label{Text="Search books by title (leave empty to show all)",AutoSize=true},0,0); + searchLayout.Controls.Add(search,0,1);layout.Controls.Add(searchLayout,0,2); layout.Controls.Add(books,0,3);layout.Controls.Add(remember,0,4); layout.Controls.Add(new Label{Text="Search by book title above. Connecting a book does not upload manuscript text.\nRemember stores the book, site and document identifier in one custom property. It marks the document modified. Save normally to keep it after reopening. Leaving Remember unchecked keeps the selection for this session and preserves any previously saved association.",AutoSize=true,MaximumSize=new Size(620,0),Margin=new Padding(0,8,0,8)},0,5); var actions=new FlowLayoutPanel{AutoSize=true,Dock=DockStyle.Fill}; @@ -57,7 +62,7 @@ namespace PlotDirector.WordAddIn selected=previous; } confirm.Enabled=adapter.CanSelectBook&&books.SelectedItem is CompanionBook; - status.Text=adapter.CanSelectBook?available.Length+" accessible books. Current book: "+adapter.BookTitle: + status.Text=adapter.CanSelectBook?available.Length+" accessible books. Current book: "+adapter.BookTitle+(available.Length>0&&filtered.Length==0?". No books match your search; clear the search field to show all.":""): "Sign in and refresh connection to load books you can access. "+adapter.CloudState; } protected override void Dispose(bool disposing){if(disposing)refresh.Dispose();base.Dispose(disposing);} diff --git a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs index 4060ee9e..7a9b11d4 100644 --- a/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs +++ b/PlotDirector.NativeCompanion/Vsto/Properties/AssemblyInfo.cs @@ -3,6 +3,6 @@ using System.Runtime.InteropServices; [assembly: AssemblyTitle("PlotDirector Word Companion — Native development")] [assembly: AssemblyCompany("Nick Beckley")] [assembly: AssemblyProduct("PlotDirector")] -[assembly: AssemblyVersion("1.0.0.7")] -[assembly: AssemblyFileVersion("1.0.0.7")] +[assembly: AssemblyVersion("1.0.0.8")] +[assembly: AssemblyFileVersion("1.0.0.8")] [assembly: ComVisible(false)] diff --git a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs index 2bd17606..54de1dbe 100644 --- a/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs +++ b/PlotDirector.NativeCompanion/Vsto/WordAdapter.cs @@ -68,6 +68,7 @@ namespace PlotDirector.WordAddIn public string Diagnostics => "PlotDirector " + typeof(WordAdapter).Assembly.GetName().Version + "\nAgent: " + ConnectionState + "\nServer: "+cloudState+" · Prose sync: unavailable\nOpen sessions: " + documents.Count + "\nIPC queued: " + link.QueueDepth + "\nWord work queued: " + scheduler.Depth + + "\nAgent startup: " + AgentProcess.LaunchStatus + "\nMain document words: " + WordCountSummary + "\nLast UI batch ms: " + lastBatchMs.ToString("F2") + "\nMax recorded COM call ms: " + (operationTimes.Count == 0 ? 0 : operationTimes.Max()).ToString("F2") + "\nCOM busy/errors: " + busyFailures + (lastWordError == null ? "" : " (last: " + lastWordError + ")") + "\n" + lastResult; @@ -196,7 +197,7 @@ namespace PlotDirector.WordAddIn state.BookId = ReadPositiveProperty(document,"PlotDirector.Native.BookID"); state.AssociationSite=ReadProperty(document,"PlotDirector.Native.ServerUrl"); if(DocumentBinding.ReadAssociation(ReadProperty(document,DocumentBinding.AssociationProperty),out var identity,out var rememberedBook,out var rememberedSite)) - {state.Identity=identity;state.IdentityPersisted=true;state.BookId=rememberedBook;state.AssociationSite=rememberedSite;} + {state.Identity=identity;state.IdentityPersisted=true;state.ProjectId=null;state.BookId=rememberedBook;state.AssociationSite=rememberedSite;} state.End = DocumentEnd(document); state.WasSaved = Com(() => document.Saved); documents.Add(document,state); RegisterState(state); RestoreAssociations(); @@ -252,7 +253,8 @@ namespace PlotDirector.WordAddIn finally { Release(range); } } private DocumentDescriptor Descriptor(LocalDocument doc) => new DocumentDescriptor { - SessionId=doc.Session,ManuscriptId=doc.Identity,ProjectId=doc.ProjectId,BookId=doc.BookId, + SessionId=doc.Session,ManuscriptId=doc.Identity, + ProjectId=doc.BookId.HasValue?doc.ProjectId:null,BookId=doc.ProjectId.HasValue?doc.BookId:null, Revision=doc.Revision,IdentityPersisted=doc.IdentityPersisted,AssociationVerified=false }; public void AnalyseDocument() @@ -572,7 +574,7 @@ namespace PlotDirector.WordAddIn try{WriteProperty(doc.Document,DocumentBinding.AssociationProperty,DocumentBinding.AssociationValue(doc.Identity,book,site),Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString);} catch(Exception error) when(error is COMException||error is ArgumentException||error is InvalidOperationException) {MessageBox.Show("Word could not remember the book in this document. You can select it again with Remember unchecked for this session. Nothing was uploaded or saved.","PlotDirector");throw;} - doc.IdentityPersisted=true;doc.BookId=book;doc.AssociationSite=site; + doc.IdentityPersisted=true;doc.ProjectId=null;doc.BookId=book;doc.AssociationSite=site; ApplyBookSelection(doc,book);link.Register(Descriptor(doc)); MessageBox.Show("Book connected. Save the document normally to remember this association after reopening. No manuscript text was uploaded.","PlotDirector"); })){MessageBox.Show("Word is busy. Please select the book again.","PlotDirector");return false;} diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Install-WordCompanion.ps1 b/PlotDirector.NativeCompanion/WindowsValidation/Install-WordCompanion.ps1 index 67f9c129..4db8a673 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Install-WordCompanion.ps1 +++ b/PlotDirector.NativeCompanion/WindowsValidation/Install-WordCompanion.ps1 @@ -9,6 +9,36 @@ $registration=Get-WordCompanionRegistration $keyName=if($registration){$registration.Name}else{'PlotDirector.WordAddIn'} $registry=Join-Path 'HKCU:\Software\Microsoft\Office\Word\Addins' $keyName $backup=Join-Path $root 'previous-registration.json' +$clickOnceBackup=Join-Path $root 'previous-clickonce.json' +function Save-InstallBackup([string]$path,$value) { + if(Test-Path -LiteralPath $path){ + $history=Join-Path $root 'history' + New-Item -ItemType Directory -Path $history -Force|Out-Null + $name=(Get-Date -Format 'yyyyMMddHHmmss')+'-'+[guid]::NewGuid().ToString('N')+'-'+[IO.Path]::GetFileName($path) + Copy-Item -LiteralPath $path -Destination (Join-Path $history $name) + } + $value|ConvertTo-Json -Depth 4|Set-Content -LiteralPath $path -Encoding UTF8 +} +function Get-CompanionClickOnce { + $found=@(Get-ChildItem 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall' -ErrorAction SilentlyContinue | ForEach-Object { + $entry=Get-ItemProperty $_.PSPath + if(($entry.PSObject.Properties.Name -contains 'DisplayName') -and $entry.DisplayName -eq 'PlotDirector.WordAddIn'){ + if(!($entry.PSObject.Properties.Name -contains 'UrlUpdateInfo')){throw 'The installed Companion has no recoverable deployment location.'} + $uri=$null + if(![uri]::TryCreate([string]$entry.UrlUpdateInfo,[UriKind]::Absolute,[ref]$uri) -or !$uri.IsFile -or [IO.Path]::GetFileName($uri.LocalPath) -ne 'PlotDirector.WordAddIn.vsto' -or !(Test-Path -LiteralPath $uri.LocalPath)){throw 'The installed ClickOnce Companion manifest is unavailable. No installation was removed.'} + [pscustomobject]@{manifest=$uri.AbsoluteUri;version=$entry.DisplayVersion} + } + }) + if($found.Count -gt 1){throw 'Multiple ClickOnce Companion installations exist; no installation was changed.'} + if($found.Count -eq 1){return $found[0]} + return $null +} +function Invoke-CompanionVsto([string]$operation,[string]$manifest) { + $installer=Join-Path $env:CommonProgramFiles 'Microsoft Shared\VSTO\10.0\VSTOInstaller.exe' + if(!(Test-Path -LiteralPath $installer)){throw 'Existing VSTO installer was not found. No runtime installation or repair was attempted.'} + $process=Start-Process -FilePath $installer -ArgumentList @($operation,('"'+$manifest+'"'),'/Silent') -Wait -PassThru -WindowStyle Hidden + if($process.ExitCode -ne 0){throw "VSTO $operation failed with exit code $($process.ExitCode). Previous deployment: $manifest. No system repair was attempted."} +} function Stop-DeveloperAgent { foreach($agent in @(Get-Process 'PlotDirector.Companion.Agent' -ErrorAction SilentlyContinue)){ if(!$StopAgent){throw 'The companion agent is running. Rerun with -StopAgent to explicitly stop this user-session agent. Word must already be closed.'} @@ -25,6 +55,12 @@ if($Rollback){ if($saved.PSObject.Properties.Name -contains 'registryKey'){if($saved.registryKey -notmatch '^[a-zA-Z0-9._ -]+$'){throw 'Invalid saved registration key.'};$registry=Join-Path 'HKCU:\Software\Microsoft\Office\Word\Addins' $saved.registryKey} if($PSCmdlet.ShouldProcess($registry,'Restore previous per-user Word registration')){ Stop-DeveloperAgent + if(Test-Path -LiteralPath $clickOnceBackup){ + $previous=Get-Content -Raw -LiteralPath $clickOnceBackup|ConvertFrom-Json + $installed=Get-CompanionClickOnce + if($installed -and $installed.manifest -ne $previous.manifest){Invoke-CompanionVsto '/Uninstall' $installed.manifest} + if(!$installed -or $installed.manifest -ne $previous.manifest){Invoke-CompanionVsto '/Install' $previous.manifest} + } if($saved.existed){New-Item -Path $registry -Force|Out-Null;foreach($name in @('Manifest','LoadBehavior','FriendlyName','Description')){Remove-ItemProperty -Path $registry -Name $name -ErrorAction SilentlyContinue};foreach($property in $saved.values.PSObject.Properties){$type=if($property.Name -eq "LoadBehavior"){"DWord"}else{"String"};New-ItemProperty -Path $registry -Name $property.Name -Value $property.Value -PropertyType $type -Force|Out-Null}} elseif(Test-Path $registry){Remove-Item -LiteralPath $registry -Recurse} Write-Output 'Previous registration restored. Signed packages were retained. Open Word to verify.' @@ -40,10 +76,17 @@ if($PSCmdlet.ShouldProcess($destination,'Stage signed package and register VSTO if(!(Test-Path -LiteralPath $destination)){New-Item -ItemType Directory -Path $destination -Force|Out-Null;Copy-Item -Path (Join-Path $PackagePath '*') -Destination $destination -Recurse} $null=Test-DeveloperPackage $destination $manifest=([uri](Join-Path $destination 'PlotDirector.WordAddIn.vsto')).AbsoluteUri+'|vstolocal' + $installed=Get-CompanionClickOnce + if($installed -and ($installed.manifest+'|vstolocal') -ne $manifest){ + # ClickOnce rejects the same product loaded from a different deployment location. + # Retain its exact URI and original signed files for supported VSTO rollback. + Save-InstallBackup $clickOnceBackup $installed + Invoke-CompanionVsto '/Uninstall' $installed.manifest + } $current=Get-ItemProperty -Path $registry -ErrorAction SilentlyContinue if($current -and $current.Manifest -eq $manifest){Write-Output "Version $($package.version) is already registered. No backup replaced.";return} $values=@{};if($current){foreach($name in @('Manifest','LoadBehavior','FriendlyName','Description')){if($current.PSObject.Properties.Name -contains $name){$values[$name]=$current.$name}}} - @{registryKey=$keyName;existed=[bool]$current;values=$values} | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $backup -Encoding UTF8 + Save-InstallBackup $backup @{registryKey=$keyName;existed=[bool]$current;values=$values} try{ New-Item -Path $registry -Force|Out-Null New-ItemProperty -Path $registry -Name Manifest -PropertyType String -Value $manifest -Force|Out-Null diff --git a/PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1 b/PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1 index 2fbcf7bf..15fa865b 100644 --- a/PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1 +++ b/PlotDirector.NativeCompanion/WindowsValidation/Update-WordCompanion.ps1 @@ -42,8 +42,8 @@ try { Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion') Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-companion-http') Invoke-Checked dotnet @('run','--no-build','-c','Release','--project','PlotLine.Tests/PlotLine.Tests.csproj','--','--native-workflow') - # The qualified command-line target bypasses Office registration/F5 while generating signed manifests. - Invoke-Checked $msbuild @('PlotDirector.NativeCompanion\Vsto\PlotDirector.WordAddIn.csproj','/restore','/t:Clean;Build;VisualStudioForApplicationsBuild','/p:Configuration=Release','/p:PrepareForRunDependsOn=CopyFilesToOutputDirectory','/p:SignManifests=true',"/p:ManifestCertificateThumbprint=$CertificateThumbprint","/p:ApplicationVersion=$version") + # Office Clean unregisters the installed add-in. Build signed outputs without that target or F5 registration. + Invoke-Checked $msbuild @('PlotDirector.NativeCompanion\Vsto\PlotDirector.WordAddIn.csproj','/restore','/t:Build;VisualStudioForApplicationsBuild','/p:Configuration=Release','/p:PrepareForRunDependsOn=CopyFilesToOutputDirectory','/p:SignManifests=true',"/p:ManifestCertificateThumbprint=$CertificateThumbprint","/p:ApplicationVersion=$version") $bin=Join-Path $repo 'PlotDirector.NativeCompanion\Vsto\bin\Release' $staging=$output+'.preparing-'+[guid]::NewGuid().ToString('N') New-Item -ItemType Directory -Path $staging -Force | Out-Null