Repository: microsoft/terminal (language: cpp)

Issue:
Settings could not be loaded from file. Element not found (when running unpackaged)
### Windows Terminal version

Preview 1.11.2421

### Windows build number

10.0.18363

### Other Software

_No response_

### Steps to reproduce

Install the Preview version from this link then open. Can't open the settings file and can't save settings after change

### Expected Behavior

Was expecting to load and be able to open and set the default profile

### Actual Behavior

Got the following dialog:
![TerminalIssue](https://user-images.githubusercontent.com/92752337/151882485-bc038602-2208-4252-9d53-38042f420254.png)
 
I see no settings.json file in the installation and the one named defaults.json doesn't change. Also, there was no directory created here: %LOCALAPPDATA%\Packages\Microsoft. WindowsTerminal_8wekyb3d8bbwe\LocalState\

I found it here: %USERPROFILE%\AppData\Local\Microsoft\Windows Terminal 
But after checking for well-formed JSON, it looks correct. Just can't understand why it won't open.

Not sure if it matters but I did NOT run through and actual installation, I renamed the files, msixbundle/msix, as zip and extracted them


Discussion / hints:
Can you share the actual json file, and maybe also the contents of `state.json`, if there is one next to `settings.json`?
```
// This file was initially generated by Windows Terminal 0.11.1333.0    
// It should still be usable in newer versions, but newer versions might have additional    
// settings, help text, or changes that you will not see unless you clear this file    
// and let us generate a new one for you.    
    
// To view the default settings, hold "alt" while clicking on the "Settings" button.    
// For documentation on these settings, see: https://aka.ms/terminal-documentation    
{    
    "$schema": "https://aka.ms/terminal-profiles-schema",    
    
    "defaultProfile": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",    

    // You can add more global application settings here.
    // To learn more about global settings, visit https://aka.ms/terminal-global-settings

    // If enabled, selections are automatically copied to your clipboard.
    "copyOnSelect": false,

    // If enabled, formatted data is also copied to your clipboard
    "copyFormatting": false,

    // A profile specifies a command to execute paired with information about how it should look and feel.
    // Each one of them will appear in the 'New Tab' dropdown,
    //   and can be invoked from the commandline with `wt.exe -p xxx`
    // To learn more about profiles, visit https://aka.ms/terminal-profile-settings
    "profiles":
    {
        "defaults":
        {
            // Put settings here that you want to apply to all profiles.
        },
      "list": [
        {
          // Make changes here to the powershell.exe profile.
          "guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
          "name": "Windows PowerShell",
          "commandline": "powershell.exe",
          "hidden": false
        },
        {
          // Make changes here to the cmd.exe profile.
          "guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
          "name": "Command Prompt",
          "commandline": "cmd.exe",
          "hidden": false
        }
      ]
    },

    // Add custom color schemes to this array.
    // To learn more about color schemes, visit https://aka.ms/terminal-color-schemes
    "schemes": [],

    // Add custom keybindings to this array.
    // To unbind a key combination from your defaults.json, set the command to "unbound".
    // To learn more about keybindings, visit https://aka.ms/terminal-keybindings
    "keybindings":
    [
        // Copy and paste are bound to Ctrl+Shift+C and Ctrl+Shift+V in your defaults.json.
        // These two lines additionally bind them to Ctrl+C and Ctrl+V.
        // To learn more about selection, visit https://aka.ms/terminal-selection
        { "command": {"action": "copy", "singleLine": false }, "keys": "ctrl+c" },
        { "command": "paste", "keys": "ctrl+v" },

        // Press Ctrl+Shift+F to open the search box
        { "command": "find", "keys": "ctrl+shift+f" },

        // Press Alt+Shift+D to open a new pane.
        // - "split": "auto" makes this pane open in the direction that provides the most surface area.
        // - "splitMode": "duplicate" makes the new pane use the focused pane's profile.
        // To learn more about panes, visit https://aka.ms/terminal-panes
        { "command": { "action": "splitPane", "split": "auto", "splitMode": "duplicate" }, "keys": "alt+shift+d" }
    ]
}
```
There is no state.json file. I found the location of settings.json is actually in
%USERPROFILE%\AppData\Local\Microsoft\Windows Terminal
instead of in
%USERPROFILE%\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState

Even if I copy the file to both locations, I still get the error dialog.

I tried unzipping to a new installation folder after deleting the above directories. It did not create the LocalState folder upon running or editing the settings; it crated the other folder but there is no settings.json file there. I clicked the _Open JSON file_ button, it opened Visual Studio with no file open. Making changes to the settings results in the same error when attempting to save.

The error dialog says "Element not found" What element is it looking for, do you think?
I've got the same issue after updating windows terminal via scoop to the latest stable version. Uninstalling/reinstalling did not help. The json files were valid too.

I have uninstalled the latest version and reinstalled [1.11.3471.0](https://github.com/microsoft/terminal/releases/tag/v1.11.3471.0) and everything works again.

One thing I noticed is that after windows terminal loads the default settings since it cannot read the settings.json apparently, in the default config there is no wsl. If I remember correctly, wsl is detected automatically also in the default config right? So maybe the latest version has a problem that is somehow related to wsl? I did remove the wsl part of my config but that did not help though. Also it did not help to remove all the files from `\AppData\Local\Microsoft\Windows Terminal`. 
@JSamir Thanks for that, I downloaded that version and it worked for me. I'm just curious as to what is causing the error

@zadjii-msft  Mike, any ideas on why it happened?
Honestly, no idea. `%USERPROFILE%\AppData\Local\Microsoft\Windows Terminal` is a perfectly fine place for the settings to be if you're running unpackaged (which is what happens when the Terminal is installed from scoop).


Only theory is that we somehow failed to create the settings file entirely, but that should give a more descriptive error... Actually I think it's supposed to: #7950
Same problem here. After update from scoop, settings.json can't be loaded anymore. I tried to remove the `%USERPROFILE%\AppData\Local\Microsoft\Windows Terminal` completely. At next startup the folder is created again and I get the error nonetheless.

```
Terminal (Unpackaged)
Version: 1.12.220208003-release1.12
```
Since we've got a number of reports of this happening for unpackaged installs, I'm gonna bump this one into 1.14, so we make sure someone takes a look sooner than later. I wonder if this has anything to do with `state.json` loading? I honestly have no idea. 
Well, the `state.json` is created in that same folder. But I removed it so... 
~I had this happen to me as well when my instance of WT preview updated from 1.12.x to 1.13 through the store so it isn't just unpackaged installs,.~

I misremembered and had a different error than this / cannot reproduce.
I can't replicate this issue personally with neither 1.12 nor 1.13. I also tried using the settings.json posted at the beginning of this issue.

Can someone who has this issue try and download the latest release on GitHub, extract it and run it? Basically:
* [Download a release](https://github.com/microsoft/terminal/releases/tag/v1.12.10393.0)
* Extract the .msixbundle (it's just a zip)
* Extract the .msix file matching your platform (it's also a zip)
* Run WindowsTerminal.exe

I just want to make sure whether running our "official release" unpackaged would produce the same issue, since I personally can't...
> I can't replicate this issue personally with neither 1.12 nor 1.13. I also tried using the settings.json posted at the beginning of this issue.
> 
> Can someone who has this issue try and download the latest release on GitHub, extract it and run it? Basically:
> 
>     * [Download a release](https://github.com/microsoft/terminal/releases/tag/v1.12.10393.0)
> 
>     * Extract the .msixbundle (it's just a zip)
> 
>     * Extract the .msix file matching your platform (it's also a zip)
> 
>     * Run WindowsTerminal.exe
> 
> 
> I just want to make sure whether running our "official release" unpackaged would produce the same issue, since I personally can't...

Can confirm I can reproduce the issue with above steps using versions v1.12.10393.0 and v1.13.10395.0.
> Can someone who has this issue try and download the latest release on GitHub, extract it and run it? Basically:
> 
>     * [Download a release](https://github.com/microsoft/terminal/releases/tag/v1.12.10393.0)
> 
>     * Extract the .msixbundle (it's just a zip)
> 
>     * Extract the .msix file matching your platform (it's also a zip)
> 
>     * Run WindowsTerminal.exe

This is exactly what I reported the very first time with 1.12.10393.0 (see https://github.com/microsoft/terminal/issues/12547)
Ah dang, I only read the most recent comments in this issue. I'm sorry about that. 😕
I'll try to replicate the issue on Windows 10, but I suspect I won't succeed with that either.
Since only someone who's able to reproduce the issue can fix it, this bug is a bit troublesome unfortunately...
This happened in Preview 1.11.2421
Initially, I did NOT run through an actual installation, I renamed the files, msixbundle/msix, as zip and extracted them.

The error dialog says "Element not found" What element is it looking for, do you think?
> The error dialog says "Element not found" What element is it looking for, do you think?

It's probably a `ERROR_NOT_FOUND` or `TYPE_E_ELEMENTNOTFOUND`. You could try to run [DebugView](https://docs.microsoft.com/en-us/sysinternals/downloads/debugview) and see if anything obvious comes up when you start Windows Terminal. There's a good chance that the source of this error is written in there.
I tried to build it from source, but it has proven very hard.
Would it not be possible to provide a "debug/logging" version which tells a bit more which file and which element is looking for?
I downloaded 1.11.3471.0 and the error didn't occur, so it has to be some change that happened between those versions.
Do you happen to have any files in...

```
C:\ProgramData\Microsoft\Windows Terminal\Fragments
%LOCALAPPDATA%\Microsoft\Windows Terminal\Fragments
```
?

If not, can you run the following PowerShell command? It might produce a lot of output...

```powershell
Get-AppxPackage | ? {
    If (-Not [String]::IsNullOrEmpty($_.InstallLocation)) {
        $am = [xml](Get-Content (Join-Path $_.InstallLocation "AppxManifest.xml"))
        $am.InnerXml.Contains("terminal.settings")
        Return
    }
    $False
} | Select -Expand PackageFullName
```
I was able to downgrade to version 1.11.3471.0 and everything worked as desired.
In addition to the request above, would you mind collecting a trace for us? I'd love to get this issue kicked once and for all. [Here is how to capture a trace](https://github.com/microsoft/terminal/wiki/Capturing-a-Debug-ETL-Trace).
Running 1.12.10393.0 in VS2019

![image](https://user-images.githubusercontent.com/212523/158064779-4269e3e5-b28e-4577-95e7-c9685888a5f9.png)

any useful?
I have a trace but it is inside the corporate network... I will have to ask how to bring it out. Anything I could do with it?

Maybe make it readable and take a screenshot?



Fix patch:
diff --git a/.github/actions/spelling/expect/expect.txt b/.github/actions/spelling/expect/expect.txt
index b08ed0b9011..0ae5cecb6a7 100644
--- a/.github/actions/spelling/expect/expect.txt
+++ b/.github/actions/spelling/expect/expect.txt
@@ -2575,6 +2575,7 @@ uuidv
 UVWX
 UVWXY
 UWA
+UWAs
 uwp
 uxtheme
 vals
diff --git a/src/cascadia/TerminalSettingsModel/CascadiaSettingsSerialization.cpp b/src/cascadia/TerminalSettingsModel/CascadiaSettingsSerialization.cpp
index 483f74c6cb6..e008c5e6d61 100644
--- a/src/cascadia/TerminalSettingsModel/CascadiaSettingsSerialization.cpp
+++ b/src/cascadia/TerminalSettingsModel/CascadiaSettingsSerialization.cpp
@@ -27,6 +27,8 @@
 #include "DefaultTerminal.h"
 #include "FileUtils.h"
 
+using namespace winrt::Windows::Foundation::Collections;
+using namespace winrt::Windows::ApplicationModel::AppExtensions;
 using namespace winrt::Microsoft::Terminal::Settings;
 using namespace winrt::Microsoft::Terminal::Settings::Model::implementation;
 
@@ -235,10 +237,29 @@ void SettingsLoader::FindFragmentsAndMergeIntoUserSettings()
         }
     }
 
-    // Search through app extensions
-    // Gets the catalog of extensions with the name "com.microsoft.windows.terminal.settings"
-    const auto catalog = winrt::Windows::ApplicationModel::AppExtensions::AppExtensionCatalog::Open(AppExtensionHostName);
-    const auto extensions = extractValueFromTaskWithoutMainThreadAwait(catalog.FindAllAsync());
+    // Search through app extensions.
+    // Gets the catalog of extensions with the name "com.microsoft.windows.terminal.settings".
+    //
+    // GH#12305: Open() can throw an 0x80070490 "Element not found.".
+    // It's unclear to me under which circumstances this happens as no one on the team
+    // was able to reproduce the user's issue, even if the application was run unpackaged.
+    // The error originates from `CallerIdentity::GetCallingProcessAppId` which returns E_NOT_SET.
+    // A comment can be found, reading:
+    // > Gets the "strong" AppId from the process token. This works for UWAs and Centennial apps,
+    // > strongly named processes where the AppId is stored securely in the process token. [...]
+    // > E_NOT_SET is returned for processes without strong AppIds.
+    IVectorView<AppExtension> extensions;
+    try
+    {
+        const auto catalog = AppExtensionCatalog::Open(AppExtensionHostName);
+        extensions = extractValueFromTaskWithoutMainThreadAwait(catalog.FindAllAsync());
+    }
+    CATCH_LOG();
+
+    if (!extensions)
+    {
+        return;
+    }
 
     for (const auto& ext : extensions)
     {


Test patch: