Open new terminal tab in same directory as existing tab (OSC 7?)

Description of the new feature/enhancement
Have the option (or default) of a new terminal tab opening in the current directory of the window of which you hit the hotkey to open a new tab. This is the standard way most linux terminals work and is most handy. I often work in a directory where I need to launch multiple seperate processes, its a pain to CD back into the directory each time.
Proposed technical implementation details (optional)
Hit the new tab hotkey, the new terminal should then be in the same folder as the previouse.

There's a "standard" escape sequence (OSC 7 ; URI ST) to set the terminal emulator's belief about the current directory. It originates from macOS Terminal.app, and was later adopted by some other ones, including GNOME Terminal and as far as I know Konsole too.
Another possible approach is to do some OS-specific hacks to examine the inner state of the child process (or even further down to descendents).
Yet another possibility is to mix the two, e.g. go to the directory set via OSC 7 if it was ever emitted, otherwise dig into the process.
The advantage of the OSC 7 approach is that it's clever regarding when to and when not to follow a child process. E.g. you start another nested subshell, it'll be the subdirectory of that subshell that's taken into account because that one also emits this sequence. However, launch an app that internally changes directory (e.g. make) and it – luckily – won't be make's internal subdir that's used.
The disadvantage of OSC 7 is that it requires cooperation from the shell, or other apps that matter.

I've been rejecting this feature request for as long as this project has been open-source, and I never learned about OSC 7. This is very exciting.
I'm not happy to crawl through the process tree to dig up the leafmost process's CWD, but I am extremely happy to support OSC 7.

FYI I asked about OSC 7 handling for Alacritty, which eventually led to this issue being created in the "Terminal WG" on gitlab: https://gitlab.freedesktop.org/terminal-wg/specifications/issues/20
There's not been much movement on that ticket, but you may be interested to follow it. Especially if you guys have any opinions regarding what a "formal" specification for OSC 7 might look like.

So for the record, the thread at https://github.com/jwilm/alacritty/pull/2937 has a pretty great discussion.
Honestly, I'm pretty okay using the de-facto standard that's already in place, the OSC 7 ; <URI> ST mechanism. I'm not really sure there needs to be anything more formal than that.

Wait no I had a terrible thought. Say bash is configured to emit that, and someone runs bash in WSL. What are we supposed to do when someone tries to set the working directory to /home/zadjii? How we:

tell that this is a WSL path, not a Windows path
know which WSL distro this came from?

Do we need to add some property on our side that indicates "this is a WSL distro, not a Windows exe"? What happens to users who don't set that, does the duplicate tab functionality just not work (effectively silently)?
Then the next part gets harder. What happens when this command is output over SSH? The terminal can't know that the path isn't on this machine anymore, right? How does Terminal.app handle this?
Maybe this does need more specification 😨

(Off: How long is it going to be until I mix up the two of you, D Howett and D Hewitt? :))

This is a crucial missing feature.

For anybody using Bash (from Git for Windows), a temporary workaround which has been saving me, is to store the new path every time you change dir (aliasing the cd command), then cd there when a new shell is started; this is in my .bashrc:
if [ "${PWD,,}" = "/c/windows/system32" ]; then
	if [ -f /tmp/pwd ]; then
		cd "$(cat /tmp/pwd)"
	else
		cd ~
	fi
fi

cd() {
	command cd "$@"
	pwd > /tmp/pwd
}

I'm actually testing if I start in System32 (my terminal default start location), so that I can still type wt in the Explorer address bar and start somewhere else, but this bit is optional and should be customized if your shell starts in a different folder.
I'm not fluent enough with the PowerShell or other shells, but I guess you can do something alike.

@danielepaolella

I'm not fluent enough with the PowerShell or other shells, but I guess you can do something alike.

I can do something with it! :)

Ctrl+T should open a new tab with the same shell and the same directory.

Not everybody agrees with that assertion.

Not everybody agrees with that assertion.

Maybe many aggree. That's how terminal app works on most Linux desktop.

Hi, I believe it is already clear in this thread that many agree this is a useful feature, and the Windows Terminal team is also away of this. And it is also clear that the problem here is not they don’t want to make this configurable, but they need to first figure out some technical stuff that prevents the feature from being possible.
I follow this thread to keep up to date on this feature and related discussions, but the messages like this only clutter the interface and do not help. I want to ask people to please refrain from posting messages that do little other than reiterating points that are already known.

Atleast it can be made as an option

This is what I don't get about the stubbornness. If you want to go against how most terminals behave, cool. Not even giving an option though? Where's the logic in that? Even Ctrl+Shit+D that represents duplicating a tab doesn't actually duplicate it as it sticks you in the default directory. Like you have a duplicate feature that doesn't even duplicate.
What's the "technical stuff" that prevents this feature from being possible? The code already exists. There's already a duplicate tab in Ctrl+Shift+D. It just needs to be fed the current working directory and you have the behaviour that most people are used to and that people are requesting. So I'm confused at how this has "technical stuff" blocking it.
I appreciate this type of discussion because it's quite clear that there is stubbornness involved which means this type of discussion is necessary.

Ah you're right, the original discussion is lost, because it didn't ever get linked to this thread. I'm copying the content of another post (https://github.com/microsoft/terminal/issues/2427#issuecomment-521307534) here for reference:

https://github.com/microsoft/terminal/issues/1756#issuecomment-520048598

Just chiming in;

_ (profile,working dir, environment var, etc)._

Anything about the actual process on the other end is, in the general case, impossible to replicate. The connected process could be ssh.exe, whose environment variables and working directory have no bearing on the detectable environment and working directory from the terminal side. The same actually, weirdly enough, applies to WSL. It doesn't use "working directory" and it doesn't expose its environment variables to interested Windows processes in any way.
Powershell doesn't even set the current working directory, so its directory can't be detected (!) either.

https://github.com/microsoft/terminal/issues/2315#issuecomment-519317472

This is one of those things that is impossible in the general case but technically possible. There's a lot of intricacies here, like:
cmd
powershell
cd d:\users

well, powershell isn't the first process we launched. we'd ignore the path d:\users
(in powershell)
cd d:\users

we'd ignore d:\users because powershell doesn't actually set the current working directory (!!)
If your "shell" is ssh<EMAIL_ADDRESS>(where we strictly define shell to be "the first process Terminal spawns on your behalf"), its working directory is always going to be C:\windows\system32 regardless of what the remote working directory is.
I'd rather not provide the feature than provide the feature with so many caveats that they'd fill a documentation page. ☹ sorry.

https://github.com/microsoft/terminal/issues/1536#issuecomment-519107586

No, because that would likely be neigh impossible to do in a general sense. How would we duplicate an instance of vim for example? What if the foreground process has opened some sort of file for exclusive access - how could we duplicate that process?
If there's a way this can be done safely and generally I'm all ears for proposed technical solutions, but I don't think it's something that's possible, so I'm not going to be investigating it.

Even if Powershell did set the working directory, we're still not positive that it's technically possible on Windows to get the CWD of another process. So that's the "technical" stuff that's preventing this from working. I'd love to add this as a setting. But there are definitely still technical questions that need answering.
The solution that's being discussed in this thread involves adding support for another VT sequence to the Terminal, that the shell would be able to emit to clue the Terminal in to what path it's in. This VT sequence isn't super well defined, and has edge cases that still need solving. Namely:

What happens when a WSL shell says "my CWD is /home/foo? There's no way for the Terminal to know that path is a WSL path, or even which distro it belongs to, so duplicating this tab would likely end up in C:\home\foo (if it exists)
What happens when you're connected to another machine over SSH? The Terminal won't be able to differentiate those paths from paths on your own local machine, so again, duplicating that path would be the wrong behavior
Every user will need to customize their prompt for various shells manually to cooperate with this behavior. This isn't a blocker, but this does mean it'll be a setting that won't just work out of the box.

You're trying to duplicate the running processes? Let's look at Linux for example. If you're running SSH in your terminal and open a new tab, the new tab doesn't open an SSH connection and browse to where you are in the SSH connection. It opens up a new tab where you are on your machine. Even if the process was local and not SSH it doesn't run the process. All that's being duplicated is the tab, not the running processes.
It sounds like this is being overly complicated. You aren't duplicating VIM or SSH or any other application that's running. You're duplicating the terminal and that answers the edge cases:

For WSL you aren't browsing your local. If the return is /home/foo that's the location. If the location was C:\home\foo it would return /mnt/c/home/foo.
SSH is a process. It runs in the shell. You aren't duplicating processes. Other terminals don't. You're duplicating the tab.
I'm not sure what the user would have to customize, but since when is customization an issue?

There's nothing wrong with duplicating the processes. I'm sure some would love that. It's just that would be another option on top of the option to duplicate the tabs. It shouldn't be a road-block. That's extra and optional.

@PandaClone it might surprise you to learn that some people set ssh.exe as the first thing that a profile launches, without running it from a shell.
Like as not, there really isn’t a way for the Terminal to interrogate wsl.exe, the wrapper application that communicates with Linux processes, to get it to say what the current working directory is of the first process in its process tree.
Because it doesn’t use the windows working directory infrastructure, which stores the WD in the process environment block, just using the boring old Windows APIs is not sufficient to tell what its working directory is.
These are technical problems that we have to solve. Otherwise, we write a feature that only works for, like, 25% of people.
If it proves to be easy: we are always willing to accept community contributions.

For WSL you aren't browsing your local. If the return is /home/foo that's the location. If the location was C:\home\foo it would return /mnt/c/home/foo.

Ah but see, the way this feature works as spec'd, the Terminal doesn't know who or what said "The current working directory is /home/foo". This could be cmd.exe - then yea, the user wants C:\home\foo. This could be their Ubuntu distro, or their Fedora distro, or this could be ssh connected to centos or any other possibility. All the terminal gets is a string saying "this is the working directory now".

I'm not sure what the user would have to customize, but since when is customization an issue?

Pretty much every shell the user runs is going to need to manually be configured to enable sending this sequence. For cmd users, they'll need to manually configure their %PROMPT% to include the sequence $e]7;$P$e. bash users will need to set it up in their PS1. PowerShell will certainly have another way to do it. The fundamental issue here though is that the shells don't emit this sequence by default.

SSH isn't a shell. You can set your profile to run it first, but it's still being run from the shell. It's just your profile is being instructed to run an application immediately. That application can be anything. It doesn't have to SSH. You can instruct your profile to run another shell if you wanted to.
And even in the case that there is no terminal, how is that a problem? There are always exceptions. Defaulting to the home directory when there is no directory to go to is fine. That's not a problem where you just "oh this can't be done".
Also, this is a feature that's standard in the majority terminals with tabs. Run any Linux distro which has their own terminal flavours and they all exhibit this behaviour of opening a new tab. This isn't a feature that's going to be ground breaking magic for Windows Terminal. It's a standard feature.

Terminal doesn’t just spawn shells. It literally calls CreateProcess on the thing you provide in the profile config. SSH isn’t running in, or spawned by, a shell.
Look, we’re arguing about how possible this feature is. Can we just agree that we want this, everyone wants it, and if we had a reasonable way forward that worked in the vast majority of the use cases users care about that we would have done it already? I’m trying to reduce the number of times we have to say “on that can’t be done” with some upfront planning and design work.
It’s not groundbreaking magic, it’s just complicated by the Windows and WSL process model and we think it’ll fall over in some circumstances. Nobody’s saying anything more than that.

For WSL you aren't browsing your local. If the return is /home/foo that's the location. If the location was C:\home\foo it would return /mnt/c/home/foo.

Ah but see, the way this feature works as spec'd, the Terminal doesn't know who or what said "The current working directory is /home/foo". This could be cmd.exe - then yea, the user wants C:\home\foo. This could be their Ubuntu distro, or their Fedora distro, or this could be ssh connected to centos or any other possibility. All the terminal gets is a string saying "this is the working directory now".

How doesn't it know who or what said the current working directory is? You're the one asking for it. You know whether it's a Command Prompt or a WSL or a PowerShell. You know where it's coming from so you know how to format the location.

I'm not sure what the user would have to customize, but since when is customization an issue?

Pretty much every shell the user runs is going to need to manually be configured to enable sending this sequence. For cmd users, they'll need to manually configure their %PROMPT% to include the sequence $e]7;$P$e. bash users will need to set it up in their PS1. PowerShell will certainly have another way to do it. The fundamental issue here though is that the shells don't emit this sequence by default.

How is that a problem? This wouldn't be the first application to require configuration and it won't be the last. Not everything is plug and play and that's understandable. If the only way to make this work is for the user to require a configuration, how is that stopping point?

What happens when a WSL shell says "my CWD is /home/foo? There's no way for the Terminal to know that path is a WSL path, or even which distro it belongs to, so duplicating this tab would likely end up in C:\home\foo (if it exists)

I can only really speak for myself, but if I had a tab open using one profile, navigated somewhere specific, and then opened a new tab in a different profile, it would not surprise or disappoint me in the slightest if the working dir did not carry over, and the default was used instead.
I think you understand that most people asking for this feature are missing the behaviour in terminals such as those included with GNOME and macOS. Those terminals don't have to deal with the same complexities that this does, but at the same time, I don't think anyone is expecting you to try and smartly handle edge cases that simply don't exist in the software they're using as a reference point.
It sounds like a pretty hairy task even if you reduce the scope somewhat though. I hope a way can be found to include some version of this feature, as it is a nice time saver.

Could this use case be handled by #4472 in the short term? I'd personally be content with some variant of cmd.exe /c "wt.exe" new-tab -p "Ubuntu-20.04" -d $(pwd) (probably bound to a Bash macro) that would open up a new tab in the most recently focused window (which is almost certainly the window that I typed the command in).

Gonna go out on a limb and say that implementing detection for the root process's current directory is easier than implementing commandline remoting and IPC to get WT to open tabs in the same window :smile:

wow, i just came here and realize that it seems need a long journey :)

เมื่อ อา. 21 มิ.ย. 2563 เวลา 21:32 arbaieffendi<EMAIL_ADDRESS>เขียนว่า:

wow, i just came here and realize that it seems need a long journey :)
—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/microsoft/terminal/issues/3158#issuecomment-647135852,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/AP55P57YXGPWKP7E7TZWOVTRXYKYNANCNFSM4I73YYBA
.

We found that in windows terminal we could split the shell windows by press shortcut alt+shift+D, but it doesn't set to same directory

any updates?

https://gitlab.freedesktop.org/terminal-wg/specifications/-/merge_requests/7#note_552774

I've come with a workaround: change the starting directory.
Put this function into $PROFILE (make sure to adjust $path)
function sd {
    $path = 'C:\Users\Admin\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json'
     ((Get-Content -path $path) -replace '"startingDirectory":.*', ("`"startingDirectory`": `"$pwd`"") -replace "\\", "\\") | Set-Content -Path $path
}

.. and you'll be able to a open new tab in the same directory almost with no hassle, just make sure to type sd before opening a new tab.
Of course, the drawback is that startingDirectory is changed every time the function is called.
It would be best to use this approach with a key re-mapper, so that when Ctrl+T is pressed the function is called automatically, and when Ctrl+F4 is pressed startingDirectory is reverted back to its original value.

Hey guys, I've found something interesting.... You can just put
"startingDirectory": "./"
In the terminal configuration....
Like this:

Alternative solution
Inside whatever profile you are using example profile.sh or .zshrc create a ~/paths.sh file located within your $HOME directory. Paths will be updated whenever you call setCWD
This solution overrides the startingDirectory completely. Whenever you spawn a new terminal call setCWD before spawning the terminal and it will always start in the directly you last called setCWD in.
Note that I did this within .zshrc
Code:
source ~/paths.sh

if [[ $SAVED_PWD != $PWD  ]]
then
  cd $SAVED_PWD
fi

function setCWD(){
  echo export SAVED_PWD=$(pwd) > ~/paths.sh
}

You may need to create an initial file so just call setCWD.

Guys, this is very important for productivity, almost like it's above everything else. Please fix this and me and my friends can abandon all of the other inferior terminal emulators.

It looks like the attempt to 'standardise' OSC 7 at terminal-wg has stalled.
Is there still interest in implementing OSC 7 basically as it stands in Terminal.app?
Given that, we'd have "current host and CWD" for a given terminal, which just blats the 'process hacking' discusison; and then can decide/implement the user behaviours to make use of that information, e.g.,:

a "new Tab in current directory" command;
making "split" do this by default;
something magic to distinguish a WSL session from a Windows session (if they even report the same hostname? I haven't looked...);
a config option for "suppress OSC 7" on profiles where you know it's going to send a valid-looking OSC 7 that you don't want to use, such as sshing to a remote machine that claims the same hostname as your Windows host;
exposing the value into something you can stick on the command line, so your ssh or wsl session can appear at the same working directory as one you just duplicated.

This discussion was very focused on the first part (getting the current CWD) but I suspect the second part is the one that will need more consideration, based on the existing comments so far above. Even for that list of ideas, I'm sure a reasonable objection exists to every one of them.

For those who are still intersted in this topic, I made a early PR in #7668 . This is a a friendly ping. I'd really love to hear from everyone about it.

What is the point of multiple tabs, especially fast duplicating of windows, if they don't inherit the current directory? This is such an important feature. Why not add a "hacky" workaround for now? I really don't see a problem extracting CWD from a process on Windows if it increases productivity for all the users, considering Windows itself has contained multiple such solutions for more than 20 years.

I can't understand why this feature isn't the default. I truly am boggled as to why there isn't even a way to enable this feature. This is the biggest user experience detractor I have with Windows Terminal: from an expedience perspective I am better served by not using Windows Terminal and instead using explorer and right clicking in the directory I want to open the shell and selecting "Open PowerShell window here" because it's faster than hitting alt+shift+d then having to cd to the right place.
Terminal adds a lot of quality of life for Windows devs. This feature would be huge jump forward for me (and I suspect others). I'll add my voice in advocating for this feature be a top priority.

I can't understand why this feature isn't the default.

I can't understand why people can't be bothered to read all the investigation that's been done in this thread, in #7668, #8214, #8166, and the other linked threads, to understand why this is actually a hard problem to solve. It turns out you can't just have a client app emit it's path - because the Terminal won't necessarily know whether that's a Windows or a WSL or a cygwin path.
It's a good thing we've got a bunch of talented contributors who are hard at work finding out the right way of implementing support for this feature, without breaking backwards-compatibility for other apps. We've just this week come up with a solution we're happy with, shouldn't be long before it's implemented.

Thanks @zadjii-msft !
In rereading my comment I'm realizing it comes off super accusatory and that was not my intent. I came here to say this:

Terminal adds a lot of quality of life for Windows devs. This feature would be huge jump forward for me (and I suspect others). I'll add my voice in advocating for this feature be a top priority.

And that my user experience so far has been this:

I can't understand why this feature isn't the default. I truly am boggled as to why there isn't even a way to enable this feature. This is the biggest user experience...etc

I probably should have put "as a user," at the beginning of my first paragraph.
I apologize for any offense I've given.

Happy new year :D I hope this feature so so much

Happy new year :D I hope this feature so so much

I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance.
To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh)
Add following to the /root/.config/fish/config.fish or your shell's equivalent.
function cd
    builtin cd $argv
    pwd > ~/.last_dir
end
if test -f ~/.last_dir
    cd ( cat ~/.last_dir )
end

⭐As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎

I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance.
To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh)
Add following to the /root/.config/fish/config.fish or your shell's equivalent.
function cd
    builtin cd $argv
    pwd > ~/.last_dir
end
if test -f ~/.last_dir
    cd ( cat ~/.last_dir )
end

⭐As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎

I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance.
To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh)
Add following to the /root/.config/fish/config.fish or your shell's equivalent.
function cd
    builtin cd $argv
    pwd > ~/.last_dir
end
if test -f ~/.last_dir
    cd ( cat ~/.last_dir )
end

⭐As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎

Nice, thanks!
The shell script version if this:
cd() {
  builtin cd $argv
  pwd > ~/.last_dir
}

if [ -f ~/.last_dir ]; then
  cd `cat ~/.last_dir`
fi

I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance.
To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh)
Add following to the /root/.config/fish/config.fish or your shell's equivalent.
function cd
    builtin cd $argv
    pwd > ~/.last_dir
end
if test -f ~/.last_dir
    cd ( cat ~/.last_dir )
end

⭐As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎

Nice, thanks!
The shell script version if this:
cd() {
  builtin cd $argv
  pwd > ~/.last_dir
}

if [ -f ~/.last_dir ]; then
  cd `cat ~/.last_dir`
fi

I've tried a similar solution to @azterizm's one in the past. Always opening a terminal in the previous cd location can be inconvenient in some situations :

When we open a terminal from a custom location (for instance, in an explorer with a "Open a terminal here" option
When PowerShell is embedded in another tool (e.g. in an IDE)

I've tried a similar solution to @azterizm's one in the past. Always opening a terminal in the previous cd location can be inconvenient in some situations :

When we open a terminal from a custom location (for instance, in an explorer with a "Open a terminal here" option
When PowerShell is embedded in another tool (e.g. in an IDE)

I've tried a similar solution to @azterizm's one in the past. Always opening a terminal in the previous cd location can be inconvenient in some situations :

When we open a terminal from a custom location (for instance, in an explorer with a "Open a terminal here" option
When PowerShell is embedded in another tool (e.g. in an IDE)

About the option in the context menu "Open a terminal here", we can make a script for this.
A script that takes the directory of where the context menu was called from, then we convert the slashes to what Linux uses (C:\ to /mnt/c) then run the Linux command from Powershell that updates ~/.last_dir. Finally in the same script, open the terminal normally. It will be exactly what you want.
The command that will update the file should be wsl /mnt/c >> ~/.last_dir
Currently, I do not know how to make scripts for Powershell but surely someone should try that.
As for the IDE's or other embedded tools, we might need to add a script to them that clears ~/.last_dir file on opening the terminal in there.

I've tried a similar solution to @azterizm's one in the past. Always opening a terminal in the previous cd location can be inconvenient in some situations :

When we open a terminal from a custom location (for instance, in an explorer with a "Open a terminal here" option
When PowerShell is embedded in another tool (e.g. in an IDE)

About the option in the context menu "Open a terminal here", we can make a script for this.
A script that takes the directory of where the context menu was called from, then we convert the slashes to what Linux uses (C:\ to /mnt/c) then run the Linux command from Powershell that updates ~/.last_dir. Finally in the same script, open the terminal normally. It will be exactly what you want.
The command that will update the file should be wsl /mnt/c >> ~/.last_dir
Currently, I do not know how to make scripts for Powershell but surely someone should try that.
As for the IDE's or other embedded tools, we might need to add a script to them that clears ~/.last_dir file on opening the terminal in there.

#8330 implemented the infrastructure needed for this, it should be part of the next Terminal 1.5 preview release.
You'll need your shell to generate the OSC 9;9 messages, and once that's working, you will get this behaviour for duplicating tabs and splitting panes when that release happens.
This is compatible with ConEmu, so ConEmu's OSC 9;9 "How to set it up" instructions should roughly work, where they use ANSI codes rather than ConEmuC; the "WSL/cygwin/msys" instructions need to be adjusted as they generate Unix paths, and for Windows Terminal you need Windows paths.
These instructions also do a bunch more, the part you need is the part that generates the 9;9 message, I am unaware of Windows Terminal consuming the 9;12 message, but of course it wouldn't hurt.
e.g. for PowerShell, the given example can be trimmed to this for the minimal change:
function prompt
{
  $loc = Get-Location

  # Emulate standard PS prompt with location followed by ">"
  $out = "PS $loc> "

  # Add current working directory (FileSystem)
  if ($loc.Provider.Name -eq "FileSystem") {
    $out += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)"
  }

  return $out
}

Note: I haven't tested this myself, but I wanted to make sure people knew this feature desire wasn't being ignored.

#8330 implemented the infrastructure needed for this, it should be part of the next Terminal 1.5 preview release.
You'll need your shell to generate the OSC 9;9 messages, and once that's working, you will get this behaviour for duplicating tabs and splitting panes when that release happens.
This is compatible with ConEmu, so ConEmu's OSC 9;9 "How to set it up" instructions should roughly work, where they use ANSI codes rather than ConEmuC; the "WSL/cygwin/msys" instructions need to be adjusted as they generate Unix paths, and for Windows Terminal you need Windows paths.
These instructions also do a bunch more, the part you need is the part that generates the 9;9 message, I am unaware of Windows Terminal consuming the 9;12 message, but of course it wouldn't hurt.
e.g. for PowerShell, the given example can be trimmed to this for the minimal change:
function prompt
{
  $loc = Get-Location

  # Emulate standard PS prompt with location followed by ">"
  $out = "PS $loc> "

  # Add current working directory (FileSystem)
  if ($loc.Provider.Name -eq "FileSystem") {
    $out += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)"
  }

  return $out
}

Note: I haven't tested this myself, but I wanted to make sure people knew this feature desire wasn't being ignored.

The author of #8330 here. I can confirm it in fact works with the current dev branch. It should be available in 1.6 preview.

The author of #8330 here. I can confirm it in fact works with the current dev branch. It should be available in 1.6 preview.

I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance.
To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh)
Add following to the /root/.config/fish/config.fish or your shell's equivalent.
function cd
    builtin cd $argv
    pwd > ~/.last_dir
end
if test -f ~/.last_dir
    cd ( cat ~/.last_dir )
end

⭐As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎

Nice, thanks!
The shell script version if this:
cd() {
  builtin cd $argv
  pwd > ~/.last_dir
}

if [ -f ~/.last_dir ]; then
  cd `cat ~/.last_dir`
fi

for bash, $argv should be $1

I've found a very simple solution to this. What you need to do is execute a function on every cd command and save that somewhere so that it can be read on new instance.
To achieve this, you will modify your shell config file. I am using Fish shell on my machine (that uses ruby-like syntax), but you may convert this syntax to make it work for others. (tested on Zsh)
Add following to the /root/.config/fish/config.fish or your shell's equivalent.
function cd
    builtin cd $argv
    pwd > ~/.last_dir
end
if test -f ~/.last_dir
    cd ( cat ~/.last_dir )
end

⭐As a bonus, if I shutdown/restart my PC and open terminal again I automatically cd into my last project directory. Cool! 😎

Nice, thanks!
The shell script version if this:
cd() {
  builtin cd $argv
  pwd > ~/.last_dir
}

if [ -f ~/.last_dir ]; then
  cd `cat ~/.last_dir`
fi

for bash, $argv should be $1

In a cmd environment I call start to open a new console. Can Terminal not capture a call to start and open a new tab instead?

In a cmd environment I call start to open a new console. Can Terminal not capture a call to start and open a new tab instead?

no that would require #492

no that would require #492

Is OSC 9;9 something that can be natively supported by shells? Should I file an issue in PowerShell repo?

Is OSC 9;9 something that can be natively supported by shells? Should I file an issue in PowerShell repo?

@saschanaz probably, you will get a better shot on psreadline repo.
but it's pretty easy to DIY, just put this in your $profile
function prompt {
        $p = $pwd.ProviderPath
	# $ansi_escape = [char]27 on powershell 5.1 replace "`e" whith this variable
	Write-host "`e]9;9;$p`e\" -NoNewline
	"PS $p$('>' * ($nestedPromptLevel + 1)) "
}

@saschanaz probably, you will get a better shot on psreadline repo.
but it's pretty easy to DIY, just put this in your $profile
function prompt {
        $p = $pwd.ProviderPath
	# $ansi_escape = [char]27 on powershell 5.1 replace "`e" whith this variable
	Write-host "`e]9;9;$p`e\" -NoNewline
	"PS $p$('>' * ($nestedPromptLevel + 1)) "
}

So now that this is working for duplicate tab and split pane w/duplicate, I'd like it for "new tab", as per the original request. Probably as a parameter for the newTab action, not a change in the default. My use-case is that sometimes I'm in a directory in PowerShell, and I want "Git Bash here".
Should I open a new issue for that request, or is that in-scope for this one as further work after #8330?
I also noticed that the default keybindings for splitPane (alt+shift+- and alt+shift+plus) do not get this behaviour, because they are using the default splitMode, 'Manual', which launches the default shell due to lack of other parameters. I guess it might be surprising for users that a 'Manual' splitPane that picks the same profile as my current terminal, is different from a 'Duplicate' splitPane. It certainly surprised me. ^_^
It's possible that for what I want, a magic token for the startingDirectory parameter of the splitPane and newTab actions would be sufficient, but personally I'd lean towards a boolean field for copyWorkingDirectory, except that this might incorrectly set the expectation that it "just works" without the current shell calling OSC 9;9 (or OSC 7 etc. in future).
A magic token could be explicitly tied to "the directory set by OSC 9;9 or OSC 7, see the WT OSC docs for details".

So now that this is working for duplicate tab and split pane w/duplicate, I'd like it for "new tab", as per the original request. Probably as a parameter for the newTab action, not a change in the default. My use-case is that sometimes I'm in a directory in PowerShell, and I want "Git Bash here".
Should I open a new issue for that request, or is that in-scope for this one as further work after #8330?
I also noticed that the default keybindings for splitPane (alt+shift+- and alt+shift+plus) do not get this behaviour, because they are using the default splitMode, 'Manual', which launches the default shell due to lack of other parameters. I guess it might be surprising for users that a 'Manual' splitPane that picks the same profile as my current terminal, is different from a 'Duplicate' splitPane. It certainly surprised me. ^_^
It's possible that for what I want, a magic token for the startingDirectory parameter of the splitPane and newTab actions would be sufficient, but personally I'd lean towards a boolean field for copyWorkingDirectory, except that this might incorrectly set the expectation that it "just works" without the current shell calling OSC 9;9 (or OSC 7 etc. in future).
A magic token could be explicitly tied to "the directory set by OSC 9;9 or OSC 7, see the WT OSC docs for details".

It wasn't clear to me how to enable OSC 9;9 for WSL but I've finally figured it out. You should add this line to your .bashrc:
export PROMPT_COMMAND='printf "\033]9;9;%s\033\\" "$(wslpath -m $(pwd))"'

It wasn't clear to me how to enable OSC 9;9 for WSL but I've finally figured it out. You should add this line to your .bashrc:
export PROMPT_COMMAND='printf "\033]9;9;%s\033\\" "$(wslpath -m $(pwd))"'

If anyone is using PowerLine, this is what I'm using in the Prompt array of ${ENV:AppData}\powershell\HuddledMasses.org\PowerLine\Configuration.psd1 to generate OSC 9;9, as well as output the current directory:
(ScriptBlock ' New-PromptText { "&OSC;9;9;"+$executionContext.SessionState.Path.CurrentLocation+"&ST;" + $executionContext.SessionState.Path.CurrentLocation } -ForegroundColor DarkYellow ')

I've added the last two escape sequences as well:
  EscapeSequences    = @{
    Esc    = '['
    Store  = ''
    Recall = ''
    Clear  = ''
    OSC    = ']'
    ST     = '\'
  }

Each of those lines has the same character at the start. I just copied the 'Esc' line (really should be "CSI", I think), changed the non-hidden character, and the name.

 My whole Configuration.psd1 file for context
Originally generated with Export-PowerLinePrompt and then modified as the mood hit me.

@{
  ExtendedCharacters = @{
    ColorSeparator        = ''
    ReverseColorSeparator = ''
    Separator             = ''
    ReverseSeparator      = ''
    Branch                = ''
    Lock                  = ''
    Gear                  = '⛯'
    Power                 = '⚡'
  }
  PowerLineConfig    = @{
    RestoreVirtualTerminal = $True
    Prompt                 = @((ScriptBlock ' New-PromptText { "&OSC;9;9;"+$executionContext.SessionState.Path.CurrentLocation+"&ST;" + $executionContext.SessionState.Path.CurrentLocation } -ForegroundColor DarkYellow '), (ScriptBlock ' "`t" '), (ScriptBlock ' Write-VcsStatus '), (ScriptBlock ' "`n" '), (ScriptBlock ' New-PromptText { ">" * ($NestedPromptLevel + 1) } -ForegroundColor Blue -ElevatedForegroundColor Yellow '))
    Colors                 = @((RgbColor 'Black'), (RgbColor 'Black'), (RgbColor 'Black'))
    PowerLineFont          = $True
    FullColor              = $True
    DefaultAddIndex        = 2
    SetCurrentDirectory    = $True
  }
  EscapeSequences    = @{
    Esc    = '['
    Store  = ''
    Recall = ''
    Clear  = ''
    OSC    = ']'
    ST     = '\'
  }
}

If anyone is using PowerLine, this is what I'm using in the Prompt array of ${ENV:AppData}\powershell\HuddledMasses.org\PowerLine\Configuration.psd1 to generate OSC 9;9, as well as output the current directory:
(ScriptBlock ' New-PromptText { "&OSC;9;9;"+$executionContext.SessionState.Path.CurrentLocation+"&ST;" + $executionContext.SessionState.Path.CurrentLocation } -ForegroundColor DarkYellow ')

I've added the last two escape sequences as well:
  EscapeSequences    = @{
    Esc    = '['
    Store  = ''
    Recall = ''
    Clear  = ''
    OSC    = ']'
    ST     = '\'
  }

Each of those lines has the same character at the start. I just copied the 'Esc' line (really should be "CSI", I think), changed the non-hidden character, and the name.

 My whole Configuration.psd1 file for context
Originally generated with Export-PowerLinePrompt and then modified as the mood hit me.

@{
  ExtendedCharacters = @{
    ColorSeparator        = ''
    ReverseColorSeparator = ''
    Separator             = ''
    ReverseSeparator      = ''
    Branch                = ''
    Lock                  = ''
    Gear                  = '⛯'
    Power                 = '⚡'
  }
  PowerLineConfig    = @{
    RestoreVirtualTerminal = $True
    Prompt                 = @((ScriptBlock ' New-PromptText { "&OSC;9;9;"+$executionContext.SessionState.Path.CurrentLocation+"&ST;" + $executionContext.SessionState.Path.CurrentLocation } -ForegroundColor DarkYellow '), (ScriptBlock ' "`t" '), (ScriptBlock ' Write-VcsStatus '), (ScriptBlock ' "`n" '), (ScriptBlock ' New-PromptText { ">" * ($NestedPromptLevel + 1) } -ForegroundColor Blue -ElevatedForegroundColor Yellow '))
    Colors                 = @((RgbColor 'Black'), (RgbColor 'Black'), (RgbColor 'Black'))
    PowerLineFont          = $True
    FullColor              = $True
    DefaultAddIndex        = 2
    SetCurrentDirectory    = $True
  }
  EscapeSequences    = @{
    Esc    = '['
    Store  = ''
    Recall = ''
    Clear  = ''
    OSC    = ']'
    ST     = '\'
  }
}

As suggested in #9063, here is an other UI proposition for such a feature.
Proposed technical implementation details (optional)

Right click on a tab could have a "New" contextual menu (between rename tab and close) which could show same entries as those in the "+" tab.
The main difference would be that a new tab will be created with the "context" of a tab which was opened previously (context being here the current working directory)

It wasn't clear to me how to enable OSC 9;9 for WSL but I've finally figured it out. You should put this line in your .bashrc:
export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'

If you tried this and it didn't work, it could be that you're running the stable version of terminal which doesn't have this yet.
You can get the preview version from the store: https://www.microsoft.com/store/productId/9N8G5RFZ9XK3
Just confirmed it working for WSL 😃

It wasn't clear to me how to enable OSC 9;9 for WSL but I've finally figured it out. You should put this line in your .bashrc:
export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'

If you tried this and it didn't work, it could be that you're running the stable version of terminal which doesn't have this yet.
You can get the preview version from the store: https://www.microsoft.com/store/productId/9N8G5RFZ9XK3
Just confirmed it working for WSL 😃

I have a very strange issue with this solution. I've installed Ubuntu 20.04, put the export into my .bashrc and as expected, it started working. I've then played around, installed some additional packages into my ubuntu and reinstalled whole distro Ubuntu 20.04 from microsoft store a few times, to reset clean my wsl.
At some point, I've noticed that this trick stopped working. No matter what I do, the windows terminal no longer has the ability to properly set the directory for a new tab to match the existing tab. I've tried everything that came to my mind: reinstalling windows terminal, reinstaling all the linux distributions, installing additional distributions (Ubuntu 18.04, openSUSE Leap 15.2), reinstalling linux kernel update package, disabling and reenabling the wsl from windows features, and updating my Windows version. Nothing works.
I've no idea how to debug the issue. Is this some wsl problem? Windows terminal problem? How to make sure that everything is properly cleaned up before reinstalling everything?
Operating System info

Edition: Microsoft Windows 10 Education
Version: 20H2
OS build: 19042.844
Experience: Windows Feature Experience Pack 120.2212.551.0

Additional info

Windows Terminal Preview 1.6.10412.0
Ubuntu 20.04 LTS, WSL 2
Windows Subsystem for Linux Update: <IP_ADDRESS>

put
    "debugFeatures": true,

in the global settings for windows terminal
then hold down both alt keys and open the profile that you are having problems, should something look like this:

verify if osc9;9 is being emitted

Anyone happen to know how to add OSC 9;9 to Powerlevel10K? I don't think export PROMPT_COMMAND= works.

here:
 __wt_osc9_9 () {
      _win_path=$(wslpath -m "$(pwd)")
      printf "\033]9;9;\"%s\"\033\\" "$_win_path"
  }

  [ -n "$BASH_VERSION" ] && [ -n "$WT_SESSION" ] && PROMPT_COMMAND="__wt_osc9_9"
  [ -n "$ZSH_VERSION"  ] && [ -n "$WT_SESSION" ] && precmd_functions+=(__wt_osc9_9)

put it in a file and then source it from .zshrc or .bashrc

put
    "debugFeatures": true,

After turning on the debugFeatures I got the following result:

The 9;9;//wsl$/Ubuntu-20.04/home/gemboj before my prompt (which is not visible in the non debugging terminal) tells me that the osc9;9 is properly emitted. Still, the directory of a new tab is not set properly.

@gemboj Just to be sure, you're using a duplicateTab action/keybinding to attempt to duplicate the tab, right?

@gemboj Just to be sure, you're using a duplicateTab action/keybinding to attempt to duplicate the tab, right?

Okay. This is the moment I want to curl up and die. At some point my muscle memory must have kicked in and I started using ctrl+shift+t (new tab) instead of duplicating the current tab. At least I've learned the neat trick with debugFeatures. Now to never come back here out of embarrassment...

  [ -n "$ZSH_VERSION"  ] && [ -n "$WT_SESSION" ] && precmd_functions+=(__wt_osc9_9)

Putting the above in my .zshrc meant the function was re-added each time I sourced .zshrc, and I think I noticed a slowdown in showing the prompt that worsens for each occurrence. To limit this to one instance I tweaked it slightly to this:
if [ -n "$WT_SESSION" ] ; then
    if ((!precmd_functions[(I)__wt_osc9_9])); then
        precmd_functions+=(__wt_osc9_9)
    fi
fi

I confirm that @ojroques's solution works for me on wsl
If you are using fish shell like me, I managed to make make it work by adding a new file in ~/.config/fish/conf.d for ex. windows-terminal.fish and added this to it
function windows-terminal --on-event fish_prompt
    printf "\e]9;9;%s\e\\" (wslpath -m "$PWD")
end

I just added this to my $profile without luck:
function prompt
{
  $loc = Get-Location

  # Emulate standard PS prompt with location followed by ">"
  $out = "PS $loc> "

  # Add current working directory (FileSystem)
  if ($loc.Provider.Name -eq "FileSystem") {
    $out += "$([char]27)]9;9;`"$($loc.Path)`"$([char]7)"
  }

  return $out
}

Running the new v1.6.10571.0 on Windows 10

@robsonsobral here:
function prompt{
	$esc=[char]27
	$p = $pwd.ProviderPath
	Write-host "$esc]9;9;`"$p`"$esc\" -NoNewline
	"PS $p$('>' * ($nestedPromptLevel + 1)) "
}

Thank you, @LuanVSO ! It worked!
I also had to move PSHAZZ script to the top of the file.
try { $null = gcm pshazz -ea stop; pshazz init } catch { }

A brief look at pshazz's prompt management suggests that you could write a plugin something like the z plugin to act on each prompt-display and call the Write-Host you want (i.e. the first three lines of the prompt function from @LuanVSO), although you have to activate the plugin in your preferred theme, I assume.
Otherwise, perhaps modify global:pshazz_write_prompt, to call Write-Host with the relevant values irrespective of theme.

Thank you, @TBBle ! It worked!

I already wrote a plugin to customize things. So I added:
Import-Module "$pluginDir\z"
Set-Alias z Search-NavigationHistory -Scope "global"
function global:pshazz:z:prompt {
	$esc=[char]27
	$p = $pwd.ProviderPath
	Write-host "$esc]9;9;`"$p`"$esc\" -NoNewline
}

Thank you so much!

I was having trouble getting to work the new duplicate tab in the same directory, after adding the code to my PowerShell profile now it seems to be working fine and the OSC9;9 is added, i don't know why this was happening. I added both images of the debug terminal before and after adding the function.

function prompt {
        $p = $pwd.ProviderPath
	# $ansi_escape = [char]27 on powershell 5.1 replace "`e" whith this variable
	Write-host "`e]9;9;$p`e\" -NoNewline
	"PS $p$('>' * ($nestedPromptLevel + 1)) "
}

Before

After

Thank you, @LuanVSO!

that's because PowerShell by default does not emit the required escape esquece for it to work

Has anyone gotten OSC9;9 to work with Windows CMD? I tried the setx example above, but it didn't work...
I also noticed some weird behavior in Powershell 7.1, but I don't know if this is the best place to ask. When I pipe a command I start seeing OSC9;9 outputs, for example:
PS C:\code\online_repos\terminal> git branch | grep ^\*
* main
PS C:\code\online_repos\terminal> ←]9;9;"C:\code\online_repos\terminal"

Has anyone else seen this behavior?

I also noticed some weird behavior in Powershell 7.1, but I don't know if this is the best place to ask. When I pipe a command I start seeing OSC9;9 outputs, for example:
PS C:\code\online_repos\terminal> git branch | grep ^\*
* main
PS C:\code\online_repos\terminal> ←]9;9;"C:\code\online_repos\terminal"

Has anyone else seen this behavior?
that's because the git for windows commands explicitly disables vt processing and powershell doesn't turn it back on when native commands exit, this was resolved in the latest powershell 7.2 preview

Has anyone gotten OSC9;9 to work with Windows CMD? I tried the setx example above, but it didn't work...
https://gist.github.com/LuanVSO/09ba0239fe7c1a959a9b07c7156c5e13

For anyone looking for a workaround that is nearly as good (but not exactly the same), there is an alternative approach. Instead of maintaining the current working directory, you can at least ensure that new tabs and panes open in the same starting directory (since current will vary over time).
Alternative steps:

Use the custom right-click integration by BroJenuel/Explorer-Context-Menu-Integration-for-windows-terminal (which isn't subject to the separate but related bug documented in #8933).
Since that creates a duplicate right-click entry, remove it by using the fix documented here: https://github.com/microsoft/terminal/issues/7008#issuecomment-662621638

End result is that it will at least persist the same starting directory (albeit it will not be up-to-date with cd changes, which is really what this issue is about).
Demo:

Has anyone gotten OSC9;9 to work with Windows CMD? I tried the setx example above, but it didn't work...

https://gist.github.com/LuanVSO/09ba0239fe7c1a959a9b07c7156c5e13

Thanks for this, however it doesn't work for me. The split panes always open in my default user path.

I also noticed some weird behavior in Powershell 7.1, but I don't know if this is the best place to ask. When I pipe a command I start seeing OSC9;9 outputs, for example:
PS C:\code\online_repos\terminal> git branch | grep ^\*
* main
PS C:\code\online_repos\terminal> ←]9;9;"C:\code\online_repos\terminal"

Has anyone else seen this behavior?

that's because the git for windows commands explicitly disables vt processing and powershell doesn't turn it back on when native commands exit, this was resolved in the latest powershell 7.2 preview

Aha, thanks for clarifying! I'll test the latest Powershell 7.2 preview.

@joshmer Remember to use "duplicate pane" instead of "new pane". Only by duplicating a pane, you'll have the same CWD in the new pane.

Duplicate pane is alt+shift+d correct? That's what I'm using. Here's a snippet from my settings file to confirm:

@joshmer Yes. Seems like you're doing the right thing. The setx thing works for me in plain CMD. But it doesn't work for like VS Developer Command Prompt for some reason. Are you also trying to make it work for Developer Command Prompt or something?

@joshmer could you also try this steps please

@joshmer Yes. Seems like you're doing the right thing. The setx thing works for me in plain CMD. But it doesn't work for like VS Developer Command Prompt for some reason. Are you also trying to make it work for Developer Command Prompt or something?

Nope, I'm using standard CMD via Windows Terminal.

@joshmer could you also try this steps please

I tried this and am not seeing any debug output like the screenshot. I'm also not seeing this for Powershell or Ubuntu WSL2, both of which are working fine.
I also have clink and MSYS2 setup in my system, so maybe something there is messing with things?

OK I see clink.bat and related things in it. Guess that's the cause, since it's working fine in plain CMD. Perhaps this is the same reason why VS Developer Command Prompt doesn't work.
Unfortunately I'm no expert at CMD. I hope someone could shed light on this topic.

Is there a chance vsdevcmd just ... overrides the directory on startup?

Actually, yeah, the only OSC I'm seeing in that trace is OSC 0 (set title). There's something stripping it out before it gets printed.

run
echo %prompt%

Ok, so I tried to rename all vsdevcmd.bat files to prevent them from doing anything, and it didn't work. Then I uninstalled clink and I'm now getting the correct OSC prompts! I reverted the vsdevcmd file names and it's still working fine.
As a sanity check I reinstalled clink and OSC is broken again, so I'll have to do some digging into what's happening there. Thanks all for the help!

I was just poking around in the Clink source, and it seems like it should be passing OSC codes through but it definitely has code to parse then, e.g., 0.4.9, 1.0.0a1, and I suspect that it's locally handling them to generate Console API calls, and hence stripping them even if it doesn't handle them.
So possibly (although I couldn't find this code in 0.4.9 as GitHub has indexed after a refactoring) it's only passing through recognised codes, and OSC 9;9 isn't recognised yet.
Either way, sounds like a bug report for clink is in-order here.

TL;DR
For the ones reading this right now that wants this behaviour on windows terminal WSL, just put the following line on ~/.bashrc:
export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'
Then the terminal will maintain the path when you press "Alt+Shift+D", but when you split with "Alt+Shift+-" or "Alt+Shift+=" it will open with the standard path, and that is pretty ok in my opinion. To configure the standard path to be your wsl home directory, edit your setting of WSL profile to be something like this:
{ "guid": "{2c4de342-38b7-51cf-b940-2309a097f518}", "name": "Ubuntu", "source": "Windows.Terminal.Wsl", "startingDirectory": "\\\\wsl$\\Ubuntu\\home\\<Your_User>", "hidden": false }
Cheers!!

Is it currently possible to pass split mode to the wt CLI?

Is it currently possible to pass split mode to the wt CLI?

Yes.

Actually that might not be right - you can pass the split direction but the splitMode is always manual

@zadjii-msft do you want me to open a new issue with that feature request or that is not needed? 😄

Nope, I already filed one 😉

I've come with a workaround: change the starting directory.
Put this function into $PROFILE (make sure to adjust $path)
function sd {
    $path = 'C:\Users\Admin\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json'
     ((Get-Content -path $path) -replace '"startingDirectory":.*', ("`"startingDirectory`": `"$pwd`"") -replace "\\", "\\") | Set-Content -Path $path
}

.. and you'll be able to a open new tab in the same directory almost with no hassle, just make sure to type sd before opening a new tab.
Of course, the drawback is that startingDirectory is changed every time the function is called.
It would be best to use this approach with a key re-mapper, so that when Ctrl+T is pressed the function is called automatically, and when Ctrl+F4 is pressed startingDirectory is reverted back to its original value.

Thanks for you, I have made some changes to the code to accommodate those with commas after them, It work's for me!
function sdd {
  $path = "$env:USERPROFILE\AppData\Local\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState\settings.json"
  $todir = ("$pwd") -replace "\\","\\"
   ((Get-Content -path $path)  -replace '("startingDirectory":)(.*")(.*)', ("`$1`"$todir`"`$3")) | Set-Content -Path $path
}

@robsonsobral here:
https://gist.github.com/LuanVSO/6f2b94cf3bd90f184722676c43ccc1c6

Many thanks for that, been wanting that feature for ages!
Unfortunately, it seems to break Chocolatey/Scoop. After installing programs with them the PATH seems to not be edited anymore. I just pasted that on my $profile, am I missing something?

Many thanks for that, been wanting that feature for ages!
Unfortunately, it seems to break Chocolatey/Scoop. After installing programs with them the PATH seems to not be edited anymore. I just pasted that on my $profile, am I missing something?

@ropbastos você quer dizer o comando refreshenv não funciona mais?
se sim manda o conteúdo do seu $profile

My bad, I don't really know what went on when I made that comment. I remember running "choco install nodejs" and not having node show on path but I just tried to reproduce it and, happily, I guess x), failed. It works perfectly it seems, sorry! And many thanks to all contributors here!

I am able to replicate Panes and tabs(with same working directory) in windows terminal using these steps.

obtained terminal context menu item using this library Windows-terminal-context-menu. For some reason it does not work with default context menu option

set Starting directory of all profiles to "use parent process directory"

this is my key-mapping for split-pane
{         "command":          {             "action": "splitPane",             "split": "auto",             "splitMode": "duplicate"         },         "keys":          [             "alt+shift+d"         ]     },

Result

I hope this helps.
maybe devs can see how differently this library is making context menu options.
let me know if you need some more details.\
One drawback
if you open terminal from start menu or its icon, then starting directory will be "C:\WINDOWS\system32>" instead of "C:\Users\UserName> "

That approach is no different to just going into the directory in a console, and running Terminal from there.
It doesn't help this ticket at all, which is for this:

Still does not keep the CWD same if you change it after opening the terminal. but will keep the initial directory(from where terminal was opened) as CWD.

It won't interfere with it though, so if you then add "OSC9;9" to your various shells, then 'duplicate' and 'split-Duplicate' will work, but 'New tab' and 'split-new' are still to be done.
That said, that's a clever shell extension idea.

Yes you are absolutely correct.
while mentioning known issues in my workaround I realized this wasn't exactly what this thread was about.
But because almost all issues mentioning duplicate tabs/panes with same directory are marked duplicate of #3158 and closed. I thought I would leave it here for some like me  willing to make do with this solution in the meantime.

I want to open new terminal tab of other command lines in the same directory. For example I have a currently active tab of powershell in a specific folder. Not I want to open cmd in the same folder seperated from the current tab.

@Trance-Paradox I think what you looking for is #10232

@Trance-Paradox I think what you looking for is #10232

Yes thank you

Hello,
I wasn't sure this was specified already.
But I'd like to add this.
Any way to have a function to tell wt -w -0 nt program.exe to also run from the current directory ?
I don't want to write extra logic for saving the current directory in my rust program every time.

@NicTanghe try wt -w -0 nt -d . program.exe

Thanks 4 the lightning fast helpfulness as always :D

For anyone having difficulty, I put together a a quick guide on accomplishing this(as long as you're willing to use OSC 9;9), as reading through everything here and in the related threads was pretty confusing.

[Jan 31 2021] So now that this is working for duplicate tab and split pane w/duplicate...

Umm, is it? I'm on 1.10.2383.0 and both split and duplicate still always open in my home folder. What build should I be using to get this behaviour? (I only care about Powershell tabs)

Have you set up our PowerShell to output OSC 9;9 data so that Windows Terminal knows the current working directory? Also, the default split command in the Windows Terminal key bindings is not 'duplicate', so you'll have to rebind that or it splits into a new copy of the profile, and won't look at the current working directory of the existing profile.

Have you set up our PowerShell to output OSC 9;9 data so that Windows Terminal knows the current working directory? Also, the default split command in the Windows Terminal key bindings is not 'duplicate', so you'll have to rebind that or it splits into a new copy of the profile, and won't look at the current working directory of the existing profile.

Is that a documented process? I have no idea what it even means let alone how to do it, and if the position of the Windows Terminal team is that this commonly requested feature is a solved problem, then I would expect to see some reference to it in the official documentation.

It's on the todo list. We'd be happy to accept contributions in this space, especially since folks have plenty of different ways of doing this for plenty of different shells already.

[Jan 31 2021] So now that this is working for duplicate tab and split pane w/duplicate...

Umm, is it? I'm on 1.10.2383.0 and both split and duplicate still always open in my home folder. What build should I be using to get this behaviour? (I only care about Powershell tabs)

Perhaps you, like me, have previously fixed the silly default behavior that wsl has where it starts you in %USERPROFILE% instead of $HOME, and did something like:
"commandline": "wsl.exe ~ -d Ubuntu"
in your settings.json, and it is thus overriding the default path and forcing to HOME.  If you remove the ~ argument there, it will work, provided that this is indeed what you did.

For anyone trying to get it to work with Cmder/Clink.

Add a my_prompt.lua file in the "config/" folder.
Add the following to the file (the "\x1b]9;9;{cwd}\x1b\" part is the osc9;9 sequence, the rest is the default cmder prompt with background color fix, see https://stackoverflow.com/questions/67541540/cmder-wrong-colors-using-windows-terminal)
Use the duplicateTab action in windows terminal

function custom_prompt()
  cwd = clink.get_cwd()
  prompt = "\x1b[1;32;49m{cwd} {git}{hg}{svn} \n\x1b[1;39;49m{lamb} \x1b[0m \x1b]9;9;{cwd}\x1b\\"
  new_value = string.gsub(prompt, "{cwd}", cwd)
  clink.prompt.value = string.gsub(new_value, "{lamb}", "λ")
end

clink.prompt.register_filter(custom_prompt, 1)

As mentionned in https://github.com/microsoft/terminal/issues/10232#issuecomment-948303453 I'm looking for an "out of the box" solution to have duplicated tabs in the same current directory then source tab.

Proposed technical implementation details (optional)
Hit the new tab hotkey, the new terminal should then be in the same folder as the previouse.

Any updates on work (possibly) going on regarding this functionality and/or any available workarounds? There is a way to do it like
wt -w 0 -p <profile-name> -d .

But, more elegant ways?
There are so many different topics discussed in this thread that I cannot figure out what to look for.

This issue should probably be closed, given that an officially supported solution exists in a stable release (unless I'm missing something).
There is support for the OSC 9;9 escape sequence, which when set up, allows you to duplicate a tab in the same directory with ctrl+d. Yet people are still discussing hacky workarounds. I think the issue still being open is potentially confusing people.
If you use bash, put this in your .bashrc:
export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"'

If you use zsh, put this in your .zshrc:
precmd() {
  printf "\e]9;9;%s\e\\" "$(wslpath -m "$PWD")"
}

I use zsh personally so I've only tested the latter, but they should both work.

Thanks, it works just fine to me <3

@robsonsobral if you started using Windows 11, then you don't need wslpath anymore if you're using WSL. The normal linux path is what you can provide in the printf now. So this should work:
export PROMPT_COMMAND='printf "\e]9;9;%s\e\\" "$PWD"

Thank you, @JelteF , but I'm not using WSL neither Windows 11.

I'm so dumb! I forgot I've installed Starship! Now, I need to find how to enable things again.

For Starship, what you need will be very similar to this recipe. There, they're passing the current directory (and possibly some other text) into OSC 0, so it's pretty close to what you already have, e.g., in the PowerShell recipe replace
  $host.ui.Write("`e]0; PS> $env:USERNAME@$env:COMPUTERNAME`: $pwd `a")

with
  $host.ui.Write("`e]9;9;$pwd`a")

If you're using bash from cygwin, MSYS2, or Git For Windows, then it'll be very similar to the WSL recipe give above, by use cygpath -w instead of wslpath -m, i.e. replace
    echo -ne "\033]0; $(basename "$PWD") \007"

with
    echo -ne "\033]9;9;$(cygpath -w "$PWD")\007"

I'm so dumb! I forgot I've installed Starship! Now, I need to find how to enable things again.

In case you’re using PowerShell, this is what works for me to both register the working directory and update the window title:
Invoke-Expression (&starship init powershell)

# https://github.com/starship/starship/issues/2585#issuecomment-821791006
$script:oldPrompt = $function:prompt

function prompt {
    $pp = $pwd.ProviderPath
    Write-Host -NoNewline "$([char]27)]9;9;`"$pp`"$([char]7)"
    & $script:oldPrompt

    $Host.UI.RawUI.WindowTitle = "PS: $(Split-Path $pp -Leaf)"
}

Thank you so much, @TBBle and @shivjm !
Couldn't we add all these recipes to docs?

Couldn't we add all these recipes to docs?

I’d certainly love to see that! Note that the just-released Starship v1.0.0 supports a PowerShell pre-command. I adapted the example from the website:
function Invoke-Starship-PreCommand {
    $pp = $pwd.ProviderPath
    Write-Host -NoNewline "`e]9;9;`"$pp`"`a"
    $host.ui.Write("`e]0; PS> $(Split-Path $pp -Leaf) `a")
}

Invoke-Expression (&starship init powershell)

Couldn't we add all these recipes to docs?

The docs don't exist yet, there's a ticket at https://github.com/MicrosoftDocs/terminal/issues/285 to put something together, but it's not trivial, or at least no one's attempted it yet, AFAIK, due to the wide variety of shells, prompt automation scripts, and general system setups people use.

Thanks to above users. This should work on Windows 11 + Zsh.
# ~/.zshrc
precmd() {
  printf "\e]9;9;%s\e\\" "$PWD"
}

Not sure what happened, but with Windows Terminal (Ubuntu + bash) 1.11.3471.0 the "OSC 9;9 escape" no longer seem to be working.

Not sure what happened, but with Windows Terminal (Ubuntu + bash) 1.11.3471.0 the "OSC 9;9 escape" no longer seem to be working. UPDATE: it seems to be an issue with oh-my-posh. UPDATE2: this has been fixed in JanDeDobbeleer/oh-my-posh#1516. If you suffer from the same problem, get the latest oh-my-posh binary (thanks Inu!)

Mine stopped working as well, and I wasn't sure what was amiss... but MANY examples use $(wslpath -m "$PWD") or equivalent, and indeed I had implemented this feature using that approach as well.  If you look at the change made by oh-my-posh, it simply started using $PWD without "wslpath -m" processing it.  Removing this from my own fixed the issue as well.
I don't know that I'd call this a bug in oh-my-posh, it WORKED previously with this approach, so there was some sort of behavioral change in windows terminal along the way too...
my own fix commit

In case you missed it, there is a tutorial on how to open a new tab/split pane in the same directory at https://docs.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory
As far as I can tell, the fix does not involve OSC 7 but I am guessing that 90% of people here are more interested in opening a new terminal with the same directory, than the technical details. In that regard, I think this issue can be closed as solved.
I have followed the tutorial and it is working in my WSL2 Ubuntu setup.

Go read this guide: Opening a tab/pane in the same directory in Windows Terminal
thanks to everyone in this thread who's recipes I was able to use to help write that ☺

Ok, I am a folk in the back...
I tried those solutions for CMD and WSL, and only the WSL one works for me.
I am following exactly the instructions steps for Command Prompt: cmd.exe :
This works:
set PROMPT=$e]9;9;$P$e\%PROMPT%
But this one fails:
setx PROMPT %PROMPT%
So, I quoted it:

But still not getting duplicated tabs on the same path, neither split panes (with splitMode duplicate) on the same path.
Am I forgetting something?
Best Regards.

I'm pretty sure clink is your problem here, as without it, both commands worked for me as per the instructions. Somewhere in the hidden comments of this ticket, there was a note that clink was interfering with the relevant ANSI codes, and I don't believe it was ever resolved.
My guess would be that it's eating the ANSI codes, so the OSC command is never seen by Windows Terminal.
For the setx issue, it's probably because a " " has ended up in your prompt env-var (I would guess that clink lives in your prompt already). So the instructions should be updated to quote the %PROMPT% as you have done. I was able to reproduce this problem by manually putting a space into my local PROMPT var, so it's not a clink problem per-se, but I guess in your case, clink is why the space is there, even though it's not visible in the displayed prompt.
You could echo %PROMPT% to confirm this.

Ok, that makes sense, and clink came to my mind when it didn't work.
Thanks for taking the time to answer. 🙏
I am using clink's fork now and everything works.
Hurrah! 🥇

It seems I'm also one of the folks in the back.
Followed the guide, were not able to just create the profile file with notepad $PROFILE.AllUsersAllHosts as for some reason, even elevated notepad cannot save things there, in WindowsApps\ps... folder (or elevated terminal doesn't start notepad elevated?).
Had to settle for  $PROFILE.CurrentUserAllHosts, and it did sort of work, with a side effect.
When opening a new tab in WSL, instead of username@PC-NAME:~, I get PS Microsoft.PowerShell.Core\FileSystem::\\wsl.localhost\Ubuntu-20.04\home\username, as current path, which I guess is technically correct, but not what I want. Any solutions to that?

Yeah, $PROFILE.AllUsersAllHosts seems like the wrong directory, that'll be in the PowerShell installation directory; generally "AllUsers" is only for system admins to set. so for personal settings you want "CurrentUser" versions.
That said, I put all these settings directly in $PROFILE and it works fine for me, since I probably don't want these settings to apply to, e.g. VSCode's integrated terminal. (Or maybe I do, if they also support OSC;9;9... Huh, I need to think about that.)

The guide for WSL does not work for me.
I'm on Windows 11 using WSL 2 and oh-my-posh.
I've added the following to the end of my bashrc file
PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'

I get the following error:
-bash: PROMPT_COMMAND: line 0: syntax error near unexpected token `;'
-bash: PROMPT_COMMAND: line 0: `_omp_hook; ; printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'

@RedFour
The problem is that whatever adds _omp_hook to PROMPT_COMMAND earlier included a trailing semicolon, and the guide's command assumes that an existing PROMPT_COMMAND doesn't do that, so it adds one before its new command.
So remove the semicolon after PROMPT_COMMAND, i.e.
PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'

I reckon this is a bug in oh-my-posh's bash support, because it assumes PROMPT_COMMAND is already set and blindly adds the semicolon.
You'd also find if you put the existing OSC9;9 command from the Windows Terminal docs before the oh-my-posh setup line in your .bashrc, it works fine, as the Windows Terminal command handles "No PROMPT_COMMAND set" correctly, and oh-my-posh will then prepend to that correctly.
All that said, oh-my-posh has built-in OSC9;9 support, so you probably don't need this command at all, just set osc99 to true in your config and it'll include it without needing to modify your bash config (or anywhere else you're using oh-my-posh).

Thanks @TBBle for explaining how to fix it.
After following your suggestions, I had to do the following changes to get it working for me.

Command line to use wsl.exe instead of Ubuntu.exe
Starting directory to \\wsl.localhost\Ubuntu\home\<username>

https://github.com/microsoft/WSL/issues/6995 has more information on Windows Terminal unable to start in a linux path.
In the end I used the osc99 option in my oh-my-posh config instead of adding that extra line in the bashrc. Changing the Windows Terminal profile setting was also necessary with the oh-my-posh config option.

2. Command line to use wsl.exe instead of Ubuntu.exe

Ah yes, that's something we need to work through with Canonical. Ubuntu.exe seemingly totally disregards the startingDirectory, which helps power this.

Dang! For some reason the solution from https://docs.microsoft.com/en-us/windows/terminal/tutorials/new-tab-same-directory stopped working in Windows Terminal 1.13.10983.0 (or before). It's working for window splitting (panes) but not for new tabs.

Are you using "new tab" or "duplicate tab". The former doesn't carry the working directory over.

I'm using new tab. Turns out the profile needs to properly escape single slash on Server 2022, something I didn't have to do in Windows 10/11. Fix mentioned by nuixtech fixed the issue. I have terminal installed on Windows 11 and Server 2022 (using the win10 msixbundle). This is how Ubuntu-20.04 profile looks on Windows 11.

On Server 2022, this is how it looks.

I don't understand how that makes a difference (because that path should be processed by Terminal, well before Ubuntu sees it), but it might be worth opening as a separate specific bug report so it can be fixed in the code that auto-generates the profile, or if there's a bug elsewhere in Terminal causing this issue, that can be fixed instead.

@codtiger , thank you for your answer. It saved me :D
One additional detail: with default settings, when I change ubuntu.exe to wsl.exe -d Ubuntu, the starting directory becomes the /mnt/c/WINDOWS/system32. To fix that, I've changed starting directory to ~:
                "startingDirectory": "~",

@codtiger @tristanbarcelon was irritated by this problem, thanks for the suggestions! 😄

Good day!
I am using Windows 10 22H2
Windows Terminal 1.16.10261.0
Ubuntu 22.04.2 LTS
Following this instruction Tutorial: Opening a tab or pane in the same directory in Windows Terminal added to .bash_profile line
PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'

After that, Windows Terminal began to remember directories, thanks!
But other problems arose, for example, nvm broke
Command 'nvm' not found
Adding these lines to .bash_profile helped fix this problem
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

I decided to write this comment because neither in the article Tutorial: Opening a tab or pane in the same directory in Windows Terminal nor in this issue did I see that adding this line
PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND; "}'printf "\e]9;9;%s\e\\" "$(wslpath -w "$PWD")"'

to .bash_profile may cause additional problems.
nvm is the first thing I tried to use, most likely there are more such problems. Did I do something wrong when I edited .bash_profile? Or is it known that adding this line breaks paths or something like that?

That line definitely shouldn't have broken stuff you described. It's not obvious how nvm was working, but my best-guess is that you actually newly created the .bash_profile, and now bash is running that instead of some other file, like .profile, and your existing NVM setup was in that. This site suggests that this is the case, but I haven't looked myself. This answer suggests that maybe it's .bashrc that is no longer being read, but that's older than Ubuntu 22.04.
If that's the case, then you could either add the PROMPT_COMMAND to .profile (or whatever it is) and delete the newly-created .bash_profile, or add something like source ~/.profile to the start of your .bash_profile.

Thank you!
Important clarification — I did not do anything unusual, on the contrary, yesterday I performed a clean installation of Ubuntu 22.04.2 LTS.
After a clean install, of the files listed here: .bash_profile, .bash_login, .profile, only exists .profile. File .bash_profile I created, as it was written here. In addition to the problem with nvm, there was a problem with colors, but I did not betray this.
Indeed, adding PROMPT_COMMAND to the .profile and deleting .bash_profile helped.
Thanks again! Cheers!

Okay, so it might make sense to add a note to the docs along the lines of "If .bash_profile does not exist, but .profile does, add the line there instead", to avoid confusion for the default Ubuntu 22.04 setup and any similar situations.

The creator of powerlevel10k has created a Zsh plugin for this.
He claims it "...achieves the same thing as the code snippet in the official Windows Terminal documentation but with fewer bugs and better performance".
Linking it here for visibility:
https://github.com/romkatv/windows-terminal-zsh-integration

I don't know the zsh ecosystem, but is that plugin widely-suitable-enough to be added as a preferred option to the Windows Terminal docs?
It's clearly too-long to inline into the docs (and is doing a lot more than the one-liner does, such as caching, some TMUX-specific magic and for some reason using wslpath -am and mangling the output rather than wslpath -w), but if general zsh users can do an extra git clone over the current docs and get a much better result, then it seems like an easy win to me.
If zsh plugin managers are commonly used, then that's even better, IMHO.
The main concern I envisage is making the docs dependent on an external site.

Just wanted to say that this app is pretty useless for me without the ability to restore where I left off. This mostly includes tabs and folders.

Thanks for deleting my comment btw

In regard to comments made by alkorlos and TBBle.
This might help somebody in the future:

TL;DR:

remove potential "cd ~" or "cd ~/my-preferred-starting-dir" from .bashrc
remove .bash_profile if using .profile (then move PROMPT_COMMAND to .profile or .bashrc)

On a few forums on the Internet it is advised to put "cd ~" or some variation of this in .bashrc to change the starting directory. This can be overlooked and will obviously make PROMPT_COMMAND not produce the desired result.

If you did not have .bash_profile and you created it, as it was written here, PROMPT_COMMAND will work, given you put it in .bash_profile, however this will also "skip" your "config" (.bashrc and .profile). .bashrc is not "loaded" by default. .profile is responsible for that, but it is also not always "loaded".

First few lines of .profile:
# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.

Solutions:

copy the contents of .profile to .bash_profile. e.g.

...
# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
	. "$HOME/.bashrc"
    fi
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$HOME/bin:$PATH"
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/.local/bin" ] ; then
    PATH="$HOME/.local/bin:$PATH"
fi
...

or

remove .bash_profile and put PROMPT_COMMAND in either .profile or .bashrc

why is this not implemented even 5 years later?
i don't think this is unreasonable for any web developer working on a project that requires to spin up >2 scripts in the same directory.

Well, I mean, it has and it hasn't.
You've been able to use shell integration to open a new tab/pane in the same CWD for a couple years now, using OSC9;9. (osc9;9 was originally tracked in #8166) This thread is technically tracking a similar escape sequence, OSC7, which we haven't had a chance to come back around on yet (because it's got some trickier edge cases with WSL distros). #8214 (linked earlier in this thread) has some of the most complete discussion on the whole problem space.
Alas, automagic CWD detection (like linux) will almost certainly never work, as some shells (cough powershell) don't actually set their CWD.
Then there's of course the potential for automatically modifying people's prompts, such that shell integration is automatically enabled for them. This is definitely something that I want to investigate going forward, maybe sometime next year. But I doubt that'll work for everyone or every shell.

I know this is an old topic but I just wanted to say for anyone trying to get split panes to same directory using GitBash in 2024, adding this line to .bashrc finally worked for me.
PROMPT_COMMAND=${PROMPT_COMMAND:+"$PROMPT_COMMAND "}'printf "\e]9;9;%s\e\\" "$(cygpath -w "$PWD")"'

Hi @zadjii-msft , you mentioned shell integration which works fine in This works fine in Powershell, but when I configure my wsl / zsh using the method described in it, the root directory still opens when I split the pane. I'm trying to understand if I'm missing something?

@Daydreamer-riri I'd suggest checking what settings are used to launch WSL. I don't know if it's still the default, but IIRC it used to default to including a path on the command line (so it wouldn't start in C:\Windows\System32), and that would override the path provided by this feature.
Also worth checking if you haven't already that nothing else in your zsh startup scripts are changing the current directory, e.g., see point 1 of https://github.com/microsoft/terminal/issues/3158#issuecomment-1624390767.
For example, this Ubuntu WSL config block works for me with the bash setup from the shell integration docs:
            {
                "guid": "{2c4de342-38b7-51cf-b940-2309a097f518}",
                "hidden": false,
                "icon": "C:/Program Files/WindowsApps/CanonicalGroupLimited.UbuntuonWindows_2004.2022.1.0_x64__79rhkp1fndgsc/Assets/Square44x44Logo.altform-unplated_targetsize-256.png",
                "name": "Ubuntu",
                "source": "Windows.Terminal.Wsl",
                "startingDirectory": "//wsl$/Ubuntu/home/paulh"
            },

If changing the startingDirectory value changes the start directory successfully, then your zsh startup scripts are not overriding the directory set by this feature, at least, as that's the value this feature overrides.

Hi @TBBle, the settings in my Terminal are:

I found something interesting: when I use the former (which is, the source is Windows.Terminal.Wsl), the path can be duplicate correctly. But it is hidden by default and the latter is used by default. The latter cannot duplicate the path correctly. Is this perhaps a bug?

Try adding a manual commandLine to the non-working profile, something like C:\Windows\System32\wsl.exe -d Ubuntu-24.04. I don't know what command line that dynamic profile source is actually providing on your machine, but my guess it it hard-codes the starting directory in some way. (You could also try adding a startingDirectory value to it (~ should work), since the Windows.Terminal.Wsl profile source generates one by default, but that shouldn't make a difference, and my research below suggests that it's the command-line.)
Anyway, I did some more digging: I have a different Ubuntu build installed (CanonicalGroupLimited.UbuntuonWindows_2004.2022.1.0_x64__79rhkp1fndgsc) but I checked its snippet (with this process), and it apparently just runs ubuntu.exe, which does (or at least used to) override startingDirectory and hence is incompatible with this feature, so I'm fairly confident this is the problem.
If you confirm that adding a commandLine entry fixes the starting directory, then it's an issue specific to the Ubuntu-provided snippet (or a behaviour choice in their ubuntu.exe launcher, probably the false in this line, which was inherited from MS's template launcher project originally implemented by a familiar author) and you would need to raise it as a ticket with them to fix in some way. You're welcome to link or quote this comment in any such issue you raise.

Thank you very much for your survey. It's incredible to have accomplished so much work in such a short time.
However, after I added these two lines to the configuration, everything behaved the same as before, with no improvement.

Did you set "commandline"? or "commandLine"? (note the capital L)
The setup from the docs Works On My Machine when I don't use the profile that Canonical provides, and use the built-in WSL profiles instead:
Using the canonical profile: ("commandline": "ubuntu2204.exe")

Using the built-in dynamic profile: ("commandline": "C:\WINDOWS\system32\wsl.exe -d Ubuntu-22.04")

I have not set up "commandline". The configuration was automatically generated after installing WSL:
{
    "colorScheme": "Chester",
    "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}",
    "hidden": false,
    "name": "Ubuntu 24.04 LTS",
    "opacity": 95,
    "source": "CanonicalGroupLimited.Ubuntu24.04LTS_79rhkp1fndgsc"
}

Yes, that works because by changing the source, you're changing the profile you're inheriting from Ubuntu's one, to the built-in profile that includes the two lines I shared. If you do that, you may as well just unhide the actual profile generated by Windows Terminal, and hide the Ubuntu-generated one, to avoid any risk of confusion in-future. (If you go this way, you can add Ubuntu to the list of profile generators to ignore, and then remove that generated profile entirely, for a cleaner config file.)
Can you share the version of that profile with the two lines I provided added, that wasn't working, so if we can see if there's anything else needed?
I expect this should work, is that what you had?
{
    "commandLine": "ubuntu.exe run",
    "startingDirectory": "~",
    "colorScheme": "Chester",
    "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}",
    "hidden": false,
    "name": "Ubuntu 24.04 LTS",
    "opacity": 95,
    "source": "CanonicalGroupLimited.Ubuntu24.04LTS_79rhkp1fndgsc"
}

Yes, that works because by changing the source, you're changing the profile you're inheriting from Ubuntu's one, to the built-in profile that includes the two lines I shared. If you do that, you may as well just unhide the actual profile generated by Windows Terminal, and hide the Ubuntu-generated one, to avoid any risk of confusion in-future. (If you go this way, you can add Ubuntu to the list of profile generators to ignore, and then remove that generated profile entirely, for a cleaner config file.)是的，这是可行的，因为通过更改源代码，您将从 Ubuntu 的配置文件继承的配置文件更改为包含我共享的两行的内置配置文件。如果您这样做，您也可以取消隐藏 Windows 终端生成的实际配置文件，并隐藏 Ubuntu 生成的配置文件，以避免将来出现任何混淆的风险。 （如果你这样做，你可以将 Ubuntu 添加到要忽略的配置文件生成器列表中，然后完全删除生成的配置文件，以获得更干净的配置文件。）
Can you share the version of that profile with the two lines I provided added, that wasn't working, so if we can see if there's anything else needed?您能否分享该配置文件的版本，其中添加了我提供的两行，这行不起作用，所以我们是否可以看看是否还需要其他任何内容？
I expect this should work, is that what you had?我希望这应该有效，这是你的吗？
{
    "commandLine": "ubuntu2204.exe run",
    "startingDirectory": "~",
    "colorScheme": "Chester",
    "guid": "{acbafd15-cbbb-5bb3-8a61-bed446ff4b83}",
    "hidden": false,
    "name": "Ubuntu 24.04 LTS",
    "opacity": 95,
    "source": "CanonicalGroupLimited.Ubuntu24.04LTS_79rhkp1fndgsc"
}

Sorry, the configuration you provided works, the reason I said it didn't work before was because I filled in the name of the executable wrong (my ubuntu version is 2404 but I wrote 2204). The only problem with it now is that my wsl default directory becomes my Windows user directory instead of the user directory in wsl, which I think can be fixed by changing startDirectory.

Ah yeah, sorry about getting the number wrong. I originally typed "2004" out of habit, and fixed it looking at the example in the other ticket, not your settings. >_<
Anyway, I'd go with that command-line then. That should be all the launcher is doing underneath, after the first-run setup anyway.
Otherwise, I expect you can also put your real desired startup directory in the startingDirectory parameter, e.g., you can see in my earlier example I use //wsl$/Ubuntu/home/paulh which is /home/paulh inside the Ubuntu WSL install. If you navigate to \\wsl$ in Windows Explorer, you should be able to get the correct path to use by browsing in there, but I assume it'll be something like \\wsl$\Ubuntu-2404\home\<yourWSLAccountName>. (My use of / is probably legacy here and only works with wsl.exe, \-based paths like you'd copy from Explorer should work, but remember to double the backslashes if you're editing the JSON directly. I just changed mine to use \ and it works fine.)
Sadly, it turns out Windows Terminal makes the ~ starting directory work by specifically looking for wsl.exe on the command line and otherwise turns it into USERPROFILE as you have discovered. There's a separate hack that specifically looks for the source Windows.Terminal.Wsl (used for drag-and-drop support AFAICT, see #17691) so clearly some outstanding work to be done to make this all work nicely out-of-the-box, and be able to support WSL profiles/launchers in config.

Thank you! Thanks for your guidance.
I think it should be stated in the documentation that “Opening a tab or pane in the same directory” requires some extra work when using the default generated "source": ‘CanonicalGroupLimited... profile”.
Hopefully this will help more people.

I think it should be stated in the documentation that “Opening a tab or pane in the same directory” requires some extra work when using the default generated "source": ‘CanonicalGroupLimited... profile”.

The problem is the "source": ‘CanonicalGroupLimited... profile” is not part of Windows Terminal, so I'd suggest you raise a suggestion with the project providing that source (https://github.com/ubuntu/WSL) to change it to work "better", or better-document the effect their profile has on Windows Terminal, and any extra steps the user needs to take to make it work.
There's some work that could be done in Windows Terminal, but it wouldn't be Ubuntu-specific and would require coordination with any such WSL distributions in their profile contributions too.

Hi @Daydreamer-riri mentioned CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc being faulty. I am also observing the same behaviour. How did you change it to Windows.Terminal.Wsl Whenever I try to change it in settings.json, I get the following error:
Could not find your default profile in your list of profiles - using the first profile. Check to make sure the "defaultProfile" matches the GUID of one of your profiles.


No-install

This is what i get when i bundle install
Fetching gem metadata from https://rubygems.org/........
Fetching additional metadata from https://rubygems.org/..
Resolving dependencies...
Bundler could not find compatible versions for gem "httparty":
  In Gemfile:
    cachebar (>= 0) x86-mingw32 depends on
      httparty (~> 0.8.3) x86-mingw32

    httparty (0.13.1)

HI,
I am also facing the same issue.
Fetching gem metadata from https://rubygems.org/............
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies.....
Bundler could not find compatible versions for gem "httparty":
In snapshot (Gemfile.lock):
httparty (= 0.11.0)
In Gemfile:
jawbone (>= 0) ruby depends on
httparty (~> 0.11.0) ruby
simplificator-withings (>= 0) ruby depends on
  httparty (>= 0) ruby

cachebar (>= 0) ruby depends on
  httparty (~> 0.8.3) ruby

simplificator-withings (>= 0) ruby depends on
  httparty (>= 0) ruby

Running bundle update will rebuild your snapshot from scratch, using only
the gems in your Gemfile, which may resolve the conflict.
Let me know, how you have fixed it ?
Thanks

Hi, just in case anyone has this problem again, I added the gem 'cachebar' to the Gemfile first and then I ran bundle update. It installed without errors.


New/Added items

@joseegm - gulp is not compiling and I get the error below.
'./techne-patterns/_new-added-items.less' wasn't found.

Git somehow loosed some changes... fixed now


sfdx command via proxy not resilient on 5xx errors - zombie loop

Summary
Context: Deploying on scratches
We are struggling with  sdx-cli via proxy. For several days we have been noticing a lot of 5xx errors on proxy side (your DNS changes A records every 30 seonds and our Squid in many cases does not get A records from DNS and responds to sfdx with the code 500 ) that led to many timeouts on sfdx command side (Metadata API request failed: The client has timed out. )...
So if you get 500 via tunnel sfdx starts behaving like a zombie. It cannot move farther.
Steps To Reproduce:

You need a proxy, we use squid v5.7
set proxy env accordingly (e.g. https_proxy) accordingly
For at least 5  parallel deployments
a. Build scratch
b. Start deploying a lot of metadata, e..g 8000 shoud be enough (e..g sfdx force:source:deploy -u alias -p force-app -g -w 120)

Expected result
sfdx should retry on 5xx errors not stop responding.
Actual result
Screenshot:

lef hand side: gitlab runner job - zombie loop which ends with "Metadata API request failed: The client has timed out."
right hand side: top record /500 - from this point in time sfdx becomes "zombie" (waiting loop)

System Information

GKE
Alpine containers
sfdx-cli/7.187.1 linux-x64 node-v18.14.0

Feel free to attach a screenshot.

For at least 2-3 weeks we've been investigating a huge problem with your DNS which one of the side effects is the "zombie loop" I've raised above. We figured out what's wrong. So to catch the context.  Our scratch orgs fabric works as a fabric not a  craft manufacture, so we build a lot of scratches every day.
We face the problem of NXDomain error code (especially on your scratch orgs) handled by our Squid proxy which we try to rescue by a farm of proxies which handle NXDomain error after a 1-2-3 seconds and try to get A Record from a public DNS server once again. Sometimes it's not possible and the last-resort proxy returns the 500 error code which leads here to 'zombie loop' (it does not matter what sfdx command we run - it happens everywhere where TCP connection with an org is needed).
So, what we figured out:

No matter if we use proxy or not we struggled with NXDomain error on public DNS servers (the same one you recommend in the official docs) - on GCP, or even AWS (with nameservers set to <IP_ADDRESS>, <IP_ADDRESS>,...)
SF works on AWS and you probably test it only on AWS which does not need using public DNS so the path to the AWS Authoritative DNS Server there is short.

P.S. Public DNS server IPs are VIPs so the problem may lay in our localization (Poland@Europe).

I don't think the CLI should retry on http 5xx errors.  The CLI can't distinguish between a 500 that should not be retried and a proxy returning a 500 that might be ok to retry.  It's safest to stop and report the error or "Metadata API request failed: The client has timed out."

It turned out to be a problem with your infrastructure (DNS), but let's back to the issue. If you get a 5xx error why don't you stop the whole command? If you do not want to retry you should immediately exit with an error (5xx) .

@shetzel
sfdx-cli/7.198.7 - Is it good enough?

If all the plugin versions are (core), meaning you have not overridden any plugins used by the CLI, then that is probably enough.


Add LEA Extended Input

Based on the spacedock site I gather the user also needs some kind of "server", shouldn't we somehow make this apperent in the abstract or in some other way?


Add a Docker entrypoint script for easier process starting

Looks reasonable to me. :)

Somewhat terrifying, but :+1: